1use 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
43const RELAY_COST: u64 = 10;
48
49#[derive(Debug, Clone)]
51#[non_exhaustive]
52pub struct RelayConfig {
53 pub url: Url,
59 pub tokens: Vec<Token>,
65 pub consume: bool,
73}
74
75impl RelayConfig {
76 #[must_use]
78 pub fn new(url: Url) -> Self {
79 Self {
80 url,
81 tokens: Vec::new(),
82 consume: true,
83 }
84 }
85
86 #[must_use]
90 pub fn with_consume(mut self, consume: bool) -> Self {
91 self.consume = consume;
92 self
93 }
94
95 #[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 #[must_use]
117 pub fn with_token(mut self, token: Token) -> Self {
118 self.tokens = vec![token];
119 self
120 }
121}
122
123#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
125pub enum RelayStatus {
126 #[default]
128 Connecting,
129 Connected,
131 Reconnecting,
133 Detached,
135}
136
137#[derive(Debug, Clone)]
160pub struct RelayLink {
161 inner: Arc<RelayInner>,
162}
163
164#[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 #[must_use]
183 pub fn status(&self) -> n0_watcher::Direct<RelayStatus> {
184 self.inner.status.watch()
185 }
186
187 #[must_use]
189 pub fn id(&self) -> LinkId {
190 self.inner.link
191 }
192
193 #[must_use]
199 pub fn tokens(&self) -> auth::Tokens {
200 self.inner.tokens.clone()
201 }
202
203 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 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
234pub(crate) struct RelayTask {
236 task: AbortOnDropHandle<()>,
237 status: Watchable<RelayStatus>,
238}
239
240impl Tasks {
241 fn insert_relay(&self, link: LinkId, task: RelayTask) {
243 let mut relays = self.relays.lock().expect("poisoned");
244 relays.retain(|_, relay| !relay.task.is_finished());
246 relays.insert(link, task);
247 }
248
249 fn remove_relay(&self, link: LinkId) -> Option<RelayTask> {
251 self.relays.lock().expect("poisoned").remove(&link)
252 }
253
254 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 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 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
289pub(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 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 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
356fn 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
377fn 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 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
420fn 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
436struct LinkParts {
438 shared: Arc<Shared>,
439 config: RelayConfig,
440 tokens: auth::Tokens,
442 subscriber: Option<origin::Producer>,
444 link: LinkId,
445 latest_sample: LatestSample,
446 status: Watchable<RelayStatus>,
447}
448
449fn 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
469enum Uplink {
471 Tokio(Box<moq_tokio::Connecting>),
474 Iroh {
476 relay: EndpointId,
477 stop: CancellationToken,
478 },
479}
480
481const REDIAL_MIN: Duration = Duration::from_secs(1);
483
484const STABLE_SESSION: Duration = Duration::from_secs(10);
486
487const REDIAL_MAX: Duration = Duration::from_secs(30);
489
490async 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 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 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 _ = shared.shutdown.cancelled() => break,
534 update = watch.state_changed(seen.revision) => update,
535 };
536 match update {
537 Ok(observation) => seen = observation,
538 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
553fn 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
569async 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 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#[derive(Debug, Clone, derive_more::Display, derive_more::From)]
643enum LinkFailure {
644 Moq(moq_net::Error),
646 Policy(reconnect::Failure),
648 Dial(Error),
650}
651
652struct Dialed {
654 session: moq_net::Session,
655 driver: moq_net::Driver,
656 connection: iroh::endpoint::Connection,
657}
658
659type Dialing = Pin<Box<dyn Future<Output = Result<Dialed, (LinkFailure, Verdict)>> + Send>>;
661
662struct IrohUplink {
664 endpoint: iroh::Endpoint,
665 client: moq_net::Client,
667 latest_sample: LatestSample,
668 sampler: link::SharedSampler,
669 status: Watchable<RelayStatus>,
670 monitor: Option<AbortOnDropHandle<()>>,
672 drivers: JoinSet<()>,
674 established: bool,
676}
677
678impl IrohUplink {
679 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 Action::Abandon => dial = None,
721 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 Action::Probe(_) | Action::Wait(_) => {}
743 Action::Done(result) => return result,
744 }
745 }
746 }
747
748 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 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 fn offline(&mut self) {
773 self.monitor = None;
775 let generation = self.sampler.lock().expect("poisoned").path_generation();
776 self.latest_sample.clear(generation);
777 }
778
779 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 join_all(sessions.map(|session| async move { session.close().await.ok() })).await;
788 }
789}
790
791async 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
825fn 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
838fn 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
847async 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
860struct 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}