1use std::{
11 sync::{Arc, Mutex, OnceLock, Weak},
12 time::Duration,
13};
14
15use moq_net::{
16 Identity, Path, Prefix, Prefixes, broadcast,
17 origin::{self, Link, RouteEvent, RouteKind},
18};
19use n0_error::e;
20use n0_future::task::AbortOnDropHandle;
21use serde::de::DeserializeOwned;
22use tokio::sync::watch;
23use tokio_util::sync::CancellationToken;
24use tracing::{debug, info};
25
26use crate::{
27 BroadcastTicket, Error, LinkId, Node, PathClaim, Reach, ServingLink, Session, ValueReader,
28 handshake::{Hop, Source},
29 node::Shared,
30 publish::check_path,
31 state::{LinkEntry, State},
32};
33
34const REASK_PAUSE: Duration = Duration::from_millis(100);
39
40#[derive(Clone, derive_more::Debug)]
66#[debug("Subscription({}, pinned {})", inner.path, inner.pin.is_some())]
67pub struct Subscription {
68 inner: Arc<SubscriptionInner>,
69}
70
71struct SubscriptionInner {
73 path: Path,
74 origin: origin::Consumer,
75 current: watch::Sender<broadcast::Consumer>,
77 ended: CancellationToken,
79 _follow: AbortOnDropHandle<()>,
81 pin: Option<LinkId>,
83 routes: Mutex<Routes>,
85 shared: Weak<Shared>,
86 claim: OnceLock<PathClaim>,
88}
89
90struct Routes {
92 path: Path,
93 announced: Option<origin::Routes>,
94 source: Option<Source>,
95}
96
97impl Routes {
98 fn new(table: &origin::Consumer, path: &Path) -> Self {
100 let announced = routes_under(table, path).ok();
101 Self {
102 path: path.clone(),
103 announced,
104 source: None,
105 }
106 }
107
108 fn source(&mut self) -> Option<Source> {
110 let announced = self.announced.as_mut()?;
111 while let Some(event) = announced.try_next() {
112 if event.announce.prefix == self.path {
113 self.source = live_route(&event).map(|announce| Source::of(&announce.route));
114 }
115 }
116 self.source
117 }
118}
119
120fn routes_under(table: &origin::Consumer, path: &Path) -> Result<origin::Routes, moq_net::Error> {
125 let prefix = path
126 .as_str()
127 .parse::<Prefix>()
128 .map_err(|_| moq_net::Error::Unauthorized)?;
129 Ok(table.scope("", &Prefixes::from(prefix))?.routes())
130}
131
132impl Subscription {
133 pub(crate) fn new(
138 path: Path,
139 origin: origin::Consumer,
140 broadcast: broadcast::Consumer,
141 pin: Option<(LinkId, Identity)>,
142 shared: Weak<Shared>,
143 ) -> Self {
144 let routes = Routes::new(&origin, &path);
145 let current = watch::Sender::new(broadcast);
146 let ended = CancellationToken::new();
147 let follow = tokio::spawn(follow(
148 path.clone(),
149 origin.clone(),
150 pin.as_ref().map(|(_, identity)| identity.clone()),
151 current.clone(),
152 ended.clone(),
153 ));
154 Self {
155 inner: Arc::new(SubscriptionInner {
156 path,
157 origin,
158 current,
159 ended,
160 _follow: AbortOnDropHandle::new(follow),
161 pin: pin.map(|(link, _)| link),
162 routes: Mutex::new(routes),
163 shared,
164 claim: OnceLock::new(),
165 }),
166 }
167 }
168
169 fn holding(self, claim: PathClaim) -> Self {
171 self.inner.claim.set(claim).ok();
172 self
173 }
174
175 #[must_use]
177 pub fn path(&self) -> &Path {
178 &self.inner.path
179 }
180
181 #[must_use]
183 pub fn origin(&self) -> origin::Consumer {
184 self.inner.origin.clone()
185 }
186
187 #[must_use]
193 pub fn broadcast(&self) -> broadcast::Consumer {
194 self.inner.current.borrow().clone()
195 }
196
197 pub fn value_track<T: DeserializeOwned>(&self, name: &str) -> Result<ValueReader<T>, Error> {
231 let reader = ValueReader::new(self.clone(), self.inner.current.subscribe(), name)
232 .map_err(|source| e!(Error::Moq { source }))?;
233 debug!(path = %self.inner.path, track = name, "reading value track");
234 Ok(reader)
235 }
236
237 #[must_use]
245 pub fn session(&self) -> Option<Session> {
246 let shared = self.inner.shared.upgrade()?;
247 let (link, _) = self.serving(&shared.state.lock().expect("poisoned"))?;
248 shared
250 .sessions
251 .get()
252 .into_iter()
253 .find(|session| session.inner.link == link)
254 }
255
256 #[must_use]
265 pub fn serving_link(&self) -> Option<ServingLink> {
266 let shared = self.inner.shared.upgrade()?;
267 let state = shared.state.lock().expect("poisoned");
268 let (link, entry) = self.serving(&state)?;
269 Some(ServingLink {
270 id: link,
271 kind: entry.kind(),
272 sample: entry.latest_sample.get(),
273 })
274 }
275
276 fn serving<'a>(&self, state: &'a State) -> Option<(LinkId, &'a LinkEntry)> {
278 let link = match self.inner.pin {
279 Some(link) => link,
280 None => {
281 let source = self.inner.routes.lock().expect("poisoned").source()?;
282 state.link_for(source)?
283 }
284 };
285 Some((link, state.links.get(&link)?))
286 }
287
288 pub async fn closed(&self) {
293 self.inner.ended.cancelled().await;
294 }
295}
296
297async fn follow(
304 path: Path,
305 origin: origin::Consumer,
306 identity: Option<Identity>,
307 current: watch::Sender<broadcast::Consumer>,
308 ended: CancellationToken,
309) {
310 let _ended = ended.drop_guard();
311 let mut following = origin.follow(&path, identity.clone()).ok();
312 loop {
313 let serving = current.borrow().clone();
314 let taken = async {
315 match following.as_mut() {
316 Some(following) => following.available().await,
317 None => std::future::pending().await,
318 }
319 };
320 tokio::select! {
321 taken = taken => match taken {
322 Ok(Some(next)) if !next.is_closed() => {
323 debug!(%path, "another identity serves the path");
324 current.send_replace(next);
325 continue;
326 }
327 Ok(_) => continue,
330 Err(moq_net::Error::Closed) => return,
331 Err(_) => continue,
333 },
334 _ = serving.closed() => {}
335 }
336 tokio::time::sleep(REASK_PAUSE).await;
337 match origin.request(&path, identity.clone()).await {
338 Ok(next) if !next.is_closed() => {
339 debug!(%path, "broadcast ended, a route still serves it");
340 current.send_replace(next);
341 }
342 _ => return,
343 }
344 }
345}
346
347pub(crate) async fn subscribe_ticket(
349 node: &Node,
350 ticket: &BroadcastTicket,
351) -> Result<Subscription, Error> {
352 let (peer, path) = (ticket.peer(), ticket.path());
353 let claim = node.claim_path(peer, path)?;
355 let subscription = node.subscribe(path.clone(), Reach::Both(peer)).await?;
356 Ok(subscription.holding(claim))
357}
358
359pub(crate) fn direct_view(table: &origin::Producer) -> origin::Consumer {
361 table.clone().with_link(Link::Upstream).consume()
362}
363
364pub(crate) async fn announced_by(
366 view: &origin::Consumer,
367 path: &Path,
368 from: impl Fn(Hop) -> bool,
369) -> Result<Identity, moq_net::Error> {
370 let mut announced = routes_under(view, path)?;
371 while let Some(event) = announced.next().await {
372 if event.announce.prefix == *path
373 && let Some(announce) = live_route(&event)
374 && Hop::of_route(Source::of(&announce.route)).is_some_and(&from)
375 {
376 return Ok(announce.route.identity().clone());
377 }
378 }
379 Err(moq_net::Error::Closed)
380}
381
382fn live_route(event: &RouteEvent) -> Option<&moq_net::announce::Announce> {
384 match event.kind {
385 RouteKind::Start | RouteKind::Update | RouteKind::Restart => Some(&event.announce),
386 RouteKind::End | RouteKind::Offline => None,
387 kind => {
388 debug!(?kind, prefix = %event.announce.prefix, "unknown route kind, read as ended");
389 None
390 }
391 }
392}
393
394pub(crate) async fn subscribe(
396 node: &Node,
397 path: Path,
398 reach: Reach,
399) -> Result<Subscription, Error> {
400 check_path(&path)?;
401 if node.shared.shutdown.is_cancelled() {
402 return Err(e!(Error::ShutDown));
403 }
404 let table = node.shared.table.consume();
405 if let Ok(broadcast) = table.request(&path, None).await {
407 debug!(%path, "resolved through an existing route");
408 return Ok(subscription(&node.shared, path, table, broadcast));
409 }
410
411 let (dial, relays) = match reach {
412 Reach::Direct(peer) => (Some(peer), false),
413 Reach::Relays => (None, true),
414 Reach::Both(peer) => (Some(peer), true),
415 };
416 let relays = relays && node.shared.state.lock().expect("poisoned").has_relays();
417 let Some(peer) = dial.filter(|peer| *peer != node.shared.id) else {
419 if !relays {
420 return Err(e!(Error::NoRoute { path }));
421 }
422 debug!(%path, "waiting for a relay to route the path");
423 let resolved = routed(&table, &path).await;
424 return outcome(&node.shared, path, table, resolved);
425 };
426
427 debug!(%path, peer = %peer.fmt_short(), relays, "dialing the publisher");
428 let routed = {
429 let (table, path) = (table.clone(), path.clone());
430 async move { routed(&table, &path).await }
431 };
432 tokio::pin!(routed);
433 let connected = tokio::select! {
434 resolved = &mut routed => return outcome(&node.shared, path, table, resolved),
435 connected = node.connect(peer) => connected,
436 };
437 match connected {
438 Ok(session) if !session.grant().allows_publish(path.as_str()) => {
440 if !relays {
441 return Err(Error::not_granted(path, peer, &session.grant()));
442 }
443 info!(%path, "the publisher may not publish the path here, waiting for a relay");
444 }
445 Ok(session) => {
446 tokio::select! {
449 resolved = &mut routed => return outcome(&node.shared, path, table, resolved),
450 _ = session.closed() => {}
451 }
452 if !relays {
453 return Err(e!(Error::NotAnnounced { path }));
454 }
455 }
456 Err(err) if relays => {
457 info!(%path, error = %err, "publisher unreachable, waiting for a relay")
458 }
459 Err(err) => return Err(err),
460 }
461 let resolved = routed.await;
462 outcome(&node.shared, path, table, resolved)
463}
464
465pub(crate) async fn routed(
467 table: &origin::Consumer,
468 path: &Path,
469) -> Result<broadcast::Consumer, moq_net::Error> {
470 table
471 .follow(path, None)?
472 .available()
473 .await?
474 .ok_or(moq_net::Error::Closed)
475}
476
477fn outcome(
479 shared: &Arc<Shared>,
480 path: Path,
481 table: origin::Consumer,
482 resolved: Result<broadcast::Consumer, moq_net::Error>,
483) -> Result<Subscription, Error> {
484 match resolved {
485 Ok(broadcast) => Ok(subscription(shared, path, table, broadcast)),
486 Err(moq_net::Error::Closed) => Err(e!(Error::ShutDown)),
487 Err(source) => Err(e!(Error::Unresolved { path, source })),
488 }
489}
490
491fn subscription(
493 shared: &Arc<Shared>,
494 path: Path,
495 table: origin::Consumer,
496 broadcast: broadcast::Consumer,
497) -> Subscription {
498 Subscription::new(path, table, broadcast, None, Arc::downgrade(shared))
499}
500
501#[cfg(test)]
502mod tests {
503 use moq_net::origin::RouteOptions;
504
505 use super::*;
506
507 const TIMEOUT: Duration = Duration::from_secs(5);
508
509 struct Followed {
511 current: watch::Sender<broadcast::Consumer>,
512 ended: CancellationToken,
513 _task: AbortOnDropHandle<()>,
514 }
515
516 impl Followed {
517 async fn start(table: &origin::Producer, path: &str, identity: Option<Identity>) -> Self {
519 let path = Path::new(path).expect("a path");
520 let consumer = table.consume();
521 let broadcast =
522 tokio::time::timeout(TIMEOUT, consumer.request(&path, identity.clone()))
523 .await
524 .expect("resolved in time")
525 .expect("a route serves the path");
526 let current = watch::Sender::new(broadcast);
527 let ended = CancellationToken::new();
528 let task = tokio::spawn(follow(
529 path,
530 consumer,
531 identity,
532 current.clone(),
533 ended.clone(),
534 ));
535 Self {
536 current,
537 ended,
538 _task: AbortOnDropHandle::new(task),
539 }
540 }
541
542 fn identity(&self) -> Option<Identity> {
544 self.current.borrow().info().identity.clone()
545 }
546
547 async fn moves_to(&self, identity: &Identity) {
549 tokio::time::timeout(TIMEOUT, async {
550 while self.identity().as_ref() != Some(identity) {
551 tokio::time::sleep(Duration::from_millis(10)).await;
552 }
553 })
554 .await
555 .expect("the subscription moved in time");
556 }
557
558 async fn ends(&self) {
560 tokio::time::timeout(TIMEOUT, self.ended.cancelled())
561 .await
562 .expect("the subscription ended in time");
563 }
564 }
565
566 fn route(table: &origin::Producer, path: &str, cost: u64) -> origin::Route {
568 table
569 .route(path, RouteOptions::default().with_cost(cost))
570 .expect("a route")
571 }
572
573 #[tokio::test]
574 async fn a_cheaper_instance_taking_over_moves_the_subscription() {
575 let table = moq_tokio::origin::spawn();
576 let first = route(&table, "cam", 5);
577 let followed = Followed::start(&table, "cam", None).await;
578 assert_eq!(followed.identity(), Some(first.identity()));
579
580 let second = route(&table, "cam", 1);
581 followed.moves_to(&second.identity()).await;
582 assert!(!followed.ended.is_cancelled());
583 }
584
585 #[tokio::test]
586 async fn an_ending_instance_hands_over_to_one_that_remains() {
587 let table = moq_tokio::origin::spawn();
588 let first = route(&table, "cam", 1);
589 let second = route(&table, "cam", 5);
590 let followed = Followed::start(&table, "cam", None).await;
591 assert_eq!(followed.identity(), Some(first.identity()));
592
593 drop(first);
594 followed.moves_to(&second.identity()).await;
595 assert!(!followed.ended.is_cancelled());
596 }
597
598 #[tokio::test]
599 async fn a_successor_that_routes_just_after_the_end_takes_over() {
600 let table = moq_tokio::origin::spawn();
601 let first = route(&table, "cam", 1);
602 let followed = Followed::start(&table, "cam", None).await;
603 tokio::time::sleep(Duration::from_millis(1100)).await;
605
606 drop(first);
607 tokio::time::sleep(REASK_PAUSE / 4).await;
608 let second = route(&table, "cam", 1);
609 followed.moves_to(&second.identity()).await;
610 assert!(!followed.ended.is_cancelled());
611 }
612
613 #[tokio::test]
614 async fn the_subscription_ends_once_nothing_serves_the_path() {
615 let table = moq_tokio::origin::spawn();
616 let only = route(&table, "cam", 1);
617 let followed = Followed::start(&table, "cam", None).await;
618
619 drop(only);
620 followed.ends().await;
621 }
622
623 #[tokio::test]
624 async fn a_pinned_subscription_never_moves_to_another_instance() {
625 let table = moq_tokio::origin::spawn();
626 let first = route(&table, "cam", 5);
627 let followed = Followed::start(&table, "cam", Some(first.identity())).await;
628
629 let _second = route(&table, "cam", 1);
630 tokio::time::sleep(Duration::from_millis(200)).await;
631 assert_eq!(followed.identity(), Some(first.identity()));
632 drop(first);
633 followed.ends().await;
634 }
635
636 #[tokio::test]
637 async fn a_pinned_subscription_stays_while_its_instance_serves() {
638 let table = moq_tokio::origin::spawn();
639 let first = route(&table, "cam", 1);
640 let followed = Followed::start(&table, "cam", Some(first.identity())).await;
641
642 let other = route(&table, "other", 1);
643 tokio::time::sleep(Duration::from_millis(200)).await;
644 assert!(!followed.ended.is_cancelled());
645 drop((first, other));
646 followed.ends().await;
647 }
648}