Diffinery

homeflare/celldpublic

330 lines · 14.8 KBRaw History
1// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2
3//! The command line: what the process was asked to do, and the help text
4//! that documents it.
5//!
6//! Parsing answers one question — which `Action` to take — and refuses
7//! anything ambiguous rather than guessing. The help text is the public
8//! description of the configuration surface, so a test asserts on it.
9pub(crate) struct Settings {
10 pub(crate) control_plane: bool,
11 pub(crate) bucket: Option<String>,
12 pub(crate) load_deployment: bool,
13 pub(crate) endpoint: Option<String>,
14 pub(crate) region: String,
15 pub(crate) listen: celld::startup::Listen,
16 pub(crate) internal_listen: celld::startup::Listen,
17 pub(crate) advertise: Option<String>,
18 pub(crate) unsafe_public_advertise: bool,
19 /// Whether forwarded scheme and host headers can set `request.url`.
20 /// This option is off unless a trusted proxy replaces both headers.
21 pub(crate) trust_forwarded_headers: bool,
22 /// Whether a node tests the bucket's conditional write before it
23 /// serves. On by default, because a store that accepts the
24 /// precondition and ignores it makes the node self-fence in a loop.
25 pub(crate) storage_probe: bool,
26}
27
28pub(crate) enum Action {
29 Run(Settings),
30 Diagnose {
31 settings: Settings,
32 peers: Vec<String>,
33 /// Skip the write probe, for an operator who diagnoses with a
34 /// credential that cannot write.
35 read_only: bool,
36 },
37 Deploy(Vec<String>),
38 D1(Vec<String>),
39 Connect(Vec<String>),
40 Credentials(Vec<String>),
41 Token(Vec<String>),
42 Disconnect(Vec<String>),
43 Help,
44 Version,
45}
46
47pub(crate) fn action_from_process() -> anyhow::Result<Action> {
48 let mut arguments = std::env::args().skip(1).collect::<Vec<_>>();
49 if let Some(action) = arguments.first().map(String::as_str) {
50 let arguments = arguments[1..].to_vec();
51 match action {
52 "deploy" => return Ok(Action::Deploy(arguments)),
53 "d1" => return Ok(Action::D1(arguments)),
54 "connect" => return Ok(Action::Connect(arguments)),
55 "credentials" => return Ok(Action::Credentials(arguments)),
56 "token" => return Ok(Action::Token(arguments)),
57 "disconnect" => return Ok(Action::Disconnect(arguments)),
58 _ => {}
59 }
60 }
61 let diagnose = arguments.first().is_some_and(|value| value == "diagnose");
62 if diagnose {
63 arguments.remove(0);
64 }
65 if matches!(
66 arguments.first().map(String::as_str),
67 Some("--help" | "-h" | "help")
68 ) {
69 return Ok(Action::Help);
70 }
71 if matches!(
72 arguments.first().map(String::as_str),
73 Some("--version" | "-V" | "version")
74 ) {
75 return Ok(Action::Version);
76 }
77 let env = |name: &str| {
78 std::env::var(name)
79 .ok()
80 .filter(|value| !value.trim().is_empty())
81 };
82 let celld_bucket = env("CELLD_BUCKET");
83 let fixture_bucket = env("CELLD_TEST_BUCKET");
84 let control_plane = celld::env_vars::flag("CELLD_CLOUD", false)?;
85 let configured_listen = env("CELLD_ADDR");
86 let configured_internal_listen = env("CELLD_INTERNAL_ADDR");
87 let configured_advertise = env("CELLD_ADVERTISE");
88 if !diagnose
89 && arguments.is_empty()
90 && !control_plane
91 && celld_bucket.is_none()
92 && fixture_bucket.is_none()
93 && configured_listen.is_none()
94 && configured_internal_listen.is_none()
95 && configured_advertise.is_none()
96 {
97 return Ok(Action::Help);
98 }
99 let mut listen_configured = configured_listen.is_some();
100 let mut internal_listen_configured = configured_internal_listen.is_some();
101 let mut peers = Vec::new();
102 let mut read_only = false;
103 let mut settings = Settings {
104 control_plane,
105 bucket: fixture_bucket
106 .or_else(|| celld_bucket.clone())
107 .map(|value| value.trim_start_matches("s3://").to_string()),
108 load_deployment: celld_bucket.is_some(),
109 endpoint: env("S3_ENDPOINT"),
110 region: env("AWS_REGION")
111 .or_else(|| env("AWS_DEFAULT_REGION"))
112 .unwrap_or_else(|| "us-east-1".to_string()),
113 // This placeholder is resolved after command-line mode flags. An
114 // explicit environment or CLI address always wins; otherwise managed
115 // mode selects the first free demo port and standalone uses 8080,
116 // matching celld's listener contract.
117 listen: configured_listen
118 .map(celld::startup::Listen::Explicit)
119 .unwrap_or(celld::startup::Listen::AutoLoopback),
120 internal_listen: configured_internal_listen
121 .map(celld::startup::Listen::Explicit)
122 .unwrap_or(celld::startup::Listen::LoopbackEphemeral),
123 advertise: configured_advertise,
124 unsafe_public_advertise: celld::env_vars::flag("CELLD_UNSAFE_PUBLIC_ADVERTISE", false)?,
125 trust_forwarded_headers: celld::env_vars::flag("CELLD_TRUST_FORWARDED_HEADERS", false)?,
126 storage_probe: celld::env_vars::flag("CELLD_STORAGE_PROBE", true)?,
127 };
128 let mut args = arguments.into_iter();
129 while let Some(argument) = args.next() {
130 match argument.as_str() {
131 "--control-plane" => settings.control_plane = true,
132 "--bucket" => {
133 let bucket = args
134 .next()
135 .ok_or_else(|| anyhow::anyhow!("--bucket requires a value"))?;
136 settings.bucket = Some(bucket.trim_start_matches("s3://").to_string());
137 settings.load_deployment = true;
138 }
139 "--endpoint" => {
140 settings.endpoint = Some(
141 args.next()
142 .ok_or_else(|| anyhow::anyhow!("--endpoint requires a value"))?,
143 );
144 }
145 "--region" => {
146 settings.region = args
147 .next()
148 .ok_or_else(|| anyhow::anyhow!("--region requires a value"))?;
149 }
150 "--listen" => {
151 settings.listen = celld::startup::Listen::Explicit(
152 args.next()
153 .ok_or_else(|| anyhow::anyhow!("--listen requires a value"))?,
154 );
155 listen_configured = true;
156 }
157 "--internal-listen" => {
158 settings.internal_listen = celld::startup::Listen::Explicit(
159 args.next()
160 .ok_or_else(|| anyhow::anyhow!("--internal-listen requires a value"))?,
161 );
162 internal_listen_configured = true;
163 }
164 "--advertise" => {
165 settings.advertise = Some(
166 args.next()
167 .ok_or_else(|| anyhow::anyhow!("--advertise requires a value"))?,
168 );
169 }
170 "--unsafe-public-advertise" => settings.unsafe_public_advertise = true,
171 "--trust-forwarded-headers" => settings.trust_forwarded_headers = true,
172 "--peer" if diagnose => {
173 let peer = args
174 .next()
175 .ok_or_else(|| anyhow::anyhow!("--peer requires a node-session ID"))?;
176 celld::startup::validate_peer_id(&peer)?;
177 peers.push(peer);
178 }
179 "--read-only" if diagnose => read_only = true,
180 "--no-control-plane" => settings.control_plane = false,
181 other => {
182 anyhow::bail!("unknown command or option: {other}; run `celld --help` for usage")
183 }
184 }
185 }
186 if !listen_configured {
187 settings.listen = if settings.control_plane {
188 celld::startup::Listen::AutoLoopback
189 } else {
190 celld::startup::Listen::Explicit("127.0.0.1:8080".to_string())
191 };
192 }
193 let public_listener_is_non_loopback = match &settings.listen {
194 celld::startup::Listen::Explicit(address) => address
195 .parse::<std::net::SocketAddr>()
196 .is_ok_and(|address| !address.ip().is_loopback()),
197 _ => false,
198 };
199 if listen_configured && public_listener_is_non_loopback && !internal_listen_configured {
200 anyhow::bail!(
201 "a non-loopback --listen or CELLD_ADDR requires an explicit --internal-listen or \
202 CELLD_INTERNAL_ADDR; celld does not reuse the public Worker listener for peers"
203 );
204 }
205 if settings.advertise.is_some() && !internal_listen_configured {
206 anyhow::bail!(
207 "--advertise or CELLD_ADVERTISE requires an explicit --internal-listen or \
208 CELLD_INTERNAL_ADDR; the default internal listener uses a random loopback port"
209 );
210 }
211 Ok(if diagnose {
212 Action::Diagnose {
213 settings,
214 peers,
215 read_only,
216 }
217 } else {
218 Action::Run(settings)
219 })
220}
221
222pub(crate) fn print_help() {
223 println!(
224 r#"celld — self-hosted, distributed Durable Objects
225
226USAGE:
227 celld --bucket [s3://|gs://|az://]NAME[/PREFIX] [OPTIONS]
228 celld deploy [PROJECT] --bucket [s3://|gs://|az://]NAME[/PREFIX] [OPTIONS]
229 celld d1 migrations apply DATABASE [PROJECT] --bucket [s3://|gs://|az://]NAME[/PREFIX]
230 celld d1 execute DATABASE --command SQL [PROJECT] --bucket [s3://|gs://|az://]NAME[/PREFIX]
231 celld diagnose --bucket [s3://|gs://|az://]NAME[/PREFIX] [OPTIONS] [--peer NODE_ID]...
232
233Production install: celld --bucket s3://NAME [OPTIONS]
234 celld --bucket gs://NAME [OPTIONS]
235
236OPTIONS:
237 --bucket [s3://|gs://|az://]NAME[/PREFIX]
238 Fleet bucket; s3:// (or no scheme) uses the standard
239 AWS credential chain, gs:// selects Google Cloud
240 Storage via Application Default Credentials, az://
241 names an Azure Blob Storage container and takes its
242 account from AZURE_STORAGE_ACCOUNT_NAME (celld
243 rejects --endpoint and ignores --region for both). A
244 PREFIX puts every object under it, so several fleets
245 can share one bucket
246 --endpoint URL Optional S3-compatible endpoint
247 --region REGION Storage region (default: AWS_REGION or us-east-1)
248 --listen IP:PORT Public Worker listener (default: 127.0.0.1:8080;
249 a non-loopback address requires --internal-listen)
250 --internal-listen IP:PORT
251 Peer and unauthenticated operator listener
252 (default: 127.0.0.1:0)
253 --advertise ADDR:PORT Address peers can reach: IP:PORT or HOST:PORT
254 (requires --internal-listen or CELLD_INTERNAL_ADDR)
255 --peer NODE_ID Diagnose one node with a signed direct probe; repeatable
256 --read-only Skip the bucket write probe. celld diagnose otherwise
257 tests the conditional write, which writes and deletes a
258 small object under the probe/ prefix
259 --unsafe-public-advertise
260 Permit a literal public IP in --advertise. The flag does
261 not resolve hostnames or restrict --internal-listen.
262 Peer traffic has no built-in TLS, and operator routes
263 permit unauthenticated work, eviction, state inspection,
264 and shutdown
265 --trust-forwarded-headers
266 Let X-Forwarded-Host and X-Forwarded-Proto set the
267 scheme and host in request.url. Set this option only
268 when a trusted proxy replaces both headers
269 -h, --help Show this help
270 -V, --version Show the celld version
271
272ENVIRONMENT:
273 Boolean variables accept only `0` or `1`; invalid values stop startup.
274 CELLD_BUCKET Fleet bucket and prefix; same as --bucket
275 S3_ENDPOINT S3-compatible endpoint; same as --endpoint
276 AWS_REGION, AWS_DEFAULT_REGION Storage region (default: us-east-1)
277 AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN
278 Explicit credentials in the standard AWS chain
279 CELLD_ADDR Public Worker listener; same as --listen
280 CELLD_INTERNAL_ADDR Peer and operator listener; same as --internal-listen
281 CELLD_ADVERTISE Peer-reachable address; same as --advertise
282 CELLD_UNSAFE_PUBLIC_ADVERTISE `1` permits a literal public IP in
283 CELLD_ADVERTISE; it does not resolve hostnames
284 or restrict CELLD_INTERNAL_ADDR
285 CELLD_TRUST_FORWARDED_HEADERS `1` trusts X-Forwarded-Host and
286 X-Forwarded-Proto
287 CELLD_NODE Node-session ID (default: generated)
288 CELLD_WATCH Local SQLite/replication working directory
289 CELLD_ESBUILD Override esbuild executable path
290 CELLD_ACTIVATIONS Concurrent cold activations
291 CELLD_EVICTIONS Concurrent evictions (default: 4)
292 CELLD_VARS_FILE, CELLD_VAR_* Worker variable overrides
293 CELLD_ASSET_CACHE_DIR Downloaded static-asset cache directory
294 CELLD_ASSET_CACHE_BYTES Asset cache limit
295
296TUNING:
297 CELLD_STORAGE_PROBE `0` skips the startup conditional-write test
298 (default: on)
299 CELLD_TTL_MS Node lease lifetime (default: 10000)
300 CELLD_OPERATION_DEADLINE_MS Non-restore operation deadline (default: 15000)
301 CELLD_IDLE_EVICT_S Idle-cell eviction age (disabled unless set)
302 CELLD_LOCAL_CACHE_MAX_BYTES Hibernated SQLite cache limit (default: 2 GiB; 0 disables)
303 CELLD_MAX_RESIDENT_CELLS Resident-cell hard cap, enforced at admission
304 CELLD_PRESSURE_OWNERSHIP release to rebalance, sticky to cache locally
305 CELLD_MAX_RSS_MB RSS shed threshold (default: 80% of memory; 0 disables)
306 CELLD_ALARM_RESIDENT_MS Near-alarm residency window
307 CELLD_WAKER_TICK_MS Orphan-alarm scan interval
308 CELLD_V8_HEAP_LIMIT_MB Per-isolate V8 heap limit
309 CELLD_FETCH_TIMEOUT_S Outbound fetch timeout
310 CELLD_HANDLER_BUDGET_S JavaScript handler budget
311 CELLD_TOKIO_THREADS Tokio runtime worker threads
312 CELLD_OUTPUT_GATE `0` removes the durability wait from writes
313 RUST_LOG Runtime log filter (default: info)
314
315EXPERIMENTAL:
316 CELLD_DURABILITY `fleet` acks writes at follower-fsync
317 quorum and tiers to the bucket behind
318 (default: `fleet`; `bucket` waits for storage)
319 CELLD_WORKER_LOADER Worker Loader binding name for Code Mode
320 CELLD_AI_BINDING, CELLD_AI_URL AI binding name and endpoint
321
322Documentation: https://celld.dev/docs"#
323 );
324}
325
326pub(crate) fn worker_loader_binding() -> Option<String> {
327 std::env::var("CELLD_WORKER_LOADER")
328 .ok()
329 .filter(|name| !name.is_empty())
330}