1pub mod cli;
42pub mod command;
43pub mod diagnostic;
44pub mod error;
45pub mod runtime_dir;
46
47use std::io::Write;
48use std::time::Duration;
49
50use clap::CommandFactory;
51
52pub use cli::{Cli, Command};
53pub use error::CliError;
54
55use command::client::{DataflowRef, Endpoint};
56
57#[must_use]
65#[allow(clippy::too_many_lines)]
66pub fn dispatch(
67 cli: Cli,
68 stdout: &mut dyn Write,
69 stderr: &mut dyn Write,
70 stdout_is_terminal: bool,
71) -> i32 {
72 let json = cli.json;
73 let use_color = match cli.color {
74 cli::ColorMode::Always => true,
75 cli::ColorMode::Never => false,
76 cli::ColorMode::Auto => stdout_is_terminal,
77 };
78
79 match cli.command {
80 Command::Validate(args) => {
81 let a = command::validate::ValidateArgs {
82 manifest_path: args.manifest,
83 prove: args.prove,
84 profile: args.profile,
85 json,
86 color: use_color,
87 };
88 finish(stderr, command::validate::run(stdout, &a), |r| {
89 r.exit_code()
90 })
91 }
92 Command::Expand(args) => {
93 let a = command::expand::ExpandArgs {
94 manifest_path: args.manifest,
95 };
96 finish(stderr, command::expand::run(stdout, &a), |_| 0)
97 }
98 Command::Graph(args) => {
99 let a = command::graph::GraphArgs {
100 manifest_path: args.manifest,
101 format: args.format.into(),
102 };
103 finish(stderr, command::graph::run(stdout, &a), |_| 0)
104 }
105 Command::New(new_command) => {
106 let a = new_command.into_new_args(json);
107 finish(stderr, command::new::run(stdout, &a), |_| 0)
108 }
109 Command::Migrate(cli::MigrateCommand::FromDora(args)) => {
110 let a = command::migrate::FromDoraArgs {
111 input: args.input,
112 output: args.output,
113 json,
114 };
115 finish(stderr, command::migrate::run_from_dora(stdout, &a), |r| {
116 r.exit_code()
117 })
118 }
119 Command::Migrate(cli::MigrateCommand::FromRos2(args)) => {
120 let a = command::migrate::FromRos2Args {
121 input: args.input,
122 output: args.output,
123 json,
124 };
125 finish(stderr, command::migrate::run_from_ros2(stdout, &a), |r| {
126 r.exit_code()
127 })
128 }
129 Command::Doctor(args) => {
130 let a = command::doctor::DoctorArgs {
131 json,
132 coordinator_port: args.coordinator_port,
133 daemon_port: args.daemon_port,
134 };
135 finish(stderr, command::doctor::run(stdout, &a), |r| r.exit_code())
136 }
137 Command::Completion(args) => {
138 let a = command::completion::CompletionArgs { shell: args.shell };
139 finish(
140 stderr,
141 command::completion::run(stdout, cli::Cli::command(), &a),
142 |_| 0,
143 )
144 }
145 Command::Schema(args) => {
146 let a = command::schema::SchemaArgs {
147 output: args.output,
148 };
149 finish(stderr, command::schema::run(stdout, &a), |_| 0)
150 }
151 Command::Token(cli::TokenCommand::Mint(args)) => {
152 let a = command::token::MintArgs {
153 scope: args.scope,
154 token: args.token,
155 token_file: args.token_file,
156 working_dir: args.working_dir,
157 out: args.out,
158 json,
159 };
160 finish(stderr, command::token::mint(stdout, &a), |_| 0)
161 }
162 Command::Hub(cli::HubCommand::Update(args)) => {
163 let a = command::hub::UpdateArgs {
164 index: args.index,
165 cache_dir: None,
166 config_path: None,
167 json,
168 };
169 finish(stderr, command::hub::update(stdout, &a), |_| 0)
170 }
171 Command::Hub(cli::HubCommand::Search(args)) => {
172 let a = command::hub::SearchArgs {
173 term: args.term,
174 cache_dir: None,
175 json,
176 };
177 finish(stderr, command::hub::search(stdout, &a), |_| 0)
178 }
179 Command::Hub(cli::HubCommand::Info(args)) => {
180 let a = command::hub::InfoArgs {
181 name: args.name,
182 cache_dir: None,
183 json,
184 };
185 finish(stderr, command::hub::info(stdout, &a), |_| 0)
186 }
187 Command::Hub(cli::HubCommand::Init(args)) => {
188 let a = command::hub::InitArgs {
189 dir: args.dir,
190 force: args.force,
191 json,
192 };
193 finish(stderr, command::hub::init(stdout, &a), |_| 0)
194 }
195
196 Command::Run(args) => {
198 let level = match level_of(args.level.as_deref()) {
199 Ok(level) => level,
200 Err(err) => return report_error(stderr, &err),
201 };
202 let a = command::run::RunArgs {
203 manifest_path: args.manifest,
204 deterministic: args.deterministic,
205 from_recording: args.from_recording,
206 speed: args.speed,
207 exit_when_nodes_finish: args.exit_when_nodes_finish,
208 skip_build: args.skip_build,
209 level,
210 working_dir: args.working_dir,
211 runtime_dir: args.runtime_dir,
212 timeout: args.timeout.map(Duration::from_secs_f64),
213 grace: args.grace.map(Duration::from_secs_f64),
214 json,
215 color: use_color,
216 };
217 finish(stderr, command::run::run(stdout, &a), |r| r.exit_code())
221 }
222 Command::Build(args) => {
223 let a = command::build::BuildArgs {
224 manifest_path: args.manifest,
225 release: args.release,
226 node: args.node,
227 working_dir: args.working_dir,
228 runtime_dir: args.runtime_dir,
229 json,
230 };
231 finish(stderr, command::build::run(stdout, &a), |r| r.exit_code())
232 }
233
234 Command::Up(args) => {
236 let a = command::cluster::UpArgs {
237 port: args.port,
238 runtime_dir: args.runtime_dir,
239 working_dir: args.connect.working_dir,
240 token: args.connect.token,
241 token_file: args.connect.token_file,
242 recreate_store: args.recreate_store,
243 no_daemon: args.no_daemon,
244 json,
245 };
246 finish(stderr, command::cluster::up(stdout, &a), |_| 0)
247 }
248 Command::Down(args) => {
249 let a = command::cluster::DownArgs {
250 runtime_dir: args.runtime_dir,
251 working_dir: args.connect.working_dir,
252 coordinator: args.connect.coordinator,
253 token: args.connect.token,
254 token_file: args.connect.token_file,
255 force: args.force,
256 json,
257 };
258 finish(stderr, command::cluster::down(stdout, &a), |_| 0)
259 }
260 Command::Status(args) => match args.dataflow {
261 Some(reference) => {
264 let a = command::monitor::DataflowStatusArgs {
265 dataflow: Some(DataflowRef::parse(&reference)),
266 json,
267 };
268 with_endpoint(stdout, stderr, &args.connect, false, |out, endpoint| {
269 command::monitor::dataflow_status(out, endpoint, &a)
270 .map(|report| report.exit_code())
271 })
272 }
273 None => {
274 let a = command::cluster::StatusArgs {
275 runtime_dir: args.runtime_dir,
276 working_dir: args.connect.working_dir,
277 coordinator: args.connect.coordinator,
278 token: args.connect.token,
279 token_file: args.connect.token_file,
280 json,
281 };
282 finish(stderr, command::cluster::status(stdout, &a), |r| {
283 r.exit_code()
284 })
285 }
286 },
287
288 Command::Start(args) => {
290 let level = match level_of(args.level.as_deref()) {
291 Ok(level) => level,
292 Err(err) => return report_error(stderr, &err),
293 };
294 let a = command::lifecycle::StartArgs {
295 manifest_path: args.manifest,
296 name: args.name,
297 machines: args.machines,
298 attach: args.attach,
299 level,
300 json,
301 color: use_color,
302 };
303 with_endpoint(stdout, stderr, &args.connect, true, |out, endpoint| {
304 command::lifecycle::start(out, endpoint, &a).map(|report| report.exit_code())
305 })
306 }
307 Command::Stop(args) => {
308 let a = command::lifecycle::StopArgs {
309 dataflow: DataflowRef::parse(&args.dataflow),
310 grace: args.grace.map(Duration::from_secs_f64),
311 json,
312 };
313 with_endpoint(stdout, stderr, &args.connect, true, |out, endpoint| {
314 command::lifecycle::stop(out, endpoint, &a).map(|()| 0)
315 })
316 }
317 Command::Restart(args) => {
318 let a = command::lifecycle::RestartArgs {
319 dataflow: DataflowRef::parse(&args.dataflow),
320 rebuild: args.rebuild,
321 json,
322 };
323 with_endpoint(stdout, stderr, &args.connect, true, |out, endpoint| {
324 command::lifecycle::restart(out, endpoint, &a).map(|()| 0)
325 })
326 }
327 Command::Destroy(args) => {
328 let a = command::lifecycle::DestroyArgs {
329 dataflow: args.dataflow.as_deref().map(DataflowRef::parse),
330 force: args.force,
331 json,
332 };
333 with_endpoint(stdout, stderr, &args.connect, true, |out, endpoint| {
334 command::lifecycle::destroy(out, endpoint, &a).map(|()| 0)
335 })
336 }
337 Command::Clean(args) => {
338 let a = command::lifecycle::CleanArgs {
339 dataflow: args.dataflow.as_deref().map(DataflowRef::parse),
340 artifacts: args.artifacts,
341 logs: args.logs,
342 json,
343 };
344 with_endpoint(stdout, stderr, &args.connect, true, |out, endpoint| {
345 command::lifecycle::clean(out, endpoint, &a).map(|()| 0)
346 })
347 }
348
349 Command::List(args) => {
351 let a = command::monitor::ListArgs {
352 all: args.all,
353 json,
354 };
355 with_endpoint(stdout, stderr, &args.connect, false, |out, endpoint| {
356 command::monitor::list(out, endpoint, &a).map(|_| 0)
357 })
358 }
359 Command::Logs(args) => {
360 let level = match level_of(args.level.as_deref()) {
361 Ok(level) => level,
362 Err(err) => return report_error(stderr, &err),
363 };
364 let a = command::monitor::LogsArgs {
365 dataflow: args.dataflow.as_deref().map(DataflowRef::parse),
366 node: args.node,
367 level,
368 limit: args.limit,
369 follow: args.follow,
370 json,
371 color: use_color,
372 };
373 with_endpoint(stdout, stderr, &args.connect, false, |out, endpoint| {
374 command::monitor::logs(out, endpoint, &a).map(|_| 0)
375 })
376 }
377
378 Command::Param(cli::ParamCommand::Get(args)) => {
380 let scope = command::param::ScopeArgs {
381 dataflow: args.dataflow,
382 node: args.node,
383 json,
384 };
385 let inherited = !args.exact;
386 if args.watch {
387 with_endpoint(stdout, stderr, &args.connect, false, |out, endpoint| {
388 command::param::watch(out, endpoint, &scope, &args.key, inherited, args.count)
389 .map(|_| 0)
390 })
391 } else {
392 with_endpoint(stdout, stderr, &args.connect, false, |out, endpoint| {
393 command::param::get(out, endpoint, &scope, &args.key, inherited)
394 .map(|value| i32::from(value.is_none()))
397 })
398 }
399 }
400 Command::Param(cli::ParamCommand::Set(args)) => {
401 let scope = command::param::ScopeArgs {
402 dataflow: args.dataflow,
403 node: args.node,
404 json,
405 };
406 with_endpoint(stdout, stderr, &args.connect, true, |out, endpoint| {
407 command::param::set(
408 out,
409 endpoint,
410 &scope,
411 &args.key,
412 &args.value,
413 args.create_only,
414 )
415 .map(|_| 0)
416 })
417 }
418 Command::Param(cli::ParamCommand::List(args)) => {
419 let scope = command::param::ScopeArgs {
420 dataflow: args.dataflow,
421 node: args.node,
422 json,
423 };
424 with_endpoint(stdout, stderr, &args.connect, false, |out, endpoint| {
425 command::param::list(
426 out,
427 endpoint,
428 &scope,
429 args.prefix.as_deref(),
430 args.inherited,
431 )
432 .map(|_| 0)
433 })
434 }
435 Command::Param(cli::ParamCommand::Delete(args)) => {
436 let scope = command::param::ScopeArgs {
437 dataflow: args.dataflow,
438 node: args.node,
439 json,
440 };
441 with_endpoint(stdout, stderr, &args.connect, true, |out, endpoint| {
442 command::param::delete(out, endpoint, &scope, &args.key).map(|()| 0)
443 })
444 }
445
446 Command::Coordinator(args) => {
448 let a = command::serve::CoordinatorServeArgs {
449 port: args.port,
450 bind: args.bind,
451 token: args.token,
452 token_file: args.token_file,
453 working_dir: args.working_dir,
454 store: args.store,
455 recreate_store: args.recreate_store,
456 pidfile: args.pidfile,
457 announce: args.announce,
458 ha_node_id: args.ha_node_id,
459 ha_peers: args.ha_peers,
460 };
461 finish(stderr, command::serve::coordinator(stdout, &a), |r| {
462 r.exit_code()
463 })
464 }
465 Command::Daemon(args) => {
466 let a = command::serve::DaemonServeArgs {
467 coordinator: args.coordinator,
468 machine: args.machine,
469 port: args.port,
470 peer_port: args.peer_port,
471 peer_bind: args.peer_bind,
472 labels: args.labels,
473 runtime_dir: args.runtime_dir,
474 working_dir: args.working_dir,
475 token: args.token,
476 token_file: args.token_file,
477 pidfile: args.pidfile,
478 announce: args.announce,
479 };
480 finish(stderr, command::serve::daemon(stdout, &a), |r| {
481 r.exit_code()
482 })
483 }
484 Command::Runtime(args) => {
485 let a = command::serve::RuntimeServeArgs {
486 node_id: args.node_id,
487 };
488 finish(stderr, command::serve::runtime(stdout, &a), |r| {
489 r.exit_code()
490 })
491 }
492
493 Command::Topic(cli::TopicCommand::Echo(args)) => {
495 let a = command::topic::TopicStreamArgs {
496 topic: args.topic,
497 dataflow: args.dataflow,
498 json,
499 count: args.count,
500 };
501 with_endpoint(stdout, stderr, &args.connect, false, |out, endpoint| {
502 command::topic::echo(out, endpoint, &a).map(|_| 0)
503 })
504 }
505 Command::Topic(cli::TopicCommand::Hz(args)) => {
506 let window = std::time::Duration::from_secs_f64(args.window.max(0.001));
507 let a = command::topic::TopicStreamArgs {
508 topic: args.topic,
509 dataflow: args.dataflow,
510 json,
511 count: args.count,
512 };
513 with_endpoint(stdout, stderr, &args.connect, false, |out, endpoint| {
514 command::topic::hz(out, endpoint, &a, window).map(|_| 0)
515 })
516 }
517 Command::Topic(cli::TopicCommand::Info(args)) => {
518 with_endpoint(stdout, stderr, &args.connect, false, |out, endpoint| {
519 command::topic::info(
520 out,
521 endpoint,
522 &args.topic,
523 args.dataflow.as_deref(),
524 args.manifest.as_deref(),
525 json,
526 )
527 .map(|_| 0)
528 })
529 }
530 Command::Topic(cli::TopicCommand::Pub(args)) => {
531 let a = command::topic::PublishArgs {
532 topic: args.topic,
533 message: args.message,
534 dataflow: args.dataflow,
535 rate: args.rate,
536 json,
537 };
538 with_endpoint(stdout, stderr, &args.connect, true, |out, endpoint| {
539 command::topic::publish(out, endpoint, &a).map(|_| 0)
540 })
541 }
542 Command::Trace(args) => {
543 let a = command::trace::TraceArgs {
544 dataflow: args.dataflow,
545 node: args.node,
546 since: None,
547 limit: args.limit,
548 json,
549 };
550 with_endpoint(stdout, stderr, &args.connect, false, |out, endpoint| {
551 command::trace::run(out, endpoint, &a).map(|_| 0)
552 })
553 }
554
555 Command::Top(args) => {
556 let a = command::top::TopArgs {
557 replay: args.replay,
558 };
559 with_endpoint(stdout, stderr, &args.connect, false, |_out, endpoint| {
560 command::top::run(endpoint, &a).map(|()| 0)
561 })
562 }
563
564 Command::Node(cli::NodeCommand::Add(args)) => {
566 let a = command::node::AddArgs {
567 dataflow: DataflowRef::parse(&args.dataflow),
568 node_manifest: args.node_manifest,
569 start: !args.no_start,
570 json,
571 };
572 with_endpoint(stdout, stderr, &args.connect, true, |out, endpoint| {
573 command::node::add(out, endpoint, &a).map(|()| 0)
574 })
575 }
576 Command::Node(cli::NodeCommand::Remove(args)) => {
577 let a = command::node::RemoveArgs {
578 dataflow: DataflowRef::parse(&args.dataflow),
579 node_id: args.node_id,
580 grace: args.grace,
581 json,
582 };
583 with_endpoint(stdout, stderr, &args.connect, true, |out, endpoint| {
584 command::node::remove(out, endpoint, &a).map(|()| 0)
585 })
586 }
587 Command::Node(cli::NodeCommand::Replace(args)) => {
588 let a = command::node::ReplaceArgs {
589 dataflow: DataflowRef::parse(&args.dataflow),
590 node_id: args.node_id,
591 node_manifest: args.node_manifest,
592 drain: args.drain,
593 json,
594 };
595 with_endpoint(stdout, stderr, &args.connect, true, |out, endpoint| {
596 command::node::replace(out, endpoint, &a).map(|()| 0)
597 })
598 }
599 Command::Node(cli::NodeCommand::Connect(args)) => {
600 let a = command::node::ConnectArgs {
601 dataflow: DataflowRef::parse(&args.dataflow),
602 node_id: args.node_id,
603 input: args.input,
604 source: args.source,
605 queue_size: args.queue_size,
606 queue_policy: args.queue_policy,
607 json,
608 };
609 with_endpoint(stdout, stderr, &args.connect, true, |out, endpoint| {
610 command::node::connect(out, endpoint, &a).map(|()| 0)
611 })
612 }
613 Command::Node(cli::NodeCommand::Disconnect(args)) => {
614 let a = command::node::DisconnectArgs {
615 dataflow: DataflowRef::parse(&args.dataflow),
616 node_id: args.node_id,
617 input: args.input,
618 json,
619 };
620 with_endpoint(stdout, stderr, &args.connect, true, |out, endpoint| {
621 command::node::disconnect(out, endpoint, &a).map(|()| 0)
622 })
623 }
624 Command::Record(cli::RecordCommand::Start(args)) => {
625 let a = command::record::StartArgs {
626 dataflow: args.dataflow,
627 output: args.output.display().to_string(),
628 only: args.only,
629 overwrite: args.overwrite,
630 json,
631 };
632 with_endpoint(stdout, stderr, &args.connect, true, |out, endpoint| {
633 command::record::start(out, endpoint, &a).map(|()| 0)
634 })
635 }
636 Command::Record(cli::RecordCommand::Stop(args)) => {
637 let a = command::record::StopArgs {
638 dataflow: args.dataflow,
639 json,
640 };
641 with_endpoint(stdout, stderr, &args.connect, true, |out, endpoint| {
642 command::record::stop(out, endpoint, &a).map(|()| 0)
643 })
644 }
645 Command::Replay(args) => {
646 match (args.into, args.dataflow) {
647 (Some(into), _) => {
648 let a = command::replay::ReplayIntoArgs {
649 input: args.input,
650 into: std::path::PathBuf::from(into),
651 mode: args.mode,
652 speed: args.speed,
653 rate: args.rate,
654 r#loop: args.r#loop,
655 replace: args.replace,
656 };
657 finish(stderr, command::replay::run(stdout, &a), |_| 0)
658 }
659 (None, Some(dataflow)) => {
660 let a = command::replay::ReplayLiveArgs {
661 input: args.input,
662 dataflow: DataflowRef::parse(&dataflow),
663 mode: args.mode,
664 speed: args.speed,
665 rate: args.rate,
666 r#loop: args.r#loop,
667 replace: args.replace,
668 drain: args.drain,
669 json,
670 };
671 with_endpoint(stdout, stderr, &args.connect, true, |out, endpoint| {
674 command::replay::run_live(out, endpoint, &a).map(|_| 0)
675 })
676 }
677 (None, None) => report_error(
681 stderr,
682 &CliError::BadArgument {
683 flag: "into",
684 value: String::new(),
685 reason: "astrs replay needs a target: `--into <manifest.yml>` to \
686 print a rewritten manifest, or a running dataflow's id \
687 or name to cut it over in place"
688 .to_owned(),
689 },
690 ),
691 }
692 }
693 Command::Bag(cli::BagCommand::Info(args)) => {
694 let a = command::bag::InfoArgs {
695 input: args.input,
696 json,
697 };
698 finish(stderr, command::bag::info(stdout, &a), |_| 0)
699 }
700 Command::Bag(cli::BagCommand::Convert(args)) => {
701 let a = command::bag::ConvertArgs {
702 input: args.input,
703 output: args.output,
704 json,
705 };
706 finish(stderr, command::bag::convert(stdout, &a), |_| 0)
707 }
708 Command::Ros2(cli::Ros2Command::Doctor(args)) => {
709 let a = probe_args(args.domain_id, args.timeout, args.hidden, json);
710 finish(stderr, command::ros2_doctor::run(stdout, &a), |r| {
711 r.exit_code()
712 })
713 }
714 Command::Ros2(cli::Ros2Command::Topics(args)) => {
715 let a = probe_args(args.domain_id, args.timeout, args.hidden, json);
716 finish(stderr, command::ros2_topics::run(stdout, &a), |r| {
717 r.exit_code()
718 })
719 }
720 }
721}
722
723fn probe_args(
728 domain_id: Option<u32>,
729 timeout_ms: Option<u64>,
730 hidden: bool,
731 json: bool,
732) -> command::ros2::ProbeArgs {
733 let defaults = command::ros2::ProbeArgs::default();
734 command::ros2::ProbeArgs {
735 domain_id: domain_id.unwrap_or(defaults.domain_id),
736 timeout: timeout_ms.map_or(defaults.timeout, std::time::Duration::from_millis),
737 include_hidden: hidden,
738 json,
739 }
740}
741
742fn level_of(text: Option<&str>) -> Result<Option<astrs_wire::LogLevel>, CliError> {
748 match text {
749 Some(text) => command::log_stream::parse_level("level", text).map(Some),
750 None => Ok(None),
751 }
752}
753
754fn with_endpoint(
760 stdout: &mut dyn Write,
761 stderr: &mut dyn Write,
762 connect: &cli::ConnectArgs,
763 require_token: bool,
764 body: impl FnOnce(&mut dyn Write, &Endpoint) -> Result<i32, CliError>,
765) -> i32 {
766 let endpoint = match endpoint_of(connect, require_token) {
767 Ok(endpoint) => endpoint,
768 Err(err) => return report_error(stderr, &err),
769 };
770 finish(stderr, body(stdout, &endpoint), |code| *code)
771}
772
773fn endpoint_of(connect: &cli::ConnectArgs, require_token: bool) -> Result<Endpoint, CliError> {
780 command::client::endpoint(
781 connect.coordinator.as_deref(),
782 connect.token.as_deref(),
783 connect.token_file.as_deref(),
784 connect.working_dir.as_deref(),
785 require_token,
786 )
787}
788
789fn report_error(stderr: &mut dyn Write, err: &CliError) -> i32 {
791 let _ = writeln!(stderr, "error: {err}");
792 err.exit_code()
793}
794
795fn finish<R>(
803 stderr: &mut dyn Write,
804 result: Result<R, CliError>,
805 ok_exit_code: impl FnOnce(&R) -> i32,
806) -> i32 {
807 match result {
808 Ok(report) => ok_exit_code(&report),
809 Err(err) => report_error(stderr, &err),
810 }
811}
812
813#[cfg(test)]
814mod tests {
815 #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
816 use super::*;
817 use clap::Parser;
818
819 fn parse(argv: &[&str]) -> Cli {
820 Cli::try_parse_from(argv).unwrap()
821 }
822
823 fn scratch(name: &str) -> std::path::PathBuf {
824 let dir =
825 std::env::temp_dir().join(format!("astrs-cli-dispatch-{}-{name}", std::process::id()));
826 let _ = std::fs::remove_dir_all(&dir);
827 std::fs::create_dir_all(&dir).unwrap();
828 dir
829 }
830
831 #[test]
837 fn the_ros2_verbs_map_their_flags_onto_probe_arguments() {
838 let defaults = probe_args(None, None, false, false);
839 assert_eq!(defaults.timeout, command::ros2::DEFAULT_TIMEOUT);
840 assert!(!defaults.include_hidden);
841 assert!(!defaults.json);
842
843 let explicit = probe_args(Some(7), Some(250), true, true);
844 assert_eq!(explicit.domain_id, 7);
845 assert_eq!(explicit.timeout, std::time::Duration::from_millis(250));
846 assert!(explicit.include_hidden);
847 assert!(explicit.json);
848
849 for verb in ["doctor", "topics"] {
851 let cli = parse(&[
852 "astrs",
853 "ros2",
854 verb,
855 "--domain-id",
856 "3",
857 "--timeout",
858 "100",
859 "--hidden",
860 ]);
861 match cli.command {
862 Command::Ros2(cli::Ros2Command::Doctor(args)) => {
863 assert_eq!(args.domain_id, Some(3));
864 assert_eq!(args.timeout, Some(100));
865 assert!(args.hidden);
866 }
867 Command::Ros2(cli::Ros2Command::Topics(args)) => {
868 assert_eq!(args.domain_id, Some(3));
869 assert_eq!(args.timeout, Some(100));
870 assert!(args.hidden);
871 }
872 other => panic!("`ros2 {verb}` parsed as {other:?}"),
873 }
874 }
875 }
876
877 #[test]
878 fn bag_info_dispatches_end_to_end_against_a_real_file() {
879 let dir = scratch("bag-info");
880 let path = dir.join("session.arec");
881 let options = astrs_recording::WriterOptions::new(
882 astrs_wire::DataflowId::from_u128(1),
883 astrs_time::HlcTimestamp::EPOCH,
884 );
885 let mut writer = astrs_recording::Writer::create(&path, options).unwrap();
886 writer
887 .append_parts(
888 astrs_wire::NodeId::new("camera").unwrap(),
889 astrs_wire::DataId::new("frames").unwrap(),
890 astrs_wire::Metadata::new(astrs_time::HlcTimestamp::new(1, 0)),
891 vec![1, 2, 3],
892 )
893 .unwrap();
894 writer.finish().unwrap();
895
896 let cli = parse(&["astrs", "bag", "info", path.to_str().unwrap()]);
897 let mut out = Vec::new();
898 let mut err = Vec::new();
899 let code = dispatch(cli, &mut out, &mut err, false);
900 assert_eq!(code, 0, "{}", String::from_utf8(err).unwrap());
901 let printed = String::from_utf8(out).unwrap();
902 assert!(printed.contains("camera/frames"), "{printed}");
903 }
904
905 #[test]
906 fn bag_convert_dispatches_end_to_end_against_a_real_file() {
907 let dir = scratch("bag-convert");
908 let input = dir.join("session.arec");
909 let output = dir.join("session.db3");
910 let options = astrs_recording::WriterOptions::new(
911 astrs_wire::DataflowId::from_u128(1),
912 astrs_time::HlcTimestamp::EPOCH,
913 );
914 let mut writer = astrs_recording::Writer::create(&input, options).unwrap();
915 writer
916 .append_parts(
917 astrs_wire::NodeId::new("camera").unwrap(),
918 astrs_wire::DataId::new("frames").unwrap(),
919 astrs_wire::Metadata::new(astrs_time::HlcTimestamp::new(1, 0)),
920 vec![1, 2, 3],
921 )
922 .unwrap();
923 writer.finish().unwrap();
924
925 let cli = parse(&[
926 "astrs",
927 "bag",
928 "convert",
929 input.to_str().unwrap(),
930 output.to_str().unwrap(),
931 ]);
932 let mut out = Vec::new();
933 let mut err = Vec::new();
934 let code = dispatch(cli, &mut out, &mut err, false);
935 assert_eq!(code, 0, "{}", String::from_utf8(err).unwrap());
936 let printed = String::from_utf8(out).unwrap();
937 assert!(printed.contains("arec -> db3"), "{printed}");
938 assert!(output.exists());
939
940 let reader = astrs_rosbag::db3::Reader::open(&output).unwrap();
943 assert_eq!(reader.topics().len(), 1);
944 }
945
946 #[test]
947 fn replay_dispatches_end_to_end_and_prints_a_rewritten_manifest() {
948 let dir = scratch("replay-into");
949 let recording = dir.join("session.arec");
950 let options = astrs_recording::WriterOptions::new(
951 astrs_wire::DataflowId::from_u128(1),
952 astrs_time::HlcTimestamp::EPOCH,
953 );
954 let mut writer = astrs_recording::Writer::create(&recording, options).unwrap();
955 writer
956 .append_parts(
957 astrs_wire::NodeId::new("camera").unwrap(),
958 astrs_wire::DataId::new("frames").unwrap(),
959 astrs_wire::Metadata::new(astrs_time::HlcTimestamp::new(1, 0)),
960 vec![1],
961 )
962 .unwrap();
963 writer.finish().unwrap();
964
965 let manifest = dir.join("graph.yaml");
966 std::fs::write(
967 &manifest,
968 "nodes:\n - id: camera\n path: ./camera\n outputs: [frames]\n",
969 )
970 .unwrap();
971
972 let cli = parse(&[
973 "astrs",
974 "replay",
975 recording.to_str().unwrap(),
976 "--into",
977 manifest.to_str().unwrap(),
978 ]);
979 let mut out = Vec::new();
980 let mut err = Vec::new();
981 let code = dispatch(cli, &mut out, &mut err, false);
982 assert_eq!(code, 0, "{}", String::from_utf8(err).unwrap());
983 let printed = String::from_utf8(out).unwrap();
984 assert!(printed.contains("astrs-replay-node"), "{printed}");
985 let rewritten = astrs_manifest::Manifest::from_yaml_str(&printed).unwrap();
986 rewritten.validate().expect("must still validate");
987 }
988
989 #[test]
990 fn replay_without_into_is_reported_rather_than_guessed() {
991 let cli = parse(&["astrs", "replay", "session.arec"]);
992 let mut out = Vec::new();
993 let mut err = Vec::new();
994 let code = dispatch(cli, &mut out, &mut err, false);
995 assert_eq!(code, 1);
996 let message = String::from_utf8(err).unwrap();
997 assert!(message.contains("--into"), "{message}");
998 }
999
1000 #[test]
1001 fn schema_dispatches_and_prints_json_to_stdout() {
1002 let cli = parse(&["astrs", "schema"]);
1003 let mut out = Vec::new();
1004 let mut err = Vec::new();
1005 let code = dispatch(cli, &mut out, &mut err, false);
1006 assert_eq!(code, 0);
1007 assert!(err.is_empty());
1008 let printed = String::from_utf8(out).unwrap();
1009 let value: serde_json::Value = serde_json::from_str(printed.trim_end()).unwrap();
1010 assert!(value.is_object());
1011 }
1012
1013 #[test]
1014 fn validate_dispatches_with_exit_code_two_for_a_missing_file() {
1015 let cli = parse(&["astrs", "validate", "/does/not/exist.yaml"]);
1016 let mut out = Vec::new();
1017 let mut err = Vec::new();
1018 let code = dispatch(cli, &mut out, &mut err, false);
1019 assert_eq!(code, 2);
1020 assert!(
1021 err.is_empty(),
1022 "validate embeds failures in its report, not stderr"
1023 );
1024 }
1025
1026 #[test]
1027 fn migrate_from_ros2_reports_a_missing_file_on_stderr() {
1028 let cli = parse(&["astrs", "migrate", "from-ros2", "does-not-exist.launch.xml"]);
1029 let mut out = Vec::new();
1030 let mut err = Vec::new();
1031 let code = dispatch(cli, &mut out, &mut err, false);
1032 assert_eq!(code, 1, "a missing input file is an ordinary failure");
1033 assert!(out.is_empty());
1034 assert!(!err.is_empty());
1035 }
1036
1037 #[test]
1038 fn migrate_from_ros2_dispatches_a_real_launch_file() {
1039 let dir = scratch("migrate-ros2");
1040 let input = dir.join("robot.launch.xml");
1041 std::fs::write(
1042 &input,
1043 r#"<launch><node pkg="p" exec="e" name="n"/></launch>"#,
1044 )
1045 .unwrap();
1046 let cli = parse(&["astrs", "migrate", "from-ros2", input.to_str().unwrap()]);
1047 let mut out = Vec::new();
1048 let mut err = Vec::new();
1049 let code = dispatch(cli, &mut out, &mut err, false);
1050 assert_eq!(
1051 code, 2,
1052 "message_type is never inferable from a launch file"
1053 );
1054 assert!(err.is_empty(), "err: {}", String::from_utf8_lossy(&err));
1055 assert!(!out.is_empty());
1056 }
1057
1058 #[test]
1059 fn completion_dispatches_for_every_shell() {
1060 for shell in ["bash", "zsh", "fish"] {
1061 let cli = parse(&["astrs", "completion", shell]);
1062 let mut out = Vec::new();
1063 let mut err = Vec::new();
1064 let code = dispatch(cli, &mut out, &mut err, false);
1065 assert_eq!(code, 0, "shell {shell}");
1066 assert!(!out.is_empty());
1067 }
1068 }
1069
1070 #[test]
1071 fn new_graph_dispatches_into_a_real_scaffold() {
1072 let dir = scratch("new-graph");
1073 let cli = parse(&[
1074 "astrs",
1075 "new",
1076 "graph",
1077 "perception",
1078 "--dir",
1079 dir.to_str().unwrap(),
1080 ]);
1081 let mut out = Vec::new();
1082 let mut err = Vec::new();
1083 let code = dispatch(cli, &mut out, &mut err, false);
1084 assert_eq!(code, 0, "stderr: {}", String::from_utf8_lossy(&err));
1085 assert!(dir.join("perception.astrs.yml").exists());
1086 }
1087
1088 #[test]
1089 fn a_bad_level_is_reported_before_anything_runs() {
1090 for argv in [
1091 &["astrs", "run", "d.yml", "--level", "loud"][..],
1092 &["astrs", "logs", "--level", "loud"][..],
1093 &["astrs", "start", "d.yml", "--level", "loud"][..],
1094 ] {
1095 let mut out = Vec::new();
1096 let mut err = Vec::new();
1097 let code = dispatch(parse(argv), &mut out, &mut err, false);
1098 assert_eq!(code, 1, "{argv:?}");
1099 assert!(out.is_empty(), "{argv:?}");
1100 let message = String::from_utf8(err).unwrap();
1101 assert!(message.contains("trace"), "{message}");
1102 }
1103 }
1104
1105 #[test]
1106 fn every_mutating_verb_refuses_locally_without_a_token() {
1107 let dir = scratch("no-token");
1110 let working = dir.to_str().unwrap();
1111 for argv in [
1112 &["astrs", "stop", "flow"][..],
1113 &["astrs", "restart", "flow"][..],
1114 &["astrs", "destroy"][..],
1115 &["astrs", "clean"][..],
1116 &["astrs", "param", "set", "flow", "k", "1"][..],
1117 &["astrs", "param", "delete", "flow", "k"][..],
1118 &["astrs", "record", "start", "flow", "out.arec"][..],
1119 &["astrs", "record", "stop", "flow"][..],
1120 ] {
1121 let mut full: Vec<&str> = argv.to_vec();
1122 full.extend(["--working-dir", working, "--coordinator", "127.0.0.1:1"]);
1123 let mut out = Vec::new();
1124 let mut err = Vec::new();
1125 let code = dispatch(parse(&full), &mut out, &mut err, false);
1126 assert_eq!(code, 1, "{full:?}");
1127 let message = String::from_utf8(err).unwrap();
1128 assert!(message.contains("no cluster token"), "{full:?}: {message}");
1129 }
1130 }
1131
1132 #[test]
1133 fn every_read_verb_dials_without_a_token_and_reports_no_cluster() {
1134 let dir = scratch("read-verbs");
1135 let working = dir.to_str().unwrap();
1136 for argv in [
1137 &["astrs", "list"][..],
1138 &["astrs", "logs"][..],
1139 &["astrs", "status", "flow"][..],
1140 &["astrs", "param", "get", "flow", "k"][..],
1141 &["astrs", "param", "list", "flow"][..],
1142 ] {
1143 let mut full: Vec<&str> = argv.to_vec();
1144 full.extend(["--working-dir", working, "--coordinator", "127.0.0.1:1"]);
1145 let mut out = Vec::new();
1146 let mut err = Vec::new();
1147 let code = dispatch(parse(&full), &mut out, &mut err, false);
1148 assert_eq!(code, 1, "{full:?}");
1149 let message = String::from_utf8(err).unwrap();
1150 assert!(
1151 message.contains("no cluster is running"),
1152 "{full:?}: {message}"
1153 );
1154 }
1155 }
1156
1157 #[test]
1158 fn cluster_status_reports_an_empty_runtime_directory_rather_than_failing() {
1159 let dir = scratch("status");
1160 let cli = parse(&[
1161 "astrs",
1162 "--json",
1163 "status",
1164 "--runtime-dir",
1165 dir.to_str().unwrap(),
1166 "--working-dir",
1167 dir.to_str().unwrap(),
1168 "--coordinator",
1169 "127.0.0.1:1",
1170 ]);
1171 let mut out = Vec::new();
1172 let mut err = Vec::new();
1173 let code = dispatch(cli, &mut out, &mut err, false);
1174 assert_eq!(code, 1, "an unreachable cluster exits non-zero");
1175 let printed = String::from_utf8(out).unwrap();
1176 let value: serde_json::Value = serde_json::from_str(&printed).unwrap();
1177 assert_eq!(value["reachable"], false);
1178 assert_eq!(value["coordinator"]["running"], false);
1179 assert!(err.is_empty(), "status embeds the outcome in its report");
1180 }
1181
1182 #[test]
1183 fn down_on_an_empty_runtime_directory_succeeds() {
1184 let dir = scratch("down");
1185 let cli = parse(&[
1186 "astrs",
1187 "down",
1188 "--runtime-dir",
1189 dir.to_str().unwrap(),
1190 "--working-dir",
1191 dir.to_str().unwrap(),
1192 ]);
1193 let mut out = Vec::new();
1194 let mut err = Vec::new();
1195 let code = dispatch(cli, &mut out, &mut err, false);
1196 assert_eq!(code, 0, "stderr: {}", String::from_utf8_lossy(&err));
1197 assert!(
1198 String::from_utf8(out)
1199 .unwrap()
1200 .contains("nothing was running")
1201 );
1202 }
1203
1204 #[test]
1205 fn build_dispatches_into_the_real_build_engine() {
1206 let dir = scratch("build");
1207 let manifest = dir.join("d.yml");
1208 std::fs::write(
1209 &manifest,
1210 "nodes:\n - id: a\n path: /usr/bin/true\n build: /bin/sh -c 'echo built-by-dispatch'\n",
1211 )
1212 .unwrap();
1213 let cli = parse(&[
1214 "astrs",
1215 "build",
1216 manifest.to_str().unwrap(),
1217 "--runtime-dir",
1218 dir.to_str().unwrap(),
1219 "--working-dir",
1220 dir.to_str().unwrap(),
1221 ]);
1222 let mut out = Vec::new();
1223 let mut err = Vec::new();
1224 let code = dispatch(cli, &mut out, &mut err, false);
1225 assert_eq!(code, 0, "stderr: {}", String::from_utf8_lossy(&err));
1226 assert!(
1227 String::from_utf8(out)
1228 .unwrap()
1229 .contains("built-by-dispatch")
1230 );
1231 }
1232
1233 #[test]
1234 fn a_runtime_process_started_by_hand_fails_with_a_typed_node_error() {
1235 let cli = parse(&["astrs", "runtime", "--node-id", "cam"]);
1238 let mut out = Vec::new();
1239 let mut err = Vec::new();
1240 let code = dispatch(cli, &mut out, &mut err, false);
1241 assert_eq!(code, 1);
1242 assert!(!err.is_empty());
1243 }
1244}