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 futures::StreamExt;
16use moqros::ros::r2r::ParameterValue;
17use moqros::ros::{MoqToRos, QosProfile, ROS_IMAGE_TYPE, r2r};
18use tokio::task::JoinHandle;
19
20/// Relay connection flags.
21#[derive(Debug, Clone, Args)]
22pub struct RelayArgs {
23	/// Relay URL; its path scopes broadcast names.
24	#[arg(long, env = "MOQROS_URL", default_value = "http://localhost:4443/anon")]
25	pub url: moqros::Url,
26
27	/// Disable TLS certificate verification (development only).
28	#[arg(long, env = "MOQROS_INSECURE", action = ArgAction::Set, value_parser = BoolishValueParser::new(),
29		num_args = 0..=1, require_equals = true, default_value_t = false, default_missing_value = "true")]
30	pub insecure: bool,
31
32	/// PEM client certificate chain to present to the relay (mTLS).
33	#[arg(long, env = "MOQROS_TLS_CERT", requires = "tls_key")]
34	pub tls_cert: Option<PathBuf>,
35
36	/// PEM private key of `--tls-cert`.
37	#[arg(long, env = "MOQROS_TLS_KEY", requires = "tls_cert")]
38	pub tls_key: Option<PathBuf>,
39}
40
41impl RelayArgs {
42	pub fn config(&self) -> moqros::ClientConfig {
43		moqros::ClientConfig {
44			url: self.url.clone(),
45			insecure: self.insecure,
46			tls_cert: self.tls_cert.clone(),
47			tls_key: self.tls_key.clone(),
48		}
49	}
50
51	/// The relay URL with its tokens and password hidden, for logging.
52	pub fn redacted_url(&self) -> moqros::Url {
53		redact_url(&self.url)
54	}
55
56	/// Log a warning if these settings let anyone on the network path read or alter the stream.
57	pub fn warn_if_insecure(&self) {
58		if let Some(reason) = insecurity(&self.url, self.insecure) {
59			tracing::warn!("{reason}; anyone on the network path can read or alter the stream");
60		}
61	}
62}
63
64/// Why connecting to `url` doesn't authenticate the relay, unless it's a development setup
65/// on this machine.
66fn insecurity(url: &moqros::Url, insecure: bool) -> Option<&'static str> {
67	if insecure {
68		return Some("--insecure skips TLS certificate verification");
69	}
70	let loopback = url.host_str().is_some_and(|host| {
71		host == "localhost"
72			|| host.ends_with(".localhost")
73			|| host
74				.trim_matches(['[', ']'])
75				.parse::<std::net::IpAddr>()
76				.is_ok_and(|ip| ip.is_loopback())
77	});
78	(url.scheme() == "http" && !loopback).then_some(
79		"an http:// relay URL fetches the certificate fingerprint over plain HTTP; use https:// outside development",
80	)
81}
82
83fn redact_url(url: &moqros::Url) -> moqros::Url {
84	const REDACTED: &str = "REDACTED";
85	let mut url = url.clone();
86	if url.password().is_some() {
87		let _ = url.set_password(Some(REDACTED));
88	}
89	// Some relays (e.g. Cloudflare) take the token as a path segment instead of `?jwt=`.
90	if url.path_segments().is_some_and(|mut segments| segments.any(is_jwt)) {
91		let path = url
92			.path_segments()
93			.into_iter()
94			.flatten()
95			.map(|segment| if is_jwt(segment) { REDACTED } else { segment })
96			.collect::<Vec<_>>()
97			.join("/");
98		url.set_path(&path);
99	}
100	if url.query_pairs().any(|(key, _)| key == "jwt") {
101		let pairs: Vec<(String, String)> = url
102			.query_pairs()
103			.map(|(key, value)| {
104				let value = if key == "jwt" {
105					REDACTED.into()
106				} else {
107					value.into_owned()
108				};
109				(key.into_owned(), value)
110			})
111			.collect();
112		url.query_pairs_mut().clear().extend_pairs(pairs);
113	}
114	url
115}
116
117/// Whether a path segment looks like a JWT: three base64url parts, the first a JSON header (`eyJ`).
118fn is_jwt(segment: &str) -> bool {
119	segment.starts_with("eyJ")
120		&& segment.split('.').count() == 3
121		&& segment
122			.bytes()
123			.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
124}
125
126/// What `moqros-pub` sends.
127#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
128pub enum Format {
129	/// Encode `sensor_msgs/msg/Image` messages as video.
130	Video,
131	/// Any message type, as one JSON document per message.
132	Json,
133	/// Any message type, in its ROS serialization (CDR).
134	Cdr,
135}
136
137impl Format {
138	/// The data track format, or `None` for video.
139	pub fn data(self) -> Option<moqros::DataFormat> {
140		match self {
141			Self::Video => None,
142			Self::Json => Some(moqros::DataFormat::Json),
143			Self::Cdr => Some(moqros::DataFormat::Cdr),
144		}
145	}
146}
147
148/// `NAME[,key=value...]` split into the name and its options.
149type Spec<'a> = (&'a str, Vec<(&'a str, &'a str)>);
150
151/// Split `NAME[,key=value...]` into the name and its options, rejecting keys not in `keys`.
152fn split_spec<'a>(spec: &'a str, keys: &[&str]) -> Result<Spec<'a>, String> {
153	let mut parts = spec.split(',');
154	let name = parts.next().unwrap_or_default().trim();
155	if name.is_empty() {
156		return Err(format!("{spec:?} doesn't start with a name"));
157	}
158	let mut options: Vec<(&str, &str)> = Vec::new();
159	for part in parts {
160		let (key, value) = part
161			.split_once('=')
162			.ok_or_else(|| format!("expected key=value, got {part:?}"))?;
163		let (key, value) = (key.trim(), value.trim());
164		if !keys.contains(&key) {
165			return Err(format!("unknown option {key:?} (expected one of: {})", keys.join(", ")));
166		}
167		if options.iter().any(|(k, _)| *k == key) {
168			return Err(format!("option {key:?} given twice"));
169		}
170		options.push((key, value));
171	}
172	Ok((name, options))
173}
174
175/// A topic for `moqros-pub`: `TOPIC[,format=…][,type=…][,mode=…][,broadcast=…]`.
176///
177/// Options left out fall back to the matching command-line flags.
178#[derive(Debug, Clone, PartialEq, Eq)]
179pub struct TopicSpec {
180	pub topic: String,
181	pub format: Option<Format>,
182	pub ros_type: Option<String>,
183	pub mode: Option<moqros::DataMode>,
184	pub broadcast: Option<String>,
185}
186
187impl FromStr for TopicSpec {
188	type Err = String;
189
190	fn from_str(spec: &str) -> Result<Self, String> {
191		let (topic, options) = split_spec(spec, &["format", "type", "mode", "broadcast"])?;
192		let mut parsed = Self {
193			topic: topic.to_string(),
194			format: None,
195			ros_type: None,
196			mode: None,
197			broadcast: None,
198		};
199		for (key, value) in options {
200			match key {
201				"format" => parsed.format = Some(Format::from_str(value, true)?),
202				"type" => parsed.ros_type = Some(value.to_string()),
203				"mode" => parsed.mode = Some(value.parse().map_err(|err| format!("{err}"))?),
204				_ => parsed.broadcast = Some(value.to_string()),
205			}
206		}
207		Ok(parsed)
208	}
209}
210
211/// What `moqros-pub` does with one topic.
212#[derive(Debug, Clone, PartialEq, Eq)]
213pub struct PubTopic {
214	pub topic: String,
215	pub broadcast: String,
216	pub format: Format,
217	pub mode: moqros::DataMode,
218	/// Looked up in the ROS graph when `None` (unless the format is video).
219	pub ros_type: Option<String>,
220}
221
222/// Fill in each topic's options from the flags: `format` and `mode` apply to every topic,
223/// while `ros_type` and `broadcast` name one topic, so they need exactly one.
224pub fn pub_topics(
225	specs: Vec<TopicSpec>,
226	format: Format,
227	mode: moqros::DataMode,
228	ros_type: Option<String>,
229	broadcast: Option<String>,
230) -> anyhow::Result<Vec<PubTopic>> {
231	ensure!(!specs.is_empty(), "no topic to publish");
232	ensure!(
233		specs.len() == 1 || (ros_type.is_none() && broadcast.is_none()),
234		"--type and --broadcast need a single --topic; give several topics `type=` and `broadcast=` options instead"
235	);
236	let mut broadcasts = HashSet::new();
237	specs
238		.into_iter()
239		.map(|spec| {
240			let topic = PubTopic {
241				broadcast: spec
242					.broadcast
243					.or(broadcast.clone())
244					.unwrap_or_else(|| moqros::broadcast_name_for_topic(&spec.topic)),
245				format: spec.format.unwrap_or(format),
246				mode: spec.mode.unwrap_or(mode),
247				ros_type: spec.ros_type.or(ros_type.clone()),
248				topic: spec.topic,
249			};
250			if topic.format == Format::Video
251				&& let Some(ros_type) = topic.ros_type.as_deref().filter(|t| *t != ROS_IMAGE_TYPE)
252			{
253				bail!(
254					"{}: video needs {ROS_IMAGE_TYPE} messages, not {ros_type}; use format=json or cdr",
255					topic.topic
256				);
257			}
258			ensure!(
259				broadcasts.insert(topic.broadcast.clone()),
260				"several topics publish the broadcast {:?}",
261				topic.broadcast
262			);
263			Ok(topic)
264		})
265		.collect()
266}
267
268/// A broadcast for `moqros-sub`: `BROADCAST[,topic=…][,type=…][,frame_id=…]`.
269///
270/// Options left out fall back to the matching command-line flags.
271#[derive(Debug, Clone, PartialEq, Eq)]
272pub struct BroadcastSpec {
273	pub broadcast: String,
274	pub topic: Option<String>,
275	pub ros_type: Option<String>,
276	pub frame_id: Option<String>,
277}
278
279impl FromStr for BroadcastSpec {
280	type Err = String;
281
282	fn from_str(spec: &str) -> Result<Self, String> {
283		let (broadcast, options) = split_spec(spec, &["topic", "type", "frame_id"])?;
284		let mut parsed = Self {
285			broadcast: broadcast.to_string(),
286			topic: None,
287			ros_type: None,
288			frame_id: None,
289		};
290		for (key, value) in options {
291			let value = Some(value.to_string());
292			match key {
293				"topic" => parsed.topic = value,
294				"type" => parsed.ros_type = value,
295				_ => parsed.frame_id = value,
296			}
297		}
298		Ok(parsed)
299	}
300}
301
302/// What `moqros-sub` does with one broadcast.
303#[derive(Debug, Clone, PartialEq, Eq)]
304pub struct SubBroadcast {
305	pub broadcast: String,
306	pub topic: String,
307	/// Taken from the catalog when `None`.
308	pub ros_type: Option<String>,
309	pub frame_id: String,
310}
311
312/// Topic of a lone broadcast that neither `topic=` nor `--topic` names.
313pub const DEFAULT_SUB_TOPIC: &str = "/moqros/image";
314
315/// Fill in each broadcast's options from the flags. `topic` and `ros_type` name one
316/// broadcast, so they need exactly one. Without either `topic=` or `--topic`, a lone
317/// broadcast goes to [`DEFAULT_SUB_TOPIC`], and each of several to `/moqros/<broadcast>`.
318pub fn sub_broadcasts(
319	specs: Vec<BroadcastSpec>,
320	topic: Option<String>,
321	ros_type: Option<String>,
322	frame_id: &str,
323) -> anyhow::Result<Vec<SubBroadcast>> {
324	ensure!(!specs.is_empty(), "no broadcast to subscribe to");
325	let single = specs.len() == 1;
326	ensure!(
327		single || (topic.is_none() && ros_type.is_none()),
328		"--topic and --type need a single --broadcast; give several broadcasts `topic=` and `type=` options instead"
329	);
330	let mut topics = HashSet::new();
331	specs
332		.into_iter()
333		.map(|spec| {
334			let broadcast = SubBroadcast {
335				topic: spec.topic.or(topic.clone()).unwrap_or_else(|| match single {
336					true => DEFAULT_SUB_TOPIC.to_string(),
337					false => format!("/moqros/{}", spec.broadcast.trim_matches('/')),
338				}),
339				ros_type: spec.ros_type.or(ros_type.clone()),
340				frame_id: spec.frame_id.unwrap_or_else(|| frame_id.to_string()),
341				broadcast: spec.broadcast,
342			};
343			ensure!(
344				topics.insert(broadcast.topic.clone()),
345				"several broadcasts publish on {}",
346				broadcast.topic
347			);
348			Ok(broadcast)
349		})
350		.collect()
351}
352
353/// What a bridge node does: ROS topics to publish to the relay, and broadcasts to republish
354/// on ROS.
355pub struct Bridges {
356	pub topics: Vec<PubTopic>,
357	pub broadcasts: Vec<SubBroadcast>,
358	/// For video topics.
359	pub encoder: moqros::EncoderSettings,
360	pub qos: QosProfile,
361}
362
363/// The relay connection of a bridge node: a publisher for its topics, a subscriber for its
364/// broadcasts, or both over one connection.
365pub struct Relay {
366	publisher: Option<moqros::Publisher>,
367	subscriber: Option<moqros::Subscriber>,
368}
369
370impl Relay {
371	/// For a node that only has topics.
372	pub fn publisher(publisher: moqros::Publisher) -> Self {
373		Self {
374			publisher: Some(publisher),
375			subscriber: None,
376		}
377	}
378
379	/// For a node that only has broadcasts.
380	pub fn subscriber(subscriber: moqros::Subscriber) -> Self {
381		Self {
382			publisher: None,
383			subscriber: Some(subscriber),
384		}
385	}
386
387	/// Both directions over the one connection [`moqros::connect_both`] returns.
388	pub fn both(publisher: moqros::Publisher, subscriber: moqros::Subscriber) -> Self {
389		Self {
390			publisher: Some(publisher),
391			subscriber: Some(subscriber),
392		}
393	}
394
395	// Both handles share one connection, so either one stands for it.
396	async fn closed(&self) -> moqros::Result<()> {
397		match (&self.publisher, &self.subscriber) {
398			(Some(publisher), _) => publisher.closed().await,
399			(None, Some(subscriber)) => subscriber.closed().await,
400			(None, None) => std::future::pending().await,
401		}
402	}
403
404	async fn close(&self) -> moqros::Result<()> {
405		match (&self.publisher, &self.subscriber) {
406			(Some(publisher), _) => publisher.close().await,
407			(None, Some(subscriber)) => subscriber.close().await,
408			(None, None) => Ok(()),
409		}
410	}
411}
412
413/// Run `bridges` until one of them ends, the relay connection gives up, or SIGINT or SIGTERM
414/// arrives (which closes the connection first, so the relay ends this node's broadcasts and
415/// subscriptions right away).
416///
417/// Video topics start at once. A data topic without a type starts when it appears in the ROS
418/// graph. Broadcasts are waited for all at once, each starting when it's announced; one whose
419/// topic can't be created (e.g. a message type without bindings) is skipped.
420pub async fn run_bridges(node: r2r::Node, relay: Relay, bridges: Bridges) -> anyhow::Result<()> {
421	let Bridges {
422		topics: mut pending,
423		broadcasts,
424		encoder,
425		qos,
426	} = bridges;
427	ensure!(
428		pending.is_empty() || relay.publisher.is_some(),
429		"topics to publish need a publisher"
430	);
431	ensure!(
432		broadcasts.is_empty() || relay.subscriber.is_some(),
433		"broadcasts to republish need a subscriber"
434	);
435
436	let node = SharedNode::new(node);
437	// Only the ROS -> MoQ side subscribes to anything; a node that only publishes has
438	// nothing to spin for.
439	let mut spinner = match pending.is_empty() {
440		true => Spinner::idle(),
441		false => spawn_spinner(node.clone()),
442	};
443
444	// A topic's type depends on what its broadcast carries, so wait for each broadcast
445	// (all at once) before creating its publisher.
446	let mut subscribing: futures::stream::FuturesUnordered<_> = broadcasts
447		.into_iter()
448		.filter_map(|broadcast| {
449			let subscriber = relay.subscriber.clone()?;
450			Some(async move { (MoqToRos::subscribe(subscriber, &broadcast.broadcast).await, broadcast) })
451		})
452		.collect();
453	let mut pub_bridges = futures::stream::FuturesUnordered::new();
454	let mut sub_bridges = futures::stream::FuturesUnordered::new();
455	let mut logged = false;
456	// Created once, so a signal arriving while the loop body runs isn't missed.
457	let shutdown = shutdown_signal();
458	tokio::pin!(shutdown);
459
460	loop {
461		// Start every topic whose type is known by now; data topics without a `type`
462		// wait until something publishes them.
463		if let Some(publisher) = &relay.publisher {
464			let mut waiting = Vec::new();
465			for topic in std::mem::take(&mut pending) {
466				match node.with(|node| start_pub_topic(node, publisher, &topic, &encoder, qos.clone()))? {
467					Some(bridge) => {
468						let topic_name = topic.topic.clone();
469						pub_bridges.push(async move { (topic_name, bridge.await) });
470					}
471					None => {
472						waiting.push(topic.topic.clone());
473						pending.push(topic);
474					}
475				}
476			}
477			if !waiting.is_empty() && !logged {
478				tracing::info!(topics = ?waiting, "waiting for topics to appear to learn their types");
479				logged = true;
480			}
481		}
482
483		tokio::select! {
484			Some((ready, broadcast)) = subscribing.next() => {
485				match node.with(|node| spawn_sub_broadcast(ready, node, &broadcast, qos.clone())) {
486					Ok(bridge) => sub_bridges.push(async move { (broadcast.broadcast, bridge.await) }),
487					// E.g. a message type this build has no bindings for: the other
488					// broadcasts and topics can still go on.
489					Err(err) => {
490						tracing::error!(%err, broadcast = broadcast.broadcast, topic = broadcast.topic, "skipping broadcast");
491						if subscribing.is_empty() && sub_bridges.is_empty() && pub_bridges.is_empty() && pending.is_empty() {
492							bail!("nothing left to bridge: no broadcast could be republished");
493						}
494					}
495				}
496			}
497			Some((topic, res)) = pub_bridges.next() => {
498				let stats = res.context("bridge panicked")??;
499				tracing::info!(topic, ?stats, "topic stream ended");
500				return Ok(());
501			}
502			Some((broadcast, res)) = sub_bridges.next() => {
503				res.context("bridge panicked")?.with_context(|| format!("broadcast {broadcast}"))?;
504				return Ok(());
505			}
506			_ = tokio::time::sleep(Duration::from_millis(500)), if !pending.is_empty() => {}
507			// E.g. the relay refused the session: nothing would ever be announced.
508			res = relay.closed() => return res.context("relay connection closed"),
509			err = spinner.failed() => return Err(err),
510			res = &mut shutdown => {
511				tracing::info!(signal = res?, "shutting down");
512				if let Err(err) = relay.close().await {
513					tracing::warn!(%err, "the relay connection didn't close cleanly");
514				}
515				return Ok(());
516			}
517		}
518	}
519}
520
521/// Refuse a bridge that would feed its own output back in: a broadcast or a ROS topic that
522/// both directions use. Every message would go round the loop forever.
523pub fn check_no_loop(topics: &[PubTopic], broadcasts: &[SubBroadcast]) -> anyhow::Result<()> {
524	let name = |name: &str| name.trim_matches('/').to_string();
525	for topic in topics {
526		for broadcast in broadcasts {
527			ensure!(
528				name(&topic.broadcast) != name(&broadcast.broadcast),
529				"the broadcast {:?} is both published (from {}) and subscribed to; that would loop",
530				topic.broadcast,
531				topic.topic
532			);
533			ensure!(
534				name(&topic.topic) != name(&broadcast.topic),
535				"the topic {} is both published to the relay and republished from {:?}; that would loop",
536				topic.topic,
537				broadcast.broadcast
538			);
539		}
540	}
541	Ok(())
542}
543
544/// ROS QoS flags.
545#[derive(Debug, Clone, Args)]
546pub struct QosArgs {
547	/// Use reliable QoS instead of the best-effort sensor-data profile.
548	#[arg(long, action = ArgAction::Set, value_parser = BoolishValueParser::new(),
549		num_args = 0..=1, require_equals = true, default_value_t = false, default_missing_value = "true")]
550	pub reliable: bool,
551}
552
553impl QosArgs {
554	pub fn profile(&self) -> QosProfile {
555		if self.reliable {
556			QosProfile::default().keep_last(5)
557		} else {
558			QosProfile::sensor_data()
559		}
560	}
561}
562
563/// Video encoder flags.
564#[derive(Debug, Clone, Args)]
565pub struct EncoderArgs {
566	/// Video codec: `vp8`, `av1` (built with the `av1` feature), or `h264` (built with the
567	/// `h264` feature, with OPENH264_LIBRARY pointing at Cisco's OpenH264 binary).
568	#[arg(long, default_value_t = moqros::Codec::default())]
569	pub codec: moqros::Codec,
570
571	/// Hardware video encoding (built with the `hw` feature): `auto` uses a VA-API or NVENC
572	/// encoder through GStreamer when one works and falls back to software, `off` always
573	/// encodes in software, and `require` fails without a hardware encoder.
574	#[arg(long, default_value_t = moqros::Hardware::default())]
575	pub hw: moqros::Hardware,
576
577	/// Target video bitrate in bits per second.
578	#[arg(long, default_value_t = 2_000_000)]
579	pub bitrate: u32,
580
581	/// Expected maximum input frame rate of the video.
582	#[arg(long, default_value_t = 30.0)]
583	pub fps: f32,
584
585	/// Maximum keyframe (MoQ group) interval of the video in milliseconds.
586	#[arg(long, default_value_t = 2000)]
587	pub keyframe_interval_ms: u64,
588}
589
590impl EncoderArgs {
591	pub fn settings(&self) -> moqros::EncoderSettings {
592		moqros::EncoderSettings {
593			codec: self.codec,
594			bitrate: self.bitrate,
595			max_fps: self.fps,
596			keyframe_interval: Duration::from_millis(self.keyframe_interval_ms),
597			hardware: self.hw,
598			..Default::default()
599		}
600	}
601}
602
603/// A running ROS -> MoQ bridge task.
604type PubBridge = JoinHandle<moqros::Result<moqros::ros::BridgeStats>>;
605
606/// Start bridging `topic` from ROS to MoQ once its type is known. Returns `None` while
607/// the topic hasn't appeared in the ROS graph yet.
608fn start_pub_topic(
609	node: &mut r2r::Node,
610	publisher: &moqros::Publisher,
611	topic: &PubTopic,
612	encoder: &moqros::EncoderSettings,
613	qos: QosProfile,
614) -> anyhow::Result<Option<PubBridge>> {
615	let bridge = match topic.format.data() {
616		None => {
617			let images = publisher.create_image_broadcast(&topic.broadcast, encoder.clone())?;
618			moqros::ros::spawn_ros_to_moq(node, &topic.topic, qos, images)?
619		}
620		Some(format) => {
621			let ros_type = match &topic.ros_type {
622				Some(ros_type) => ros_type.clone(),
623				None => match moqros::ros::topic_type(node, &topic.topic)? {
624					Some(ros_type) => ros_type,
625					None => return Ok(None),
626				},
627			};
628			let settings = moqros::DataSettings {
629				format,
630				mode: topic.mode,
631				ros_type: Some(ros_type),
632			};
633			let data = publisher.create_data_broadcast(&topic.broadcast, settings)?;
634			moqros::ros::spawn_ros_to_moq_data(node, &topic.topic, qos, data)?
635		}
636	};
637	tracing::info!(
638		topic = topic.topic,
639		format = ?topic.format,
640		broadcast = topic.broadcast,
641		"bridging ROS -> MoQ"
642	);
643	Ok(Some(bridge))
644}
645
646/// A running MoQ -> ROS bridge task.
647type SubBridge = JoinHandle<moqros::Result<()>>;
648
649/// Create the ROS publisher for a subscribed broadcast and start republishing it.
650fn spawn_sub_broadcast(
651	ready: moqros::ros::MoqToRos,
652	node: &mut r2r::Node,
653	broadcast: &SubBroadcast,
654	qos: QosProfile,
655) -> moqros::Result<SubBridge> {
656	let bridge = ready.spawn(
657		node,
658		&broadcast.topic,
659		qos,
660		&broadcast.frame_id,
661		broadcast.ros_type.as_deref(),
662	)?;
663	tracing::info!(
664		broadcast = broadcast.broadcast,
665		topic = broadcast.topic,
666		"bridging MoQ -> ROS"
667	);
668	Ok(bridge)
669}
670
671/// Create the ROS node and parse `T` from the command line and the node's ROS parameters.
672///
673/// Arguments between `--ros-args` and `--` are left to rcl, so the binaries accept
674/// remapping (`-r __node:=…`, `-r __ns:=…`), `-p` and `--params-file` like any ROS
675/// node. Each ROS parameter named after an argument (`bitrate`, `keyframe_interval_ms`,
676/// …) fills that argument: flags win over parameters, which win over environment
677/// variables and defaults.
678pub fn init<T: Parser>(node_name: &str) -> anyhow::Result<(T, r2r::Node)> {
679	let args = strip_ros_args(std::env::args());
680	// Answer `--help` and `--version` without bringing up ROS.
681	if let Some(err) = help_or_version(T::command(), &args) {
682		err.exit();
683	}
684
685	let ctx = r2r::Context::create().context("failed to create ROS context")?;
686	let node = r2r::Node::create(ctx, node_name, "").context("failed to create ROS node")?;
687
688	let flags = param_flags(
689		&T::command(),
690		node.params
691			.lock()
692			.unwrap()
693			.iter()
694			.map(|(name, param)| (name.as_str(), &param.value)),
695	)?;
696	let cli = match parse_args(args, flags) {
697		Ok(cli) => cli,
698		Err(ParseError::CommandLine(err)) => err.exit(),
699		Err(ParseError::Param(err)) => {
700			// Just clap's first line; its usage hints are about the command line.
701			let message = err.to_string();
702			let message = message.lines().next().unwrap_or_default().trim_start_matches("error: ");
703			bail!("invalid ROS parameter: {message}");
704		}
705	};
706	Ok((cli, node))
707}
708
709/// Drop the ROS arguments (`--ros-args … [--]`, possibly repeated) from `args`.
710pub fn strip_ros_args(args: impl IntoIterator<Item = String>) -> Vec<String> {
711	let mut in_ros_args = false;
712	args.into_iter()
713		.filter(|arg| match (in_ros_args, arg.as_str()) {
714			(false, "--ros-args") | (true, "--") => {
715				in_ros_args = !in_ros_args;
716				false
717			}
718			_ => !in_ros_args,
719		})
720		.collect()
721}
722
723/// The error to exit with if `args` ask for help or the version.
724///
725/// Clap answers these as soon as it meets the flag, before checking anything else.
726fn help_or_version(command: Command, args: &[String]) -> Option<clap::Error> {
727	let err = command.try_get_matches_from(args).err()?;
728	matches!(err.kind(), ErrorKind::DisplayHelp | ErrorKind::DisplayVersion).then_some(err)
729}
730
731/// Why [`parse_args`] failed.
732#[derive(Debug)]
733enum ParseError {
734	/// The command line itself is invalid.
735	CommandLine(clap::Error),
736	/// The command line is fine on its own, so a ROS parameter is invalid.
737	Param(clap::Error),
738}
739
740/// Parse `T` from `args` (program name first, ROS arguments already stripped) and
741/// `param_flags`.
742///
743/// The parameter flags go right after the program name. With `args_override_self` a
744/// later occurrence of a flag wins, so the command line overrides them, while
745/// environment variables and defaults only apply to flags given neither way. Repeatable
746/// flags collect every occurrence instead, so parameter flags that the command line
747/// gives again are dropped up front.
748fn parse_args<T: Parser>(args: Vec<String>, param_flags: Vec<String>) -> Result<T, ParseError> {
749	let flag = |arg: &str| arg.split_once('=').map_or(arg, |(flag, _)| flag).to_string();
750	let given: HashSet<String> = args
751		.iter()
752		.skip(1)
753		.filter(|arg| arg.starts_with("--"))
754		.map(|arg| flag(arg))
755		.collect();
756	let param_flags: Vec<String> = param_flags
757		.into_iter()
758		.filter(|param| !given.contains(&flag(param)))
759		.collect();
760	let parse = |param_flags: Vec<String>| {
761		let mut args = args.iter().cloned();
762		let args = args.next().into_iter().chain(param_flags).chain(args);
763		let matches = T::command().args_override_self(true).try_get_matches_from(args)?;
764		T::from_arg_matches(&matches)
765	};
766	parse(param_flags).map_err(|err| match parse(Vec::new()) {
767		Ok(_) => ParseError::Param(err),
768		Err(err) => ParseError::CommandLine(err),
769	})
770}
771
772/// Command-line flags (`--name=value`) for the ROS parameters named after an argument
773/// of `command`.
774fn param_flags<'a>(
775	command: &Command,
776	params: impl IntoIterator<Item = (&'a str, &'a ParameterValue)>,
777) -> anyhow::Result<Vec<String>> {
778	let mut flags = Vec::new();
779	for (name, value) in params {
780		let Some((long, arg)) = command
781			.get_arguments()
782			.find(|arg| arg.get_id() == name)
783			.and_then(|arg| Some((arg.get_long()?, arg)))
784		else {
785			// r2r reads `use_sim_time` itself.
786			if name != "use_sim_time" {
787				tracing::warn!(name, "ignoring unknown ROS parameter");
788			}
789			continue;
790		};
791		let value = match value {
792			// An empty YAML value: leave the flag to its environment variable or default.
793			ParameterValue::NotSet => continue,
794			ParameterValue::Bool(value) => value.to_string(),
795			ParameterValue::Integer(value) => value.to_string(),
796			// Keep the fraction of whole numbers for strings (`1.0` stays `1.0`), but drop
797			// it for numbers so `2000000.0` still fits an integer flag.
798			ParameterValue::Double(value) if arg.get_value_parser().type_id() == TypeId::of::<String>() => {
799				format!("{value:?}")
800			}
801			ParameterValue::Double(value) => value.to_string(),
802			ParameterValue::String(value) => value.clone(),
803			// A list fills a repeatable flag, one occurrence per element.
804			ParameterValue::StringArray(values) if matches!(arg.get_action(), ArgAction::Append) => {
805				flags.extend(values.iter().map(|value| format!("--{long}={value}")));
806				continue;
807			}
808			value => bail!("ROS parameter `{name}` has unsupported type: {value:?}"),
809		};
810		// One token, so values starting with `-` aren't taken for flags.
811		flags.push(format!("--{long}={value}"));
812	}
813	Ok(flags)
814}
815
816pub fn init_logging() {
817	tracing_subscriber::fmt()
818		.with_env_filter(
819			tracing_subscriber::EnvFilter::try_from_default_env()
820				.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
821		)
822		.init();
823}
824
825/// A node shared between [`spawn_spinner`] and code that adds subscriptions while it spins.
826pub struct SharedNode {
827	node: Mutex<r2r::Node>,
828	/// Set while [`SharedNode::with`] waits, so the spinner lets go of the lock. A mutex
829	/// isn't fair: a spinner relocking it right away could starve the waiter.
830	waiting: AtomicBool,
831}
832
833impl SharedNode {
834	pub fn new(node: r2r::Node) -> Arc<Self> {
835		Arc::new(Self {
836			node: Mutex::new(node),
837			waiting: AtomicBool::new(false),
838		})
839	}
840
841	/// Run `f` on the node, between two spins.
842	pub fn with<R>(&self, f: impl FnOnce(&mut r2r::Node) -> R) -> R {
843		self.waiting.store(true, Ordering::Relaxed);
844		let mut node = self.node.lock().unwrap_or_else(|err| err.into_inner());
845		self.waiting.store(false, Ordering::Relaxed);
846		f(&mut node)
847	}
848}
849
850/// Resolves with the signal's name on the first SIGINT (Ctrl-C) or SIGTERM (`docker stop`,
851/// systemd), so the bridges can close their relay connection before exiting.
852pub async fn shutdown_signal() -> anyhow::Result<&'static str> {
853	#[cfg(unix)]
854	{
855		use tokio::signal::unix::{SignalKind, signal};
856		let mut term = signal(SignalKind::terminate()).context("failed to listen for SIGTERM")?;
857		tokio::select! {
858			res = tokio::signal::ctrl_c() => res.map(|()| "SIGINT").context("failed to listen for SIGINT"),
859			_ = term.recv() => Ok("SIGTERM"),
860		}
861	}
862	#[cfg(not(unix))]
863	{
864		tokio::signal::ctrl_c().await.context("failed to listen for Ctrl-C")?;
865		Ok("Ctrl-C")
866	}
867}
868
869/// Spin `node` on a blocking thread until the returned guard is dropped.
870///
871/// The tokio runtime waits for blocking tasks on shutdown, so a spinner that never
872/// stops would keep the process alive after `main` returns.
873pub fn spawn_spinner(node: Arc<SharedNode>) -> Spinner {
874	let stop = Arc::new(AtomicBool::new(false));
875	let stopped = stop.clone();
876	let task = tokio::task::spawn_blocking(move || {
877		while !stopped.load(Ordering::Relaxed) {
878			if node.waiting.load(Ordering::Relaxed) {
879				std::thread::yield_now();
880				continue;
881			}
882			let mut guard = node.node.lock().unwrap_or_else(|err| err.into_inner());
883			guard.spin_once(Duration::from_millis(50));
884		}
885	});
886	Spinner { stop, task: Some(task) }
887}
888
889/// Stops the [`spawn_spinner`] thread when dropped.
890pub struct Spinner {
891	stop: Arc<AtomicBool>,
892	task: Option<JoinHandle<()>>,
893}
894
895impl Spinner {
896	/// No spinner at all, for a node that only publishes: `spin_once` would busy-loop with
897	/// nothing to wait on. [`Spinner::failed`] never resolves.
898	pub fn idle() -> Self {
899		Self {
900			stop: Arc::new(AtomicBool::new(true)),
901			task: None,
902		}
903	}
904
905	/// Resolves if the spinner thread dies, which only happens when it panics, since
906	/// without spinning no ROS message arrives anymore. Never resolves again after that.
907	pub async fn failed(&mut self) -> anyhow::Error {
908		let Some(task) = self.task.as_mut() else {
909			return std::future::pending().await;
910		};
911		let result = task.await;
912		self.task = None;
913		match result {
914			Err(err) => anyhow::Error::new(err).context("ROS spinner failed"),
915			Ok(()) => anyhow::anyhow!("ROS spinner stopped"),
916		}
917	}
918}
919
920impl Drop for Spinner {
921	fn drop(&mut self) {
922		self.stop.store(true, Ordering::Relaxed);
923	}
924}
925
926#[cfg(test)]
927mod tests {
928	use clap::CommandFactory;
929
930	use super::*;
931
932	fn strip(args: &[&str]) -> Vec<String> {
933		strip_ros_args(args.iter().map(|arg| arg.to_string()))
934	}
935
936	#[derive(Debug, Parser)]
937	#[command(version = "1.2.3")]
938	struct TestCli {
939		#[arg(long, default_value = "/image_raw")]
940		topic: String,
941
942		#[arg(long)]
943		broadcast: Option<String>,
944
945		#[arg(long, default_value_t = 30.0)]
946		fps: f32,
947
948		#[arg(long, default_value_t = 2000)]
949		keyframe_interval_ms: u64,
950
951		#[arg(long, value_enum, default_value_t = Format::Video)]
952		format: Format,
953
954		#[arg(id = "type", long = "type")]
955		ros_type: Option<String>,
956
957		#[arg(long, default_value_t = moqros::DataMode::default())]
958		mode: moqros::DataMode,
959
960		#[command(flatten)]
961		relay: RelayArgs,
962
963		#[command(flatten)]
964		qos: QosArgs,
965	}
966
967	#[derive(Debug, Parser)]
968	struct MultiCli {
969		#[arg(long, default_value = "/image_raw")]
970		topic: Vec<TopicSpec>,
971	}
972
973	/// Only parsed by `params_override_env`, in a child process of its own.
974	#[derive(Debug, Parser)]
975	struct EnvCli {
976		#[arg(long, env = "MOQROS_TEST_BITRATE", default_value_t = 1)]
977		bitrate: u32,
978	}
979
980	fn flags<T: Parser>(params: &[(&str, ParameterValue)]) -> anyhow::Result<Vec<String>> {
981		param_flags(&T::command(), params.iter().map(|(name, value)| (*name, value)))
982	}
983
984	fn args(args: &[&str]) -> Vec<String> {
985		std::iter::once("bin")
986			.chain(args.iter().copied())
987			.map(String::from)
988			.collect()
989	}
990
991	fn parse<T: Parser>(args_: &[&str], params: &[(&str, ParameterValue)]) -> Result<T, ParseError> {
992		parse_args(args(args_), flags::<T>(params).unwrap())
993	}
994
995	fn string(value: &str) -> ParameterValue {
996		ParameterValue::String(value.to_string())
997	}
998
999	#[test]
1000	fn strips_ros_args() {
1001		assert_eq!(strip(&["bin", "--topic", "a"]), ["bin", "--topic", "a"]);
1002		assert_eq!(
1003			strip(&[
1004				"bin",
1005				"--topic",
1006				"a",
1007				"--ros-args",
1008				"-r",
1009				"__node:=n",
1010				"-p",
1011				"bitrate:=1"
1012			]),
1013			["bin", "--topic", "a"]
1014		);
1015		assert_eq!(
1016			strip(&[
1017				"bin",
1018				"--ros-args",
1019				"-r",
1020				"__ns:=/x",
1021				"--",
1022				"--reliable",
1023				"--ros-args",
1024				"-p",
1025				"a:=1"
1026			]),
1027			["bin", "--reliable"]
1028		);
1029	}
1030
1031	#[test]
1032	fn params_fill_flags() {
1033		let cli: TestCli = parse(
1034			&[],
1035			&[
1036				("topic", string("/front/image_raw")),
1037				("keyframe_interval_ms", ParameterValue::Integer(500)),
1038				("reliable", ParameterValue::Bool(true)),
1039				("url", string("http://relay:4443/anon")),
1040			],
1041		)
1042		.unwrap();
1043		assert_eq!(cli.topic, "/front/image_raw");
1044		assert_eq!(cli.keyframe_interval_ms, 500);
1045		assert!(cli.qos.reliable);
1046		assert_eq!(cli.relay.url.as_str(), "http://relay:4443/anon");
1047		assert!(!cli.relay.insecure);
1048		assert_eq!(cli.broadcast, None);
1049	}
1050
1051	#[test]
1052	fn client_cert_flags_come_in_pairs() {
1053		let cli: TestCli = parse(
1054			&["--tls-cert", "/certs/robot.pem"],
1055			&[("tls_key", string("/certs/robot.key"))],
1056		)
1057		.unwrap();
1058		let config = cli.relay.config();
1059		assert_eq!(
1060			config.tls_cert.as_deref(),
1061			Some(std::path::Path::new("/certs/robot.pem"))
1062		);
1063		assert_eq!(
1064			config.tls_key.as_deref(),
1065			Some(std::path::Path::new("/certs/robot.key"))
1066		);
1067		assert!(parse::<TestCli>(&["--tls-cert", "/certs/robot.pem"], &[]).is_err());
1068		assert!(parse::<TestCli>(&["--tls-key", "/certs/robot.key"], &[]).is_err());
1069	}
1070
1071	#[test]
1072	fn data_params_fill_flags() {
1073		let cli: TestCli = parse(&[], &[]).unwrap();
1074		assert_eq!(
1075			(cli.format, cli.ros_type, cli.mode),
1076			(Format::Video, None, moqros::DataMode::Snapshot)
1077		);
1078
1079		let cli: TestCli = parse(
1080			&[],
1081			&[
1082				("format", string("json")),
1083				("type", string("sensor_msgs/msg/Imu")),
1084				("mode", string("stream")),
1085			],
1086		)
1087		.unwrap();
1088		assert_eq!(cli.format, Format::Json);
1089		assert_eq!(cli.format.data(), Some(moqros::DataFormat::Json));
1090		assert_eq!(cli.ros_type.as_deref(), Some("sensor_msgs/msg/Imu"));
1091		assert_eq!(cli.mode, moqros::DataMode::Stream);
1092
1093		let cli: TestCli = parse(&["--format", "cdr", "--type", "std_msgs/msg/String"], &[]).unwrap();
1094		assert_eq!(cli.format.data(), Some(moqros::DataFormat::Cdr));
1095		assert_eq!(cli.ros_type.as_deref(), Some("std_msgs/msg/String"));
1096		assert!(matches!(
1097			parse::<TestCli>(&[], &[("format", string("xml"))]),
1098			Err(ParseError::Param(_))
1099		));
1100	}
1101
1102	#[derive(Debug, Parser)]
1103	struct EncoderCli {
1104		#[command(flatten)]
1105		encoder: EncoderArgs,
1106	}
1107
1108	#[test]
1109	fn encoder_params_fill_flags() {
1110		let cli: EncoderCli = parse(&[], &[]).unwrap();
1111		assert_eq!(cli.encoder.settings().hardware, moqros::Hardware::Auto);
1112
1113		let params = [("codec", string("av1")), ("hw", string("off"))];
1114		let settings = parse::<EncoderCli>(&[], &params).unwrap().encoder.settings();
1115		assert_eq!(
1116			(settings.codec, settings.hardware),
1117			(moqros::Codec::Av1, moqros::Hardware::Off)
1118		);
1119
1120		let cli: EncoderCli = parse(&["--hw", "require"], &params).unwrap();
1121		assert_eq!(cli.encoder.hw, moqros::Hardware::Require);
1122		assert!(parse::<EncoderCli>(&["--hw", "gpu"], &[]).is_err());
1123	}
1124
1125	#[test]
1126	fn command_line_overrides_params() {
1127		let params = [
1128			("topic", string("/param")),
1129			("reliable", ParameterValue::Bool(true)),
1130			("insecure", ParameterValue::Bool(false)),
1131		];
1132		let cli: TestCli = parse(&["--topic", "/flag", "--reliable=false", "--insecure"], &params).unwrap();
1133		assert_eq!(cli.topic, "/flag");
1134		assert!(!cli.qos.reliable);
1135		assert!(cli.relay.insecure);
1136	}
1137
1138	/// Setting a variable while other tests read the environment is undefined behavior,
1139	/// so this test reruns itself in a child process for each value of the variable.
1140	#[test]
1141	fn params_override_env() {
1142		const VAR: &str = "MOQROS_TEST_BITRATE";
1143		let bitrate = ("bitrate", ParameterValue::Integer(2));
1144		match std::env::var(VAR).ok().as_deref() {
1145			None => {
1146				for value in ["bogus", "4"] {
1147					let output = std::process::Command::new(std::env::current_exe().unwrap())
1148						.args(["--exact", "tests::params_override_env"])
1149						.env(VAR, value)
1150						.output()
1151						.unwrap();
1152					let stdout = String::from_utf8_lossy(&output.stdout);
1153					assert!(
1154						output.status.success() && stdout.contains("1 passed"),
1155						"{VAR}={value}:\n{stdout}"
1156					);
1157				}
1158			}
1159			// An invalid variable is never looked at when a parameter or flag is set.
1160			Some("bogus") => {
1161				assert_eq!(parse::<EnvCli>(&[], std::slice::from_ref(&bitrate)).unwrap().bitrate, 2);
1162				assert_eq!(parse::<EnvCli>(&["--bitrate", "3"], &[]).unwrap().bitrate, 3);
1163				assert!(matches!(parse::<EnvCli>(&[], &[]), Err(ParseError::CommandLine(_))));
1164				let help = help_or_version(EnvCli::command(), &args(&["--help"]));
1165				assert_eq!(help.map(|err| err.kind()), Some(ErrorKind::DisplayHelp));
1166			}
1167			Some(value) => {
1168				assert_eq!(value, "4");
1169				assert_eq!(parse::<EnvCli>(&[], &[]).unwrap().bitrate, 4);
1170				assert_eq!(parse::<EnvCli>(&[], std::slice::from_ref(&bitrate)).unwrap().bitrate, 2);
1171				assert_eq!(parse::<EnvCli>(&["--bitrate=3"], &[bitrate]).unwrap().bitrate, 3);
1172			}
1173		}
1174	}
1175
1176	#[test]
1177	fn doubles_keep_their_fraction() {
1178		let cli: TestCli = parse(
1179			&[],
1180			&[
1181				("broadcast", ParameterValue::Double(1.0)),
1182				("fps", ParameterValue::Double(12.5)),
1183			],
1184		)
1185		.unwrap();
1186		assert_eq!(cli.broadcast.as_deref(), Some("1.0"));
1187		assert_eq!(cli.fps, 12.5);
1188
1189		// Whole numbers still fit integer flags.
1190		let cli: TestCli = parse(&[], &[("keyframe_interval_ms", ParameterValue::Double(500.0))]).unwrap();
1191		assert_eq!(cli.keyframe_interval_ms, 500);
1192
1193		// YAML `fps: 15` is an integer parameter.
1194		let cli: TestCli = parse(&[], &[("fps", ParameterValue::Integer(15))]).unwrap();
1195		assert_eq!(cli.fps, 15.0);
1196	}
1197
1198	#[test]
1199	fn values_starting_with_a_dash_stay_values() {
1200		let cli: TestCli = parse(&[], &[("broadcast", string("-x"))]).unwrap();
1201		assert_eq!(cli.broadcast.as_deref(), Some("-x"));
1202	}
1203
1204	#[test]
1205	fn unset_and_unknown_params_are_ignored() {
1206		let params = [
1207			("broadcast", ParameterValue::NotSet),
1208			("use_sim_time", ParameterValue::Bool(false)),
1209			("bitrat", ParameterValue::Integer(1)),
1210			("keyframe-interval-ms", ParameterValue::Integer(1)),
1211			// Clap's own arguments aren't parameters.
1212			("help", ParameterValue::Bool(true)),
1213			("version", string("2")),
1214		];
1215		assert!(flags::<TestCli>(&params).unwrap().is_empty());
1216	}
1217
1218	#[test]
1219	fn arrays_fill_repeatable_flags() {
1220		let topics = |cli: MultiCli| cli.topic.into_iter().map(|spec| spec.topic).collect::<Vec<_>>();
1221		assert_eq!(topics(parse(&[], &[]).unwrap()), ["/image_raw"]);
1222		let params = [(
1223			"topic",
1224			ParameterValue::StringArray(vec!["/a".into(), "/b,format=json".into()]),
1225		)];
1226		let cli: MultiCli = parse(&[], &params).unwrap();
1227		assert_eq!(cli.topic[1].format, Some(Format::Json));
1228		assert_eq!(topics(cli), ["/a", "/b"]);
1229		// A single string still works, and the command line replaces the whole list.
1230		assert_eq!(topics(parse(&[], &[("topic", string("/c"))]).unwrap()), ["/c"]);
1231		assert_eq!(topics(parse(&["--topic", "/d"], &params).unwrap()), ["/d"]);
1232	}
1233
1234	#[test]
1235	fn parses_topic_specs() {
1236		let spec: TopicSpec = "/scan, format=cdr ,type=sensor_msgs/msg/LaserScan,mode=stream,broadcast=lidar"
1237			.parse()
1238			.unwrap();
1239		assert_eq!(
1240			spec,
1241			TopicSpec {
1242				topic: "/scan".into(),
1243				format: Some(Format::Cdr),
1244				ros_type: Some("sensor_msgs/msg/LaserScan".into()),
1245				mode: Some(moqros::DataMode::Stream),
1246				broadcast: Some("lidar".into()),
1247			}
1248		);
1249		assert_eq!("/image_raw".parse::<TopicSpec>().unwrap().format, None);
1250		for bad in [
1251			"",
1252			",format=json",
1253			"/a,json",
1254			"/a,codec=vp8",
1255			"/a,format=xml",
1256			"/a,mode=x",
1257			"/a,type=x,type=y",
1258		] {
1259			assert!(bad.parse::<TopicSpec>().is_err(), "{bad:?}");
1260		}
1261
1262		let spec: BroadcastSpec = "camera/image_raw,topic=/out,frame_id=cam,type=sensor_msgs/msg/Image"
1263			.parse()
1264			.unwrap();
1265		assert_eq!(
1266			(spec.broadcast.as_str(), spec.topic.as_deref(), spec.frame_id.as_deref()),
1267			("camera/image_raw", Some("/out"), Some("cam"))
1268		);
1269		assert!("chatter,format=json".parse::<BroadcastSpec>().is_err());
1270	}
1271
1272	#[test]
1273	fn resolves_pub_topics() {
1274		let specs = |specs: &[&str]| {
1275			specs
1276				.iter()
1277				.map(|s| s.parse::<TopicSpec>().unwrap())
1278				.collect::<Vec<_>>()
1279		};
1280		let snapshot = moqros::DataMode::Snapshot;
1281
1282		let topics = pub_topics(
1283			specs(&[
1284				"/camera/image_raw",
1285				"/chatter,format=json",
1286				"/log,mode=stream,broadcast=logs",
1287			]),
1288			Format::Video,
1289			snapshot,
1290			None,
1291			None,
1292		)
1293		.unwrap();
1294		let summary: Vec<_> = topics
1295			.iter()
1296			.map(|t| (t.broadcast.as_str(), t.format, t.mode))
1297			.collect();
1298		assert_eq!(
1299			summary,
1300			[
1301				("camera/image_raw", Format::Video, snapshot),
1302				("chatter", Format::Json, snapshot),
1303				("logs", Format::Video, moqros::DataMode::Stream),
1304			]
1305		);
1306
1307		// Flags that name one topic.
1308		let one = pub_topics(
1309			specs(&["/a"]),
1310			Format::Cdr,
1311			snapshot,
1312			Some("t/msg/T".into()),
1313			Some("b".into()),
1314		)
1315		.unwrap();
1316		assert_eq!(
1317			(one[0].broadcast.as_str(), one[0].ros_type.as_deref()),
1318			("b", Some("t/msg/T"))
1319		);
1320		assert!(
1321			pub_topics(
1322				specs(&["/a", "/b"]),
1323				Format::Json,
1324				snapshot,
1325				Some("t/msg/T".into()),
1326				None
1327			)
1328			.is_err()
1329		);
1330		assert!(pub_topics(specs(&["/a", "/b"]), Format::Json, snapshot, None, Some("b".into())).is_err());
1331
1332		assert!(pub_topics(specs(&["/a", "a,format=json"]), Format::Video, snapshot, None, None).is_err());
1333		assert!(
1334			pub_topics(
1335				specs(&["/a,type=std_msgs/msg/String"]),
1336				Format::Video,
1337				snapshot,
1338				None,
1339				None
1340			)
1341			.is_err()
1342		);
1343		assert!(
1344			pub_topics(
1345				specs(&["/a,type=sensor_msgs/msg/Image"]),
1346				Format::Video,
1347				snapshot,
1348				None,
1349				None
1350			)
1351			.is_ok()
1352		);
1353		assert!(pub_topics(Vec::new(), Format::Video, snapshot, None, None).is_err());
1354	}
1355
1356	#[test]
1357	fn refuses_loops() {
1358		let topics = |specs: &[&str]| {
1359			let specs = specs.iter().map(|s| s.parse::<TopicSpec>().unwrap()).collect();
1360			pub_topics(specs, Format::Json, moqros::DataMode::default(), None, None).unwrap()
1361		};
1362		let broadcasts = |specs: &[&str]| {
1363			let specs = specs.iter().map(|s| s.parse::<BroadcastSpec>().unwrap()).collect();
1364			sub_broadcasts(specs, None, None, "camera").unwrap()
1365		};
1366
1367		let odom = topics(&["/odom,broadcast=robot/odom"]);
1368		assert!(check_no_loop(&odom, &broadcasts(&["robot/cmd_vel,topic=/cmd_vel"])).is_ok());
1369		// The same broadcast both ways, however it's spelled.
1370		assert!(check_no_loop(&odom, &broadcasts(&["/robot/odom/,topic=/other"])).is_err());
1371		// The same topic both ways.
1372		assert!(check_no_loop(&odom, &broadcasts(&["robot/cmd_vel,topic=/odom"])).is_err());
1373		assert!(check_no_loop(&odom, &[]).is_ok());
1374	}
1375
1376	#[test]
1377	fn resolves_sub_broadcasts() {
1378		let specs = |specs: &[&str]| {
1379			specs
1380				.iter()
1381				.map(|s| s.parse::<BroadcastSpec>().unwrap())
1382				.collect::<Vec<_>>()
1383		};
1384		let topics = |broadcasts: Vec<SubBroadcast>| broadcasts.into_iter().map(|b| b.topic).collect::<Vec<_>>();
1385
1386		assert_eq!(
1387			topics(sub_broadcasts(specs(&["image_raw"]), None, None, "camera").unwrap()),
1388			[DEFAULT_SUB_TOPIC]
1389		);
1390		assert_eq!(
1391			topics(sub_broadcasts(specs(&["image_raw"]), Some("/x".into()), None, "camera").unwrap()),
1392			["/x"]
1393		);
1394		let broadcasts = sub_broadcasts(
1395			specs(&[
1396				"sample/image_raw,topic=/moqros/image",
1397				"chatter",
1398				"/front/imu/,frame_id=imu",
1399			]),
1400			None,
1401			None,
1402			"camera",
1403		)
1404		.unwrap();
1405		assert_eq!(broadcasts[2].frame_id, "imu");
1406		assert_eq!(
1407			topics(broadcasts),
1408			["/moqros/image", "/moqros/chatter", "/moqros/front/imu"]
1409		);
1410
1411		assert!(sub_broadcasts(specs(&["a", "b"]), Some("/x".into()), None, "camera").is_err());
1412		assert!(sub_broadcasts(specs(&["a", "b"]), None, Some("t/msg/T".into()), "camera").is_err());
1413		assert!(sub_broadcasts(specs(&["a,topic=/x", "b,topic=/x"]), None, None, "camera").is_err());
1414	}
1415
1416	#[test]
1417	fn arrays_are_rejected() {
1418		let params = [("topic", ParameterValue::StringArray(vec!["/a".into()]))];
1419		let err = flags::<TestCli>(&params).unwrap_err();
1420		assert!(err.to_string().contains("`topic`"), "{err}");
1421	}
1422
1423	#[test]
1424	fn invalid_param_values_are_blamed_on_the_param() {
1425		for (name, value) in [("keyframe_interval_ms", "soon"), ("url", "not a url")] {
1426			match parse::<TestCli>(&[], &[(name, string(value))]) {
1427				Err(ParseError::Param(err)) => assert_eq!(err.kind(), ErrorKind::ValueValidation, "{name}"),
1428				other => panic!("{name}: {other:?}"),
1429			}
1430		}
1431	}
1432
1433	#[test]
1434	fn invalid_command_lines_are_blamed_on_the_command_line() {
1435		let params = [("keyframe_interval_ms", string("soon"))];
1436		for args in [&["--fps=fast"][..], &["--unknown"]] {
1437			assert!(
1438				matches!(parse::<TestCli>(args, &params), Err(ParseError::CommandLine(_))),
1439				"{args:?}"
1440			);
1441		}
1442	}
1443
1444	#[test]
1445	fn detects_help_and_version() {
1446		let kind = |args_: &[&str]| help_or_version(TestCli::command(), &args(args_)).map(|err| err.kind());
1447		assert_eq!(kind(&["--help"]), Some(ErrorKind::DisplayHelp));
1448		assert_eq!(kind(&["-V"]), Some(ErrorKind::DisplayVersion));
1449		// Arguments after the help flag aren't looked at.
1450		assert_eq!(kind(&["-h", "--fps=fast"]), Some(ErrorKind::DisplayHelp));
1451		assert_eq!(kind(&["--topic", "/a"]), None);
1452		assert_eq!(kind(&["--fps=fast"]), None);
1453	}
1454
1455	#[test]
1456	fn flags_unauthenticated_relays() {
1457		let check = |url: &str, insecure| insecurity(&url.parse().unwrap(), insecure).is_some();
1458		for url in [
1459			"http://localhost:4443/anon",
1460			"http://foo.localhost:4443/anon",
1461			"http://127.0.0.1:4443/anon",
1462			"http://[::1]:4443/anon",
1463			"https://relay.example.com/robot",
1464		] {
1465			assert!(!check(url, false), "{url}");
1466		}
1467		assert!(check("http://relay:4443/anon", false));
1468		assert!(check("http://192.168.1.10:4443/anon", false));
1469		assert!(check("http://localhost.example.com:4443/anon", false));
1470		assert!(check("https://relay.example.com/robot", true));
1471		assert!(check("http://localhost:4443/anon", true));
1472	}
1473
1474	#[test]
1475	fn redacts_relay_url_secrets() {
1476		let redact = |url: &str| redact_url(&url.parse().unwrap()).to_string();
1477		assert_eq!(
1478			redact("https://relay.example/robot?jwt=eyJ.secret&a=1"),
1479			"https://relay.example/robot?jwt=REDACTED&a=1"
1480		);
1481		assert_eq!(
1482			redact("https://user:pass@relay.example/robot"),
1483			"https://user:REDACTED@relay.example/robot"
1484		);
1485		assert_eq!(
1486			redact("https://relay.example/eyJhbGciOiJFZERTQSJ9.eyJzdWIiOiJyb2JvdCJ9.c2ln"),
1487			"https://relay.example/REDACTED"
1488		);
1489		assert_eq!(
1490			redact("https://relay.example/robot/eyJh.eyJz.sig-_/cam"),
1491			"https://relay.example/robot/REDACTED/cam"
1492		);
1493		// URLs without secrets come back unchanged.
1494		for url in [
1495			"http://localhost:4443/anon",
1496			"https://relay.example/robot?a=1",
1497			"https://relay.example/eyJ/robot.v1",
1498		] {
1499			assert_eq!(redact(url), url);
1500		}
1501	}
1502}