Skip to main content

iroh_live_node/
publish.rs

1//! Publications: a broadcast created at a path in the route table, for an audience.
2
3use std::{
4    collections::BTreeSet,
5    sync::{Arc, Weak},
6};
7
8use iroh::EndpointId;
9use moq_net::{
10    Path, Prefix, broadcast,
11    origin::{self, RouteOptions},
12};
13use n0_error::{AnyError, e};
14use n0_future::task::AbortOnDropHandle;
15use n0_watcher::Watcher;
16use tokio_util::sync::CancellationToken;
17use tracing::{Instrument, debug, debug_span, info};
18
19use crate::{
20    BroadcastTicket, Error,
21    node::Shared,
22    state::{PublicationEntry, State},
23};
24
25/// Who may see a publication.
26///
27/// See [`moq_ext_access::Audience`].
28pub type Audience = moq_ext_access::Audience<EndpointId>;
29
30/// An [`Audience`] as the registry keeps it: the current set, not its watcher.
31pub(crate) type AudienceKind = moq_ext_access::AudienceKind<EndpointId>;
32
33/// A published broadcast.
34///
35/// The broadcast lives in the node's route table: fill it through
36/// [`broadcast`](Self::broadcast), and every link whose peer may see it serves
37/// that one broadcast, with no copy in between.
38///
39/// Cheap to clone. The publication stays until [`unpublish`](Self::unpublish),
40/// until its broadcast closes, or until the node shuts down. Dropping the
41/// handles leaves it in place. [`unpublish_on_drop`](Self::unpublish_on_drop)
42/// ties it to a scope instead.
43///
44/// # Examples
45///
46/// ```no_run
47/// # fn run(node: iroh_live_node::Node, peer: iroh::EndpointId)
48/// # -> Result<(), Box<dyn std::error::Error>> {
49/// use std::collections::BTreeSet;
50///
51/// use iroh_live_node::Audience;
52///
53/// let publication = node.publish("live/studio", Audience::Granted)?;
54/// let _track = publication.broadcast().create_track("video", None).ok_or("the track exists")?;
55/// // Narrow it to one peer, who then holds the only route to it.
56/// let peers = n0_watcher::Watchable::new(BTreeSet::from([peer]));
57/// publication.set_audience(Audience::Peers(peers));
58/// println!("{}", publication.ticket());
59/// # Ok(())
60/// # }
61/// ```
62#[derive(Debug, Clone)]
63pub struct Publication {
64    inner: Arc<PublicationInner>,
65}
66
67/// What every clone of a [`Publication`] shares.
68#[derive(derive_more::Debug)]
69struct PublicationInner {
70    id: u64,
71    /// The id of the node that published.
72    publisher: EndpointId,
73    path: Path,
74    #[debug(skip)]
75    broadcast: broadcast::Producer,
76    #[debug(skip)]
77    shared: Weak<Shared>,
78    #[debug(skip)]
79    withdrawn: CancellationToken,
80}
81
82impl PartialEq for Publication {
83    fn eq(&self, other: &Self) -> bool {
84        self.inner.id == other.inner.id && Weak::ptr_eq(&self.inner.shared, &other.inner.shared)
85    }
86}
87
88impl Eq for Publication {}
89
90impl Publication {
91    /// Returns the path the broadcast is published at.
92    #[must_use]
93    pub fn path(&self) -> &Path {
94        &self.inner.path
95    }
96
97    /// Returns the ticket that names this publication.
98    ///
99    /// It holds the node's endpoint id and the path, and nothing about layouts.
100    #[must_use]
101    pub fn ticket(&self) -> BroadcastTicket {
102        BroadcastTicket::at(self.inner.publisher, self.inner.path.clone())
103    }
104
105    /// Returns the broadcast to fill.
106    ///
107    /// Tracks created here are what peers read. Closing it withdraws the
108    /// publication.
109    #[must_use]
110    pub fn broadcast(&self) -> &broadcast::Producer {
111        &self.inner.broadcast
112    }
113
114    /// Waits until the publication is withdrawn.
115    ///
116    /// Cancellation safe: dropping the future loses nothing.
117    pub async fn withdrawn(&self) {
118        self.inner.withdrawn.cancelled().await;
119    }
120
121    /// Reports whether the publication has been withdrawn.
122    #[must_use]
123    pub fn is_withdrawn(&self) -> bool {
124        self.inner.withdrawn.is_cancelled()
125    }
126
127    /// Changes who may see the publication.
128    ///
129    /// Takes effect on every live session at once: a peer that may no longer
130    /// see it loses the path, and what it reads there ends with
131    /// [`moq_net::Error::Unauthorized`]. Does nothing once withdrawn.
132    ///
133    /// # Panics
134    ///
135    /// Panics when called outside a Tokio runtime.
136    pub fn set_audience(&self, audience: Audience) {
137        let Some(shared) = self.inner.shared.upgrade() else {
138            return;
139        };
140        let mut state = shared.state.lock().expect("poisoned");
141        let id = self.inner.id;
142        let Some(entry) = state.publications.get_mut(&id) else {
143            return;
144        };
145        entry.audience_generation += 1;
146        entry.peers_task = peers_task(
147            &audience,
148            id,
149            entry.audience_generation,
150            &entry.path,
151            &self.inner.shared,
152        );
153        state.set_audience(id, AudienceKind::from(&audience));
154    }
155
156    /// Withdraws the publication from every link and from the route table.
157    ///
158    /// Peers lose the path, and what they read there ends with
159    /// [`moq_net::Error::Unauthorized`]. The broadcast stays open for whoever
160    /// holds it, unannounced.
161    pub fn unpublish(&self) {
162        let Some(shared) = self.inner.shared.upgrade() else {
163            return;
164        };
165        let removed = shared
166            .state
167            .lock()
168            .expect("poisoned")
169            .remove_publication(self.inner.id);
170        if let Some(entry) = removed {
171            info!(path = %entry.path, "unpublished");
172        }
173    }
174
175    /// Returns a guard that unpublishes the publication when it drops.
176    ///
177    /// For a publication that belongs to a task: when the task ends or is
178    /// aborted, the path is free again, and a later publish there does not
179    /// fail with [`Error::Duplicate`]. The guard unpublishes even while other
180    /// clones of the publication live. [`UnpublishOnDrop::disarm`] gives the
181    /// publication back without unpublishing.
182    ///
183    /// # Examples
184    ///
185    /// ```no_run
186    /// # fn run(node: iroh_live_node::Node) -> Result<(), iroh_live_node::Error> {
187    /// use iroh_live_node::Audience;
188    ///
189    /// let publication = node
190    ///     .publish("live/results", Audience::Granted)?
191    ///     .unpublish_on_drop();
192    /// let _track = publication.broadcast().create_track("result", None);
193    /// // Leaving the scope unpublishes `live/results`.
194    /// # Ok(())
195    /// # }
196    /// ```
197    pub fn unpublish_on_drop(self) -> UnpublishOnDrop {
198        UnpublishOnDrop {
199            publication: self,
200            armed: true,
201        }
202    }
203}
204
205/// A [`Publication`] that is unpublished when this guard drops.
206///
207/// Returned by [`Publication::unpublish_on_drop`]. Derefs to the publication.
208#[derive(Debug)]
209#[must_use = "dropping the guard unpublishes the publication at once"]
210pub struct UnpublishOnDrop {
211    publication: Publication,
212    armed: bool,
213}
214
215impl UnpublishOnDrop {
216    /// Returns the publication, which then stays published when the guard drops.
217    pub fn disarm(mut self) -> Publication {
218        self.armed = false;
219        self.publication.clone()
220    }
221}
222
223impl std::ops::Deref for UnpublishOnDrop {
224    type Target = Publication;
225
226    fn deref(&self) -> &Publication {
227        &self.publication
228    }
229}
230
231impl Drop for UnpublishOnDrop {
232    fn drop(&mut self) {
233        if self.armed {
234            debug!(path = %self.publication.path(), "guard dropped, unpublishing");
235            self.publication.unpublish();
236        }
237    }
238}
239
240/// Returns a task that re-authorizes the node's links as a `Peers` set changes.
241///
242/// `None` for any other audience. Holds the node weakly, since the task lives
243/// in the state it updates. `generation` is the publication's audience
244/// generation the task was started for.
245fn peers_task(
246    audience: &Audience,
247    id: u64,
248    generation: u64,
249    path: &Path,
250    shared: &Weak<Shared>,
251) -> Option<AbortOnDropHandle<()>> {
252    let Audience::Peers(set) = audience else {
253        return None;
254    };
255    let set = set.clone();
256    let shared = shared.clone();
257    let span = debug_span!("audience", %path, generation);
258    let task = async move {
259        let mut peers = set.watch();
260        // Applied once up front too, for a change made while publishing.
261        let mut current = peers.get();
262        loop {
263            {
264                let Some(shared) = shared.upgrade() else {
265                    return;
266                };
267                let mut state = shared.state.lock().expect("poisoned");
268                if !apply_peers(&mut state, id, generation, current) {
269                    return;
270                }
271            }
272            // This task holds `set`, so the watcher stays connected.
273            let Ok(next) = peers.updated().await else {
274                return;
275            };
276            current = next;
277        }
278    };
279    Some(AbortOnDropHandle::new(tokio::spawn(task.instrument(span))))
280}
281
282/// Sets publication `id`'s audience to `peers`, for the peers task of `generation`.
283///
284/// Returns `false`, and changes nothing, once the publication is gone or a
285/// later [`Publication::set_audience`] replaced that task. The task then
286/// ends: it may have been aborted while it waited on the lock.
287fn apply_peers(state: &mut State, id: u64, generation: u64, peers: BTreeSet<EndpointId>) -> bool {
288    let Some(entry) = state.publications.get(&id) else {
289        return false;
290    };
291    if entry.audience_generation != generation {
292        debug!(path = %entry.path, generation, "audience replaced, peers task ends");
293        return false;
294    }
295    debug!(path = %entry.path, generation, peers = peers.len(), "audience peers set");
296    state.set_audience(id, AudienceKind::Peers(peers));
297    true
298}
299
300/// Publishes a broadcast at `path`, for [`Node::publish`](crate::Node::publish).
301///
302/// Creates the broadcast and runs `fill` before taking the node's lock, so a
303/// fill that panics or calls back into the node cannot poison or deadlock
304/// it. The broadcast stays unannounced until, under the lock, every link
305/// is authorized for it.
306pub(crate) fn publish<T, E>(
307    shared: &Arc<Shared>,
308    path: Path,
309    audience: Audience,
310    fill: impl FnOnce(&broadcast::Producer) -> Result<T, E>,
311) -> Result<(Publication, T), Error>
312where
313    E: Into<Box<dyn std::error::Error + Send + Sync>>,
314{
315    check_path(&path)?;
316    if shared.shutdown.is_cancelled() {
317        return Err(e!(Error::ShutDown));
318    }
319    let (publication, filled) = filled_route(shared, &path, fill)?;
320    // Ends the broadcast `fill` may have spawned work on, if it is not published.
321    let refuse = |err: Error| {
322        publication.broadcast().close();
323        Err(err)
324    };
325    let weak = Arc::downgrade(shared);
326    let mut state = shared.state.lock().expect("poisoned");
327    if state.closed {
328        return refuse(e!(Error::ShutDown));
329    }
330    if let Err(err) = free_path(&mut state, &path) {
331        return refuse(err);
332    }
333    let broadcast = publication.broadcast().clone();
334    let id = state.next_id();
335    let closed_task = unpublish_when_closed(broadcast.consume(), weak.clone(), id, path.clone());
336    let withdrawn = CancellationToken::new();
337    // Every link is re-authorized for the publication before it is announced.
338    // A grant's prefix covers its subtree, so a link that sees a parent path
339    // would otherwise see a hidden child's announcement until its grant
340    // narrows. A grant that names a path not announced yet shows nothing.
341    state.add_publication(
342        id,
343        PublicationEntry {
344            path: path.clone(),
345            publication,
346            audience: AudienceKind::from(&audience),
347            peers_task: peers_task(&audience, id, 0, &path, &weak),
348            audience_generation: 0,
349            _closed_task: AbortOnDropHandle::new(closed_task),
350            withdrawn: withdrawn.clone(),
351        },
352    );
353    // Announced under the lock, so no link learns of the path before the
354    // table has it.
355    if let Err(source) = state.publications[&id].publication.announce() {
356        drop(state.remove_publication(id));
357        broadcast.close();
358        return Err(e!(Error::Moq { source }));
359    }
360    info!(%path, ?audience, "published");
361    let publication = Publication {
362        inner: Arc::new(PublicationInner {
363            id,
364            publisher: shared.id,
365            path,
366            broadcast,
367            shared: weak,
368            withdrawn,
369        }),
370    };
371    Ok((publication, filled))
372}
373
374/// Routes `path` in the node's table, hidden, and runs `fill` on its broadcast.
375///
376/// Filled before the announcement, so no reader finds the broadcast without
377/// the tracks `fill` creates. Closes the broadcast if `fill` fails.
378fn filled_route<T, E>(
379    shared: &Shared,
380    path: &Path,
381    fill: impl FnOnce(&broadcast::Producer) -> Result<T, E>,
382) -> Result<(origin::Route, T), Error>
383where
384    E: Into<Box<dyn std::error::Error + Send + Sync>>,
385{
386    let publication = shared
387        .table
388        .route(path.clone(), RouteOptions::hidden())
389        .map_err(|source| e!(Error::Moq { source }))?;
390    match fill(publication.broadcast()) {
391        Ok(filled) => Ok((publication, filled)),
392        Err(err) => {
393            publication.broadcast().close();
394            Err(e!(Error::Fill {
395                source: Arc::new(AnyError::from_std_box(err.into()))
396            }))
397        }
398    }
399}
400
401/// Frees `path` for a new publication, or fails if a live one holds it.
402fn free_path(state: &mut State, path: &Path) -> Result<(), Error> {
403    if let Some(existing) = state.publication_at(path) {
404        // An ended broadcast's closed task may not have run yet. Not a clash.
405        let entry = &state.publications[&existing];
406        if !entry.publication.broadcast().consume().is_closed() {
407            return Err(e!(Error::Duplicate { path: path.clone() }));
408        }
409        state.remove_publication(existing);
410    }
411    Ok(())
412}
413
414/// Spawns the task that removes publication `id` once its broadcast closes.
415fn unpublish_when_closed(
416    consumer: broadcast::Consumer,
417    shared: Weak<Shared>,
418    id: u64,
419    path: Path,
420) -> tokio::task::JoinHandle<()> {
421    tokio::spawn(async move {
422        consumer.closed().await;
423        let Some(shared) = shared.upgrade() else {
424            return;
425        };
426        let removed = shared
427            .state
428            .lock()
429            .expect("poisoned")
430            .remove_publication(id);
431        if removed.is_some() {
432            info!(%path, "broadcast ended, unpublished");
433        }
434    })
435}
436
437/// Refuses a path that is empty or that is no grant prefix.
438///
439/// moq grants have no escape for `*`, so a segment that holds one cannot be
440/// granted, and neither can a path with more segments than a prefix takes.
441pub(crate) fn check_path(path: &Path) -> Result<(), Error> {
442    if path.is_empty() || path.as_str().parse::<Prefix>().is_err() {
443        return Err(e!(Error::InvalidPath {
444            path: path.as_str().to_owned()
445        }));
446    }
447    Ok(())
448}
449
450#[cfg(test)]
451mod tests {
452    use iroh::{Endpoint, SecretKey};
453
454    use super::*;
455    use crate::{Node, NodeConfig};
456
457    #[test]
458    fn check_path_refuses_empty_and_wildcard_paths() {
459        let check = |path: &str| check_path(&Path::new(path).expect("a path"));
460        assert!(check("live/alice/cam").is_ok());
461        assert!(matches!(check(""), Err(Error::InvalidPath { .. })));
462        assert!(matches!(
463            check("live/*/cam"),
464            Err(Error::InvalidPath { .. })
465        ));
466        assert!(matches!(check("live/**"), Err(Error::InvalidPath { .. })));
467        assert!(matches!(
468            check("live/a*b/cam"),
469            Err(Error::InvalidPath { .. })
470        ));
471    }
472
473    /// Dropping the guard frees the path, and a disarmed guard leaves it published.
474    #[tokio::test]
475    async fn the_unpublish_guard_frees_the_path_unless_disarmed() {
476        let endpoint = Endpoint::bind(crate::MinimalPreset).await.expect("binds");
477        let node = Node::new(endpoint.clone(), NodeConfig::default());
478        let path = "live/test/results";
479
480        let guard = node
481            .publish(path, Audience::Granted)
482            .expect("publish")
483            .unpublish_on_drop();
484        let publication = Publication::clone(&guard);
485        drop(guard);
486        assert!(publication.is_withdrawn(), "the guard did not unpublish");
487
488        let kept = node
489            .publish(path, Audience::Granted)
490            .expect("the path is free again")
491            .unpublish_on_drop()
492            .disarm();
493        assert!(!kept.is_withdrawn(), "disarming unpublished");
494        let err = node
495            .publish(path, Audience::Granted)
496            .expect_err("the disarmed publication still holds the path");
497        assert!(matches!(err, Error::Duplicate { .. }), "{err:#}");
498
499        node.shutdown().await;
500        endpoint.close().await;
501    }
502
503    /// A peers task that `set_audience` replaced cannot write its old set back.
504    ///
505    /// Aborting the task does not stop one that already waits on the lock, so
506    /// this calls the step it takes under the lock with its old generation.
507    #[tokio::test]
508    async fn a_replaced_peers_task_does_not_restore_its_set() {
509        let endpoint = Endpoint::bind(crate::MinimalPreset).await.expect("binds");
510        let node = Node::new(endpoint.clone(), NodeConfig::default());
511        let (revoked, kept) = (
512            SecretKey::generate().public(),
513            SecretKey::generate().public(),
514        );
515        let old = BTreeSet::from([revoked, kept]);
516        let publication = node
517            .publish("live/test/cam", Audience::peers(old.clone()))
518            .expect("publish");
519        let new = BTreeSet::from([kept]);
520        publication.set_audience(Audience::peers(new.clone()));
521
522        let id = publication.inner.id;
523        {
524            let mut state = node.shared.state.lock().expect("poisoned");
525            assert!(!apply_peers(&mut state, id, 0, old), "the old task wrote");
526            assert_eq!(state.publications[&id].audience, AudienceKind::Peers(new));
527        }
528
529        node.shutdown().await;
530        endpoint.close().await;
531    }
532}