Skip to main content

moqros_cli/
lib.rs

1//! Shared plumbing for the moqros bridge binaries.
2
3use std::any::TypeId;
4use std::collections::HashSet;
5use std::path::PathBuf;
6use std::str::FromStr;
7use std::sync::atomic::{AtomicBool, Ordering};
8use std::sync::{Arc, Mutex};
9use std::time::Duration;
10
11use anyhow::{Context, bail, ensure};
12use clap::builder::BoolishValueParser;
13use clap::error::ErrorKind;
14use clap::{ArgAction, Args, Command, Parser, ValueEnum};
15use moqros::ros::r2r::ParameterValue;
16use moqros::ros::{QosProfile, ROS_IMAGE_TYPE, r2r};
17use tokio::task::JoinHandle;
18
19/// Relay connection flags.
20#[derive(Debug, Clone, Args)]
21pub struct RelayArgs {
22	/// Relay URL; its path scopes broadcast names.
23	#[arg(long, env = "MOQROS_URL", default_value = "http://localhost:4443/anon")]
24	pub url: moqros::Url,
25
26	/// Disable TLS certificate verification (development only).
27	#[arg(long, env = "MOQROS_INSECURE", action = ArgAction::Set, value_parser = BoolishValueParser::new(),
28		num_args = 0..=1, require_equals = true, default_value_t = false, default_missing_value = "true")]
29	pub insecure: bool,
30
31	/// PEM client certificate chain to present to the relay (mTLS).
32	#[arg(long, env = "MOQROS_TLS_CERT", requires = "tls_key")]
33	pub tls_cert: Option<PathBuf>,
34
35	/// PEM private key of `--tls-cert`.
36	#[arg(long, env = "MOQROS_TLS_KEY", requires = "tls_cert")]
37	pub tls_key: Option<PathBuf>,
38}
39
40impl RelayArgs {
41	pub fn config(&self) -> moqros::ClientConfig {
42		moqros::ClientConfig {
43			url: self.url.clone(),
44			insecure: self.insecure,
45			tls_cert: self.tls_cert.clone(),
46			tls_key: self.tls_key.clone(),
47		}
48	}
49
50	/// The relay URL with its `jwt` token and password hidden, for logging.
51	pub fn redacted_url(&self) -> moqros::Url {
52		redact_url(&self.url)
53	}
54}
55
56fn redact_url(url: &moqros::Url) -> moqros::Url {
57	const REDACTED: &str = "REDACTED";
58	let mut url = url.clone();
59	if url.password().is_some() {
60		let _ = url.set_password(Some(REDACTED));
61	}
62	if url.query_pairs().any(|(key, _)| key == "jwt") {
63		let pairs: Vec<(String, String)> = url
64			.query_pairs()
65			.map(|(key, value)| {
66				let value = if key == "jwt" {
67					REDACTED.into()
68				} else {
69					value.into_owned()
70				};
71				(key.into_owned(), value)
72			})
73			.collect();
74		url.query_pairs_mut().clear().extend_pairs(pairs);
75	}
76	url
77}
78
79/// What `moqros-pub` sends.
80#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
81pub enum Format {
82	/// Encode `sensor_msgs/msg/Image` messages as video.
83	Video,
84	/// Any message type, as one JSON document per message.
85	Json,
86	/// Any message type, in its ROS serialization (CDR).
87	Cdr,
88}
89
90impl Format {
91	/// The data track format, or `None` for video.
92	pub fn data(self) -> Option<moqros::DataFormat> {
93		match self {
94			Self::Video => None,
95			Self::Json => Some(moqros::DataFormat::Json),
96			Self::Cdr => Some(moqros::DataFormat::Cdr),
97		}
98	}
99}
100
101/// `NAME[,key=value...]` split into the name and its options.
102type Spec<'a> = (&'a str, Vec<(&'a str, &'a str)>);
103
104/// Split `NAME[,key=value...]` into the name and its options, rejecting keys not in `keys`.
105fn split_spec<'a>(spec: &'a str, keys: &[&str]) -> Result<Spec<'a>, String> {
106	let mut parts = spec.split(',');
107	let name = parts.next().unwrap_or_default().trim();
108	if name.is_empty() {
109		return Err(format!("{spec:?} doesn't start with a name"));
110	}
111	let mut options: Vec<(&str, &str)> = Vec::new();
112	for part in parts {
113		let (key, value) = part
114			.split_once('=')
115			.ok_or_else(|| format!("expected key=value, got {part:?}"))?;
116		let (key, value) = (key.trim(), value.trim());
117		if !keys.contains(&key) {
118			return Err(format!("unknown option {key:?} (expected one of: {})", keys.join(", ")));
119		}
120		if options.iter().any(|(k, _)| *k == key) {
121			return Err(format!("option {key:?} given twice"));
122		}
123		options.push((key, value));
124	}
125	Ok((name, options))
126}
127
128/// A topic for `moqros-pub`: `TOPIC[,format=…][,type=…][,mode=…][,broadcast=…]`.
129///
130/// Options left out fall back to the matching command-line flags.
131#[derive(Debug, Clone, PartialEq, Eq)]
132pub struct TopicSpec {
133	pub topic: String,
134	pub format: Option<Format>,
135	pub ros_type: Option<String>,
136	pub mode: Option<moqros::DataMode>,
137	pub broadcast: Option<String>,
138}
139
140impl FromStr for TopicSpec {
141	type Err = String;
142
143	fn from_str(spec: &str) -> Result<Self, String> {
144		let (topic, options) = split_spec(spec, &["format", "type", "mode", "broadcast"])?;
145		let mut parsed = Self {
146			topic: topic.to_string(),
147			format: None,
148			ros_type: None,
149			mode: None,
150			broadcast: None,
151		};
152		for (key, value) in options {
153			match key {
154				"format" => parsed.format = Some(Format::from_str(value, true)?),
155				"type" => parsed.ros_type = Some(value.to_string()),
156				"mode" => parsed.mode = Some(value.parse().map_err(|err| format!("{err}"))?),
157				_ => parsed.broadcast = Some(value.to_string()),
158			}
159		}
160		Ok(parsed)
161	}
162}
163
164/// What `moqros-pub` does with one topic.
165#[derive(Debug, Clone, PartialEq, Eq)]
166pub struct PubTopic {
167	pub topic: String,
168	pub broadcast: String,
169	pub format: Format,
170	pub mode: moqros::DataMode,
171	/// Looked up in the ROS graph when `None` (unless the format is video).
172	pub ros_type: Option<String>,
173}
174
175/// Fill in each topic's options from the flags: `format` and `mode` apply to every topic,
176/// while `ros_type` and `broadcast` name one topic, so they need exactly one.
177pub fn pub_topics(
178	specs: Vec<TopicSpec>,
179	format: Format,
180	mode: moqros::DataMode,
181	ros_type: Option<String>,
182	broadcast: Option<String>,
183) -> anyhow::Result<Vec<PubTopic>> {
184	ensure!(!specs.is_empty(), "no topic to publish");
185	ensure!(
186		specs.len() == 1 || (ros_type.is_none() && broadcast.is_none()),
187		"--type and --broadcast need a single --topic; give several topics `type=` and `broadcast=` options instead"
188	);
189	let mut broadcasts = HashSet::new();
190	specs
191		.into_iter()
192		.map(|spec| {
193			let topic = PubTopic {
194				broadcast: spec
195					.broadcast
196					.or(broadcast.clone())
197					.unwrap_or_else(|| moqros::broadcast_name_for_topic(&spec.topic)),
198				format: spec.format.unwrap_or(format),
199				mode: spec.mode.unwrap_or(mode),
200				ros_type: spec.ros_type.or(ros_type.clone()),
201				topic: spec.topic,
202			};
203			if topic.format == Format::Video
204				&& let Some(ros_type) = topic.ros_type.as_deref().filter(|t| *t != ROS_IMAGE_TYPE)
205			{
206				bail!(
207					"{}: video needs {ROS_IMAGE_TYPE} messages, not {ros_type}; use format=json or cdr",
208					topic.topic
209				);
210			}
211			ensure!(
212				broadcasts.insert(topic.broadcast.clone()),
213				"several topics publish the broadcast {:?}",
214				topic.broadcast
215			);
216			Ok(topic)
217		})
218		.collect()
219}
220
221/// A broadcast for `moqros-sub`: `BROADCAST[,topic=…][,type=…][,frame_id=…]`.
222///
223/// Options left out fall back to the matching command-line flags.
224#[derive(Debug, Clone, PartialEq, Eq)]
225pub struct BroadcastSpec {
226	pub broadcast: String,
227	pub topic: Option<String>,
228	pub ros_type: Option<String>,
229	pub frame_id: Option<String>,
230}
231
232impl FromStr for BroadcastSpec {
233	type Err = String;
234
235	fn from_str(spec: &str) -> Result<Self, String> {
236		let (broadcast, options) = split_spec(spec, &["topic", "type", "frame_id"])?;
237		let mut parsed = Self {
238			broadcast: broadcast.to_string(),
239			topic: None,
240			ros_type: None,
241			frame_id: None,
242		};
243		for (key, value) in options {
244			let value = Some(value.to_string());
245			match key {
246				"topic" => parsed.topic = value,
247				"type" => parsed.ros_type = value,
248				_ => parsed.frame_id = value,
249			}
250		}
251		Ok(parsed)
252	}
253}
254
255/// What `moqros-sub` does with one broadcast.
256#[derive(Debug, Clone, PartialEq, Eq)]
257pub struct SubBroadcast {
258	pub broadcast: String,
259	pub topic: String,
260	/// Taken from the catalog when `None`.
261	pub ros_type: Option<String>,
262	pub frame_id: String,
263}
264
265/// Topic of a lone broadcast that neither `topic=` nor `--topic` names.
266pub const DEFAULT_SUB_TOPIC: &str = "/moqros/image";
267
268/// Fill in each broadcast's options from the flags. `topic` and `ros_type` name one
269/// broadcast, so they need exactly one. Without either `topic=` or `--topic`, a lone
270/// broadcast goes to [`DEFAULT_SUB_TOPIC`], and each of several to `/moqros/<broadcast>`.
271pub fn sub_broadcasts(
272	specs: Vec<BroadcastSpec>,
273	topic: Option<String>,
274	ros_type: Option<String>,
275	frame_id: &str,
276) -> anyhow::Result<Vec<SubBroadcast>> {
277	ensure!(!specs.is_empty(), "no broadcast to subscribe to");
278	let single = specs.len() == 1;
279	ensure!(
280		single || (topic.is_none() && ros_type.is_none()),
281		"--topic and --type need a single --broadcast; give several broadcasts `topic=` and `type=` options instead"
282	);
283	let mut topics = HashSet::new();
284	specs
285		.into_iter()
286		.map(|spec| {
287			let broadcast = SubBroadcast {
288				topic: spec.topic.or(topic.clone()).unwrap_or_else(|| match single {
289					true => DEFAULT_SUB_TOPIC.to_string(),
290					false => format!("/moqros/{}", spec.broadcast.trim_matches('/')),
291				}),
292				ros_type: spec.ros_type.or(ros_type.clone()),
293				frame_id: spec.frame_id.unwrap_or_else(|| frame_id.to_string()),
294				broadcast: spec.broadcast,
295			};
296			ensure!(
297				topics.insert(broadcast.topic.clone()),
298				"several broadcasts publish on {}",
299				broadcast.topic
300			);
301			Ok(broadcast)
302		})
303		.collect()
304}
305
306/// ROS QoS flags.
307#[derive(Debug, Clone, Args)]
308pub struct QosArgs {
309	/// Use reliable QoS instead of the best-effort sensor-data profile.
310	#[arg(long, action = ArgAction::Set, value_parser = BoolishValueParser::new(),
311		num_args = 0..=1, require_equals = true, default_value_t = false, default_missing_value = "true")]
312	pub reliable: bool,
313}
314
315impl QosArgs {
316	pub fn profile(&self) -> QosProfile {
317		if self.reliable {
318			QosProfile::default().keep_last(5)
319		} else {
320			QosProfile::sensor_data()
321		}
322	}
323}
324
325/// Create the ROS node and parse `T` from the command line and the node's ROS parameters.
326///
327/// Arguments between `--ros-args` and `--` are left to rcl, so the binaries accept
328/// remapping (`-r __node:=…`, `-r __ns:=…`), `-p` and `--params-file` like any ROS
329/// node. Each ROS parameter named after an argument (`bitrate`, `keyframe_interval_ms`,
330/// …) fills that argument: flags win over parameters, which win over environment
331/// variables and defaults.
332pub fn init<T: Parser>(node_name: &str) -> anyhow::Result<(T, r2r::Node)> {
333	let args = strip_ros_args(std::env::args());
334	// Answer `--help` and `--version` without bringing up ROS.
335	if let Some(err) = help_or_version(T::command(), &args) {
336		err.exit();
337	}
338
339	let ctx = r2r::Context::create().context("failed to create ROS context")?;
340	let node = r2r::Node::create(ctx, node_name, "").context("failed to create ROS node")?;
341
342	let flags = param_flags(
343		&T::command(),
344		node.params
345			.lock()
346			.unwrap()
347			.iter()
348			.map(|(name, param)| (name.as_str(), &param.value)),
349	)?;
350	let cli = match parse_args(args, flags) {
351		Ok(cli) => cli,
352		Err(ParseError::CommandLine(err)) => err.exit(),
353		Err(ParseError::Param(err)) => {
354			// Just clap's first line; its usage hints are about the command line.
355			let message = err.to_string();
356			let message = message.lines().next().unwrap_or_default().trim_start_matches("error: ");
357			bail!("invalid ROS parameter: {message}");
358		}
359	};
360	Ok((cli, node))
361}
362
363/// Drop the ROS arguments (`--ros-args … [--]`, possibly repeated) from `args`.
364pub fn strip_ros_args(args: impl IntoIterator<Item = String>) -> Vec<String> {
365	let mut in_ros_args = false;
366	args.into_iter()
367		.filter(|arg| match (in_ros_args, arg.as_str()) {
368			(false, "--ros-args") | (true, "--") => {
369				in_ros_args = !in_ros_args;
370				false
371			}
372			_ => !in_ros_args,
373		})
374		.collect()
375}
376
377/// The error to exit with if `args` ask for help or the version.
378///
379/// Clap answers these as soon as it meets the flag, before checking anything else.
380fn help_or_version(command: Command, args: &[String]) -> Option<clap::Error> {
381	let err = command.try_get_matches_from(args).err()?;
382	matches!(err.kind(), ErrorKind::DisplayHelp | ErrorKind::DisplayVersion).then_some(err)
383}
384
385/// Why [`parse_args`] failed.
386#[derive(Debug)]
387enum ParseError {
388	/// The command line itself is invalid.
389	CommandLine(clap::Error),
390	/// The command line is fine on its own, so a ROS parameter is invalid.
391	Param(clap::Error),
392}
393
394/// Parse `T` from `args` (program name first, ROS arguments already stripped) and
395/// `param_flags`.
396///
397/// The parameter flags go right after the program name. With `args_override_self` a
398/// later occurrence of a flag wins, so the command line overrides them, while
399/// environment variables and defaults only apply to flags given neither way. Repeatable
400/// flags collect every occurrence instead, so parameter flags that the command line
401/// gives again are dropped up front.
402fn parse_args<T: Parser>(args: Vec<String>, param_flags: Vec<String>) -> Result<T, ParseError> {
403	let flag = |arg: &str| arg.split_once('=').map_or(arg, |(flag, _)| flag).to_string();
404	let given: HashSet<String> = args
405		.iter()
406		.skip(1)
407		.filter(|arg| arg.starts_with("--"))
408		.map(|arg| flag(arg))
409		.collect();
410	let param_flags: Vec<String> = param_flags
411		.into_iter()
412		.filter(|param| !given.contains(&flag(param)))
413		.collect();
414	let parse = |param_flags: Vec<String>| {
415		let mut args = args.iter().cloned();
416		let args = args.next().into_iter().chain(param_flags).chain(args);
417		let matches = T::command().args_override_self(true).try_get_matches_from(args)?;
418		T::from_arg_matches(&matches)
419	};
420	parse(param_flags).map_err(|err| match parse(Vec::new()) {
421		Ok(_) => ParseError::Param(err),
422		Err(err) => ParseError::CommandLine(err),
423	})
424}
425
426/// Command-line flags (`--name=value`) for the ROS parameters named after an argument
427/// of `command`.
428fn param_flags<'a>(
429	command: &Command,
430	params: impl IntoIterator<Item = (&'a str, &'a ParameterValue)>,
431) -> anyhow::Result<Vec<String>> {
432	let mut flags = Vec::new();
433	for (name, value) in params {
434		let Some((long, arg)) = command
435			.get_arguments()
436			.find(|arg| arg.get_id() == name)
437			.and_then(|arg| Some((arg.get_long()?, arg)))
438		else {
439			// r2r reads `use_sim_time` itself.
440			if name != "use_sim_time" {
441				tracing::warn!(name, "ignoring unknown ROS parameter");
442			}
443			continue;
444		};
445		let value = match value {
446			// An empty YAML value: leave the flag to its environment variable or default.
447			ParameterValue::NotSet => continue,
448			ParameterValue::Bool(value) => value.to_string(),
449			ParameterValue::Integer(value) => value.to_string(),
450			// Keep the fraction of whole numbers for strings (`1.0` stays `1.0`), but drop
451			// it for numbers so `2000000.0` still fits an integer flag.
452			ParameterValue::Double(value) if arg.get_value_parser().type_id() == TypeId::of::<String>() => {
453				format!("{value:?}")
454			}
455			ParameterValue::Double(value) => value.to_string(),
456			ParameterValue::String(value) => value.clone(),
457			// A list fills a repeatable flag, one occurrence per element.
458			ParameterValue::StringArray(values) if matches!(arg.get_action(), ArgAction::Append) => {
459				flags.extend(values.iter().map(|value| format!("--{long}={value}")));
460				continue;
461			}
462			value => bail!("ROS parameter `{name}` has unsupported type: {value:?}"),
463		};
464		// One token, so values starting with `-` aren't taken for flags.
465		flags.push(format!("--{long}={value}"));
466	}
467	Ok(flags)
468}
469
470pub fn init_logging() {
471	tracing_subscriber::fmt()
472		.with_env_filter(
473			tracing_subscriber::EnvFilter::try_from_default_env()
474				.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
475		)
476		.init();
477}
478
479/// A node shared between [`spawn_spinner`] and code that adds subscriptions while it spins.
480pub struct SharedNode {
481	node: Mutex<r2r::Node>,
482	/// Set while [`SharedNode::with`] waits, so the spinner lets go of the lock. A mutex
483	/// isn't fair: a spinner relocking it right away could starve the waiter.
484	waiting: AtomicBool,
485}
486
487impl SharedNode {
488	pub fn new(node: r2r::Node) -> Arc<Self> {
489		Arc::new(Self {
490			node: Mutex::new(node),
491			waiting: AtomicBool::new(false),
492		})
493	}
494
495	/// Run `f` on the node, between two spins.
496	pub fn with<R>(&self, f: impl FnOnce(&mut r2r::Node) -> R) -> R {
497		self.waiting.store(true, Ordering::Relaxed);
498		let mut node = self.node.lock().unwrap_or_else(|err| err.into_inner());
499		self.waiting.store(false, Ordering::Relaxed);
500		f(&mut node)
501	}
502}
503
504/// Spin `node` on a blocking thread until the returned guard is dropped.
505///
506/// The tokio runtime waits for blocking tasks on shutdown, so a spinner that never
507/// stops would keep the process alive after `main` returns.
508pub fn spawn_spinner(node: Arc<SharedNode>) -> Spinner {
509	let stop = Arc::new(AtomicBool::new(false));
510	let stopped = stop.clone();
511	let task = tokio::task::spawn_blocking(move || {
512		while !stopped.load(Ordering::Relaxed) {
513			if node.waiting.load(Ordering::Relaxed) {
514				std::thread::yield_now();
515				continue;
516			}
517			let mut guard = node.node.lock().unwrap_or_else(|err| err.into_inner());
518			guard.spin_once(Duration::from_millis(50));
519		}
520	});
521	Spinner { stop, task: Some(task) }
522}
523
524/// Stops the [`spawn_spinner`] thread when dropped.
525pub struct Spinner {
526	stop: Arc<AtomicBool>,
527	task: Option<JoinHandle<()>>,
528}
529
530impl Spinner {
531	/// Resolves if the spinner thread dies, which only happens when it panics, since
532	/// without spinning no ROS message arrives anymore. Never resolves again after that.
533	pub async fn failed(&mut self) -> anyhow::Error {
534		let Some(task) = self.task.as_mut() else {
535			return std::future::pending().await;
536		};
537		let result = task.await;
538		self.task = None;
539		match result {
540			Err(err) => anyhow::Error::new(err).context("ROS spinner failed"),
541			Ok(()) => anyhow::anyhow!("ROS spinner stopped"),
542		}
543	}
544}
545
546impl Drop for Spinner {
547	fn drop(&mut self) {
548		self.stop.store(true, Ordering::Relaxed);
549	}
550}
551
552#[cfg(test)]
553mod tests {
554	use clap::CommandFactory;
555
556	use super::*;
557
558	fn strip(args: &[&str]) -> Vec<String> {
559		strip_ros_args(args.iter().map(|arg| arg.to_string()))
560	}
561
562	#[derive(Debug, Parser)]
563	#[command(version = "1.2.3")]
564	struct TestCli {
565		#[arg(long, default_value = "/image_raw")]
566		topic: String,
567
568		#[arg(long)]
569		broadcast: Option<String>,
570
571		#[arg(long, default_value_t = 30.0)]
572		fps: f32,
573
574		#[arg(long, default_value_t = 2000)]
575		keyframe_interval_ms: u64,
576
577		#[arg(long, value_enum, default_value_t = Format::Video)]
578		format: Format,
579
580		#[arg(id = "type", long = "type")]
581		ros_type: Option<String>,
582
583		#[arg(long, default_value_t = moqros::DataMode::default())]
584		mode: moqros::DataMode,
585
586		#[command(flatten)]
587		relay: RelayArgs,
588
589		#[command(flatten)]
590		qos: QosArgs,
591	}
592
593	#[derive(Debug, Parser)]
594	struct MultiCli {
595		#[arg(long, default_value = "/image_raw")]
596		topic: Vec<TopicSpec>,
597	}
598
599	/// Only parsed by `params_override_env`, in a child process of its own.
600	#[derive(Debug, Parser)]
601	struct EnvCli {
602		#[arg(long, env = "MOQROS_TEST_BITRATE", default_value_t = 1)]
603		bitrate: u32,
604	}
605
606	fn flags<T: Parser>(params: &[(&str, ParameterValue)]) -> anyhow::Result<Vec<String>> {
607		param_flags(&T::command(), params.iter().map(|(name, value)| (*name, value)))
608	}
609
610	fn args(args: &[&str]) -> Vec<String> {
611		std::iter::once("bin")
612			.chain(args.iter().copied())
613			.map(String::from)
614			.collect()
615	}
616
617	fn parse<T: Parser>(args_: &[&str], params: &[(&str, ParameterValue)]) -> Result<T, ParseError> {
618		parse_args(args(args_), flags::<T>(params).unwrap())
619	}
620
621	fn string(value: &str) -> ParameterValue {
622		ParameterValue::String(value.to_string())
623	}
624
625	#[test]
626	fn strips_ros_args() {
627		assert_eq!(strip(&["bin", "--topic", "a"]), ["bin", "--topic", "a"]);
628		assert_eq!(
629			strip(&[
630				"bin",
631				"--topic",
632				"a",
633				"--ros-args",
634				"-r",
635				"__node:=n",
636				"-p",
637				"bitrate:=1"
638			]),
639			["bin", "--topic", "a"]
640		);
641		assert_eq!(
642			strip(&[
643				"bin",
644				"--ros-args",
645				"-r",
646				"__ns:=/x",
647				"--",
648				"--reliable",
649				"--ros-args",
650				"-p",
651				"a:=1"
652			]),
653			["bin", "--reliable"]
654		);
655	}
656
657	#[test]
658	fn params_fill_flags() {
659		let cli: TestCli = parse(
660			&[],
661			&[
662				("topic", string("/front/image_raw")),
663				("keyframe_interval_ms", ParameterValue::Integer(500)),
664				("reliable", ParameterValue::Bool(true)),
665				("url", string("http://relay:4443/anon")),
666			],
667		)
668		.unwrap();
669		assert_eq!(cli.topic, "/front/image_raw");
670		assert_eq!(cli.keyframe_interval_ms, 500);
671		assert!(cli.qos.reliable);
672		assert_eq!(cli.relay.url.as_str(), "http://relay:4443/anon");
673		assert!(!cli.relay.insecure);
674		assert_eq!(cli.broadcast, None);
675	}
676
677	#[test]
678	fn client_cert_flags_come_in_pairs() {
679		let cli: TestCli = parse(
680			&["--tls-cert", "/certs/robot.pem"],
681			&[("tls_key", string("/certs/robot.key"))],
682		)
683		.unwrap();
684		let config = cli.relay.config();
685		assert_eq!(
686			config.tls_cert.as_deref(),
687			Some(std::path::Path::new("/certs/robot.pem"))
688		);
689		assert_eq!(
690			config.tls_key.as_deref(),
691			Some(std::path::Path::new("/certs/robot.key"))
692		);
693		assert!(parse::<TestCli>(&["--tls-cert", "/certs/robot.pem"], &[]).is_err());
694		assert!(parse::<TestCli>(&["--tls-key", "/certs/robot.key"], &[]).is_err());
695	}
696
697	#[test]
698	fn data_params_fill_flags() {
699		let cli: TestCli = parse(&[], &[]).unwrap();
700		assert_eq!(
701			(cli.format, cli.ros_type, cli.mode),
702			(Format::Video, None, moqros::DataMode::Snapshot)
703		);
704
705		let cli: TestCli = parse(
706			&[],
707			&[
708				("format", string("json")),
709				("type", string("sensor_msgs/msg/Imu")),
710				("mode", string("stream")),
711			],
712		)
713		.unwrap();
714		assert_eq!(cli.format, Format::Json);
715		assert_eq!(cli.format.data(), Some(moqros::DataFormat::Json));
716		assert_eq!(cli.ros_type.as_deref(), Some("sensor_msgs/msg/Imu"));
717		assert_eq!(cli.mode, moqros::DataMode::Stream);
718
719		let cli: TestCli = parse(&["--format", "cdr", "--type", "std_msgs/msg/String"], &[]).unwrap();
720		assert_eq!(cli.format.data(), Some(moqros::DataFormat::Cdr));
721		assert_eq!(cli.ros_type.as_deref(), Some("std_msgs/msg/String"));
722		assert!(matches!(
723			parse::<TestCli>(&[], &[("format", string("xml"))]),
724			Err(ParseError::Param(_))
725		));
726	}
727
728	#[test]
729	fn command_line_overrides_params() {
730		let params = [
731			("topic", string("/param")),
732			("reliable", ParameterValue::Bool(true)),
733			("insecure", ParameterValue::Bool(false)),
734		];
735		let cli: TestCli = parse(&["--topic", "/flag", "--reliable=false", "--insecure"], &params).unwrap();
736		assert_eq!(cli.topic, "/flag");
737		assert!(!cli.qos.reliable);
738		assert!(cli.relay.insecure);
739	}
740
741	/// Setting a variable while other tests read the environment is undefined behavior,
742	/// so this test reruns itself in a child process for each value of the variable.
743	#[test]
744	fn params_override_env() {
745		const VAR: &str = "MOQROS_TEST_BITRATE";
746		let bitrate = ("bitrate", ParameterValue::Integer(2));
747		match std::env::var(VAR).ok().as_deref() {
748			None => {
749				for value in ["bogus", "4"] {
750					let output = std::process::Command::new(std::env::current_exe().unwrap())
751						.args(["--exact", "tests::params_override_env"])
752						.env(VAR, value)
753						.output()
754						.unwrap();
755					let stdout = String::from_utf8_lossy(&output.stdout);
756					assert!(
757						output.status.success() && stdout.contains("1 passed"),
758						"{VAR}={value}:\n{stdout}"
759					);
760				}
761			}
762			// An invalid variable is never looked at when a parameter or flag is set.
763			Some("bogus") => {
764				assert_eq!(parse::<EnvCli>(&[], std::slice::from_ref(&bitrate)).unwrap().bitrate, 2);
765				assert_eq!(parse::<EnvCli>(&["--bitrate", "3"], &[]).unwrap().bitrate, 3);
766				assert!(matches!(parse::<EnvCli>(&[], &[]), Err(ParseError::CommandLine(_))));
767				let help = help_or_version(EnvCli::command(), &args(&["--help"]));
768				assert_eq!(help.map(|err| err.kind()), Some(ErrorKind::DisplayHelp));
769			}
770			Some(value) => {
771				assert_eq!(value, "4");
772				assert_eq!(parse::<EnvCli>(&[], &[]).unwrap().bitrate, 4);
773				assert_eq!(parse::<EnvCli>(&[], std::slice::from_ref(&bitrate)).unwrap().bitrate, 2);
774				assert_eq!(parse::<EnvCli>(&["--bitrate=3"], &[bitrate]).unwrap().bitrate, 3);
775			}
776		}
777	}
778
779	#[test]
780	fn doubles_keep_their_fraction() {
781		let cli: TestCli = parse(
782			&[],
783			&[
784				("broadcast", ParameterValue::Double(1.0)),
785				("fps", ParameterValue::Double(12.5)),
786			],
787		)
788		.unwrap();
789		assert_eq!(cli.broadcast.as_deref(), Some("1.0"));
790		assert_eq!(cli.fps, 12.5);
791
792		// Whole numbers still fit integer flags.
793		let cli: TestCli = parse(&[], &[("keyframe_interval_ms", ParameterValue::Double(500.0))]).unwrap();
794		assert_eq!(cli.keyframe_interval_ms, 500);
795
796		// YAML `fps: 15` is an integer parameter.
797		let cli: TestCli = parse(&[], &[("fps", ParameterValue::Integer(15))]).unwrap();
798		assert_eq!(cli.fps, 15.0);
799	}
800
801	#[test]
802	fn values_starting_with_a_dash_stay_values() {
803		let cli: TestCli = parse(&[], &[("broadcast", string("-x"))]).unwrap();
804		assert_eq!(cli.broadcast.as_deref(), Some("-x"));
805	}
806
807	#[test]
808	fn unset_and_unknown_params_are_ignored() {
809		let params = [
810			("broadcast", ParameterValue::NotSet),
811			("use_sim_time", ParameterValue::Bool(false)),
812			("bitrat", ParameterValue::Integer(1)),
813			("keyframe-interval-ms", ParameterValue::Integer(1)),
814			// Clap's own arguments aren't parameters.
815			("help", ParameterValue::Bool(true)),
816			("version", string("2")),
817		];
818		assert!(flags::<TestCli>(&params).unwrap().is_empty());
819	}
820
821	#[test]
822	fn arrays_fill_repeatable_flags() {
823		let topics = |cli: MultiCli| cli.topic.into_iter().map(|spec| spec.topic).collect::<Vec<_>>();
824		assert_eq!(topics(parse(&[], &[]).unwrap()), ["/image_raw"]);
825		let params = [(
826			"topic",
827			ParameterValue::StringArray(vec!["/a".into(), "/b,format=json".into()]),
828		)];
829		let cli: MultiCli = parse(&[], &params).unwrap();
830		assert_eq!(cli.topic[1].format, Some(Format::Json));
831		assert_eq!(topics(cli), ["/a", "/b"]);
832		// A single string still works, and the command line replaces the whole list.
833		assert_eq!(topics(parse(&[], &[("topic", string("/c"))]).unwrap()), ["/c"]);
834		assert_eq!(topics(parse(&["--topic", "/d"], &params).unwrap()), ["/d"]);
835	}
836
837	#[test]
838	fn parses_topic_specs() {
839		let spec: TopicSpec = "/scan, format=cdr ,type=sensor_msgs/msg/LaserScan,mode=stream,broadcast=lidar"
840			.parse()
841			.unwrap();
842		assert_eq!(
843			spec,
844			TopicSpec {
845				topic: "/scan".into(),
846				format: Some(Format::Cdr),
847				ros_type: Some("sensor_msgs/msg/LaserScan".into()),
848				mode: Some(moqros::DataMode::Stream),
849				broadcast: Some("lidar".into()),
850			}
851		);
852		assert_eq!("/image_raw".parse::<TopicSpec>().unwrap().format, None);
853		for bad in [
854			"",
855			",format=json",
856			"/a,json",
857			"/a,codec=vp8",
858			"/a,format=xml",
859			"/a,mode=x",
860			"/a,type=x,type=y",
861		] {
862			assert!(bad.parse::<TopicSpec>().is_err(), "{bad:?}");
863		}
864
865		let spec: BroadcastSpec = "camera/image_raw,topic=/out,frame_id=cam,type=sensor_msgs/msg/Image"
866			.parse()
867			.unwrap();
868		assert_eq!(
869			(spec.broadcast.as_str(), spec.topic.as_deref(), spec.frame_id.as_deref()),
870			("camera/image_raw", Some("/out"), Some("cam"))
871		);
872		assert!("chatter,format=json".parse::<BroadcastSpec>().is_err());
873	}
874
875	#[test]
876	fn resolves_pub_topics() {
877		let specs = |specs: &[&str]| {
878			specs
879				.iter()
880				.map(|s| s.parse::<TopicSpec>().unwrap())
881				.collect::<Vec<_>>()
882		};
883		let snapshot = moqros::DataMode::Snapshot;
884
885		let topics = pub_topics(
886			specs(&[
887				"/camera/image_raw",
888				"/chatter,format=json",
889				"/log,mode=stream,broadcast=logs",
890			]),
891			Format::Video,
892			snapshot,
893			None,
894			None,
895		)
896		.unwrap();
897		let summary: Vec<_> = topics
898			.iter()
899			.map(|t| (t.broadcast.as_str(), t.format, t.mode))
900			.collect();
901		assert_eq!(
902			summary,
903			[
904				("camera/image_raw", Format::Video, snapshot),
905				("chatter", Format::Json, snapshot),
906				("logs", Format::Video, moqros::DataMode::Stream),
907			]
908		);
909
910		// Flags that name one topic.
911		let one = pub_topics(
912			specs(&["/a"]),
913			Format::Cdr,
914			snapshot,
915			Some("t/msg/T".into()),
916			Some("b".into()),
917		)
918		.unwrap();
919		assert_eq!(
920			(one[0].broadcast.as_str(), one[0].ros_type.as_deref()),
921			("b", Some("t/msg/T"))
922		);
923		assert!(
924			pub_topics(
925				specs(&["/a", "/b"]),
926				Format::Json,
927				snapshot,
928				Some("t/msg/T".into()),
929				None
930			)
931			.is_err()
932		);
933		assert!(pub_topics(specs(&["/a", "/b"]), Format::Json, snapshot, None, Some("b".into())).is_err());
934
935		assert!(pub_topics(specs(&["/a", "a,format=json"]), Format::Video, snapshot, None, None).is_err());
936		assert!(
937			pub_topics(
938				specs(&["/a,type=std_msgs/msg/String"]),
939				Format::Video,
940				snapshot,
941				None,
942				None
943			)
944			.is_err()
945		);
946		assert!(
947			pub_topics(
948				specs(&["/a,type=sensor_msgs/msg/Image"]),
949				Format::Video,
950				snapshot,
951				None,
952				None
953			)
954			.is_ok()
955		);
956		assert!(pub_topics(Vec::new(), Format::Video, snapshot, None, None).is_err());
957	}
958
959	#[test]
960	fn resolves_sub_broadcasts() {
961		let specs = |specs: &[&str]| {
962			specs
963				.iter()
964				.map(|s| s.parse::<BroadcastSpec>().unwrap())
965				.collect::<Vec<_>>()
966		};
967		let topics = |broadcasts: Vec<SubBroadcast>| broadcasts.into_iter().map(|b| b.topic).collect::<Vec<_>>();
968
969		assert_eq!(
970			topics(sub_broadcasts(specs(&["image_raw"]), None, None, "camera").unwrap()),
971			[DEFAULT_SUB_TOPIC]
972		);
973		assert_eq!(
974			topics(sub_broadcasts(specs(&["image_raw"]), Some("/x".into()), None, "camera").unwrap()),
975			["/x"]
976		);
977		let broadcasts = sub_broadcasts(
978			specs(&[
979				"sample/image_raw,topic=/moqros/image",
980				"chatter",
981				"/front/imu/,frame_id=imu",
982			]),
983			None,
984			None,
985			"camera",
986		)
987		.unwrap();
988		assert_eq!(broadcasts[2].frame_id, "imu");
989		assert_eq!(
990			topics(broadcasts),
991			["/moqros/image", "/moqros/chatter", "/moqros/front/imu"]
992		);
993
994		assert!(sub_broadcasts(specs(&["a", "b"]), Some("/x".into()), None, "camera").is_err());
995		assert!(sub_broadcasts(specs(&["a", "b"]), None, Some("t/msg/T".into()), "camera").is_err());
996		assert!(sub_broadcasts(specs(&["a,topic=/x", "b,topic=/x"]), None, None, "camera").is_err());
997	}
998
999	#[test]
1000	fn arrays_are_rejected() {
1001		let params = [("topic", ParameterValue::StringArray(vec!["/a".into()]))];
1002		let err = flags::<TestCli>(&params).unwrap_err();
1003		assert!(err.to_string().contains("`topic`"), "{err}");
1004	}
1005
1006	#[test]
1007	fn invalid_param_values_are_blamed_on_the_param() {
1008		for (name, value) in [("keyframe_interval_ms", "soon"), ("url", "not a url")] {
1009			match parse::<TestCli>(&[], &[(name, string(value))]) {
1010				Err(ParseError::Param(err)) => assert_eq!(err.kind(), ErrorKind::ValueValidation, "{name}"),
1011				other => panic!("{name}: {other:?}"),
1012			}
1013		}
1014	}
1015
1016	#[test]
1017	fn invalid_command_lines_are_blamed_on_the_command_line() {
1018		let params = [("keyframe_interval_ms", string("soon"))];
1019		for args in [&["--fps=fast"][..], &["--unknown"]] {
1020			assert!(
1021				matches!(parse::<TestCli>(args, &params), Err(ParseError::CommandLine(_))),
1022				"{args:?}"
1023			);
1024		}
1025	}
1026
1027	#[test]
1028	fn detects_help_and_version() {
1029		let kind = |args_: &[&str]| help_or_version(TestCli::command(), &args(args_)).map(|err| err.kind());
1030		assert_eq!(kind(&["--help"]), Some(ErrorKind::DisplayHelp));
1031		assert_eq!(kind(&["-V"]), Some(ErrorKind::DisplayVersion));
1032		// Arguments after the help flag aren't looked at.
1033		assert_eq!(kind(&["-h", "--fps=fast"]), Some(ErrorKind::DisplayHelp));
1034		assert_eq!(kind(&["--topic", "/a"]), None);
1035		assert_eq!(kind(&["--fps=fast"]), None);
1036	}
1037
1038	#[test]
1039	fn redacts_relay_url_secrets() {
1040		let redact = |url: &str| redact_url(&url.parse().unwrap()).to_string();
1041		assert_eq!(
1042			redact("https://relay.example/robot?jwt=eyJ.secret&a=1"),
1043			"https://relay.example/robot?jwt=REDACTED&a=1"
1044		);
1045		assert_eq!(
1046			redact("https://user:pass@relay.example/robot"),
1047			"https://user:REDACTED@relay.example/robot"
1048		);
1049		// URLs without secrets come back unchanged.
1050		for url in ["http://localhost:4443/anon", "https://relay.example/robot?a=1"] {
1051			assert_eq!(redact(url), url);
1052		}
1053	}
1054}