Diffinery

homeflare/celldpublic

918 lines · 32.4 KBRaw History
1// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2
3//! The local application stack behind `celld dev`.
4//!
5//! Development still uses the standalone deployment, ownership, and LTX
6//! paths. This module supplies only the infrastructure those paths require:
7//! one persisted local object store and one supervised celld node.
8
9use crate::bucket::Bucket;
10use crate::{deploy, fleet};
11use anyhow::{bail, Context as _};
12use glob::{MatchOptions, Pattern};
13use notify::{RecursiveMode, Watcher as _};
14use nu_ansi_term::{Color, Style};
15use sha2::{Digest as _, Sha256};
16use std::collections::BTreeMap;
17use std::io::IsTerminal as _;
18use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
19use std::path::{Path, PathBuf};
20use std::process::Stdio;
21use std::time::Duration;
22use tokio::io::{AsyncBufReadExt as _, BufReader};
23use tokio::process::{Child, Command};
24use tokio::sync::{mpsc, oneshot};
25
26pub const DEFAULT_PORT: u16 = 9876;
27const BUCKET: &str = "celld-dev";
28
29/// The narrow bridge used by the supervised binary process. The public fleet
30/// parser never receives this path, so no regular subcommand can select it.
31#[doc(hidden)]
32pub fn open_local_bucket(database: &Path) -> anyhow::Result<Bucket> {
33 Bucket::open_dev(database)
34}
35
36#[derive(Debug)]
37struct Options {
38 project: Option<PathBuf>,
39 clean: bool,
40 stack: StackOptions,
41}
42
43/// The local state directory of one project.
44///
45/// `--clean` deletes this directory and everything below it. The path is
46/// private and the only constructor takes the project directory that `run`
47/// resolved, so a command-line value can never become the target of the
48/// delete. A newtype carries that rule instead of a comment, because a
49/// `PathBuf` field would let a later caller pass any path and lose nothing at
50/// compile time.
51#[derive(Debug)]
52struct DevState {
53 path: PathBuf,
54}
55
56impl DevState {
57 /// The project-relative location of the local state, and also the suffix
58 /// that `discard` requires before it deletes.
59 const DIRECTORY: &'static str = ".celld/dev";
60
61 fn for_project(project: &Path) -> Self {
62 Self {
63 path: project.join(Self::DIRECTORY),
64 }
65 }
66
67 fn path(&self) -> &Path {
68 &self.path
69 }
70
71 /// Delete the local state so the next run starts from nothing. The answer
72 /// reports whether a directory was present, because the console line for
73 /// an empty project must not claim that data was removed.
74 ///
75 /// An absent directory is the wanted result of this command, so it is not
76 /// an error.
77 #[allow(clippy::disallowed_methods)] // Local development state is an operator-owned host path.
78 fn discard(&self) -> anyhow::Result<bool> {
79 // The constructor already guarantees this. The check stays because it
80 // is the tripwire for a future constructor that takes a path: a
81 // recursive delete must never widen by accident.
82 anyhow::ensure!(
83 self.path.ends_with(Self::DIRECTORY),
84 "refusing to discard {}, which is not a celld dev state directory",
85 self.path.display()
86 );
87 match std::fs::remove_dir_all(&self.path) {
88 Ok(()) => Ok(true),
89 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
90 Err(error) => Err(error)
91 .with_context(|| format!("discard local state directory {}", self.path.display())),
92 }
93 }
94}
95
96#[derive(Debug)]
97struct StackOptions {
98 listener: SocketAddr,
99 logs: bool,
100 watch: bool,
101 watch_ignores: Vec<Pattern>,
102}
103
104struct Store {
105 database: PathBuf,
106}
107
108#[derive(Clone, Copy)]
109struct Console {
110 color: bool,
111}
112
113impl Console {
114 fn new() -> Self {
115 let force = std::env::var_os("FORCE_COLOR").is_some_and(|value| value != "0");
116 let color =
117 std::env::var_os("NO_COLOR").is_none() && (force || std::io::stdout().is_terminal());
118 Self { color }
119 }
120
121 fn paint(&self, style: Style, value: &str) -> String {
122 if self.color {
123 style.paint(value).to_string()
124 } else {
125 value.to_string()
126 }
127 }
128
129 fn header(&self) {
130 crate::note!("{}", self.paint(Color::Cyan.bold(), "celld dev"));
131 }
132
133 fn detail(&self, label: &str, value: &str) {
134 crate::note!(
135 " {} {value}",
136 self.paint(Style::new().dimmed(), &format!("{label:<7}"))
137 );
138 }
139
140 fn progress(&self, message: &str) {
141 crate::note!(" {} {message}", self.paint(Color::Yellow.normal(), "●"));
142 }
143
144 fn ready(&self, origin: &str) {
145 crate::note!(
146 " {} {}",
147 self.paint(Color::Green.bold(), "ready"),
148 self.paint(Color::Cyan.bold(), origin)
149 );
150 }
151
152 fn log(&self, line: &str) {
153 let style = if line.contains(" ERROR ") {
154 Color::Red.normal()
155 } else if line.contains(" WARN ") {
156 Color::Yellow.normal()
157 } else {
158 Style::new().dimmed()
159 };
160 crate::note!("{}", self.paint(style, line));
161 }
162
163 fn failure(&self, message: &str) {
164 crate::note!(" {} {message}", self.paint(Color::Red.bold(), "error"));
165 }
166}
167
168struct ProjectWatcher {
169 project: PathBuf,
170 ignored: Vec<Pattern>,
171 _watcher: notify::RecommendedWatcher,
172 changes: mpsc::UnboundedReceiver<notify::Result<notify::Event>>,
173}
174
175impl ProjectWatcher {
176 fn new(project: &Path, ignored: Vec<Pattern>) -> anyhow::Result<Self> {
177 let (sender, changes) = mpsc::unbounded_channel();
178 let mut watcher = notify::recommended_watcher(move |event| {
179 let _ = sender.send(event);
180 })
181 .context("create the project watcher")?;
182 watcher
183 .watch(project, RecursiveMode::Recursive)
184 .with_context(|| format!("watch the project directory {}", project.display()))?;
185 Ok(Self {
186 project: project.to_path_buf(),
187 ignored,
188 _watcher: watcher,
189 changes,
190 })
191 }
192
193 #[allow(clippy::disallowed_methods)] // Host-side debounce time is outside the Actor domain.
194 async fn changed(&mut self) -> anyhow::Result<()> {
195 self.next_relevant_change().await?;
196 loop {
197 // An editor can replace one save through several writes and a
198 // rename. Wait for one quiet interval so esbuild never reads the
199 // temporary middle of that transaction.
200 match tokio::time::timeout(Duration::from_millis(150), self.next_relevant_change())
201 .await
202 {
203 Ok(result) => result?,
204 Err(_) => return Ok(()),
205 }
206 }
207 }
208
209 async fn next_relevant_change(&mut self) -> anyhow::Result<()> {
210 loop {
211 match self
212 .changes
213 .recv()
214 .await
215 .context("the project watcher stopped")?
216 {
217 Ok(event) if relevant_project_event(&self.project, &event, &self.ignored) => {
218 return Ok(())
219 }
220 Ok(_) => {}
221 Err(error) => return Err(error).context("watch the project directory"),
222 }
223 }
224 }
225}
226
227fn relevant_project_event(project: &Path, event: &notify::Event, ignored: &[Pattern]) -> bool {
228 // A read is not a change. The inotify backend reports `Access(Open(Any))`
229 // for every file that the bundler and the deploy step read, so a rebuild
230 // produces the events that request the next rebuild and the supervisor
231 // never settles. The path filters cannot close this loop, because the
232 // files that the rebuild reads are the project sources it must watch. A
233 // write still arrives as a `Modify` event, and a `Create` or a `Remove`
234 // event keeps its own kind, so no real change becomes invisible.
235 if matches!(event.kind, notify::EventKind::Access(_)) {
236 return false;
237 }
238 event
239 .paths
240 .iter()
241 .any(|path| !ignored_project_path(project, path, ignored))
242}
243
244fn ignored_project_path(project: &Path, path: &Path, ignored: &[Pattern]) -> bool {
245 const IGNORED_DIRECTORIES: &[&str] = &[
246 ".cache",
247 ".celld",
248 ".git",
249 ".hg",
250 ".next",
251 ".nuxt",
252 ".parcel-cache",
253 ".pnpm-store",
254 ".svn",
255 ".turbo",
256 ".wrangler",
257 ".yarn",
258 "bower_components",
259 "coverage",
260 "node_modules",
261 "target",
262 ];
263 let relative = path.strip_prefix(project).unwrap_or(path);
264 relative
265 .components()
266 .filter_map(|component| match component {
267 std::path::Component::Normal(name) => Some(name),
268 _ => None,
269 })
270 .any(|name| IGNORED_DIRECTORIES.iter().any(|ignored| name == *ignored))
271 || relative.ancestors().any(|candidate| {
272 !candidate.as_os_str().is_empty()
273 && ignored.iter().any(|pattern| {
274 let options = MatchOptions {
275 case_sensitive: true,
276 require_literal_separator: true,
277 require_literal_leading_dot: true,
278 };
279 pattern.matches_path_with(candidate, options)
280 // A directory creation event arrives before its child
281 // path. Probe one child so `generated/**` also ignores
282 // the event that creates `generated` itself.
283 || pattern.matches_path_with(
284 &candidate.join("__celld_watch_descendant__"),
285 options,
286 )
287 })
288 })
289}
290
291#[cfg(all(test, celld_internal_tests))]
292mod dev_contract {
293 include!(env!("CELLD_INTERNAL_DEV_TESTS"));
294}
295
296struct ShutdownSignals {
297 #[cfg(unix)]
298 interrupt: tokio::signal::unix::Signal,
299 #[cfg(unix)]
300 terminate: tokio::signal::unix::Signal,
301}
302
303impl ShutdownSignals {
304 fn install() -> anyhow::Result<Self> {
305 #[cfg(unix)]
306 {
307 Ok(Self {
308 interrupt: tokio::signal::unix::signal(
309 tokio::signal::unix::SignalKind::interrupt(),
310 )?,
311 terminate: tokio::signal::unix::signal(
312 tokio::signal::unix::SignalKind::terminate(),
313 )?,
314 })
315 }
316 #[cfg(not(unix))]
317 {
318 Ok(Self {})
319 }
320 }
321
322 async fn received(&mut self) {
323 #[cfg(unix)]
324 crate::asyncrt::select! {
325 _ = self.interrupt.recv() => {}
326 _ = self.terminate.recv() => {}
327 }
328 #[cfg(not(unix))]
329 let _ = tokio::signal::ctrl_c().await;
330 }
331}
332
333pub fn print_help() -> anyhow::Result<()> {
334 crate::cli_output::Output::new(crate::cli_output::Format::Text).help(
335 &format!("celld dev — run an application with persistent local storage\n\n\
336USAGE:\n celld dev [PROJECT] [--host IP] [--port PORT] [--logs] [--no-watch] [--clean]\n\n\
337PROJECT is a directory or a Wrangler config. It defaults to the current\n\
338directory. celld stores all local state in PROJECT/.celld/dev, and it keeps\n\
339that state across a restart. A configuration change does not migrate the\n\
340state, so a cell can keep a value that the new configuration rejects. Use\n\
341--clean to start from an empty local state.\n\n\
342A .dev.vars file beside the config supplies Worker variables in dotenv form,\n\
343as for wrangler dev. Without one, .env and then .env.local supply them, and\n\
344an entry of these files that cannot be a binding is skipped with a warning.\n\
345The entries override the vars of the config.\n\n\
346OPTIONS:\n --host IP Worker listener host (default: 127.0.0.1)\n --port PORT Worker listener port (default: {DEFAULT_PORT})\n --clean Delete PROJECT/.celld/dev before the server starts\n --logs Show the node warning and information logs\n --no-watch Do not rebuild when a project file changes\n --watch-ignore PATTERN Ignore a project-relative glob; repeat as needed\n -h, --help Show this help"
347 ),
348 )
349}
350
351fn options_from_arguments(arguments: Vec<String>) -> anyhow::Result<Option<Options>> {
352 let mut project = None;
353 let mut host = IpAddr::V4(Ipv4Addr::LOCALHOST);
354 let mut port = DEFAULT_PORT;
355 let mut clean = false;
356 let mut logs = false;
357 let mut watch = true;
358 let mut watch_ignores = Vec::new();
359 let mut arguments = arguments.into_iter();
360 while let Some(argument) = arguments.next() {
361 match argument.as_str() {
362 "--help" | "-h" => return Ok(None),
363 "--clean" => clean = true,
364 "--logs" => logs = true,
365 "--no-watch" => watch = false,
366 "--watch-ignore" => {
367 let value = arguments
368 .next()
369 .context("--watch-ignore requires a value")?;
370 watch_ignores.push(
371 Pattern::new(&value)
372 .with_context(|| format!("invalid --watch-ignore pattern {value:?}"))?,
373 );
374 }
375 "--host" => {
376 let value = arguments.next().context("--host requires a value")?;
377 host = value
378 .parse::<IpAddr>()
379 .with_context(|| format!("invalid --host value {value:?}"))?;
380 }
381 "--port" => {
382 let value = arguments.next().context("--port requires a value")?;
383 port = value
384 .parse::<u16>()
385 .with_context(|| format!("invalid --port value {value:?}"))?;
386 if port == 0 {
387 bail!("--port must be between 1 and 65535");
388 }
389 }
390 other if other.starts_with('-') => bail!("unknown argument for `celld dev`: {other}"),
391 value if project.is_none() => project = Some(PathBuf::from(value)),
392 value => bail!("celld dev accepts one PROJECT, but also received {value:?}"),
393 }
394 }
395 if !watch && !watch_ignores.is_empty() {
396 bail!("--watch-ignore cannot be used with --no-watch");
397 }
398 Ok(Some(Options {
399 project,
400 clean,
401 stack: StackOptions {
402 listener: SocketAddr::new(host, port),
403 logs,
404 watch,
405 watch_ignores,
406 },
407 }))
408}
409
410#[allow(clippy::disallowed_methods)] // Project resolution uses the operator's host filesystem.
411pub async fn run(arguments: Vec<String>) -> anyhow::Result<()> {
412 let Some(options) = options_from_arguments(arguments)? else {
413 print_help()?;
414 return Ok(());
415 };
416 let config = deploy::resolve_config(options.project)?;
417 let config = std::fs::canonicalize(&config)
418 .with_context(|| format!("resolve Wrangler config {}", config.display()))?;
419 let project = config
420 .parent()
421 .context("the Wrangler config has no project directory")?;
422 let state = DevState::for_project(project);
423 let console = Console::new();
424 console.header();
425 console.detail("Project", &config.display().to_string());
426 console.detail("State", &state.path().display().to_string());
427 // The delete runs before the directory is recreated, and the console names
428 // the outcome. A developer who reaches for this flag is already unsure
429 // which state the run uses, so a silent delete would answer nothing.
430 if options.clean {
431 let discarded = state.discard()?;
432 console.detail(
433 "Clean",
434 if discarded {
435 "discarded the existing local state"
436 } else {
437 "no local state to discard"
438 },
439 );
440 }
441 prepare_state(state.path())?;
442 if !options.stack.logs {
443 console.detail("Logs", "hidden (use --logs)");
444 }
445 if !options.stack.watch {
446 console.detail("Watch", "disabled");
447 }
448
449 let project_hash = format!(
450 "{:x}",
451 Sha256::digest(project.as_os_str().as_encoded_bytes())
452 );
453 let store = open_store(state.path(), &console).await?;
454 run_stack(
455 &config,
456 state.path(),
457 options.stack,
458 &project_hash,
459 &store,
460 &console,
461 )
462 .await
463}
464
465#[allow(clippy::disallowed_methods)] // Local development state is an operator-owned host path.
466fn prepare_state(state: &Path) -> anyhow::Result<()> {
467 for directory in [state.to_path_buf(), state.join("runtime")] {
468 std::fs::create_dir_all(&directory)
469 .with_context(|| format!("create local state directory {}", directory.display()))?;
470 }
471 Ok(())
472}
473
474#[allow(clippy::disallowed_methods)] // Local development state is an operator-owned host path.
475async fn open_store(state: &Path, console: &Console) -> anyhow::Result<Store> {
476 console.progress("opening the local storage");
477 let database = std::fs::canonicalize(state)
478 .context("resolve the local state directory")?
479 .join("objects.sqlite3");
480 let bucket = open_local_bucket(&database)?;
481 fleet::validate_bucket(&bucket).await?;
482 bucket.probe_cas().await?;
483 Ok(Store { database })
484}
485
486/// The Worker variables for `celld dev`, from the files that `wrangler dev`
487/// reads beside the config (Wrangler getVarsForDev()). A `.dev.vars` file
488/// wins outright. Without one, `.env` and then `.env.local` apply, and a later
489/// file overrides an earlier one. Each entry overrides the `vars` of the
490/// config. Only `celld dev` reads the files, so a local credential cannot
491/// reach a fleet.
492fn read_dev_vars(config: &Path) -> anyhow::Result<deploy::VarOverrides> {
493 // A present `.dev.vars` replaces the dotenv files even when it is empty,
494 // as in Wrangler, so an entry that the project keeps in `.env` for
495 // another tool does not reach the Worker beside it.
496 if let Some(contents) = read_optional(&config.with_file_name(".dev.vars"))? {
497 return Ok(deploy::VarOverrides::DevVars(parse_dotenv(&contents)));
498 }
499 let mut vars = BTreeMap::new();
500 for name in [".env", ".env.local"] {
501 if let Some(contents) = read_optional(&config.with_file_name(name))? {
502 vars.extend(parse_dotenv(&contents));
503 }
504 }
505 Ok(deploy::VarOverrides::DotEnv(vars))
506}
507
508/// The contents of `path`, or `None` when it does not exist. One read, not an
509/// existence probe and then a read, so a file that vanishes between the two
510/// cannot fail the build.
511#[allow(clippy::disallowed_methods)] // The project is on the operator's host filesystem.
512fn read_optional(path: &Path) -> anyhow::Result<Option<String>> {
513 match std::fs::read_to_string(path) {
514 Ok(contents) => Ok(Some(contents)),
515 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
516 Err(error) => Err(error).with_context(|| format!("read {}", path.display())),
517 }
518}
519
520fn parse_dotenv(contents: &str) -> BTreeMap<String, String> {
521 let mut vars = BTreeMap::new();
522 let mut lines = contents.lines();
523 while let Some(line) = lines.next() {
524 let line = line.trim();
525 if line.is_empty() || line.starts_with('#') {
526 continue;
527 }
528 // dotenv accepts the `export NAME=value` form of a shell-sourced
529 // file. Without the strip, the name `export NAME` fails binding
530 // validation, and a `.env` that loaded before stops the build.
531 let line = line.strip_prefix("export ").map_or(line, str::trim_start);
532 let Some((name, value)) = line.split_once('=') else {
533 continue;
534 };
535 let (name, value) = (name.trim(), value.trim());
536 if name.is_empty() {
537 continue;
538 }
539 let value = match quoted_lines(value, &mut lines) {
540 Some(value) => value,
541 // One matched pair of quotes comes off; a lone quote is part of
542 // the value, as in dotenv, so a secret that ends in one survives.
543 None => ['"', '\'']
544 .into_iter()
545 .find_map(|quote| value.strip_prefix(quote)?.strip_suffix(quote))
546 .unwrap_or(value)
547 .to_string(),
548 };
549 vars.insert(name.to_string(), value);
550 }
551 vars
552}
553
554/// A quoted value that continues on the following lines, as dotenv reads a
555/// PEM key, joined by newlines without its quotes. Line by line, each base64
556/// line of the key became a variable of its own or a name that fails binding
557/// validation. `None` leaves `lines` untouched: the value ends on its own
558/// line, or no later line closes the quote, so the opening quote is a lone
559/// character of a one-line value.
560fn quoted_lines(value: &str, lines: &mut std::str::Lines<'_>) -> Option<String> {
561 let quote = value
562 .chars()
563 .next()
564 .filter(|quote| matches!(quote, '"' | '\''))?;
565 let first = &value[1..];
566 if first.ends_with(quote) {
567 return None;
568 }
569 let mut rest = lines.clone();
570 let mut joined = first.to_string();
571 while let Some(line) = rest.next() {
572 joined.push('\n');
573 match line.trim_end().strip_suffix(quote) {
574 Some(last) => {
575 joined.push_str(last);
576 *lines = rest;
577 return Some(joined);
578 }
579 None => joined.push_str(line),
580 }
581 }
582 None
583}
584
585async fn deploy_project(config: &Path, store: &Store, logs: bool) -> anyhow::Result<()> {
586 let bucket = open_local_bucket(&store.database)?;
587 let built = deploy::build(&deploy::Options {
588 config: Some(config.to_path_buf()),
589 bucket: None,
590 endpoint: None,
591 region: None,
592 dry_run: false,
593 json: false,
594 vars: read_dev_vars(config)?,
595 local_images: true,
596 })?;
597 if logs {
598 built.report();
599 }
600 crate::wake_format::ensure_ready(&bucket).await?;
601 deploy::write(&bucket, &built).await
602}
603
604async fn run_stack(
605 config: &Path,
606 state: &Path,
607 options: StackOptions,
608 project_hash: &str,
609 store: &Store,
610 console: &Console,
611) -> anyhow::Result<()> {
612 // Install both handlers before the child can become ready. A caller can
613 // send SIGTERM as soon as the readiness request answers, and installing a
614 // handler afterwards leaves the new node orphaned under the default Unix
615 // signal action.
616 let mut signals = ShutdownSignals::install()?;
617 let project = config
618 .parent()
619 .context("the Wrangler config has no project directory")?;
620 let mut watcher = options
621 .watch
622 .then(|| ProjectWatcher::new(project, options.watch_ignores))
623 .transpose()?;
624
625 console.progress("building the application");
626 deploy_project(config, store, options.logs).await?;
627 let mut running = start_node(
628 state,
629 options.listener,
630 options.logs,
631 project_hash,
632 store,
633 console,
634 )
635 .await?;
636
637 loop {
638 match wait_for_node_event(&mut running.child, &mut signals, watcher.as_mut()).await? {
639 NodeEvent::Exited(status) => {
640 let _ = running.output.await;
641 if status.success() {
642 return Ok(());
643 }
644 bail!("the local celld node exited with {status}");
645 }
646 NodeEvent::Shutdown => {
647 stop_running_node(running).await;
648 return Ok(());
649 }
650 NodeEvent::Reload => {
651 console.progress("change detected; rebuilding the application");
652 if let Err(error) = deploy_project(config, store, options.logs).await {
653 console.failure(&format!("reload failed: {error:#}"));
654 continue;
655 }
656 console.progress("restarting the application");
657 stop_running_node(running).await;
658 running = start_node(
659 state,
660 options.listener,
661 options.logs,
662 project_hash,
663 store,
664 console,
665 )
666 .await?;
667 }
668 }
669 }
670}
671
672struct RunningNode {
673 child: Child,
674 internal: String,
675 output: tokio::task::JoinHandle<()>,
676}
677
678enum NodeEvent {
679 Exited(std::process::ExitStatus),
680 Reload,
681 Shutdown,
682}
683
684#[allow(clippy::disallowed_methods)] // Child supervision uses real host process and time APIs.
685async fn start_node(
686 state: &Path,
687 listener: SocketAddr,
688 logs: bool,
689 project_hash: &str,
690 store: &Store,
691 console: &Console,
692) -> anyhow::Result<RunningNode> {
693 let executable = std::env::current_exe().context("locate the celld executable")?;
694 let listen = listener.to_string();
695 let mut command = Command::new(executable);
696 // The supervisor owns the child's complete storage and listener topology.
697 // Inherited fleet settings can otherwise override that private topology or
698 // make its guard reject a valid `celld dev` invocation.
699 for variable in [
700 "AWS_DEFAULT_REGION",
701 "AWS_REGION",
702 "CELLD_ADDR",
703 "CELLD_ADVERTISE",
704 "CELLD_BUCKET",
705 "CELLD_CLOUD",
706 "CELLD_INTERNAL_ADDR",
707 "CELLD_TEST_BUCKET",
708 "CELLD_TRUST_FORWARDED_HEADERS",
709 "CELLD_UNSAFE_PUBLIC_ADVERTISE",
710 "S3_ENDPOINT",
711 ] {
712 command.env_remove(variable);
713 }
714 command
715 .args([
716 "--no-control-plane",
717 "--bucket",
718 BUCKET,
719 "--listen",
720 &listen,
721 "--internal-listen",
722 "127.0.0.1:0",
723 ])
724 .env("CELLD_INTERNAL_DEV_STORE", &store.database)
725 .env("CELLD_WATCH", state.join("runtime"))
726 .env("CELLD_NODE", format!("dev-{}", &project_hash[..12]))
727 .stdin(Stdio::null())
728 .stdout(Stdio::piped())
729 .stderr(Stdio::inherit());
730 // `run_stack` normally consumes `RunningNode` through the graceful stop
731 // path. An error or cancellation can instead drop it, so the child must
732 // not outlive the value that proves the supervisor still owns it.
733 command.kill_on_drop(true);
734 if !logs {
735 // The supervisor still forwards ERROR records and the child's stderr.
736 // INFO and WARN records stay hidden until the operator asks for them.
737 command.env("RUST_LOG", "error");
738 }
739 #[cfg(unix)]
740 {
741 use std::os::unix::process::CommandExt as _;
742 // A terminal sends Ctrl-C to its foreground process group. Keep the
743 // node in a child group so only this supervisor selects the shutdown
744 // mode; otherwise the node can begin a slow fleet handoff before the
745 // supervisor asks for the fast same-node preserve path.
746 command.as_std_mut().process_group(0);
747 }
748 #[cfg(target_os = "linux")]
749 {
750 use std::os::unix::process::CommandExt as _;
751
752 let supervisor = unsafe { libc::getpid() };
753 // Drop cannot run after SIGKILL or a supervisor crash. Ask the kernel
754 // to kill the node in that case. The parent check closes the race in
755 // which the supervisor exits between `fork` and `prctl`.
756 unsafe {
757 command.as_std_mut().pre_exec(move || {
758 if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL) == -1 {
759 return Err(std::io::Error::last_os_error());
760 }
761 if libc::getppid() != supervisor {
762 return Err(std::io::Error::from_raw_os_error(libc::ESRCH));
763 }
764 Ok(())
765 });
766 }
767 }
768 let mut child = command.spawn().context("start the local celld node")?;
769
770 let stdout = child
771 .stdout
772 .take()
773 .expect("the local node was configured with piped output");
774 let (internal_tx, internal_rx) = oneshot::channel();
775 let output_console = *console;
776 let output = tokio::spawn(async move {
777 let mut lines = BufReader::new(stdout).lines();
778 let mut internal_tx = Some(internal_tx);
779 while let Ok(Some(line)) = lines.next_line().await {
780 if let Some(origin) = internal_origin(&line) {
781 if let Some(sender) = internal_tx.take() {
782 let _ = sender.send(origin);
783 }
784 }
785 if logs || line.contains(" ERROR ") {
786 output_console.log(&line);
787 }
788 }
789 });
790 let internal = match tokio::time::timeout(Duration::from_secs(30), internal_rx).await {
791 Ok(Ok(internal)) => internal,
792 result => {
793 stop_child(&mut child, None).await;
794 let _ = output.await;
795 match result {
796 Err(_) => bail!("the local node did not announce its operator listener"),
797 Ok(Err(_)) => {
798 bail!("the local node exited before it announced its operator listener")
799 }
800 Ok(Ok(_)) => unreachable!(),
801 }
802 }
803 };
804
805 if let Err(error) = wait_for_node(&mut child, listener).await {
806 stop_child(&mut child, Some(&internal)).await;
807 let _ = output.await;
808 return Err(error);
809 }
810 console.ready(&format!("http://{listener}"));
811 Ok(RunningNode {
812 child,
813 internal,
814 output,
815 })
816}
817
818fn internal_origin(line: &str) -> Option<String> {
819 let address = line
820 .strip_prefix("celld internal listening on ")?
821 .split_once(' ')?
822 .0;
823 Some(format!("http://{address}"))
824}
825
826#[allow(clippy::disallowed_methods)] // Readiness waits on a real child and wall-clock deadline.
827async fn wait_for_node(child: &mut Child, listener: SocketAddr) -> anyhow::Result<()> {
828 let client = reqwest::Client::builder()
829 .connect_timeout(Duration::from_millis(200))
830 .timeout(Duration::from_secs(1))
831 .build()?;
832 let readiness_host = match listener.ip() {
833 IpAddr::V4(address) if address.is_unspecified() => IpAddr::V4(Ipv4Addr::LOCALHOST),
834 IpAddr::V6(address) if address.is_unspecified() => IpAddr::V6(Ipv6Addr::LOCALHOST),
835 address => address,
836 };
837 let url = format!(
838 "http://{}/.well-known/celld/health",
839 SocketAddr::new(readiness_host, listener.port())
840 );
841 let mut last = "the node did not answer".to_string();
842 for _ in 0..300 {
843 if let Some(status) = child.try_wait().context("read the local node status")? {
844 bail!("the local celld node exited during startup with {status}");
845 }
846 match client.get(&url).send().await {
847 Ok(response) if response.status().is_success() => return Ok(()),
848 Ok(response) => last = format!("the readiness endpoint returned {}", response.status()),
849 Err(error) => last = error.to_string(),
850 }
851 tokio::time::sleep(Duration::from_millis(100)).await;
852 }
853 bail!("the local celld node did not become ready: {last}")
854}
855
856async fn wait_for_node_event(
857 child: &mut Child,
858 signals: &mut ShutdownSignals,
859 watcher: Option<&mut ProjectWatcher>,
860) -> anyhow::Result<NodeEvent> {
861 crate::asyncrt::select! {
862 status = child.wait() => {
863 let status = status.context("wait for the local celld node")?;
864 Ok(NodeEvent::Exited(status))
865 }
866 _ = signals.received() => Ok(NodeEvent::Shutdown),
867 changed = wait_for_project_change(watcher) => {
868 changed?;
869 Ok(NodeEvent::Reload)
870 }
871 }
872}
873
874async fn wait_for_project_change(watcher: Option<&mut ProjectWatcher>) -> anyhow::Result<()> {
875 match watcher {
876 Some(watcher) => watcher.changed().await,
877 None => std::future::pending().await,
878 }
879}
880
881async fn stop_running_node(mut running: RunningNode) {
882 stop_child(&mut running.child, Some(&running.internal)).await;
883 let _ = running.output.await;
884}
885
886#[allow(clippy::disallowed_methods)] // Shutdown deadlines govern a real child process.
887async fn stop_child(child: &mut Child, internal: Option<&str>) {
888 let requested = if let Some(internal) = internal {
889 match reqwest::Client::builder()
890 .timeout(Duration::from_secs(2))
891 .build()
892 {
893 Ok(client) => client
894 .post(format!("{internal}/shutdown?handoff=preserve"))
895 .send()
896 .await
897 .is_ok_and(|response| response.status().is_success()),
898 Err(_) => false,
899 }
900 } else {
901 false
902 };
903 #[cfg(unix)]
904 if !requested {
905 if let Some(id) = child.id() {
906 // The child installs SIGTERM as its graceful durability handoff. The
907 // supervisor sends that signal instead of Child::kill, which is a
908 // SIGKILL on Unix and can leave the last local transaction unflushed.
909 unsafe {
910 libc::kill(id as libc::pid_t, libc::SIGTERM);
911 }
912 }
913 }
914 let waited = tokio::time::timeout(Duration::from_secs(35), child.wait()).await;
915 if waited.is_err() {
916 let _ = child.kill().await;
917 }
918}