Skip to main content

iroh_live/
calls.rs

1//! One-to-one calls over a layout's call path.
2//!
3//! [`Calls`] publishes this node's side of its calls at `<root>/<its id>/call`
4//! and offers it to nobody until [`ring`](Calls::ring) adds a peer to its
5//! audience. A peer learns it is called when that path appears in its route
6//! table, and answers by ringing back and subscribing to the caller's side.
7//! Two peers that ring each other at once resolve into one [`Call`] on each
8//! side.
9//!
10//! A peer that was hung up on rings again only once it withdraws its side and
11//! offers it anew. Publishing the side again without a withdrawal in between
12//! is no new offer, since the route table lists the path throughout.
13//!
14//! ```no_run
15//! use iroh_live::{Node, calls::Calls, layout::LiveLayout};
16//! use moq_net::broadcast;
17//!
18//! # async fn run(node: Node, peer: iroh::EndpointId) -> Result<(), Box<dyn std::error::Error>> {
19//! let (calls, _side): (Calls, broadcast::Producer) = Calls::new(&node, &LiveLayout::default())?;
20//!
21//! // Place a call: ring, wait for the peer to answer, subscribe.
22//! let call = tokio::time::timeout(std::time::Duration::from_secs(30), calls.call(peer)).await??;
23//!
24//! // Take the first call that rings.
25//! let peer = calls.next_ring().await.ok_or("the call service ended")?;
26//! let answered = calls.answer(peer).await?;
27//! // Ends with the reason once the peer hangs up.
28//! let reason = answered.ended().await;
29//! # drop(reason);
30//! # drop(call);
31//! # Ok(())
32//! # }
33//! ```
34//!
35//! [`Calls::call`] and [`Calls::answer`] are cancellation safe: dropping the
36//! future hangs up. [`Call::ended`] and [`Calls::closed`] lose nothing when
37//! dropped.
38
39use std::{
40    collections::{BTreeMap, BTreeSet},
41    sync::{Arc, Mutex, MutexGuard, OnceLock, Weak},
42};
43
44use iroh::EndpointId;
45use iroh_live_node::{Audience, BroadcastTicket, Node, Publication, Reach, Session, Subscription};
46use moq_net::{announce::Event, broadcast};
47use n0_error::{e, stack_error};
48use n0_future::task::AbortOnDropHandle;
49use n0_watcher::{Watchable, Watcher};
50use tokio::select;
51use tokio_util::sync::CancellationToken;
52use tracing::{debug, info, warn};
53
54use crate::layout::LiveLayout;
55
56/// The broadcast name of a call side, as `irl call` and the Android demo use it.
57pub const CALL: &str = "call";
58
59/// Why a call ended.
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub enum HangUpReason {
62    /// The peer withdrew its side of the call.
63    Withdrawn,
64    /// The session with the peer ended.
65    Lost,
66}
67
68/// An error from [`Calls`].
69#[stack_error(derive, add_meta, from_sources)]
70pub enum Error {
71    /// The peer is not calling this node.
72    #[error("{peer} is not ringing")]
73    NotRinging { peer: EndpointId },
74    /// A call with the peer is in progress or being placed.
75    #[error("already in a call with {peer}")]
76    AlreadyInCall { peer: EndpointId },
77    /// The peer's session ended before it offered its side of the call.
78    #[error("{peer} did not answer")]
79    NotAnswered { peer: EndpointId },
80    /// The node failed.
81    #[error(transparent)]
82    Node(iroh_live_node::Error),
83}
84
85/// What the call service keeps under one lock.
86#[derive(Debug, Default)]
87struct CallState {
88    /// Peers whose side is in the route table.
89    visible: BTreeSet<EndpointId>,
90    /// Calls being placed.
91    pending: BTreeSet<EndpointId>,
92    /// Calls in progress.
93    active: BTreeSet<EndpointId>,
94    /// Peers that were hung up on, until they withdraw their side.
95    ended: BTreeSet<EndpointId>,
96    /// Dials started by [`Calls::ring`].
97    dialing: BTreeMap<EndpointId, AbortOnDropHandle<()>>,
98}
99
100impl CallState {
101    /// Returns the peers that ring, as [`Calls::ringing`] describes.
102    fn ringing(&self) -> BTreeSet<EndpointId> {
103        self.visible
104            .iter()
105            .filter(|&peer| {
106                !self.pending.contains(peer)
107                    && !self.active.contains(peer)
108                    && !self.ended.contains(peer)
109            })
110            .copied()
111            .collect()
112    }
113}
114
115/// The shared state behind every clone of [`Calls`] and every [`Call`].
116struct Inner {
117    node: Node,
118    layout: LiveLayout,
119    /// The ticket a peer calls this node with.
120    ticket: BroadcastTicket,
121    /// Who this node's side is offered to.
122    audience: Watchable<BTreeSet<EndpointId>>,
123    /// The peers that ring, as [`CallState::ringing`] derives them.
124    ringing: Watchable<BTreeSet<EndpointId>>,
125    /// Cancelled once the service ends.
126    closed: CancellationToken,
127    state: Mutex<CallState>,
128    /// Keeps the announce watcher alive for as long as the service is.
129    task: OnceLock<AbortOnDropHandle<()>>,
130}
131
132impl Inner {
133    /// Updates the ringing set from `state`.
134    fn update_ringing(&self, state: &CallState) {
135        let now = state.ringing();
136        let before = self.ringing.get();
137        if now == before {
138            return;
139        }
140        for peer in now.difference(&before) {
141            debug!(peer = %peer.fmt_short(), "ringing");
142        }
143        self.ringing.set(now).ok();
144    }
145
146    /// Returns the open session with `peer`, if there is one.
147    fn session_with(&self, peer: EndpointId) -> Option<Session> {
148        self.node
149            .sessions()
150            .get()
151            .into_iter()
152            .find(|session| session.peer() == peer)
153            .filter(|session| session.connection().close_reason().is_none())
154    }
155
156    /// Returns why the call with `peer` ended, once its side is gone.
157    fn hang_up_reason(&self, peer: EndpointId) -> HangUpReason {
158        match self.session_with(peer) {
159            Some(_) => HangUpReason::Withdrawn,
160            None => HangUpReason::Lost,
161        }
162    }
163
164    /// Locks the call state.
165    fn lock(&self) -> MutexGuard<'_, CallState> {
166        self.state.lock().expect("poisoned")
167    }
168
169    /// Takes `peer` out of the audience and the call bookkeeping, as a hang-up does.
170    ///
171    /// Takes `state` so the audience changes under the state lock.
172    fn withdraw(&self, peer: EndpointId, state: &mut CallState) {
173        let mut audience = self.audience.get();
174        if audience.remove(&peer) {
175            self.audience.set(audience).ok();
176        }
177        state.pending.remove(&peer);
178        state.dialing.remove(&peer);
179    }
180}
181
182/// The call service of a node.
183///
184/// Cheap to clone. See the [module](self) for the protocol.
185///
186/// # Examples
187///
188/// ```no_run
189/// # async fn run(node: iroh_live::Node, peer: iroh::EndpointId)
190/// # -> Result<(), Box<dyn std::error::Error>> {
191/// use iroh_live::{calls::Calls, layout::LiveLayout};
192/// use moq_net::broadcast;
193///
194/// let (calls, side): (Calls, broadcast::Producer) = Calls::new(&node, &LiveLayout::default())?;
195/// let call = calls.call(peer).await?;
196/// // Fill `side` with tracks and read the peer's side from the call.
197/// # drop((call, side));
198/// # Ok(())
199/// # }
200/// ```
201#[derive(Clone, derive_more::Debug)]
202#[debug("Calls({})", inner.node.id().fmt_short())]
203pub struct Calls {
204    inner: Arc<Inner>,
205}
206
207impl Calls {
208    /// Publishes this node's call side at `<root>/<its id>/call` and starts the service.
209    ///
210    /// Returns the service with the side, which is visible to nobody until a
211    /// peer is rung. One side serves every call in turn, so a camera and a
212    /// preview keep running between calls. `B` is built from the route
213    /// table's `broadcast::Producer` before the path is announced: a
214    /// `LocalBroadcast`, or the producer itself.
215    ///
216    /// For a `LocalBroadcast`, dropping the side ends every call and
217    /// [`closed`](Self::closed) resolves. A bare producer has to be closed by
218    /// the application.
219    ///
220    /// Each node's policy has to let the other publish at
221    /// `<root>/<peer id>/call`, as [`LiveLayout::policy`] does. Otherwise
222    /// [`call`](Self::call) and [`answer`](Self::answer) fail with
223    /// [`NotGranted`](iroh_live_node::Error::NotGranted).
224    ///
225    /// # Errors
226    ///
227    /// Fails with [`Error::Node`] if the side is already published or `B`
228    /// cannot be built.
229    ///
230    /// # Panics
231    ///
232    /// Panics when called outside a Tokio runtime.
233    pub fn new<B>(node: &Node, layout: &LiveLayout) -> Result<(Self, B), Error>
234    where
235        B: TryFrom<broadcast::Producer, Error: std::error::Error + Send + Sync + 'static>,
236    {
237        let local_id = node.id();
238        let path = layout.path(local_id, CALL)?;
239        let ticket = BroadcastTicket::at(local_id, path.clone());
240        let audience = Watchable::new(BTreeSet::new());
241        let (publication, side) =
242            node.publish_with(path, Audience::Peers(audience.clone()), |producer| {
243                B::try_from(producer.clone())
244            })?;
245        let inner = Arc::new(Inner {
246            node: node.clone(),
247            layout: layout.clone(),
248            ticket,
249            audience,
250            ringing: Watchable::new(BTreeSet::new()),
251            closed: CancellationToken::new(),
252            state: Mutex::new(CallState::default()),
253            task: OnceLock::new(),
254        });
255        let task = tokio::spawn(watch_rings(Arc::downgrade(&inner), publication));
256        inner.task.set(AbortOnDropHandle::new(task)).ok();
257        info!(id = %local_id.fmt_short(), "calls started");
258        Ok((Self { inner }, side))
259    }
260
261    /// Rings `peer`: offers it this node's side, and dials it if no session exists.
262    ///
263    /// Non-blocking and idempotent. The peer sees the side appear in its route
264    /// table.
265    ///
266    /// # Panics
267    ///
268    /// Panics when called outside a Tokio runtime.
269    pub fn ring(&self, peer: EndpointId) {
270        // The audience changes under the state lock, as in `withdraw`, so a
271        // ring and a hang-up at once cannot lose either update.
272        let mut state = self.inner.lock();
273        let mut audience = self.inner.audience.get();
274        if audience.insert(peer) {
275            self.inner.audience.set(audience).ok();
276        }
277        // A session that is closing does not count, or a ring right after a
278        // hang-up would skip the redial.
279        let connected = self.inner.session_with(peer).is_some();
280        if connected || state.dialing.contains_key(&peer) {
281            return;
282        }
283        let node = self.inner.node.clone();
284        let inner = Arc::downgrade(&self.inner);
285        let dial = tokio::spawn(async move {
286            if let Err(err) = node.connect(peer).await {
287                warn!(peer = %peer.fmt_short(), error = %err, "could not dial the peer to ring it");
288            }
289            if let Some(inner) = inner.upgrade() {
290                inner.lock().dialing.remove(&peer);
291            }
292        });
293        state.dialing.insert(peer, AbortOnDropHandle::new(dial));
294    }
295
296    /// Calls `peer`: rings it, waits until it answers, and subscribes to its side.
297    ///
298    /// Waits as long as the peer takes to answer, so bound it with a timeout.
299    /// Dropping the future hangs up.
300    ///
301    /// # Errors
302    ///
303    /// Fails with [`Error::AlreadyInCall`] if a call with `peer` exists,
304    /// [`Error::NotAnswered`] if the session ends first, and [`Error::Node`]
305    /// otherwise, holding [`NotGranted`](iroh_live_node::Error::NotGranted)
306    /// if the session's grant does not let the peer publish its side.
307    pub async fn call(&self, peer: EndpointId) -> Result<Call, Error> {
308        let pending = self.begin(peer, false)?;
309        self.ring(peer);
310        self.subscribe(pending, peer).await
311    }
312
313    /// Answers the call of `peer`: rings it back, and subscribes to its side.
314    ///
315    /// Dropping the future hangs up.
316    ///
317    /// # Errors
318    ///
319    /// Fails with [`Error::NotRinging`] if `peer` is not calling, and as
320    /// [`call`](Self::call) otherwise.
321    pub async fn answer(&self, peer: EndpointId) -> Result<Call, Error> {
322        let pending = self.begin(peer, true)?;
323        self.ring(peer);
324        self.subscribe(pending, peer).await
325    }
326
327    /// Returns the peers that ring this node now, as they change.
328    ///
329    /// These are the peers whose side is visible, in no call, and not hung up
330    /// on since they last offered their side. A peer leaves the set when it
331    /// withdraws its side before an answer, and when this node answers or
332    /// calls it. [`Call::ended`] reports how a call in progress ends.
333    #[must_use]
334    pub fn ringing(&self) -> n0_watcher::Direct<BTreeSet<EndpointId>> {
335        self.inner.ringing.watch()
336    }
337
338    /// Returns the ticket a peer calls this node with.
339    ///
340    /// It names this node's side, `<root>/<its id>/call`. A peer passes its
341    /// [`peer`](BroadcastTicket::peer) to [`call`](Self::call).
342    #[must_use]
343    pub fn ticket(&self) -> BroadcastTicket {
344        self.inner.ticket.clone()
345    }
346
347    /// Waits until a peer rings, and returns the first that does.
348    ///
349    /// Returns a peer that rings already at once. Returns `None` once the
350    /// service ends. Cancellation safe.
351    pub async fn next_ring(&self) -> Option<EndpointId> {
352        let mut ringing = self.ringing();
353        let first = async {
354            loop {
355                if let Some(peer) = ringing.get().first().copied() {
356                    return Some(peer);
357                }
358                ringing.updated().await.ok()?;
359            }
360        };
361        select! {
362            peer = first => peer,
363            () = self.closed() => None,
364        }
365    }
366
367    /// Waits until the service ends: the node shut down, or the call side was withdrawn.
368    ///
369    /// Cancellation safe.
370    pub async fn closed(&self) {
371        self.inner.closed.cancelled().await;
372    }
373
374    /// Marks a call with `peer` as being placed.
375    fn begin(&self, peer: EndpointId, must_ring: bool) -> Result<Pending, Error> {
376        let mut state = self.inner.lock();
377        if state.active.contains(&peer) || state.pending.contains(&peer) {
378            return Err(e!(Error::AlreadyInCall { peer }));
379        }
380        if must_ring && !state.ringing().contains(&peer) {
381            return Err(e!(Error::NotRinging { peer }));
382        }
383        state.pending.insert(peer);
384        self.inner.update_ringing(&state);
385        Ok(Pending {
386            inner: self.inner.clone(),
387            peer,
388            connected: false,
389        })
390    }
391
392    /// Subscribes to the side of `peer`, which it offers once it answers.
393    async fn subscribe(&self, mut pending: Pending, peer: EndpointId) -> Result<Call, Error> {
394        let path = self.inner.layout.path(peer, CALL)?;
395        let subscription = self
396            .inner
397            .node
398            .subscribe(path, Reach::Direct(peer))
399            .await
400            .map_err(|err| match err {
401                iroh_live_node::Error::NotAnnounced { .. } => e!(Error::NotAnswered { peer }),
402                err => Error::from(err),
403            })?;
404        let mut state = self.inner.lock();
405        state.pending.remove(&peer);
406        state.active.insert(peer);
407        self.inner.update_ringing(&state);
408        pending.connected = true;
409        info!(peer = %peer.fmt_short(), "call connected");
410        Ok(Call {
411            inner: self.inner.clone(),
412            peer,
413            subscription,
414        })
415    }
416}
417
418/// A call being placed.
419///
420/// Dropping it before the call connects hangs up.
421struct Pending {
422    inner: Arc<Inner>,
423    peer: EndpointId,
424    /// Set once the call connects, so the drop does not hang up.
425    connected: bool,
426}
427
428impl Drop for Pending {
429    fn drop(&mut self) {
430        if self.connected {
431            return;
432        }
433        let mut state = self.inner.lock();
434        self.inner.withdraw(self.peer, &mut state);
435        self.inner.update_ringing(&state);
436        debug!(peer = %self.peer.fmt_short(), "call attempt dropped");
437    }
438}
439
440/// A call in progress.
441///
442/// Dropping it, or [`hang_up`](Self::hang_up), ends the call. See the
443/// [module](self) for when the peer can ring again.
444#[derive(derive_more::Debug)]
445#[must_use = "dropping a `Call` hangs up"]
446#[debug("Call({})", peer.fmt_short())]
447pub struct Call {
448    inner: Arc<Inner>,
449    peer: EndpointId,
450    subscription: Subscription,
451}
452
453impl Call {
454    /// Returns the peer on the other side.
455    #[must_use]
456    pub fn peer(&self) -> EndpointId {
457        self.peer
458    }
459
460    /// Returns the subscription to the peer's side.
461    #[must_use]
462    pub fn subscription(&self) -> &Subscription {
463        &self.subscription
464    }
465
466    /// Ends the call.
467    pub fn hang_up(self) {}
468
469    /// Waits until the call ends, and returns why.
470    ///
471    /// Cancellation safe.
472    pub async fn ended(&self) -> HangUpReason {
473        let broadcast = self.subscription.broadcast();
474        let mut sessions = self.inner.node.sessions();
475        // The session is looked up on every pass rather than kept from the
476        // connect, since the node may list it only after the subscribe returns.
477        loop {
478            match self.inner.session_with(self.peer) {
479                Some(session) => {
480                    return select! {
481                        _ = session.closed() => HangUpReason::Lost,
482                        _ = broadcast.closed() => self.inner.hang_up_reason(self.peer),
483                    };
484                }
485                None => select! {
486                    _ = broadcast.closed() => return HangUpReason::Lost,
487                    updated = sessions.updated() => if updated.is_err() {
488                        return HangUpReason::Lost;
489                    },
490                },
491            }
492        }
493    }
494}
495
496impl Drop for Call {
497    fn drop(&mut self) {
498        let mut state = self.inner.lock();
499        self.inner.withdraw(self.peer, &mut state);
500        state.active.remove(&self.peer);
501        if state.visible.contains(&self.peer) {
502            state.ended.insert(self.peer);
503        }
504        self.inner.update_ringing(&state);
505        info!(peer = %self.peer.fmt_short(), "call ended");
506    }
507}
508
509/// Follows the route table for rings, until the node or the call side ends.
510///
511/// Holds the service weakly, so dropping every handle stops it.
512async fn watch_rings(inner: Weak<Inner>, publication: Publication) {
513    let Some(strong) = inner.upgrade() else {
514        return;
515    };
516    let node = strong.node.clone();
517    let layout = strong.layout.clone();
518    drop(strong);
519    let local_id = node.id();
520    let mut announced = node.origin().announced();
521    let node_closed = node.closed();
522    tokio::pin!(node_closed);
523    let withdrawn = publication.withdrawn();
524    tokio::pin!(withdrawn);
525    loop {
526        let event = select! {
527            event = announced.next() => match event {
528                Some(event) => event,
529                None => break,
530            },
531            () = &mut node_closed => break,
532            () = &mut withdrawn => break,
533        };
534        let Some(inner) = inner.upgrade() else {
535            return;
536        };
537        let (announce, present) = match &event {
538            Event::Present(announce) => (announce, true),
539            Event::Absent(announce) => (announce, false),
540            _ => continue,
541        };
542        let Some((peer, CALL)) = layout.parse(&announce.prefix) else {
543            continue;
544        };
545        if peer == local_id {
546            continue;
547        }
548        let mut state = inner.lock();
549        if present {
550            state.visible.insert(peer);
551            state.ended.remove(&peer);
552        } else {
553            state.visible.remove(&peer);
554            state.ended.remove(&peer);
555        }
556        inner.update_ringing(&state);
557    }
558    if let Some(inner) = inner.upgrade() {
559        debug!(id = %local_id.fmt_short(), "calls closed");
560        inner.closed.cancel();
561    }
562}