1use std::{collections::HashMap, fmt, future::Future, time::Duration};
4
5use iroh::EndpointId;
6use iroh_live_node::{Subscription, json::Timed};
7use n0_future::task::AbortOnDropHandle;
8use n0_watcher::{Direct, Watcher};
9use serde::de::DeserializeOwned;
10use tokio::{sync::mpsc, time::Instant};
11use tracing::{debug, info};
12
13use crate::{Room, RoomState, room::WeakRoom};
14
15const RETRY: Duration = Duration::from_secs(2);
17
18const RETRY_MAX: Duration = Duration::from_secs(16);
23
24const VALUE_QUEUE: usize = 64;
26
27#[derive(Debug)]
34struct Retry {
35 wait: Duration,
36}
37
38impl Default for Retry {
39 fn default() -> Self {
40 Self { wait: RETRY }
41 }
42}
43
44impl Retry {
45 fn served(&mut self, since: Instant) -> Option<Duration> {
47 if since.elapsed() >= RETRY_MAX {
48 self.wait = RETRY;
49 return None;
50 }
51 Some(self.failed())
52 }
53
54 fn failed(&mut self) -> Duration {
56 let wait = self.wait;
57 self.wait = (self.wait * 2).min(RETRY_MAX);
58 wait
59 }
60}
61
62impl Room {
63 #[must_use = "dropping the handle stops the tasks"]
87 pub fn for_each_member<F, Fut>(&self, name: &str, task: F) -> AbortOnDropHandle<()>
88 where
89 F: FnMut(EndpointId) -> Fut + Send + 'static,
90 Fut: Future<Output = ()> + Send + 'static,
91 {
92 let follow = follow(self.watchers(), name.to_owned(), task, |_| async {});
93 AbortOnDropHandle::new(tokio::spawn(follow))
94 }
95
96 #[must_use]
123 pub fn subscriptions(&self, peer: EndpointId, name: &str) -> MemberSubscriptions {
124 let (state, left) = self.watchers();
125 MemberSubscriptions {
126 room: self.downgrade(),
127 peer,
128 name: name.to_owned(),
129 state,
130 left,
131 retry: Retry::default(),
132 listed: false,
133 current: None,
134 }
135 }
136
137 pub fn read_values<T>(&self, name: &str, track: &str) -> MemberValues<T>
168 where
169 T: DeserializeOwned + Send + 'static,
170 {
171 let (tx, rx) = mpsc::channel(VALUE_QUEUE);
172 let read = {
173 let (room, name, track, tx) = (
174 self.downgrade(),
175 name.to_owned(),
176 track.to_owned(),
177 tx.clone(),
178 );
179 move |member| {
180 let subscriptions = room.upgrade().map(|room| room.subscriptions(member, &name));
181 read_member(subscriptions, member, track.clone(), tx.clone())
182 }
183 };
184 let stopped = move |member| {
185 let tx = tx.clone();
186 async move {
187 tx.send(MemberValue {
188 member,
189 value: None,
190 })
191 .await
192 .ok();
193 }
194 };
195 let task = tokio::spawn(follow(self.watchers(), name.to_owned(), read, stopped));
196 MemberValues {
197 rx,
198 _follow: AbortOnDropHandle::new(task),
199 }
200 }
201
202 fn watchers(&self) -> (Direct<RoomState>, Direct<bool>) {
206 (self.state(), self.inner.done.watch())
207 }
208}
209
210pub struct MemberSubscriptions {
212 room: WeakRoom,
213 peer: EndpointId,
214 name: String,
215 state: Direct<RoomState>,
216 left: Direct<bool>,
217 retry: Retry,
218 listed: bool,
220 current: Option<(Subscription, Instant)>,
222}
223
224impl fmt::Debug for MemberSubscriptions {
225 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
226 f.debug_struct("MemberSubscriptions")
227 .field("peer", &format_args!("{}", self.peer.fmt_short()))
228 .field("name", &self.name)
229 .field(
230 "current",
231 &self.current.as_ref().map(|(current, _)| current),
232 )
233 .finish_non_exhaustive()
234 }
235}
236
237impl MemberSubscriptions {
238 pub async fn next(&mut self) -> Option<Subscription> {
245 if let Some((subscription, since)) = self.current.take() {
246 tokio::select! {
247 () = subscription.closed() => {}
248 () = unlisted(&mut self.state, &mut self.left, self.peer, &self.name) => return None,
249 }
250 if let Some(wait) = self.retry.served(since) {
251 debug!(peer = %self.peer.fmt_short(), name = %self.name, ?wait, "the subscription ended early, waiting");
252 if !self.sleep(wait).await {
253 return None;
254 }
255 }
256 }
257 loop {
258 if !self.until_listed().await {
259 return None;
260 }
261 let room = self.room.upgrade()?;
262 let subscribed = tokio::select! {
263 subscribed = room.subscribe(self.peer, &self.name) => subscribed,
264 () = unlisted(&mut self.state, &mut self.left, self.peer, &self.name) => return None,
265 };
266 drop(room);
267 match subscribed {
268 Ok(subscription) => {
269 self.current = Some((subscription.clone(), Instant::now()));
270 return Some(subscription);
271 }
272 Err(err) => {
273 let wait = self.retry.failed();
274 debug!(peer = %self.peer.fmt_short(), name = %self.name, error = %err, ?wait, "subscribing failed, trying again");
275 if !self.sleep(wait).await {
276 return None;
277 }
278 }
279 }
280 }
281 }
282
283 async fn until_listed(&mut self) -> bool {
285 loop {
286 if self.left.get() {
287 return false;
288 }
289 if lists(&self.state.get(), self.peer, &self.name) {
290 self.listed = true;
291 return true;
292 }
293 if self.listed {
294 return false;
295 }
296 let changed = tokio::select! {
297 changed = self.state.updated() => changed.is_ok(),
298 changed = self.left.updated() => changed.is_ok(),
299 };
300 if !changed {
301 return false;
302 }
303 }
304 }
305
306 async fn sleep(&mut self, wait: Duration) -> bool {
308 tokio::select! {
309 () = tokio::time::sleep(wait) => true,
310 () = unlisted(&mut self.state, &mut self.left, self.peer, &self.name) => false,
311 }
312 }
313}
314
315fn lists(state: &RoomState, peer: EndpointId, name: &str) -> bool {
317 state
318 .members
319 .get(&peer)
320 .is_some_and(|member| member.broadcasts.contains(name))
321}
322
323async fn unlisted(
325 state: &mut Direct<RoomState>,
326 left: &mut Direct<bool>,
327 peer: EndpointId,
328 name: &str,
329) {
330 loop {
331 if left.get() || !lists(&state.get(), peer, name) {
332 return;
333 }
334 let changed = tokio::select! {
335 changed = state.updated() => changed.is_ok(),
336 changed = left.updated() => changed.is_ok(),
337 };
338 if !changed {
339 return;
340 }
341 }
342}
343
344#[derive(Debug, Clone)]
346#[non_exhaustive]
347pub struct MemberValue<T> {
348 pub member: EndpointId,
350 pub value: Option<Timed<T>>,
352}
353
354pub struct MemberValues<T> {
358 rx: mpsc::Receiver<MemberValue<T>>,
359 _follow: AbortOnDropHandle<()>,
360}
361
362impl<T> fmt::Debug for MemberValues<T> {
363 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
364 f.debug_struct("MemberValues")
365 .field("queued", &self.rx.len())
366 .finish_non_exhaustive()
367 }
368}
369
370impl<T> MemberValues<T> {
371 pub fn try_recv(&mut self) -> Option<MemberValue<T>> {
373 self.rx.try_recv().ok()
374 }
375
376 pub async fn recv(&mut self) -> Option<MemberValue<T>> {
380 self.rx.recv().await
381 }
382}
383
384async fn follow<Fut, Stop>(
390 (mut state, mut left): (Direct<RoomState>, Direct<bool>),
391 name: String,
392 mut start: impl FnMut(EndpointId) -> Fut,
393 mut stopped: impl FnMut(EndpointId) -> Stop,
394) where
395 Fut: Future<Output = ()> + Send + 'static,
396 Stop: Future<Output = ()>,
397{
398 let mut tasks: HashMap<EndpointId, AbortOnDropHandle<()>> = HashMap::new();
399 loop {
400 if left.get() {
401 return;
402 }
403 let state_now = state.get();
404 let gone: Vec<_> = tasks
405 .keys()
406 .filter(|id| !lists(&state_now, **id, &name))
407 .copied()
408 .collect();
409 for id in gone {
410 let task = tasks.remove(&id).expect("listed above");
411 task.abort();
412 task.await.ok();
413 stopped(id).await;
414 }
415 for id in state_now.members.keys() {
416 if lists(&state_now, *id, &name) {
417 tasks
418 .entry(*id)
419 .or_insert_with(|| AbortOnDropHandle::new(tokio::spawn(start(*id))));
420 }
421 }
422 let changed = tokio::select! {
423 changed = state.updated() => changed.is_ok(),
424 changed = left.updated() => changed.is_ok(),
425 };
426 if !changed {
427 return;
428 }
429 }
430}
431
432async fn read_member<T: DeserializeOwned>(
436 subscriptions: Option<MemberSubscriptions>,
437 member: EndpointId,
438 track: String,
439 tx: mpsc::Sender<MemberValue<T>>,
440) {
441 let Some(mut subscriptions) = subscriptions else {
442 return;
443 };
444 loop {
445 let subscription = tokio::select! {
446 subscription = subscriptions.next() => subscription,
447 () = tx.closed() => return,
448 };
449 let Some(subscription) = subscription else {
450 return;
451 };
452 if !read_once(&subscription, member, &track, &tx).await {
453 return;
454 }
455 }
456}
457
458async fn read_once<T: DeserializeOwned>(
464 subscription: &Subscription,
465 member: EndpointId,
466 track: &str,
467 tx: &mpsc::Sender<MemberValue<T>>,
468) -> bool {
469 let peer = member.fmt_short();
470 let mut reader = match subscription.value_track::<T>(track) {
471 Ok(reader) => reader,
472 Err(err) => {
473 debug!(%peer, %track, error = %err, "the value track did not open");
474 return true;
475 }
476 };
477 loop {
478 let value = tokio::select! {
479 value = reader.latest() => value,
480 () = tx.closed() => return false,
481 };
482 let err = match value {
483 Ok(Some(value)) => {
484 let update = MemberValue {
485 member,
486 value: Some(value),
487 };
488 if tx.send(update).await.is_err() {
489 return false;
490 }
491 continue;
492 }
493 Ok(None) => return true,
494 Err(err) => err.into_json(),
495 };
496 match err {
497 moq_json::Error::Net(
498 moq_net::Error::NotFound | moq_net::Error::Stream(moq_net::StreamError::NotFound),
499 ) => {
500 info!(%peer, %track, "the member's broadcast has no such value track, not reading it");
501 return false;
502 }
503 moq_json::Error::Net(err) => {
504 debug!(%peer, %track, error = %err, "the value track failed");
505 return true;
506 }
507 err => debug!(%peer, %track, error = %err, "skipping a value that does not decode"),
509 }
510 }
511}
512
513#[cfg(test)]
514mod tests {
515 use super::*;
516
517 #[tokio::test(start_paused = true)]
519 async fn a_subscription_that_ends_early_waits_longer_each_time() {
520 let mut retry = Retry::default();
521 let waits: Vec<_> = (0..5).map(|_| retry.served(Instant::now())).collect();
522 let secs = |secs| Some(Duration::from_secs(secs));
523 assert_eq!(waits, [secs(2), secs(4), secs(8), secs(16), secs(16)]);
524
525 let started = Instant::now();
526 tokio::time::advance(RETRY_MAX).await;
527 assert_eq!(
528 retry.served(started),
529 None,
530 "a subscription that served on subscribes again at once"
531 );
532 assert_eq!(retry.failed(), RETRY);
533 assert_eq!(
534 retry.failed(),
535 RETRY * 2,
536 "a failed subscription waits longer"
537 );
538 }
539}