Skip to main content

moqros_cli/
bridges.rs

1//! Running the bridges of one node over one relay connection.
2
3use std::time::Duration;
4
5use anyhow::{Context, bail, ensure};
6use futures::StreamExt;
7use moqros::ros::{MoqToRos, QosProfile, r2r};
8use tokio::task::JoinHandle;
9
10use crate::runtime::{SharedNode, Spinner, shutdown_signal, spawn_spinner};
11use crate::spec::{PubTopic, SubBroadcast};
12
13/// What a bridge node does: ROS topics to publish to the relay, and broadcasts to republish
14/// on ROS.
15pub struct Bridges {
16	pub topics: Vec<PubTopic>,
17	pub broadcasts: Vec<SubBroadcast>,
18	/// For video topics.
19	pub encoder: moqros::EncoderSettings,
20	pub qos: QosProfile,
21}
22
23/// The relay connection of a bridge node: a publisher for its topics, a subscriber for its
24/// broadcasts, or both over one connection.
25pub struct Relay {
26	publisher: Option<moqros::Publisher>,
27	subscriber: Option<moqros::Subscriber>,
28	session: moqros::Session,
29}
30
31impl Relay {
32	/// For a node that only has topics.
33	pub fn publisher(publisher: moqros::Publisher) -> Self {
34		Self {
35			session: publisher.session().clone(),
36			publisher: Some(publisher),
37			subscriber: None,
38		}
39	}
40
41	/// For a node that only has broadcasts.
42	pub fn subscriber(subscriber: moqros::Subscriber) -> Self {
43		Self {
44			session: subscriber.session().clone(),
45			publisher: None,
46			subscriber: Some(subscriber),
47		}
48	}
49
50	/// Both directions over the one connection [`moqros::connect_both`] returns.
51	pub fn both(publisher: moqros::Publisher, subscriber: moqros::Subscriber) -> Self {
52		Self {
53			session: publisher.session().clone(),
54			publisher: Some(publisher),
55			subscriber: Some(subscriber),
56		}
57	}
58}
59
60/// Run `bridges` until one of them ends, the relay connection gives up, or SIGINT or SIGTERM
61/// arrives (which closes the connection first, so the relay ends this node's broadcasts and
62/// subscriptions right away).
63///
64/// Video topics start at once. A data topic without a type starts when it appears in the ROS
65/// graph. Broadcasts are waited for all at once, each starting when it's announced; one whose
66/// topic can't be created (e.g. a message type without bindings) is skipped.
67pub async fn run_bridges(node: r2r::Node, relay: Relay, bridges: Bridges) -> anyhow::Result<()> {
68	let Bridges {
69		topics,
70		broadcasts,
71		encoder,
72		qos,
73	} = bridges;
74	ensure!(
75		topics.is_empty() || relay.publisher.is_some(),
76		"topics to publish need a publisher"
77	);
78	ensure!(
79		broadcasts.is_empty() || relay.subscriber.is_some(),
80		"broadcasts to republish need a subscriber"
81	);
82
83	let node = SharedNode::new(node);
84	// Only the ROS -> MoQ side subscribes to anything; a node that only publishes has
85	// nothing to spin for.
86	let mut spinner = match topics.is_empty() {
87		true => Spinner::idle(),
88		false => spawn_spinner(node.clone()),
89	};
90
91	// A topic's type depends on what its broadcast carries, so wait for each broadcast
92	// (all at once) before creating its publisher.
93	let mut subscribing: futures::stream::FuturesUnordered<_> = broadcasts
94		.into_iter()
95		.filter_map(|broadcast| {
96			let subscriber = relay.subscriber.clone()?;
97			Some(async move { (MoqToRos::subscribe(subscriber, &broadcast.broadcast).await, broadcast) })
98		})
99		.collect();
100	let mut pub_bridges = futures::stream::FuturesUnordered::new();
101	let mut sub_bridges = futures::stream::FuturesUnordered::new();
102	let mut pending = PendingTopics::new(topics);
103	// Created once, so a signal arriving while the loop body runs isn't missed.
104	let shutdown = shutdown_signal();
105	tokio::pin!(shutdown);
106
107	loop {
108		if let Some(publisher) = &relay.publisher {
109			for (topic, bridge) in pending.start_ready(&node, publisher, &encoder, &qos)? {
110				pub_bridges.push(async move { (topic, bridge.await) });
111			}
112		}
113
114		tokio::select! {
115			Some((ready, broadcast)) = subscribing.next() => {
116				match node.with(|node| spawn_sub_broadcast(ready, node, &broadcast, qos.clone())) {
117					Ok(bridge) => sub_bridges.push(async move { (broadcast.broadcast, bridge.await) }),
118					// E.g. a message type this build has no bindings for: the other
119					// broadcasts and topics can still go on.
120					Err(err) => {
121						tracing::error!(%err, broadcast = broadcast.broadcast, topic = broadcast.topic, "skipping broadcast");
122						if subscribing.is_empty() && sub_bridges.is_empty() && pub_bridges.is_empty() && pending.is_empty() {
123							bail!("nothing left to bridge: no broadcast could be republished");
124						}
125					}
126				}
127			}
128			Some((topic, res)) = pub_bridges.next() => {
129				let stats = res.context("bridge panicked")??;
130				tracing::info!(topic, ?stats, "topic stream ended");
131				return Ok(());
132			}
133			Some((broadcast, res)) = sub_bridges.next() => {
134				res.context("bridge panicked")?.with_context(|| format!("broadcast {broadcast}"))?;
135				return Ok(());
136			}
137			_ = tokio::time::sleep(Duration::from_millis(500)), if !pending.is_empty() => {}
138			// E.g. the relay refused the session: nothing would ever be announced.
139			res = relay.session.closed() => return res.context("relay connection closed"),
140			err = spinner.failed() => return Err(err),
141			res = &mut shutdown => {
142				tracing::info!(signal = res?, "shutting down");
143				if let Err(err) = relay.session.close().await {
144					tracing::warn!(%err, "the relay connection didn't close cleanly");
145				}
146				return Ok(());
147			}
148		}
149	}
150}
151
152/// A running ROS -> MoQ bridge task.
153type PubBridge = JoinHandle<moqros::Result<moqros::ros::BridgeStats>>;
154
155/// Topics to publish that haven't started yet, because their type isn't known.
156struct PendingTopics {
157	topics: Vec<PubTopic>,
158	/// Whether the topics still waiting were logged.
159	logged: bool,
160}
161
162impl PendingTopics {
163	fn new(topics: Vec<PubTopic>) -> Self {
164		Self { topics, logged: false }
165	}
166
167	fn is_empty(&self) -> bool {
168		self.topics.is_empty()
169	}
170
171	/// Start every topic whose type is known by now, returning each one's name and bridge.
172	/// Data topics without a `type` wait until something publishes them.
173	fn start_ready(
174		&mut self,
175		node: &SharedNode,
176		publisher: &moqros::Publisher,
177		encoder: &moqros::EncoderSettings,
178		qos: &QosProfile,
179	) -> anyhow::Result<Vec<(String, PubBridge)>> {
180		let mut started = Vec::new();
181		let mut waiting = Vec::new();
182		for topic in std::mem::take(&mut self.topics) {
183			match node.with(|node| start_pub_topic(node, publisher, &topic, encoder, qos.clone()))? {
184				Some(bridge) => started.push((topic.topic.clone(), bridge)),
185				None => {
186					waiting.push(topic.topic.clone());
187					self.topics.push(topic);
188				}
189			}
190		}
191		if !waiting.is_empty() && !self.logged {
192			tracing::info!(topics = ?waiting, "waiting for topics to appear to learn their types");
193			self.logged = true;
194		}
195		Ok(started)
196	}
197}
198
199/// Start bridging `topic` from ROS to MoQ once its type is known. Returns `None` while
200/// the topic hasn't appeared in the ROS graph yet.
201fn start_pub_topic(
202	node: &mut r2r::Node,
203	publisher: &moqros::Publisher,
204	topic: &PubTopic,
205	encoder: &moqros::EncoderSettings,
206	qos: QosProfile,
207) -> anyhow::Result<Option<PubBridge>> {
208	let bridge = match topic.format.data() {
209		None => {
210			let images = publisher.create_image_broadcast(&topic.broadcast, encoder.clone())?;
211			moqros::ros::spawn_ros_to_moq(node, &topic.topic, qos, images)?
212		}
213		Some(format) => {
214			let ros_type = match &topic.ros_type {
215				Some(ros_type) => ros_type.clone(),
216				None => match moqros::ros::topic_type(node, &topic.topic)? {
217					Some(ros_type) => ros_type,
218					None => return Ok(None),
219				},
220			};
221			let settings = moqros::DataSettings {
222				format,
223				mode: topic.mode,
224				ros_type: Some(ros_type),
225			};
226			let data = publisher.create_data_broadcast(&topic.broadcast, settings)?;
227			moqros::ros::spawn_ros_to_moq_data(node, &topic.topic, qos, data)?
228		}
229	};
230	tracing::info!(
231		topic = topic.topic,
232		format = ?topic.format,
233		broadcast = topic.broadcast,
234		"bridging ROS -> MoQ"
235	);
236	Ok(Some(bridge))
237}
238
239/// A running MoQ -> ROS bridge task.
240type SubBridge = JoinHandle<moqros::Result<()>>;
241
242/// Create the ROS publisher for a subscribed broadcast and start republishing it.
243fn spawn_sub_broadcast(
244	ready: moqros::ros::MoqToRos,
245	node: &mut r2r::Node,
246	broadcast: &SubBroadcast,
247	qos: QosProfile,
248) -> moqros::Result<SubBridge> {
249	let target = moqros::ros::RosTarget {
250		topic: broadcast.topic.clone(),
251		qos,
252		frame_id: broadcast.frame_id.clone(),
253		ros_type: broadcast.ros_type.clone(),
254	};
255	let bridge = ready.spawn(node, target)?;
256	tracing::info!(
257		broadcast = broadcast.broadcast,
258		topic = broadcast.topic,
259		"bridging MoQ -> ROS"
260	);
261	Ok(bridge)
262}