Diffinery

homeflare/celldpublic

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