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