Skip to main content

moqros_cli/
lib.rs

1//! Shared plumbing for the moqros bridge binaries.
2
3use std::any::TypeId;
4use std::sync::Arc;
5use std::sync::atomic::{AtomicBool, Ordering};
6use std::time::Duration;
7
8use anyhow::{Context, bail};
9use clap::builder::BoolishValueParser;
10use clap::error::ErrorKind;
11use clap::{ArgAction, Args, Command, Parser};
12use moqros::ros::r2r::ParameterValue;
13use moqros::ros::{QosProfile, r2r};
14use tokio::task::JoinHandle;
15
16/// Relay connection flags.
17#[derive(Debug, Clone, Args)]
18pub struct RelayArgs {
19	/// Relay URL; its path scopes broadcast names.
20	#[arg(long, env = "MOQROS_URL", default_value = "http://localhost:4443/anon")]
21	pub url: moqros::Url,
22
23	/// Disable TLS certificate verification (development only).
24	#[arg(long, env = "MOQROS_INSECURE", action = ArgAction::Set, value_parser = BoolishValueParser::new(),
25		num_args = 0..=1, require_equals = true, default_value_t = false, default_missing_value = "true")]
26	pub insecure: bool,
27}
28
29impl RelayArgs {
30	pub fn config(&self) -> moqros::ClientConfig {
31		moqros::ClientConfig {
32			url: self.url.clone(),
33			insecure: self.insecure,
34		}
35	}
36}
37
38/// ROS QoS flags.
39#[derive(Debug, Clone, Args)]
40pub struct QosArgs {
41	/// Use reliable QoS instead of the best-effort sensor-data profile.
42	#[arg(long, action = ArgAction::Set, value_parser = BoolishValueParser::new(),
43		num_args = 0..=1, require_equals = true, default_value_t = false, default_missing_value = "true")]
44	pub reliable: bool,
45}
46
47impl QosArgs {
48	pub fn profile(&self) -> QosProfile {
49		if self.reliable {
50			QosProfile::default().keep_last(5)
51		} else {
52			QosProfile::sensor_data()
53		}
54	}
55}
56
57/// Create the ROS node and parse `T` from the command line and the node's ROS parameters.
58///
59/// Arguments between `--ros-args` and `--` are left to rcl, so the binaries accept
60/// remapping (`-r __node:=…`, `-r __ns:=…`), `-p` and `--params-file` like any ROS
61/// node. Each ROS parameter named after an argument (`bitrate`, `keyframe_interval_ms`,
62/// …) fills that argument: flags win over parameters, which win over environment
63/// variables and defaults.
64pub fn init<T: Parser>(node_name: &str) -> anyhow::Result<(T, r2r::Node)> {
65	let args = strip_ros_args(std::env::args());
66	// Answer `--help` and `--version` without bringing up ROS.
67	if let Some(err) = help_or_version(T::command(), &args) {
68		err.exit();
69	}
70
71	let ctx = r2r::Context::create().context("failed to create ROS context")?;
72	let node = r2r::Node::create(ctx, node_name, "").context("failed to create ROS node")?;
73
74	let flags = param_flags(
75		&T::command(),
76		node.params
77			.lock()
78			.unwrap()
79			.iter()
80			.map(|(name, param)| (name.as_str(), &param.value)),
81	)?;
82	let cli = match parse_args(args, flags) {
83		Ok(cli) => cli,
84		Err(ParseError::CommandLine(err)) => err.exit(),
85		Err(ParseError::Param(err)) => {
86			// Just clap's first line; its usage hints are about the command line.
87			let message = err.to_string();
88			let message = message.lines().next().unwrap_or_default().trim_start_matches("error: ");
89			bail!("invalid ROS parameter: {message}");
90		}
91	};
92	Ok((cli, node))
93}
94
95/// Drop the ROS arguments (`--ros-args … [--]`, possibly repeated) from `args`.
96pub fn strip_ros_args(args: impl IntoIterator<Item = String>) -> Vec<String> {
97	let mut in_ros_args = false;
98	args.into_iter()
99		.filter(|arg| match (in_ros_args, arg.as_str()) {
100			(false, "--ros-args") | (true, "--") => {
101				in_ros_args = !in_ros_args;
102				false
103			}
104			_ => !in_ros_args,
105		})
106		.collect()
107}
108
109/// The error to exit with if `args` ask for help or the version.
110///
111/// Clap answers these as soon as it meets the flag, before checking anything else.
112fn help_or_version(command: Command, args: &[String]) -> Option<clap::Error> {
113	let err = command.try_get_matches_from(args).err()?;
114	matches!(err.kind(), ErrorKind::DisplayHelp | ErrorKind::DisplayVersion).then_some(err)
115}
116
117/// Why [`parse_args`] failed.
118#[derive(Debug)]
119enum ParseError {
120	/// The command line itself is invalid.
121	CommandLine(clap::Error),
122	/// The command line is fine on its own, so a ROS parameter is invalid.
123	Param(clap::Error),
124}
125
126/// Parse `T` from `args` (program name first, ROS arguments already stripped) and
127/// `param_flags`.
128///
129/// The parameter flags go right after the program name. With `args_override_self` a
130/// later occurrence of a flag wins, so the command line overrides them, while
131/// environment variables and defaults only apply to flags given neither way.
132fn parse_args<T: Parser>(args: Vec<String>, param_flags: Vec<String>) -> Result<T, ParseError> {
133	let parse = |param_flags: Vec<String>| {
134		let mut args = args.iter().cloned();
135		let args = args.next().into_iter().chain(param_flags).chain(args);
136		let matches = T::command().args_override_self(true).try_get_matches_from(args)?;
137		T::from_arg_matches(&matches)
138	};
139	parse(param_flags).map_err(|err| match parse(Vec::new()) {
140		Ok(_) => ParseError::Param(err),
141		Err(err) => ParseError::CommandLine(err),
142	})
143}
144
145/// Command-line flags (`--name=value`) for the ROS parameters named after an argument
146/// of `command`.
147fn param_flags<'a>(
148	command: &Command,
149	params: impl IntoIterator<Item = (&'a str, &'a ParameterValue)>,
150) -> anyhow::Result<Vec<String>> {
151	let mut flags = Vec::new();
152	for (name, value) in params {
153		let Some((long, arg)) = command
154			.get_arguments()
155			.find(|arg| arg.get_id() == name)
156			.and_then(|arg| Some((arg.get_long()?, arg)))
157		else {
158			// r2r reads `use_sim_time` itself.
159			if name != "use_sim_time" {
160				tracing::warn!(name, "ignoring unknown ROS parameter");
161			}
162			continue;
163		};
164		let value = match value {
165			// An empty YAML value: leave the flag to its environment variable or default.
166			ParameterValue::NotSet => continue,
167			ParameterValue::Bool(value) => value.to_string(),
168			ParameterValue::Integer(value) => value.to_string(),
169			// Keep the fraction of whole numbers for strings (`1.0` stays `1.0`), but drop
170			// it for numbers so `2000000.0` still fits an integer flag.
171			ParameterValue::Double(value) if arg.get_value_parser().type_id() == TypeId::of::<String>() => {
172				format!("{value:?}")
173			}
174			ParameterValue::Double(value) => value.to_string(),
175			ParameterValue::String(value) => value.clone(),
176			value => bail!("ROS parameter `{name}` has unsupported type: {value:?}"),
177		};
178		// One token, so values starting with `-` aren't taken for flags.
179		flags.push(format!("--{long}={value}"));
180	}
181	Ok(flags)
182}
183
184pub fn init_logging() {
185	tracing_subscriber::fmt()
186		.with_env_filter(
187			tracing_subscriber::EnvFilter::try_from_default_env()
188				.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
189		)
190		.init();
191}
192
193/// Spin `node` on a blocking thread until the returned guard is dropped.
194///
195/// The tokio runtime waits for blocking tasks on shutdown, so a spinner that never
196/// stops would keep the process alive after `main` returns.
197pub fn spawn_spinner(mut node: r2r::Node) -> Spinner {
198	let stop = Arc::new(AtomicBool::new(false));
199	let stopped = stop.clone();
200	let task = tokio::task::spawn_blocking(move || {
201		while !stopped.load(Ordering::Relaxed) {
202			node.spin_once(Duration::from_millis(50));
203		}
204	});
205	Spinner { stop, task: Some(task) }
206}
207
208/// Stops the [`spawn_spinner`] thread when dropped.
209pub struct Spinner {
210	stop: Arc<AtomicBool>,
211	task: Option<JoinHandle<()>>,
212}
213
214impl Spinner {
215	/// Resolves if the spinner thread dies, which only happens when it panics, since
216	/// without spinning no ROS message arrives anymore. Never resolves again after that.
217	pub async fn failed(&mut self) -> anyhow::Error {
218		let Some(task) = self.task.as_mut() else {
219			return std::future::pending().await;
220		};
221		let result = task.await;
222		self.task = None;
223		match result {
224			Err(err) => anyhow::Error::new(err).context("ROS spinner failed"),
225			Ok(()) => anyhow::anyhow!("ROS spinner stopped"),
226		}
227	}
228}
229
230impl Drop for Spinner {
231	fn drop(&mut self) {
232		self.stop.store(true, Ordering::Relaxed);
233	}
234}
235
236#[cfg(test)]
237mod tests {
238	use clap::CommandFactory;
239
240	use super::*;
241
242	fn strip(args: &[&str]) -> Vec<String> {
243		strip_ros_args(args.iter().map(|arg| arg.to_string()))
244	}
245
246	#[derive(Debug, Parser)]
247	#[command(version = "1.2.3")]
248	struct TestCli {
249		#[arg(long, default_value = "/image_raw")]
250		topic: String,
251
252		#[arg(long)]
253		broadcast: Option<String>,
254
255		#[arg(long, default_value_t = 30.0)]
256		fps: f32,
257
258		#[arg(long, default_value_t = 2000)]
259		keyframe_interval_ms: u64,
260
261		#[command(flatten)]
262		relay: RelayArgs,
263
264		#[command(flatten)]
265		qos: QosArgs,
266	}
267
268	/// Only parsed by `params_override_env`, in a child process of its own.
269	#[derive(Debug, Parser)]
270	struct EnvCli {
271		#[arg(long, env = "MOQROS_TEST_BITRATE", default_value_t = 1)]
272		bitrate: u32,
273	}
274
275	fn flags<T: Parser>(params: &[(&str, ParameterValue)]) -> anyhow::Result<Vec<String>> {
276		param_flags(&T::command(), params.iter().map(|(name, value)| (*name, value)))
277	}
278
279	fn args(args: &[&str]) -> Vec<String> {
280		std::iter::once("bin")
281			.chain(args.iter().copied())
282			.map(String::from)
283			.collect()
284	}
285
286	fn parse<T: Parser>(args_: &[&str], params: &[(&str, ParameterValue)]) -> Result<T, ParseError> {
287		parse_args(args(args_), flags::<T>(params).unwrap())
288	}
289
290	fn string(value: &str) -> ParameterValue {
291		ParameterValue::String(value.to_string())
292	}
293
294	#[test]
295	fn strips_ros_args() {
296		assert_eq!(strip(&["bin", "--topic", "a"]), ["bin", "--topic", "a"]);
297		assert_eq!(
298			strip(&[
299				"bin",
300				"--topic",
301				"a",
302				"--ros-args",
303				"-r",
304				"__node:=n",
305				"-p",
306				"bitrate:=1"
307			]),
308			["bin", "--topic", "a"]
309		);
310		assert_eq!(
311			strip(&[
312				"bin",
313				"--ros-args",
314				"-r",
315				"__ns:=/x",
316				"--",
317				"--reliable",
318				"--ros-args",
319				"-p",
320				"a:=1"
321			]),
322			["bin", "--reliable"]
323		);
324	}
325
326	#[test]
327	fn params_fill_flags() {
328		let cli: TestCli = parse(
329			&[],
330			&[
331				("topic", string("/front/image_raw")),
332				("keyframe_interval_ms", ParameterValue::Integer(500)),
333				("reliable", ParameterValue::Bool(true)),
334				("url", string("http://relay:4443/anon")),
335			],
336		)
337		.unwrap();
338		assert_eq!(cli.topic, "/front/image_raw");
339		assert_eq!(cli.keyframe_interval_ms, 500);
340		assert!(cli.qos.reliable);
341		assert_eq!(cli.relay.url.as_str(), "http://relay:4443/anon");
342		assert!(!cli.relay.insecure);
343		assert_eq!(cli.broadcast, None);
344	}
345
346	#[test]
347	fn command_line_overrides_params() {
348		let params = [
349			("topic", string("/param")),
350			("reliable", ParameterValue::Bool(true)),
351			("insecure", ParameterValue::Bool(false)),
352		];
353		let cli: TestCli = parse(&["--topic", "/flag", "--reliable=false", "--insecure"], &params).unwrap();
354		assert_eq!(cli.topic, "/flag");
355		assert!(!cli.qos.reliable);
356		assert!(cli.relay.insecure);
357	}
358
359	/// Setting a variable while other tests read the environment is undefined behavior,
360	/// so this test reruns itself in a child process for each value of the variable.
361	#[test]
362	fn params_override_env() {
363		const VAR: &str = "MOQROS_TEST_BITRATE";
364		let bitrate = ("bitrate", ParameterValue::Integer(2));
365		match std::env::var(VAR).ok().as_deref() {
366			None => {
367				for value in ["bogus", "4"] {
368					let output = std::process::Command::new(std::env::current_exe().unwrap())
369						.args(["--exact", "tests::params_override_env"])
370						.env(VAR, value)
371						.output()
372						.unwrap();
373					let stdout = String::from_utf8_lossy(&output.stdout);
374					assert!(
375						output.status.success() && stdout.contains("1 passed"),
376						"{VAR}={value}:\n{stdout}"
377					);
378				}
379			}
380			// An invalid variable is never looked at when a parameter or flag is set.
381			Some("bogus") => {
382				assert_eq!(parse::<EnvCli>(&[], std::slice::from_ref(&bitrate)).unwrap().bitrate, 2);
383				assert_eq!(parse::<EnvCli>(&["--bitrate", "3"], &[]).unwrap().bitrate, 3);
384				assert!(matches!(parse::<EnvCli>(&[], &[]), Err(ParseError::CommandLine(_))));
385				let help = help_or_version(EnvCli::command(), &args(&["--help"]));
386				assert_eq!(help.map(|err| err.kind()), Some(ErrorKind::DisplayHelp));
387			}
388			Some(value) => {
389				assert_eq!(value, "4");
390				assert_eq!(parse::<EnvCli>(&[], &[]).unwrap().bitrate, 4);
391				assert_eq!(parse::<EnvCli>(&[], std::slice::from_ref(&bitrate)).unwrap().bitrate, 2);
392				assert_eq!(parse::<EnvCli>(&["--bitrate=3"], &[bitrate]).unwrap().bitrate, 3);
393			}
394		}
395	}
396
397	#[test]
398	fn doubles_keep_their_fraction() {
399		let cli: TestCli = parse(
400			&[],
401			&[
402				("broadcast", ParameterValue::Double(1.0)),
403				("fps", ParameterValue::Double(12.5)),
404			],
405		)
406		.unwrap();
407		assert_eq!(cli.broadcast.as_deref(), Some("1.0"));
408		assert_eq!(cli.fps, 12.5);
409
410		// Whole numbers still fit integer flags.
411		let cli: TestCli = parse(&[], &[("keyframe_interval_ms", ParameterValue::Double(500.0))]).unwrap();
412		assert_eq!(cli.keyframe_interval_ms, 500);
413
414		// YAML `fps: 15` is an integer parameter.
415		let cli: TestCli = parse(&[], &[("fps", ParameterValue::Integer(15))]).unwrap();
416		assert_eq!(cli.fps, 15.0);
417	}
418
419	#[test]
420	fn values_starting_with_a_dash_stay_values() {
421		let cli: TestCli = parse(&[], &[("broadcast", string("-x"))]).unwrap();
422		assert_eq!(cli.broadcast.as_deref(), Some("-x"));
423	}
424
425	#[test]
426	fn unset_and_unknown_params_are_ignored() {
427		let params = [
428			("broadcast", ParameterValue::NotSet),
429			("use_sim_time", ParameterValue::Bool(false)),
430			("bitrat", ParameterValue::Integer(1)),
431			("keyframe-interval-ms", ParameterValue::Integer(1)),
432			// Clap's own arguments aren't parameters.
433			("help", ParameterValue::Bool(true)),
434			("version", string("2")),
435		];
436		assert!(flags::<TestCli>(&params).unwrap().is_empty());
437	}
438
439	#[test]
440	fn arrays_are_rejected() {
441		let params = [("topic", ParameterValue::StringArray(vec!["/a".into()]))];
442		let err = flags::<TestCli>(&params).unwrap_err();
443		assert!(err.to_string().contains("`topic`"), "{err}");
444	}
445
446	#[test]
447	fn invalid_param_values_are_blamed_on_the_param() {
448		for (name, value) in [("keyframe_interval_ms", "soon"), ("url", "not a url")] {
449			match parse::<TestCli>(&[], &[(name, string(value))]) {
450				Err(ParseError::Param(err)) => assert_eq!(err.kind(), ErrorKind::ValueValidation, "{name}"),
451				other => panic!("{name}: {other:?}"),
452			}
453		}
454	}
455
456	#[test]
457	fn invalid_command_lines_are_blamed_on_the_command_line() {
458		let params = [("keyframe_interval_ms", string("soon"))];
459		for args in [&["--fps=fast"][..], &["--unknown"]] {
460			assert!(
461				matches!(parse::<TestCli>(args, &params), Err(ParseError::CommandLine(_))),
462				"{args:?}"
463			);
464		}
465	}
466
467	#[test]
468	fn detects_help_and_version() {
469		let kind = |args_: &[&str]| help_or_version(TestCli::command(), &args(args_)).map(|err| err.kind());
470		assert_eq!(kind(&["--help"]), Some(ErrorKind::DisplayHelp));
471		assert_eq!(kind(&["-V"]), Some(ErrorKind::DisplayVersion));
472		// Arguments after the help flag aren't looked at.
473		assert_eq!(kind(&["-h", "--fps=fast"]), Some(ErrorKind::DisplayHelp));
474		assert_eq!(kind(&["--topic", "/a"]), None);
475		assert_eq!(kind(&["--fps=fast"]), None);
476	}
477}