Skip to main content

iroh_live_node/
relay.rs

1//! Relay links: staying attached to a media relay.
2//!
3//! A relay link feeds what the media relay announces into the route table, tagged
4//! [`Link::Upstream`], so a route from a media relay is never offered to another
5//! link. moq-tokio has no iroh transport, so `iroh://` media relays are dialed
6//! through the node's own endpoint by [`iroh_uplink`], which drives moq's
7//! connect policy, [`Reconnect`], as moq-tokio does for the other schemes.
8
9use std::{
10    pin::Pin,
11    sync::{Arc, Weak},
12    task::Poll,
13    time::Duration,
14};
15
16use iroh::EndpointId;
17use moq_net::{
18    Reconnect, auth,
19    auth::Token,
20    origin::{self, Link},
21    reconnect::{self, Action, Attempt, Verdict},
22};
23use moq_tokio::connection::Phase;
24use n0_error::{AnyError, e};
25use n0_future::{
26    join_all,
27    task::{AbortOnDropHandle, JoinSet},
28};
29use n0_watcher::Watchable;
30use tokio_util::sync::CancellationToken;
31use tracing::{Instrument, debug, info, info_span, warn};
32use url::Url;
33
34use crate::{
35    Error, LinkId, Node,
36    handshake::Hop,
37    link::{self, LatestSample},
38    node::{Shared, Tasks},
39    state::{LinkEntry, LinkRole, served},
40    transport,
41};
42
43/// The cost a relay link adds to every route through it.
44///
45/// Higher than a direct link's cost of one, so a direct route wins while it
46/// exists.
47const RELAY_COST: u64 = 10;
48
49/// How to attach to a media relay.
50#[derive(Debug, Clone)]
51#[non_exhaustive]
52pub struct RelayConfig {
53    /// The media relay to dial: `iroh://<endpoint-id>/<path>` or `https://host/<path>`.
54    ///
55    /// The path and query are the ones the session requests, such as a
56    /// ticket the media relay pulls. A `jwt` in the query is the connection
57    /// credential, ahead of [`tokens`](Self::tokens).
58    pub url: Url,
59    /// The tokens the node presents to the media relay, the first as the connection credential.
60    ///
61    /// Every dial presents them, in the MoQ SETUP and as `?jwt=` in the URL,
62    /// since the SETUP of moq-lite-06 has no token field. Replace them on a
63    /// live link through [`RelayLink::tokens`], before the old ones expire.
64    pub tokens: Vec<Token>,
65    /// Whether the media relay's routes enter the node's route table.
66    ///
67    /// A node that only publishes through the media relay should turn this off.
68    /// Either way the media relay is offered every publication whose audience is
69    /// [`Granted`](crate::Audience::Granted), since a relay link's grant
70    /// covers every path: publish to [`Peers`](crate::Audience::Peers) to
71    /// keep a publication off it.
72    pub consume: bool,
73}
74
75impl RelayConfig {
76    /// Creates a config for the media relay at `url`, consuming what the media relay routes.
77    #[must_use]
78    pub fn new(url: Url) -> Self {
79        Self {
80            url,
81            tokens: Vec::new(),
82            consume: true,
83        }
84    }
85
86    /// Returns this config with `consume` saying whether the media relay's routes enter the route table.
87    ///
88    /// See [`consume`](Self::consume).
89    #[must_use]
90    pub fn with_consume(mut self, consume: bool) -> Self {
91        self.consume = consume;
92        self
93    }
94
95    /// Creates a config for the media relay with endpoint id `relay`, dialed over iroh.
96    #[must_use]
97    pub fn iroh(relay: EndpointId) -> Self {
98        let url = format!("iroh://{relay}/")
99            .parse()
100            .expect("an endpoint id is a valid URL host");
101        Self::new(url)
102    }
103
104    /// Presents `token` as the connection credential.
105    ///
106    /// # Examples
107    ///
108    /// ```
109    /// use iroh_live_node::RelayConfig;
110    ///
111    /// let relay = iroh::SecretKey::generate().public();
112    /// let token = "a.signed.jwt".parse().expect("not empty");
113    /// let config = RelayConfig::iroh(relay).with_token(token);
114    /// assert_eq!(config.tokens.len(), 1);
115    /// ```
116    #[must_use]
117    pub fn with_token(mut self, token: Token) -> Self {
118        self.tokens = vec![token];
119        self
120    }
121}
122
123/// The state of a relay link.
124#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
125pub enum RelayStatus {
126    /// Dialing for the first time.
127    #[default]
128    Connecting,
129    /// A session with the media relay is up.
130    Connected,
131    /// The session dropped, and the link redials with backoff.
132    Reconnecting,
133    /// The link was detached, or the node shut down.
134    Detached,
135}
136
137/// A media relay this node stays attached to.
138///
139/// Cheap to clone. The link stays until [`detach`](Self::detach) or the node's
140/// shutdown. Dropping the handles leaves it in place.
141///
142/// # Examples
143///
144/// ```no_run
145/// # async fn run(node: iroh_live_node::Node, relay: iroh::EndpointId)
146/// # -> Result<(), iroh_live_node::Error> {
147/// use iroh_live_node::{RelayConfig, RelayStatus};
148/// use n0_watcher::Watcher;
149///
150/// let link = node.attach_relay(RelayConfig::iroh(relay))?;
151/// let mut status = link.status();
152/// while status.get() != RelayStatus::Connected {
153///     status.updated().await.ok();
154/// }
155/// link.detach().await;
156/// # Ok(())
157/// # }
158/// ```
159#[derive(Debug, Clone)]
160pub struct RelayLink {
161    inner: Arc<RelayInner>,
162}
163
164/// What every clone of a [`RelayLink`] shares.
165#[derive(derive_more::Debug)]
166struct RelayInner {
167    link: LinkId,
168    url: Url,
169    status: Watchable<RelayStatus>,
170    #[debug(skip)]
171    tokens: auth::Tokens,
172    #[debug(skip)]
173    uplink: Uplink,
174    #[debug(skip)]
175    shared: Weak<Shared>,
176    #[debug(skip)]
177    tasks: Weak<Tasks>,
178}
179
180impl RelayLink {
181    /// Returns the media relay's status, as it changes.
182    #[must_use]
183    pub fn status(&self) -> n0_watcher::Direct<RelayStatus> {
184        self.inner.status.watch()
185    }
186
187    /// Returns this link's id, as [`ServingLink::id`](crate::ServingLink::id) names it.
188    #[must_use]
189    pub fn id(&self) -> LinkId {
190        self.inner.link
191    }
192
193    /// Returns the tokens the link presents, seeded from [`RelayConfig::tokens`].
194    ///
195    /// [`Tokens::set`](auth::Tokens::set) replaces them for every later dial,
196    /// and a media relay that refused the old ones is dialed again at once. Set new
197    /// ones before the old ones expire.
198    #[must_use]
199    pub fn tokens(&self) -> auth::Tokens {
200        self.inner.tokens.clone()
201    }
202
203    /// Detaches from the media relay.
204    ///
205    /// Closes the session, stops redialing and withdraws the media relay's routes.
206    /// Idempotent. Cancellation safe: the link's task finishes the close.
207    pub async fn detach(&self) {
208        info!(url = %self.inner.url, "detaching relay");
209        match &self.inner.uplink {
210            Uplink::Tokio(connection) => {
211                connection.abort(moq_net::Error::Cancel);
212                closed(&connection.monitor()).await;
213            }
214            Uplink::Iroh { stop, .. } => stop.cancel(),
215        }
216        if let Some(tasks) = self.inner.tasks.upgrade()
217            && let Some(relay) = tasks.remove_relay(self.inner.link)
218        {
219            // Let the task close its session before it is dropped, which
220            // would abort it.
221            relay.finish().await;
222        }
223        if let Some(shared) = self.inner.shared.upgrade() {
224            shared
225                .state
226                .lock()
227                .expect("poisoned")
228                .remove_link(self.inner.link);
229        }
230        self.inner.status.set(RelayStatus::Detached).ok();
231    }
232}
233
234/// A relay link's task, and the status it reports.
235pub(crate) struct RelayTask {
236    task: AbortOnDropHandle<()>,
237    status: Watchable<RelayStatus>,
238}
239
240impl Tasks {
241    /// Keeps a relay link's task running until the link detaches.
242    fn insert_relay(&self, link: LinkId, task: RelayTask) {
243        let mut relays = self.relays.lock().expect("poisoned");
244        // Drop the handles of links whose client gave up.
245        relays.retain(|_, relay| !relay.task.is_finished());
246        relays.insert(link, task);
247    }
248
249    /// Takes a relay link's task out, to be finished.
250    fn remove_relay(&self, link: LinkId) -> Option<RelayTask> {
251        self.relays.lock().expect("poisoned").remove(&link)
252    }
253
254    /// Aborts every relay link's task, reporting each detached.
255    ///
256    /// An aborted task never reaches its own report, so this makes it.
257    pub(crate) fn detach_relays(&self) {
258        let relays = std::mem::take(&mut *self.relays.lock().expect("poisoned"));
259        for (_, relay) in relays {
260            drop(relay.task);
261            relay.status.set(RelayStatus::Detached).ok();
262        }
263    }
264
265    /// Waits for every relay link's task to close its session.
266    ///
267    /// The node's shutdown token must be cancelled already.
268    pub(crate) async fn shutdown_relays(&self) {
269        let relays = std::mem::take(&mut *self.relays.lock().expect("poisoned"));
270        join_all(relays.into_values().map(RelayTask::finish)).await;
271    }
272}
273
274impl RelayTask {
275    /// Waits for the task to end, then reports the link detached.
276    ///
277    /// Aborts the task if it outlives the shutdown grace.
278    async fn finish(mut self) {
279        if tokio::time::timeout(crate::actor::SHUTDOWN_GRACE, &mut self.task)
280            .await
281            .is_err()
282        {
283            warn!("relay task did not stop in time, aborting");
284        }
285        self.status.set(RelayStatus::Detached).ok();
286    }
287}
288
289/// Attaches `node` to a media relay, for [`Node::attach_relay`].
290pub(crate) fn attach(node: &Node, config: RelayConfig) -> Result<RelayLink, Error> {
291    let shared = &node.shared;
292    if shared.shutdown.is_cancelled() {
293        return Err(e!(Error::ShutDown));
294    }
295    let iroh_relay = iroh_relay(&config.url)?;
296    // A relay that declares a hop of its own is matched by kind instead.
297    let hop = Hop::of(&iroh_relay.unwrap_or_else(|| iroh::SecretKey::generate().public()));
298    let subscriber = config
299        .consume
300        .then(|| shared.table.clone().with_link(Link::Upstream));
301    let (uplink, tokens) = uplink(shared, &config, iroh_relay, &hop, subscriber.clone())?;
302    let latest_sample = LatestSample::default();
303    let link = register(
304        shared,
305        &uplink,
306        LinkEntry {
307            role: LinkRole::Relay {
308                consume: config.consume,
309            },
310            hop,
311            auth: tokens.handle(),
312            latest_sample: latest_sample.clone(),
313        },
314    )?;
315    let url = config.url.clone();
316    info!(%url, consume = config.consume, "attaching relay");
317    let status = Watchable::new(RelayStatus::Connecting);
318    let task = spawn_uplink(
319        &uplink,
320        LinkParts {
321            shared: shared.clone(),
322            config,
323            tokens: tokens.clone(),
324            subscriber,
325            link,
326            latest_sample,
327            status: status.clone(),
328        },
329    );
330    node.tasks.insert_relay(
331        link,
332        RelayTask {
333            task: AbortOnDropHandle::new(task),
334            status: status.clone(),
335        },
336    );
337    // A shutdown that ran between the check above and the insert found no
338    // task to stop, so stop it here instead.
339    if shared.shutdown.is_cancelled() {
340        node.tasks.detach_relays();
341        return Err(e!(Error::ShutDown));
342    }
343    Ok(RelayLink {
344        inner: Arc::new(RelayInner {
345            link,
346            url,
347            status,
348            tokens,
349            uplink,
350            shared: Arc::downgrade(shared),
351            tasks: Arc::downgrade(&node.tasks),
352        }),
353    })
354}
355
356/// Returns the endpoint id an `iroh://` media relay URL names, or `None` for another scheme.
357fn iroh_relay(url: &Url) -> Result<Option<EndpointId>, Error> {
358    match url.scheme() {
359        "iroh" => url
360            .host_str()
361            .and_then(|host| host.parse::<EndpointId>().ok())
362            .map(Some)
363            .ok_or_else(|| {
364                e!(Error::InvalidRelayUrl {
365                    url: Box::new(url.clone()),
366                    reason: "the host is not an endpoint id",
367                })
368            }),
369        "https" | "http" | "moqt" | "moql" => Ok(None),
370        _ => Err(e!(Error::InvalidRelayUrl {
371            url: Box::new(url.clone()),
372            reason: "unsupported scheme, use iroh:// or https://",
373        })),
374    }
375}
376
377/// Builds the uplink to a media relay, and the tokens its sessions present.
378///
379/// A moq-tokio connection starts dialing at once and keeps its own tokens
380/// across redials. The tokens' handle is the authorization every session of
381/// the link shares.
382fn uplink(
383    shared: &Arc<Shared>,
384    config: &RelayConfig,
385    iroh_relay: Option<EndpointId>,
386    hop: &Hop,
387    subscriber: Option<origin::Producer>,
388) -> Result<(Uplink, auth::Tokens), Error> {
389    if let Some(relay) = iroh_relay {
390        let uplink = Uplink::Iroh {
391            relay,
392            stop: CancellationToken::new(),
393        };
394        return Ok((uplink, auth::Tokens::new(config.tokens.clone())));
395    }
396    // The client's TLS config reads the process default, and moq installs
397    // rind there if nothing is installed. Install the selected backend first,
398    // for a node whose endpoint was not bound through `MoqPreset`.
399    crate::crypto_provider();
400    let mut tokio_config = moq_tokio::client::Config::default();
401    tokio_config.connect.tokens = config.tokens.clone();
402    let mut client = tokio_config
403        .init()
404        .map_err(|err| {
405            e!(Error::Relay {
406                source: Arc::new(AnyError::from_std(err))
407            })
408        })?
409        .with_publisher(served(&shared.table))
410        .with_peer_node(hop.id())
411        .with_cost(RELAY_COST);
412    if let Some(subscriber) = subscriber {
413        client = client.with_subscriber(subscriber);
414    }
415    let connection = client.connect(config.url.clone());
416    let tokens = connection.tokens();
417    Ok((Uplink::Tokio(Box::new(connection)), tokens))
418}
419
420/// Registers a relay link in the node's state, and returns its id.
421///
422/// Fails, and stops the uplink, if the node closed meanwhile.
423fn register(shared: &Shared, uplink: &Uplink, entry: LinkEntry) -> Result<LinkId, Error> {
424    let mut state = shared.state.lock().expect("poisoned");
425    if state.closed {
426        if let Uplink::Tokio(connection) = uplink {
427            connection.abort(moq_net::Error::Cancel);
428        }
429        return Err(e!(Error::ShutDown));
430    }
431    let link = LinkId(state.next_id());
432    state.add_link(link, entry);
433    Ok(link)
434}
435
436/// What a relay link's uplink task owns.
437struct LinkParts {
438    shared: Arc<Shared>,
439    config: RelayConfig,
440    /// The tokens the link's sessions present, and the authorization they share.
441    tokens: auth::Tokens,
442    /// Where the media relay's announcements go, if the link consumes them.
443    subscriber: Option<origin::Producer>,
444    link: LinkId,
445    latest_sample: LatestSample,
446    status: Watchable<RelayStatus>,
447}
448
449/// Spawns the task that runs a relay link's uplink.
450fn spawn_uplink(uplink: &Uplink, parts: LinkParts) -> tokio::task::JoinHandle<()> {
451    let span = info_span!("relay", url = %parts.config.url, link = %parts.link);
452    match uplink {
453        Uplink::Iroh { relay, stop } => {
454            tokio::spawn(iroh_uplink(parts, *relay, stop.clone()).instrument(span))
455        }
456        Uplink::Tokio(connection) => {
457            let run = tokio_uplink(
458                parts.shared,
459                moq_tokio::Connecting::clone(connection),
460                parts.link,
461                parts.latest_sample,
462                parts.status,
463            );
464            tokio::spawn(run.instrument(span))
465        }
466    }
467}
468
469/// How a relay link reaches its media relay.
470enum Uplink {
471    /// A moq-tokio client connection, which redials itself once its first
472    /// session is established.
473    Tokio(Box<moq_tokio::Connecting>),
474    /// An iroh dial loop to the media relay with endpoint id `relay`, stopped by cancelling `stop`.
475    Iroh {
476        relay: EndpointId,
477        stop: CancellationToken,
478    },
479}
480
481/// The first pause before redialing a media relay.
482const REDIAL_MIN: Duration = Duration::from_secs(1);
483
484/// How long a session must last to reset the redial pause to [`REDIAL_MIN`].
485const STABLE_SESSION: Duration = Duration::from_secs(10);
486
487/// The longest pause between redials.
488const REDIAL_MAX: Duration = Duration::from_secs(30);
489
490/// Runs a moq-tokio relay link until its client gives up.
491async fn tokio_uplink(
492    shared: Arc<Shared>,
493    connection: moq_tokio::Connecting,
494    link: LinkId,
495    latest_sample: LatestSample,
496    status: Watchable<RelayStatus>,
497) {
498    let monitor = link::monitor_relay(connection.monitor(), latest_sample);
499    let watch = connection.monitor();
500    // Aborts the connection for every clone when the task ends, so a
501    // `RelayLink` handle held past shutdown does not keep redialing.
502    let _stop = StopOnDrop(connection);
503    let _monitor = AbortOnDropHandle::new(tokio::spawn(monitor));
504    let mut seen = watch.state();
505    loop {
506        match &seen.phase {
507            Phase::Connected { .. } | Phase::Migrating { .. } => {
508                if status.set(RelayStatus::Connected).is_ok() {
509                    info!("relay connected");
510                }
511            }
512            Phase::Disconnected { failure } => {
513                if status.set(RelayStatus::Reconnecting).is_ok() {
514                    warn!(error = ?failure, "relay session dropped, redialing");
515                }
516            }
517            Phase::Connecting { failure } => debug!(error = ?failure, "relay connecting"),
518            // A link that gave up, such as on a refused token, is worth a
519            // warning. One stopped locally is not.
520            Phase::Closed {
521                failure: Some(failure),
522            } => {
523                warn!(error = ?failure, "relay link closed for good");
524                break;
525            }
526            Phase::Closed { failure: None } => {
527                debug!("relay link closed");
528                break;
529            }
530        }
531        let update = tokio::select! {
532            // The connection aborts as the task ends.
533            _ = shared.shutdown.cancelled() => break,
534            update = watch.state_changed(seen.revision) => update,
535        };
536        match update {
537            Ok(observation) => seen = observation,
538            // A detach aborts the connection, which is no failure.
539            Err(moq_tokio::Error::Stopped) => {
540                debug!("relay link stopped");
541                break;
542            }
543            Err(err) => {
544                warn!(error = %err, "relay link ended");
545                break;
546            }
547        }
548    }
549    status.set(RelayStatus::Detached).ok();
550    shared.state.lock().expect("poisoned").remove_link(link);
551}
552
553/// Returns moq's connect policy for an iroh relay link.
554///
555/// The link redials forever with backoff from [`REDIAL_MIN`] to
556/// [`REDIAL_MAX`]. An endpoint id names one node, so a GOAWAY that names no
557/// new address redials it once, which reaches a replacement started beside
558/// the draining process, and otherwise keeps the drained session until the
559/// media relay closes it.
560fn policy_config() -> reconnect::Config {
561    let mut config = reconnect::Config::default();
562    config.backoff.initial = REDIAL_MIN;
563    config.backoff.max = Some(REDIAL_MAX);
564    config.backoff.healthy = STABLE_SESSION;
565    config.restart = reconnect::Restart::Handoff;
566    config
567}
568
569/// Runs an `iroh://` relay link until it is stopped.
570///
571/// moq's connect policy ends when its first walk reaches no session, and when
572/// the media relay refuses tokens that did not change since. This starts it again
573/// after a pause instead, so the link stays attached to a media relay that is down
574/// at attach time. The pause doubles up to [`REDIAL_MAX`], and resets when a
575/// run established a session.
576async fn iroh_uplink(parts: LinkParts, relay: EndpointId, stop: CancellationToken) {
577    let LinkParts {
578        shared,
579        config,
580        tokens,
581        subscriber,
582        link,
583        latest_sample,
584        status,
585    } = parts;
586    let mut client = moq_net::Client::new()
587        .with_publisher(served(&shared.table))
588        .with_peer_node(Hop::of(&relay).id())
589        .with_cost(RELAY_COST);
590    if let Some(subscriber) = subscriber {
591        client = client.with_subscriber(subscriber);
592    }
593    let mut uplink = IrohUplink {
594        endpoint: shared.endpoint.clone(),
595        client,
596        latest_sample,
597        sampler: link::SharedSampler::default(),
598        status: status.clone(),
599        monitor: None,
600        drivers: JoinSet::new(),
601        established: false,
602    };
603    let mut pause = REDIAL_MIN;
604    loop {
605        let mut policy =
606            Reconnect::new(policy_config(), vec![config.url.clone()], kio::clock::now())
607                .expect("one target and a nonzero healthy threshold")
608                .with_tokens(tokens.clone());
609        let ended = tokio::select! {
610            _ = stop.cancelled() => None,
611            _ = shared.shutdown.cancelled() => None,
612            ended = uplink.run(&mut policy) => Some(ended),
613        };
614        let Some(ended) = ended else {
615            uplink.close(&policy).await;
616            break;
617        };
618        if std::mem::take(&mut uplink.established) {
619            pause = REDIAL_MIN;
620        }
621        // Equal jitter, half the pause plus a random half, so relays that
622        // dropped together do not redial together.
623        let jittered = pause.mul_f64(jitter_factor());
624        match ended {
625            Ok(()) => info!(pause = ?jittered, "relay link ended, starting over"),
626            Err(err) => warn!(error = %err, pause = ?jittered, "relay link gave up, starting over"),
627        }
628        status.set(RelayStatus::Reconnecting).ok();
629        tokio::select! {
630            _ = stop.cancelled() => break,
631            _ = shared.shutdown.cancelled() => break,
632            _ = tokio::time::sleep(jittered) => {}
633        }
634        pause = (pause * 2).min(REDIAL_MAX);
635    }
636    uplink.offline();
637    status.set(RelayStatus::Detached).ok();
638    shared.state.lock().expect("poisoned").remove_link(link);
639}
640
641/// Why a dial or a session of an iroh relay link failed.
642#[derive(Debug, Clone, derive_more::Display, derive_more::From)]
643enum LinkFailure {
644    /// The MoQ handshake failed, or the session closed with this error.
645    Moq(moq_net::Error),
646    /// moq's connect policy decided on a dial or a redirect.
647    Policy(reconnect::Failure),
648    /// The media relay could not be reached, or a redirect named no iroh relay.
649    Dial(Error),
650}
651
652/// A session with the media relay, as a dial hands it over.
653struct Dialed {
654    session: moq_net::Session,
655    driver: moq_net::Driver,
656    connection: iroh::endpoint::Connection,
657}
658
659/// A dial in flight, with the verdict on its failure.
660type Dialing = Pin<Box<dyn Future<Output = Result<Dialed, (LinkFailure, Verdict)>> + Send>>;
661
662/// What an iroh relay link keeps across the runs of its connect policy.
663struct IrohUplink {
664    endpoint: iroh::Endpoint,
665    /// The client every dial starts from, before the policy adds the URL and tokens.
666    client: moq_net::Client,
667    latest_sample: LatestSample,
668    sampler: link::SharedSampler,
669    status: Watchable<RelayStatus>,
670    /// Reads the live session into `latest_sample`.
671    monitor: Option<AbortOnDropHandle<()>>,
672    /// The drivers of the live session and of one draining after a GOAWAY.
673    drivers: JoinSet<()>,
674    /// Whether the current run of the policy established a session.
675    established: bool,
676}
677
678impl IrohUplink {
679    /// Drives `policy` until it ends, dialing each attempt it asks for.
680    async fn run(&mut self, policy: &mut Reconnect<Url, LinkFailure>) -> Result<(), LinkFailure> {
681        let mut dial: Option<Dialing> = None;
682        let mut timer: Option<kio::clock::Sleep> = None;
683        loop {
684            let action = kio::wait(|waiter| {
685                loop {
686                    if let Some(pending) = dial.as_mut()
687                        && let Poll::Ready(result) = waiter.poll_future(pending.as_mut())
688                    {
689                        dial = None;
690                        match result {
691                            Ok(dialed) => self.connected(policy, dialed),
692                            Err((err, verdict)) => policy.failed(kio::clock::now(), err, verdict),
693                        }
694                    }
695                    let at = match policy.poll(kio::clock::now(), waiter) {
696                        Action::Wait(Some(at)) => at,
697                        Action::Wait(None) => return Poll::Pending,
698                        action => return Poll::Ready(action),
699                    };
700                    let sleep = timer.get_or_insert_with(|| kio::clock::sleep_until(at));
701                    if sleep.deadline() != at {
702                        sleep.reset(at);
703                    }
704                    if waiter.poll_future(Pin::new(sleep)).is_pending() {
705                        return Poll::Pending;
706                    }
707                }
708            })
709            .await;
710            match action {
711                Action::Dial(attempt) => {
712                    debug!("dialing the relay");
713                    dial = Some(Box::pin(dial_relay(
714                        self.endpoint.clone(),
715                        self.client.clone(),
716                        attempt,
717                    )));
718                }
719                // The policy counted the timeout already. Dropping the dial cancels it.
720                Action::Abandon => dial = None,
721                // The relay accepted the session's credential, so a refusal is ruled out.
722                Action::Established(_) => {
723                    debug!("the relay accepted the session");
724                    self.established = true;
725                    self.status.set(RelayStatus::Connected).ok();
726                }
727                Action::Migrating => info!("the relay sent a GOAWAY, migrating"),
728                Action::Retired => debug!("the drained relay session ended"),
729                Action::Offline(err) => {
730                    match err {
731                        Some(err) => warn!(error = %err, "relay session dropped, redialing"),
732                        None => warn!("relay session dropped, redialing"),
733                    }
734                    self.offline();
735                    self.status.set(RelayStatus::Reconnecting).ok();
736                }
737                Action::Retrying(err) => {
738                    warn!(error = %err, "relay dial failed, redialing");
739                    self.status.set(RelayStatus::Reconnecting).ok();
740                }
741                // Only a link that reports a fallback transport is asked to probe.
742                Action::Probe(_) | Action::Wait(_) => {}
743                Action::Done(result) => return result,
744            }
745        }
746    }
747
748    /// Hands `dialed` to the policy, and starts its driver and its monitor.
749    fn connected(&mut self, policy: &mut Reconnect<Url, LinkFailure>, dialed: Dialed) {
750        let Dialed {
751            session,
752            driver,
753            connection,
754        } = dialed;
755        info!("relay connected");
756        while self.drivers.try_join_next().is_some() {}
757        self.drivers.spawn(async move {
758            moq_net::time::run(driver).await;
759        });
760        // A new session is a new path, even if QUIC numbers it alike.
761        self.sampler.lock().expect("poisoned").new_session();
762        self.monitor = Some(AbortOnDropHandle::new(tokio::spawn(link::monitor_direct(
763            session.clone(),
764            connection,
765            self.latest_sample.clone(),
766            self.sampler.clone(),
767        ))));
768        policy.connected(kio::clock::now(), session);
769    }
770
771    /// Stops reading the session that ended, and clears its last reading.
772    fn offline(&mut self) {
773        // The monitor must not overwrite the cleared reading.
774        self.monitor = None;
775        let generation = self.sampler.lock().expect("poisoned").path_generation();
776        self.latest_sample.clear(generation);
777    }
778
779    /// Closes the live session and one draining after a GOAWAY, letting each finish.
780    async fn close(&self, policy: &Reconnect<Url, LinkFailure>) {
781        let sessions = policy
782            .session()
783            .into_iter()
784            .chain(policy.predecessor().map(|(session, _)| session))
785            .cloned();
786        // An error only says the session was gone already.
787        join_all(sessions.map(|session| async move { session.close().await.ok() })).await;
788    }
789}
790
791/// Dials the media relay `attempt` names and completes the MoQ handshake.
792async fn dial_relay(
793    endpoint: iroh::Endpoint,
794    client: moq_net::Client,
795    attempt: Attempt<Url>,
796) -> Result<Dialed, (LinkFailure, Verdict)> {
797    let unusable = |err: Error| (LinkFailure::Dial(err), Verdict::Unusable);
798    let relay = iroh_relay(attempt.target())
799        .map_err(unusable)?
800        .ok_or_else(|| {
801            unusable(e!(Error::InvalidRelayUrl {
802                url: Box::new(attempt.target().clone()),
803                reason: "a GOAWAY moved an iroh link to another scheme",
804            }))
805        })?;
806    let transport = transport::Transport::connect(&endpoint, relay)
807        .await
808        .map_err(|err| (LinkFailure::Dial(err.into()), Verdict::Retry))?;
809    let connection = transport.connection().clone();
810    let (session, driver) = attempt
811        .client(&client)
812        .connect(kio::clock::now(), transport)
813        .await
814        .map_err(|err| {
815            let verdict = handshake_verdict(&err);
816            (LinkFailure::Moq(err), verdict)
817        })?;
818    Ok(Dialed {
819        session,
820        driver,
821        connection,
822    })
823}
824
825/// Judges a failed MoQ handshake the way moq-tokio judges its own dials.
826///
827/// An auth rejection is the media relay's answer for every address, so it settles
828/// the walk. Every other failure, a protocol violation included, is a failed
829/// dial that the walk retries.
830fn handshake_verdict(err: &moq_net::Error) -> Verdict {
831    match err {
832        moq_net::Error::Unauthorized
833        | moq_net::Error::Session(moq_net::SessionError::Unauthorized) => Verdict::Settled,
834        _ => Verdict::Retry,
835    }
836}
837
838/// Returns a factor in `[0.5, 1)` from the clock, random enough to spread redials.
839fn jitter_factor() -> f64 {
840    let nanos = std::time::SystemTime::now()
841        .duration_since(std::time::UNIX_EPOCH)
842        .map(|elapsed| elapsed.subsec_nanos())
843        .unwrap_or(0);
844    0.5 + f64::from(nanos % 1_000_000) / 2_000_000.0
845}
846
847/// Waits until a moq-tokio connection's loop has stopped.
848///
849/// A stopped monitor means the loop is gone as well.
850async fn closed(monitor: &moq_tokio::connection::Monitor) {
851    let mut state = monitor.state();
852    while !matches!(state.phase, Phase::Closed { .. }) {
853        match monitor.state_changed(state.revision).await {
854            Ok(next) => state = next,
855            Err(_) => break,
856        }
857    }
858}
859
860/// A guard that aborts a moq-tokio connection when dropped.
861struct StopOnDrop(moq_tokio::Connecting);
862
863impl Drop for StopOnDrop {
864    fn drop(&mut self) {
865        self.0.abort(moq_net::Error::Cancel);
866    }
867}
868
869#[cfg(test)]
870mod tests {
871    use iroh::SecretKey;
872
873    use super::*;
874
875    #[test]
876    fn iroh_config_names_the_endpoint_id() {
877        let id = SecretKey::generate().public();
878        let config = RelayConfig::iroh(id);
879        assert_eq!(config.url.scheme(), "iroh");
880        assert_eq!(config.url.host_str(), Some(id.to_string().as_str()));
881    }
882
883    #[test]
884    fn an_iroh_url_names_its_relay_by_endpoint_id() {
885        let id = SecretKey::generate().public();
886        let url: Url = format!("iroh://{id}/live").parse().expect("url");
887        assert_eq!(iroh_relay(&url).expect("valid"), Some(id));
888        for other in [
889            "https://relay.example/",
890            "http://relay.example/",
891            "moqt://relay.example/",
892        ] {
893            let url: Url = other.parse().expect("url");
894            assert_eq!(iroh_relay(&url).expect(other), None, "{other}");
895        }
896    }
897
898    #[test]
899    fn an_iroh_url_without_an_endpoint_id_is_invalid() {
900        let url: Url = "iroh://relay.example/".parse().expect("url");
901        let err = iroh_relay(&url).expect_err("no endpoint id");
902        assert!(
903            matches!(err, Error::InvalidRelayUrl { reason, .. } if reason.contains("endpoint id")),
904            "{err:#}"
905        );
906    }
907
908    #[test]
909    fn an_unsupported_scheme_is_invalid() {
910        let url: Url = "ftp://relay.example/".parse().expect("url");
911        let err = iroh_relay(&url).expect_err("unsupported");
912        assert!(
913            matches!(err, Error::InvalidRelayUrl { reason, .. } if reason.contains("scheme")),
914            "{err:#}"
915        );
916    }
917
918    #[test]
919    fn the_iroh_policy_redials_forever_and_hands_off_a_restart() {
920        let config = policy_config();
921        assert_eq!(config.backoff.timeout, None, "gives up after a while");
922        assert_eq!(config.backoff.initial, REDIAL_MIN);
923        assert_eq!(config.backoff.max, Some(REDIAL_MAX));
924        assert_eq!(config.backoff.healthy, STABLE_SESSION);
925        assert_eq!(config.restart, reconnect::Restart::Handoff);
926        assert!(!config.once);
927    }
928}