Diffinery

homeflare/celldpublic

410 lines · 19.4 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 and remains stable across builds.
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 writes and ranged reads
23 /// before it serves. On by default, because a store that mishandles either
24 /// operation cannot safely serve cell data.
25 pub(crate) storage_probe: bool,
26 /// Set only by the `celld dev` supervisor for its child node. No fleet
27 /// flag or public environment variable selects the local backend.
28 pub(crate) dev_store: Option<std::path::PathBuf>,
29}
30
31pub(crate) enum Action {
32 Run(Settings),
33 Diagnose {
34 settings: Settings,
35 peers: Vec<String>,
36 /// Skip the write probe, for an operator who diagnoses with a
37 /// credential that cannot write.
38 read_only: bool,
39 /// Print one JSON object per check instead of a text verdict line.
40 json: bool,
41 },
42 Deploy(Vec<String>),
43 Dev(Vec<String>),
44 Cell(Vec<String>),
45 D1(Vec<String>),
46 Kv(Vec<String>),
47 Queue(Vec<String>),
48 Connect(Vec<String>),
49 Credentials(Vec<String>),
50 Token(Vec<String>),
51 Disconnect(Vec<String>),
52 Help,
53 Version,
54}
55
56impl Action {
57 /// Whether this invocation's stdout carries data rather than a log stream.
58 ///
59 /// A node's stdout *is* its log, and Docker and journald read it. A CLI
60 /// subcommand's stdout is its answer: `celld kv get KEY > value` must write
61 /// the value and nothing else, and `celld d1 execute` prints JSON a script
62 /// parses. Sharing one stream between the two prefixes an operator's data
63 /// with whatever the process happened to warn about at startup, which is
64 /// how this was found -- an allocator warning landed in front of a value.
65 pub(crate) fn stdout_is_data(&self) -> bool {
66 !matches!(
67 self,
68 Self::Run(_) | Self::Dev(_) | Self::Help | Self::Version
69 )
70 }
71}
72
73pub(crate) fn action_from_process() -> anyhow::Result<Action> {
74 let mut arguments = std::env::args().skip(1).collect::<Vec<_>>();
75 if let Some(action) = arguments.first().map(String::as_str) {
76 let arguments = arguments[1..].to_vec();
77 match action {
78 "deploy" => return Ok(Action::Deploy(arguments)),
79 "dev" => return Ok(Action::Dev(arguments)),
80 "cell" => return Ok(Action::Cell(arguments)),
81 "d1" => return Ok(Action::D1(arguments)),
82 "kv" => return Ok(Action::Kv(arguments)),
83 "queue" => return Ok(Action::Queue(arguments)),
84 "connect" => return Ok(Action::Connect(arguments)),
85 "credentials" => return Ok(Action::Credentials(arguments)),
86 "token" => return Ok(Action::Token(arguments)),
87 "disconnect" => return Ok(Action::Disconnect(arguments)),
88 _ => {}
89 }
90 }
91 let diagnose = arguments.first().is_some_and(|value| value == "diagnose");
92 if diagnose {
93 arguments.remove(0);
94 }
95 if matches!(
96 arguments.first().map(String::as_str),
97 Some("--help" | "-h" | "help")
98 ) {
99 return Ok(Action::Help);
100 }
101 if matches!(
102 arguments.first().map(String::as_str),
103 Some("--version" | "-V" | "version")
104 ) {
105 return Ok(Action::Version);
106 }
107 let env = |name: &str| {
108 std::env::var(name)
109 .ok()
110 .filter(|value| !value.trim().is_empty())
111 };
112 let celld_bucket = env("CELLD_BUCKET");
113 let fixture_bucket = env("CELLD_TEST_BUCKET");
114 let control_plane = celld::env_vars::flag("CELLD_CLOUD", false)?;
115 let configured_listen = env("CELLD_ADDR");
116 let configured_internal_listen = env("CELLD_INTERNAL_ADDR");
117 let configured_advertise = env("CELLD_ADVERTISE");
118 if !diagnose
119 && arguments.is_empty()
120 && !control_plane
121 && celld_bucket.is_none()
122 && fixture_bucket.is_none()
123 && configured_listen.is_none()
124 && configured_internal_listen.is_none()
125 && configured_advertise.is_none()
126 {
127 return Ok(Action::Help);
128 }
129 let mut listen_configured = configured_listen.is_some();
130 let mut internal_listen_configured = configured_internal_listen.is_some();
131 let mut peers = Vec::new();
132 let mut read_only = false;
133 let mut json = false;
134 let mut settings = Settings {
135 control_plane,
136 bucket: fixture_bucket.or_else(|| celld_bucket.clone()),
137 load_deployment: celld_bucket.is_some(),
138 endpoint: env("S3_ENDPOINT"),
139 region: env("AWS_REGION")
140 .or_else(|| env("AWS_DEFAULT_REGION"))
141 .unwrap_or_else(|| "us-east-1".to_string()),
142 // This placeholder is resolved after command-line mode flags. An
143 // explicit environment or CLI address always wins; otherwise managed
144 // mode selects the first free demo port and standalone uses 8080,
145 // matching celld's listener contract.
146 listen: configured_listen
147 .map(celld::startup::Listen::Explicit)
148 .unwrap_or(celld::startup::Listen::AutoLoopback),
149 internal_listen: configured_internal_listen
150 .map(celld::startup::Listen::Explicit)
151 .unwrap_or(celld::startup::Listen::LoopbackEphemeral),
152 advertise: configured_advertise,
153 unsafe_public_advertise: celld::env_vars::flag("CELLD_UNSAFE_PUBLIC_ADVERTISE", false)?,
154 trust_forwarded_headers: celld::env_vars::flag("CELLD_TRUST_FORWARDED_HEADERS", false)?,
155 storage_probe: celld::env_vars::flag("CELLD_STORAGE_PROBE", true)?,
156 dev_store: if diagnose {
157 None
158 } else {
159 std::env::var_os("CELLD_INTERNAL_DEV_STORE").map(std::path::PathBuf::from)
160 },
161 };
162 let mut args = arguments.into_iter();
163 while let Some(argument) = args.next() {
164 match argument.as_str() {
165 "--control-plane" => settings.control_plane = true,
166 "--bucket" => {
167 let bucket = args
168 .next()
169 .ok_or_else(|| anyhow::anyhow!("--bucket requires a value"))?;
170 settings.bucket = Some(bucket);
171 settings.load_deployment = true;
172 }
173 "--endpoint" => {
174 settings.endpoint = Some(
175 args.next()
176 .ok_or_else(|| anyhow::anyhow!("--endpoint requires a value"))?,
177 );
178 }
179 "--region" => {
180 settings.region = args
181 .next()
182 .ok_or_else(|| anyhow::anyhow!("--region requires a value"))?;
183 }
184 "--listen" => {
185 settings.listen = celld::startup::Listen::Explicit(
186 args.next()
187 .ok_or_else(|| anyhow::anyhow!("--listen requires a value"))?,
188 );
189 listen_configured = true;
190 }
191 "--internal-listen" => {
192 settings.internal_listen = celld::startup::Listen::Explicit(
193 args.next()
194 .ok_or_else(|| anyhow::anyhow!("--internal-listen requires a value"))?,
195 );
196 internal_listen_configured = true;
197 }
198 "--advertise" => {
199 settings.advertise = Some(
200 args.next()
201 .ok_or_else(|| anyhow::anyhow!("--advertise requires a value"))?,
202 );
203 }
204 "--unsafe-public-advertise" => settings.unsafe_public_advertise = true,
205 "--trust-forwarded-headers" => settings.trust_forwarded_headers = true,
206 "--peer" if diagnose => {
207 let peer = args
208 .next()
209 .ok_or_else(|| anyhow::anyhow!("--peer requires a node-session ID"))?;
210 celld::startup::validate_peer_id(&peer)?;
211 peers.push(peer);
212 }
213 "--read-only" if diagnose => read_only = true,
214 "--json" if diagnose => json = true,
215 "--no-control-plane" => settings.control_plane = false,
216 other => {
217 anyhow::bail!("unknown command or option: {other}; run `celld --help` for usage")
218 }
219 }
220 }
221 if !listen_configured {
222 settings.listen = if settings.control_plane {
223 celld::startup::Listen::AutoLoopback
224 } else {
225 celld::startup::Listen::Explicit("127.0.0.1:8080".to_string())
226 };
227 }
228 let public_listener_is_non_loopback = match &settings.listen {
229 celld::startup::Listen::Explicit(address) => address
230 .parse::<std::net::SocketAddr>()
231 .is_ok_and(|address| !address.ip().is_loopback()),
232 _ => false,
233 };
234 if listen_configured && public_listener_is_non_loopback && !internal_listen_configured {
235 anyhow::bail!(
236 "a non-loopback --listen or CELLD_ADDR requires an explicit --internal-listen or \
237 CELLD_INTERNAL_ADDR; celld does not reuse the public Worker listener for peers"
238 );
239 }
240 if settings.advertise.is_some() && !internal_listen_configured {
241 anyhow::bail!(
242 "--advertise or CELLD_ADVERTISE requires an explicit --internal-listen or \
243 CELLD_INTERNAL_ADDR; the default internal listener uses a random loopback port"
244 );
245 }
246 if settings.dev_store.is_some() {
247 anyhow::ensure!(
248 !settings.control_plane
249 && settings.bucket.as_deref() == Some("celld-dev")
250 && settings.endpoint.is_none()
251 && settings.advertise.is_none(),
252 "the internal development store requires the celld dev node configuration"
253 );
254 }
255 Ok(if diagnose {
256 Action::Diagnose {
257 settings,
258 peers,
259 read_only,
260 json,
261 }
262 } else {
263 Action::Run(settings)
264 })
265}
266
267pub(crate) fn print_help() -> anyhow::Result<()> {
268 let help = format!(
269 r#"celld — self-hosted, distributed Durable Objects
270
271USAGE:
272 celld --bucket [s3://|gs://|az://]NAME[/PREFIX] [OPTIONS]
273 celld deploy [PROJECT] --bucket [s3://|gs://|az://]NAME[/PREFIX] [OPTIONS]
274 celld dev [PROJECT] [--host IP] [--port PORT] [--logs]
275 celld cell list [CLASS] --bucket [s3://|gs://|az://]NAME[/PREFIX] [OPTIONS]
276 celld d1 migrations apply DATABASE [PROJECT] --bucket [s3://|gs://|az://]NAME[/PREFIX]
277 celld d1 execute DATABASE --command SQL [PROJECT] --bucket [s3://|gs://|az://]NAME[/PREFIX]
278 celld kv get|put|delete|list|info NAMESPACE --bucket [s3://|gs://|az://]NAME[/PREFIX]
279 celld queue info|peek|purge|pause|resume|redrive QUEUE --bucket [s3://|gs://|az://]NAME[/PREFIX]
280 celld diagnose --bucket [s3://|gs://|az://]NAME[/PREFIX] [OPTIONS] [--peer NODE_ID]...
281
282Production install: celld --bucket s3://NAME [OPTIONS]
283 celld --bucket gs://NAME [OPTIONS]
284
285OPTIONS:
286 --bucket [s3://|gs://|az://]NAME[/PREFIX]
287 Fleet bucket; s3:// (or no scheme) uses the standard
288 AWS credential chain, gs:// selects Google Cloud
289 Storage via Application Default Credentials, az://
290 names an Azure Blob Storage container and takes its
291 account from AZURE_STORAGE_ACCOUNT_NAME (celld
292 rejects --endpoint and ignores --region for both). A
293 PREFIX puts every object under it, so several fleets
294 can share one bucket
295 --endpoint URL Optional S3-compatible endpoint
296 --region REGION Storage region (default: AWS_REGION or us-east-1)
297 --listen IP:PORT Public Worker listener (default: 127.0.0.1:8080;
298 a non-loopback address requires --internal-listen)
299 --internal-listen IP:PORT
300 Peer and unauthenticated operator listener
301 (default: 127.0.0.1:0)
302 --advertise ADDR:PORT Address peers can reach: IP:PORT or HOST:PORT
303 (requires --internal-listen or CELLD_INTERNAL_ADDR)
304 --peer NODE_ID Diagnose one node with a signed direct probe; repeatable
305 --json Print one JSON object per diagnostic check
306 --read-only Skip the bucket write probe. celld diagnose otherwise
307 tests the conditional write, which writes and deletes a
308 small object under the probe/ prefix
309 --unsafe-public-advertise
310 Permit a literal public IP in --advertise. The flag does
311 not resolve hostnames or restrict --internal-listen.
312 Peer traffic has no built-in TLS, and operator routes
313 permit unauthenticated work, eviction, state inspection,
314 and shutdown
315 --trust-forwarded-headers
316 Let X-Forwarded-Host and X-Forwarded-Proto set the
317 scheme and host in request.url. Set this option only
318 when a trusted proxy replaces both headers
319 -h, --help Show this help
320 -V, --version Show the celld version
321
322ENVIRONMENT:
323 Boolean variables accept only `0` or `1`; invalid values stop startup.
324 CELLD_BUCKET Fleet bucket and prefix; same as --bucket
325 S3_ENDPOINT S3-compatible endpoint; same as --endpoint
326 AWS_REGION, AWS_DEFAULT_REGION Storage region (default: us-east-1)
327 AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN
328 Explicit credentials in the standard AWS chain
329 CELLD_ADDR Public Worker listener; same as --listen
330 CELLD_INTERNAL_ADDR Peer and operator listener; same as --internal-listen
331 CELLD_ADVERTISE Peer-reachable address; same as --advertise
332 CELLD_UNSAFE_PUBLIC_ADVERTISE `1` permits a literal public IP in
333 CELLD_ADVERTISE; it does not resolve hostnames
334 or restrict CELLD_INTERNAL_ADDR
335 CELLD_TRUST_FORWARDED_HEADERS `1` trusts X-Forwarded-Host and
336 X-Forwarded-Proto
337 CELLD_NODE Node-session ID (default: generated)
338 CELLD_WATCH Local SQLite/replication working directory
339 CELLD_ESBUILD Override esbuild executable path
340 CELLD_ACTIVATIONS Concurrent cold activations
341 CELLD_EVICTIONS Concurrent evictions (default: 4)
342 CELLD_VARS_FILE, CELLD_VAR_* Worker variable overrides
343 CELLD_ASSET_CACHE_DIR Downloaded static-asset cache directory
344 CELLD_ASSET_CACHE_BYTES Asset cache limit
345
346TUNING:
347 CELLD_STORAGE_PROBE `0` skips the startup storage-contract test
348 (default: on)
349 CELLD_TTL_MS Node lease lifetime (default: 10000)
350 CELLD_OPERATION_DEADLINE_MS Non-restore operation deadline (default: 15000)
351 CELLD_SHUTDOWN_DRAIN_MS Shutdown handoff no-progress interval (default: 25000)
352 CELLD_SHUTDOWN_TOTAL_MS Complete process stop bound (default: {shutdown_total_ms})
353 CELLD_DRAIN_TOKEN_WAIT_MS Drain-token wait before an unserialized
354 handoff; at most {token_wait_numerator}/{token_wait_denominator} of the complete
355 stop bound (default: {drain_token_wait_ms}; 0 disables)
356 CELLD_READY_FLEET_GATE_MS First-readiness wait for fleet capacity
357 (default: 120000; 0 disables)
358 CELLD_REBALANCE_INTERVAL_MS Ownership balancing sample interval
359 (default: 5000; 0 disables)
360 CELLD_REBALANCE_BATCH_CELLS Idle cells one balancing batch moves
361 (default: 32)
362 CELLD_PLACEMENT_WEIGHT Relative ownership share (default: the
363 CPU count)
364 CELLD_IDLE_EVICT_S Idle-cell eviction age (disabled unless set)
365 CELLD_RECOVERY_RETRY_MS Dead-owner recovery retry backoff (default: 1000)
366 CELLD_RECOVERY_RETRIES Recovery retries before a request fails (default: 240)
367 CELLD_LOCAL_CACHE_MAX_BYTES Hibernated SQLite cache limit (default: 2 GiB; 0 disables)
368 CELLD_MAX_RESIDENT_CELLS Resident-cell hard cap, enforced at admission
369 CELLD_MAX_CELL_REQUESTS Concurrent fetches per cell (default: 64)
370 CELLD_MAX_REQUEST_BODY_BYTES Ingress request body limit (default: 1 GiB)
371 CELLD_PRESSURE_OWNERSHIP release to rebalance, sticky to cache locally
372 CELLD_MAX_RSS_MB Active-memory shed threshold (default: 80%; 0 disables)
373 CELLD_ALARM_RESIDENT_MS Near-alarm residency window
374 CELLD_WAKER_TICK_MS Orphan-alarm scan interval
375 CELLD_V8_HEAP_LIMIT_MB Per-isolate V8 heap limit
376 CELLD_FETCH_TIMEOUT_S Outbound fetch timeout
377 CELLD_HANDLER_BUDGET_S JavaScript handler budget
378 CELLD_TOKIO_THREADS Tokio runtime worker threads
379 CELLD_OUTPUT_GATE `0` removes the durability wait from writes
380 CELLD_DURABILITY `fleet` acks when every follower holds the
381 write on disk, or when the bucket upload
382 wins, and uploads behind either way; needs
383 2+ nodes, else every ack waits for the
384 bucket and writes are much slower
385 (default: `fleet`; `bucket` always waits)
386 CELLD_LOG_CAPTURE_WORKERS Concurrent log-capture workers (default: 8)
387 CELLD_LOG_PIPELINE Fleet log rounds in flight (default: 4)
388 CELLD_LOG_GROUP_COMMIT_MS Queue group-commit wait (default: 1 ms; 0 disables)
389 CELLD_LOG_HEDGE_MS Duplicate a slow log append (default: adaptive; 0 disables)
390 CELLD_LTX_TRUNCATE_PAGES WAL pages before a truncate checkpoint (default: 128; Queues never truncate; 0 disables)
391 RUST_LOG Runtime log filter (default: info)
392
393EXPERIMENTAL:
394 CELLD_WORKER_LOADER Worker Loader binding name for Code Mode
395 CELLD_AI_BINDING, CELLD_AI_URL AI binding name and endpoint
396
397Documentation: https://celld.dev/docs"#,
398 shutdown_total_ms = celld::env_vars::DEFAULT_SHUTDOWN_TOTAL_MS,
399 drain_token_wait_ms = celld::env_vars::DEFAULT_DRAIN_TOKEN_WAIT_MS,
400 token_wait_numerator = celld::env_vars::MAX_DRAIN_TOKEN_WAIT_NUMERATOR,
401 token_wait_denominator = celld::env_vars::MAX_DRAIN_TOKEN_WAIT_DENOMINATOR,
402 );
403 celld::cli_output::Output::new(celld::cli_output::Format::Text).help(&help)
404}
405
406pub(crate) fn worker_loader_binding() -> Option<String> {
407 std::env::var("CELLD_WORKER_LOADER")
408 .ok()
409 .filter(|name| !name.is_empty())
410}