1use std::collections::BTreeMap;
38use std::io::Write;
39use std::net::{IpAddr, Ipv4Addr, SocketAddr};
40use std::path::{Path, PathBuf};
41
42use astrs_coordinator::{Coordinator, CoordinatorConfig, CoordinatorServer};
43use astrs_daemon::config::{ListenConfig, RuntimePaths};
44use astrs_daemon::{Daemon, DaemonConfig};
45use astrs_manifest::OperatorConfig;
46use astrs_node_api::Node;
47use astrs_operator_api::OperatorRegistry;
48use astrs_runtime::{RuntimeConfig, RuntimeHost};
49use astrs_store::{AsyncStore, CoordinatorStore};
50use astrs_wire::{AuthToken, MachineName, NodeSource};
51
52use crate::command::client::resolve_text;
53use crate::command::signals::Signals;
54use crate::error::CliError;
55use crate::runtime_dir::{PidFile, remove_pidfile, write_pidfile};
56
57pub const STORE_FILE: &str = "coordinator.redb";
60
61#[derive(Debug, Clone)]
63pub struct ServeReport {
64 pub role: &'static str,
66 pub pid: u32,
68 pub address: String,
70 pub detail: String,
73 pub healthy: bool,
77}
78
79impl ServeReport {
80 #[must_use]
83 pub const fn exit_code(&self) -> i32 {
84 if self.healthy { 0 } else { 1 }
85 }
86
87 #[must_use]
89 pub fn to_json(&self) -> serde_json::Value {
90 serde_json::json!({
91 "role": self.role,
92 "pid": self.pid,
93 "address": self.address,
94 "detail": self.detail,
95 "healthy": self.healthy,
96 })
97 }
98}
99
100#[derive(Debug, Clone, Default)]
102pub struct CoordinatorServeArgs {
103 pub port: u16,
105 pub bind: Option<String>,
107 pub token: Option<String>,
109 pub token_file: Option<PathBuf>,
111 pub working_dir: Option<PathBuf>,
113 pub store: Option<PathBuf>,
115 pub recreate_store: bool,
117 pub pidfile: Option<PathBuf>,
119 pub announce: bool,
121 pub ha_node_id: Option<u64>,
123 pub ha_peers: Vec<String>,
125}
126
127pub fn coordinator(
139 out: &mut dyn Write,
140 args: &CoordinatorServeArgs,
141) -> Result<ServeReport, CliError> {
142 let addr = bind_addr(args.bind.as_deref(), args.port)?;
143 let working = crate::runtime_dir::working_dir(args.working_dir.as_deref());
144 let (token, token_note) =
145 resolve_token(args.token.as_deref(), args.token_file.as_deref(), &working)?;
146 let store = open_store(args.store.as_deref(), args.recreate_store)?;
147
148 let config = CoordinatorConfig::new(token).with_bind_addr(addr);
149 let hub = Coordinator::new(config, store);
150 install_trace_sink(&hub);
151
152 let runtime = tokio::runtime::Builder::new_multi_thread()
153 .enable_all()
154 .build()
155 .map_err(|source| CliError::io("tokio runtime", source))?;
156
157 runtime.block_on(async move {
158 let mut signals = Signals::install();
163 let hub = start_high_availability(hub, args).await?;
167 let server = CoordinatorServer::bind(hub).await?;
168 let bound = server.local_addr()?;
169 let handle = server.handle();
170
171 let report = ServeReport {
172 role: "coordinator",
173 pid: std::process::id(),
174 address: bound.to_string(),
175 detail: token_note,
176 healthy: true,
177 };
178 if let Some(path) = &args.pidfile {
179 write_pidfile(path, &PidFile::listening(report.pid, bound.to_string()))?;
180 }
181 announce(out, args.announce, &report);
182
183 let mut serving = tokio::spawn(server.serve());
184 tokio::select! {
185 joined = &mut serving => finish_join(joined)?,
186 () = signals.next() => {
187 let _ = writeln!(out, "astrs coordinator: stopping on a signal");
188 let _ = out.flush();
189 handle.shutdown();
190 finish_join(serving.await)?;
191 }
192 }
193 if let Some(path) = &args.pidfile {
194 remove_pidfile(path)?;
195 }
196 Ok::<ServeReport, CliError>(report)
197 })
198}
199
200#[cfg(feature = "ha")]
206async fn start_high_availability(
207 hub: Coordinator,
208 args: &CoordinatorServeArgs,
209) -> Result<Coordinator, CliError> {
210 let Some(node_id) = args.ha_node_id else {
211 if !args.ha_peers.is_empty() {
212 return Err(CliError::BadArgument {
213 flag: "ha-peer",
214 value: args.ha_peers.join(", "),
215 reason: "--ha-peer needs --ha-node-id to say which of those peers this \
216 coordinator is"
217 .to_owned(),
218 });
219 }
220 return Ok(hub);
221 };
222 let mut config = astrs_coordinator::ha::HaConfig::parse(node_id, &args.ha_peers)?;
223 if let Some(store) = &args.store
226 && let Some(directory) = store.parent()
227 && !directory.as_os_str().is_empty()
228 {
229 config = config.with_log_dir(directory);
230 }
231 let handle = std::sync::Arc::new(astrs_coordinator::ha::HaHandle::start(&hub, config).await?);
232 Ok(hub.with_ha(handle))
233}
234
235#[cfg(not(feature = "ha"))]
241async fn start_high_availability(
242 hub: Coordinator,
243 args: &CoordinatorServeArgs,
244) -> Result<Coordinator, CliError> {
245 if args.ha_node_id.is_some() || !args.ha_peers.is_empty() {
246 return Err(CliError::BadArgument {
247 flag: "ha-node-id",
248 value: args
249 .ha_node_id
250 .map_or_else(|| args.ha_peers.join(", "), |id| id.to_string()),
251 reason: "this build has no coordinator high availability; rebuild the CLI with the \
252 `ha` feature"
253 .to_owned(),
254 });
255 }
256 Ok(hub)
257}
258
259fn finish_join(
264 joined: Result<astrs_coordinator::Result<()>, tokio::task::JoinError>,
265) -> Result<(), CliError> {
266 match joined {
267 Ok(result) => Ok(result?),
268 Err(error) => Err(CliError::Cluster {
269 action: "run",
270 process: "coordinator",
271 reason: format!("the accept loop ended abnormally: {error}"),
272 }),
273 }
274}
275
276#[derive(Debug, Clone, Default)]
278pub struct DaemonServeArgs {
279 pub coordinator: Option<String>,
282 pub machine: Option<String>,
284 pub port: Option<u16>,
287 pub peer_port: u16,
289 pub peer_bind: Option<String>,
291 pub labels: Vec<String>,
293 pub runtime_dir: Option<PathBuf>,
295 pub working_dir: Option<PathBuf>,
297 pub token: Option<String>,
299 pub token_file: Option<PathBuf>,
301 pub pidfile: Option<PathBuf>,
303 pub announce: bool,
305}
306
307pub fn daemon(out: &mut dyn Write, args: &DaemonServeArgs) -> Result<ServeReport, CliError> {
318 let runtime_dir = crate::runtime_dir::runtime_dir(args.runtime_dir.as_deref());
319 let working = crate::runtime_dir::working_dir(args.working_dir.as_deref());
320 let (token, token_note) =
321 resolve_token(args.token.as_deref(), args.token_file.as_deref(), &working)?;
322
323 let paths = RuntimePaths::under(&runtime_dir);
324 let mut listen = ListenConfig::uds(paths.socket_path());
325 if let Some(port) = args.port {
326 listen = listen.with_tcp_port(port);
327 }
328 let mut config = DaemonConfig::new(paths)
329 .with_listen(listen)
330 .with_auth(token.clone())
331 .with_working_dir(working);
332 let machine = machine_name(args.machine.as_deref())?;
333 if let Some(machine) = machine.clone() {
334 config = config.with_machine(machine);
335 }
336
337 let uplink = match &args.coordinator {
341 Some(address) => {
342 let address = astrs_daemon::coordinator::resolve_coordinator_addr(address)
343 .map_err(CliError::Daemon)?;
344 config = config.with_peer(peer_config(&token, args)?);
345 let mut uplink = astrs_daemon::coordinator::UplinkConfig::new(address, token);
346 if let Some(machine) = machine {
347 uplink = uplink.with_machine(machine);
348 }
349 uplink = uplink.with_labels(parse_labels(&args.labels)?);
350 Some(uplink)
351 }
352 None => None,
353 };
354
355 let runtime = tokio::runtime::Builder::new_multi_thread()
356 .enable_all()
357 .build()
358 .map_err(|source| CliError::io("tokio runtime", source))?;
359
360 runtime.block_on(async move {
361 let mut signals = Signals::install();
365 let mut daemon = Daemon::new(config)?;
366 daemon.bind().await?;
367 let endpoints = daemon.config().listen().endpoints().join(", ");
368
369 let mut detail = token_note;
370 if let Some(uplink) = uplink {
371 let coordinator = uplink.address();
372 daemon.connect_coordinator(uplink).await?;
373 let peer = daemon
374 .peers()
375 .listen_addr()
376 .map_or_else(|| "no peer listener".to_owned(), |addr| addr.to_string());
377 detail.push_str(&format!(
378 "; registering with the coordinator at {coordinator} (peers dial {peer})"
379 ));
380 } else {
381 detail.push_str("; no coordinator — this daemon serves local nodes only");
382 }
383 let report = ServeReport {
384 role: "daemon",
385 pid: std::process::id(),
386 address: endpoints.clone(),
387 detail,
388 healthy: true,
389 };
390 if let Some(path) = &args.pidfile {
391 write_pidfile(path, &PidFile::listening(report.pid, endpoints))?;
392 }
393 announce(out, args.announce, &report);
394
395 let handle = daemon.handle();
396 tokio::spawn(async move {
397 signals.next().await;
398 handle.shutdown();
402 });
403
404 let results = daemon.run().await;
405 if let Some(path) = &args.pidfile {
406 remove_pidfile(path)?;
407 }
408 let finished = results.len();
409 let _ = writeln!(
410 out,
411 "astrs daemon: stopped after {finished} dataflow(s) finished here"
412 );
413 let _ = out.flush();
414 Ok::<ServeReport, CliError>(ServeReport {
415 detail: format!("{} ({finished} dataflow(s) finished)", report.detail),
416 ..report
417 })
418 })
419}
420
421#[derive(Debug, Clone, Default)]
423pub struct RuntimeServeArgs {
424 pub node_id: Option<String>,
427}
428
429pub fn runtime(out: &mut dyn Write, args: &RuntimeServeArgs) -> Result<ServeReport, CliError> {
445 let (node, events) = Node::init_from_env()?;
446 let assigned = node.descriptor().node.as_str().to_owned();
447 if let Some(expected) = &args.node_id
448 && expected != &assigned
449 {
450 return Err(CliError::BadArgument {
451 flag: "node-id",
452 value: expected.clone(),
453 reason: format!("the daemon assigned this process the node `{assigned}`"),
454 });
455 }
456
457 let operators: Vec<OperatorConfig> = match &node.descriptor().source {
462 NodeSource::Runtime { operators } => operators
463 .iter()
464 .map(|spec| OperatorConfig {
465 id: spec.id.as_str().to_owned(),
466 operator: spec.registry_name.clone(),
467 dylib: None,
468 wasm: None,
469 hub: None,
470 inputs: std::collections::BTreeMap::new(),
471 outputs: Vec::new(),
472 config: std::collections::BTreeMap::new(),
473 })
474 .collect(),
475 _ => Vec::new(),
476 };
477 let hosted = operators.len();
478
479 let config = RuntimeConfig::new(operators, OperatorRegistry::new());
484 let host = RuntimeHost::new(node, events, config)?;
485 let report = host.run()?;
486
487 for operator in &report.operators {
488 let _ = writeln!(out, "{}: {:?}", operator.id, operator.outcome);
489 }
490 let _ = out.flush();
491 Ok(ServeReport {
492 role: "runtime",
493 pid: std::process::id(),
494 address: assigned,
495 detail: format!(
496 "{hosted} operator(s) hosted, {}",
497 if report.all_healthy() {
498 "all healthy"
499 } else {
500 "at least one failed"
501 }
502 ),
503 healthy: report.all_healthy(),
504 })
505}
506
507fn bind_addr(bind: Option<&str>, port: u16) -> Result<SocketAddr, CliError> {
517 let Some(text) = bind else {
518 return Ok(SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port));
519 };
520 let trimmed = text.trim();
521 if trimmed.contains(':') {
522 return resolve_text(trimmed);
523 }
524 let mut addr = resolve_text(trimmed)?;
525 addr.set_port(port);
526 Ok(addr)
527}
528
529fn resolve_token(
541 token: Option<&str>,
542 token_file: Option<&Path>,
543 working_dir: &Path,
544) -> Result<(AuthToken, String), CliError> {
545 match crate::runtime_dir::find_token(token, token_file, working_dir)? {
546 Some((token, source)) => Ok((
547 token,
548 format!("authenticating with the token from {source}"),
549 )),
550 None => Ok((
551 AuthToken::ZERO,
552 format!(
553 "no cluster token found (looked for {}, then `{}`): accepting the all-zero token, \
554 so anyone who can reach this listener can drive it",
555 crate::runtime_dir::ENV_TOKEN,
556 crate::runtime_dir::token_path(working_dir).display()
557 ),
558 )),
559 }
560}
561
562fn open_store(path: Option<&Path>, recreate: bool) -> Result<AsyncStore, CliError> {
569 let Some(path) = path else {
570 return Ok(AsyncStore::new(CoordinatorStore::open_in_memory()?));
571 };
572 if recreate {
573 match std::fs::remove_file(path) {
574 Ok(()) => {}
575 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
576 Err(source) => return Err(CliError::io(path, source)),
577 }
578 }
579 if let Some(parent) = path.parent() {
580 crate::runtime_dir::ensure_dir(parent)?;
581 }
582 Ok(AsyncStore::new(CoordinatorStore::open(path)?))
583}
584
585fn install_trace_sink(hub: &Coordinator) {
606 let directives = std::env::var("RUST_LOG").unwrap_or_else(|_| "info".to_owned());
607 let config = astrs_telemetry::subscriber::TelemetryConfig {
608 service_name: "astrs-coordinator".to_owned(),
609 filter_directives: directives,
610 ..astrs_telemetry::subscriber::TelemetryConfig::default()
611 };
612 let _ = astrs_telemetry::subscriber::init_telemetry_with_spans(config, hub.trace_sink());
613}
614
615fn machine_name(machine: Option<&str>) -> Result<Option<MachineName>, CliError> {
621 let Some(text) = machine else {
622 return Ok(None);
623 };
624 MachineName::new(text)
625 .map(Some)
626 .map_err(|error| CliError::BadArgument {
627 flag: "machine",
628 value: text.to_owned(),
629 reason: error.to_string(),
630 })
631}
632
633fn peer_config(
643 token: &AuthToken,
644 args: &DaemonServeArgs,
645) -> Result<astrs_daemon::PeerConfig, CliError> {
646 let config = astrs_daemon::PeerConfig::new(token.clone());
647 let Some(bind) = args.peer_bind.as_deref() else {
648 return Ok(config.with_loopback(args.peer_port));
649 };
650 let addr = resolve_bind(bind, args.peer_port)?;
651 Ok(config.with_listen(addr))
652}
653
654fn resolve_bind(bind: &str, port: u16) -> Result<SocketAddr, CliError> {
660 use std::net::ToSocketAddrs as _;
661
662 let candidate = if bind.contains(':') {
663 bind.to_owned()
664 } else {
665 format!("{bind}:{port}")
666 };
667 candidate
668 .to_socket_addrs()
669 .ok()
670 .and_then(|mut addrs| addrs.next())
671 .ok_or_else(|| CliError::BadAddress {
672 input: bind.to_owned(),
673 reason: "no address resolves for it".to_owned(),
674 })
675}
676
677fn parse_labels(labels: &[String]) -> Result<BTreeMap<String, String>, CliError> {
683 let mut parsed = BTreeMap::new();
684 for label in labels {
685 let Some((key, value)) = label.split_once('=') else {
686 return Err(CliError::BadArgument {
687 flag: "label",
688 value: label.clone(),
689 reason: "a label is written KEY=VALUE".to_owned(),
690 });
691 };
692 if key.is_empty() {
693 return Err(CliError::BadArgument {
694 flag: "label",
695 value: label.clone(),
696 reason: "a label's key may not be empty".to_owned(),
697 });
698 }
699 parsed.insert(key.to_owned(), value.to_owned());
700 }
701 Ok(parsed)
702}
703
704fn announce(out: &mut dyn Write, enabled: bool, report: &ServeReport) {
710 if !enabled {
711 return;
712 }
713 let line = serde_json::to_string(&report.to_json())
714 .unwrap_or_else(|_| format!("{{\"role\":\"{}\"}}", report.role));
715 let _ = writeln!(out, "{line}");
716 let _ = out.flush();
717}
718
719#[cfg(test)]
720mod tests {
721 #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
722
723 use super::*;
724
725 fn scratch(name: &str) -> PathBuf {
726 let dir =
727 std::env::temp_dir().join(format!("astrs-cli-serve-{}-{name}", std::process::id()));
728 let _ = std::fs::remove_dir_all(&dir);
729 std::fs::create_dir_all(&dir).unwrap();
730 dir
731 }
732
733 #[test]
734 fn no_bind_argument_means_loopback_on_the_asked_for_port() {
735 let addr = bind_addr(None, 7407).unwrap();
736 assert_eq!(addr, SocketAddr::from(([127, 0, 0, 1], 7407)));
737 }
738
739 #[test]
740 fn an_interface_keeps_the_port_flag() {
741 let addr = bind_addr(Some("0.0.0.0"), 9000).unwrap();
742 assert_eq!(addr, SocketAddr::from(([0, 0, 0, 0], 9000)));
743 }
744
745 #[test]
746 fn a_full_host_and_port_wins_over_the_port_flag() {
747 let addr = bind_addr(Some("127.0.0.1:9100"), 7407).unwrap();
748 assert_eq!(addr.port(), 9100);
749 }
750
751 #[test]
752 fn an_unresolvable_interface_is_refused() {
753 let error = bind_addr(Some("no-such-host.invalid"), 1).unwrap_err();
754 assert!(matches!(error, CliError::BadAddress { .. }), "{error}");
755 }
756
757 #[test]
758 fn a_missing_token_falls_back_to_zero_and_says_so_loudly() {
759 let dir = scratch("no-token");
760 let (token, note) = resolve_token(None, None, &dir).unwrap();
761 assert!(token.is_zero());
762 assert!(note.contains("all-zero"), "{note}");
763 }
764
765 #[test]
766 fn a_token_file_is_used_and_named_in_the_note() {
767 let dir = scratch("token");
768 let (written, path) = crate::runtime_dir::ensure_token_file(&dir).unwrap();
769 let (token, note) = resolve_token(None, None, &dir).unwrap();
770 assert_eq!(token, written);
771 assert!(note.contains(&path.display().to_string()), "{note}");
772 }
773
774 #[test]
775 fn a_store_path_is_created_and_recreated_on_request() {
776 let dir = scratch("store");
777 let path = dir.join("nested").join(STORE_FILE);
778 let store = open_store(Some(&path), false).unwrap();
779 drop(store);
780 assert!(path.exists(), "the store file must exist after opening it");
781
782 let before = std::fs::metadata(&path).unwrap().len();
783 let store = open_store(Some(&path), true).unwrap();
784 drop(store);
785 assert!(path.exists());
786 let _ = before;
787 }
788
789 #[test]
790 fn no_store_path_means_an_in_memory_store() {
791 let store = open_store(None, false).unwrap();
793 drop(store);
794 }
795
796 #[test]
797 fn a_machine_name_is_validated() {
798 assert!(machine_name(None).unwrap().is_none());
799 assert_eq!(
800 machine_name(Some("robot-1"))
801 .unwrap()
802 .map(|m| m.to_string()),
803 Some("robot-1".to_owned())
804 );
805 let error = machine_name(Some("robot 1")).unwrap_err();
806 match error {
807 CliError::BadArgument { flag, .. } => assert_eq!(flag, "machine"),
808 other => panic!("expected BadArgument, got {other}"),
809 }
810 }
811
812 #[test]
813 fn the_announce_line_is_one_json_object_and_is_skipped_when_off() {
814 let report = ServeReport {
815 role: "coordinator",
816 pid: 42,
817 address: "127.0.0.1:7407".to_owned(),
818 detail: "note".to_owned(),
819 healthy: true,
820 };
821 let mut out = Vec::new();
822 announce(&mut out, false, &report);
823 assert!(out.is_empty());
824
825 announce(&mut out, true, &report);
826 let text = String::from_utf8(out).unwrap();
827 assert_eq!(text.lines().count(), 1, "{text}");
828 let value: serde_json::Value = serde_json::from_str(text.trim_end()).unwrap();
829 assert_eq!(value["role"], "coordinator");
830 assert_eq!(value["address"], "127.0.0.1:7407");
831 assert_eq!(value["pid"], 42);
832 }
833
834 #[test]
835 fn ha_peers_without_a_node_id_are_refused_rather_than_ignored() {
836 let args = CoordinatorServeArgs {
839 ha_peers: vec!["1=127.0.0.1:7601".to_owned()],
840 ..CoordinatorServeArgs::default()
841 };
842 let runtime = tokio::runtime::Builder::new_current_thread()
843 .enable_all()
844 .build()
845 .unwrap();
846 let hub = astrs_coordinator::Coordinator::open_in_memory(
847 astrs_coordinator::CoordinatorConfig::new(astrs_wire::AuthToken::from_bytes([3; 32]))
848 .with_port(0),
849 )
850 .unwrap();
851 let outcome = runtime.block_on(start_high_availability(hub, &args));
852 assert!(
853 outcome.is_err(),
854 "an incomplete HA flag set must be refused"
855 );
856 }
857
858 #[test]
859 fn no_ha_flags_leaves_the_coordinator_exactly_as_it_was() {
860 let args = CoordinatorServeArgs::default();
861 let runtime = tokio::runtime::Builder::new_current_thread()
862 .enable_all()
863 .build()
864 .unwrap();
865 let hub = astrs_coordinator::Coordinator::open_in_memory(
866 astrs_coordinator::CoordinatorConfig::new(astrs_wire::AuthToken::from_bytes([3; 32]))
867 .with_port(0),
868 )
869 .unwrap();
870 assert!(
871 runtime
872 .block_on(start_high_availability(hub, &args))
873 .is_ok()
874 );
875 }
876
877 #[test]
878 fn a_coordinator_binds_announces_and_stops_on_a_signal() {
879 let dir = scratch("coordinator-lifecycle");
880 let pidfile = dir.join(crate::runtime_dir::COORDINATOR_PIDFILE);
881 let args = CoordinatorServeArgs {
882 port: 0,
883 working_dir: Some(dir.clone()),
884 store: Some(dir.join(STORE_FILE)),
885 pidfile: Some(pidfile.clone()),
886 announce: true,
887 ..CoordinatorServeArgs::default()
888 };
889
890 let waiter = std::thread::spawn(move || {
893 let pid =
894 rustix::process::Pid::from_raw(std::process::id().cast_signed()).expect("a pid");
895 for _ in 0..200 {
896 if crate::runtime_dir::read_pidfile(&pidfile)
897 .and_then(|record| record.addr)
898 .is_some()
899 {
900 break;
901 }
902 std::thread::sleep(std::time::Duration::from_millis(25));
903 }
904 let _ = rustix::process::kill_process(pid, rustix::process::Signal::TERM);
905 });
906
907 let mut out = Vec::new();
908 let report = coordinator(&mut out, &args).expect("a coordinator");
909 waiter.join().expect("the signalling thread");
910
911 assert_eq!(report.role, "coordinator");
912 assert!(report.address.starts_with("127.0.0.1:"), "{report:?}");
913 assert_ne!(
914 report.address, "127.0.0.1:0",
915 "an ephemeral port must be reported as the one actually bound"
916 );
917 let text = String::from_utf8(out).unwrap();
918 assert!(text.contains("\"role\":\"coordinator\""), "{text}");
919 assert!(
920 !dir.join(crate::runtime_dir::COORDINATOR_PIDFILE).exists(),
921 "the pidfile must not outlive the process that wrote it"
922 );
923 }
924
925 #[test]
926 fn a_daemon_binds_its_socket_starts_its_uplink_and_stops() {
927 let dir = scratch("daemon-lifecycle");
928 let pidfile = dir.join(crate::runtime_dir::DAEMON_PIDFILE);
929 let args = DaemonServeArgs {
930 coordinator: Some("127.0.0.1:1".to_owned()),
935 peer_port: 0,
936 runtime_dir: Some(dir.clone()),
937 working_dir: Some(dir.clone()),
938 pidfile: Some(pidfile.clone()),
939 announce: true,
940 ..DaemonServeArgs::default()
941 };
942
943 let waiter = std::thread::spawn(move || {
944 let pid =
945 rustix::process::Pid::from_raw(std::process::id().cast_signed()).expect("a pid");
946 for _ in 0..200 {
947 if crate::runtime_dir::read_pidfile(&pidfile).is_some() {
948 break;
949 }
950 std::thread::sleep(std::time::Duration::from_millis(25));
951 }
952 let _ = rustix::process::kill_process(pid, rustix::process::Signal::TERM);
953 });
954
955 let mut out = Vec::new();
956 let report = daemon(&mut out, &args).expect("a daemon");
957 waiter.join().expect("the signalling thread");
958
959 assert_eq!(report.role, "daemon");
960 assert!(report.address.contains("daemon.sock"), "{report:?}");
961 assert!(
962 report
963 .detail
964 .contains("registering with the coordinator at 127.0.0.1:1"),
965 "{report:?}"
966 );
967 assert!(
968 report.detail.contains("peers dial 127.0.0.1:"),
969 "{report:?}"
970 );
971 assert!(!dir.join(crate::runtime_dir::DAEMON_PIDFILE).exists());
972 }
973
974 #[test]
975 fn a_runtime_process_without_a_handshake_blob_reports_a_node_error() {
976 let error = runtime(&mut Vec::new(), &RuntimeServeArgs::default()).unwrap_err();
980 assert!(matches!(error, CliError::Node(_)), "{error}");
981 }
982}