1use 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
13pub struct Bridges {
16 pub topics: Vec<PubTopic>,
17 pub broadcasts: Vec<SubBroadcast>,
18 pub encoder: moqros::EncoderSettings,
20 pub qos: QosProfile,
21}
22
23pub struct Relay {
26 publisher: Option<moqros::Publisher>,
27 subscriber: Option<moqros::Subscriber>,
28 session: moqros::Session,
29}
30
31impl Relay {
32 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 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 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
60pub 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 let mut spinner = match topics.is_empty() {
87 true => Spinner::idle(),
88 false => spawn_spinner(node.clone()),
89 };
90
91 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 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 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 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
152type PubBridge = JoinHandle<moqros::Result<moqros::ros::BridgeStats>>;
154
155struct PendingTopics {
157 topics: Vec<PubTopic>,
158 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 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
199fn 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
239type SubBridge = JoinHandle<moqros::Result<()>>;
241
242fn 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}