Skip to main content

aidaemon_core/
endpoint.rs

1//! Where a loopback service can be reached from outside: a live origin, when
2//! something publishes one, then the static origins from config.
3//!
4//! The services hold an [`EndpointSource`]; whatever publishes them (a
5//! tunnel supervisor) holds the matching [`EndpointPublisher`]. Origins are
6//! plain strings (`https://host[:port]`), validated by the publisher before
7//! they are set.
8
9use std::sync::Arc;
10
11use tokio::sync::watch;
12
13/// The origins a service is reachable at, live origin first.
14#[derive(Clone, Debug)]
15pub struct EndpointSource {
16    live: Option<watch::Receiver<Option<String>>>,
17    fallback: Arc<[String]>,
18}
19
20/// Sets the live origin of one [`EndpointSource`].
21#[derive(Debug)]
22pub struct EndpointPublisher {
23    tx: watch::Sender<Option<String>>,
24}
25
26fn same_origin(a: &str, b: &str) -> bool {
27    a.trim_end_matches('/') == b.trim_end_matches('/')
28}
29
30impl EndpointSource {
31    /// Only these origins, never a live one.
32    pub fn fixed(origins: Vec<String>) -> Self {
33        Self {
34            live: None,
35            fallback: origins.into(),
36        }
37    }
38
39    /// A source whose live origin the returned publisher sets; `fallback`
40    /// is served after it, and alone while there is none.
41    pub fn live(fallback: Vec<String>) -> (Self, EndpointPublisher) {
42        let (tx, rx) = watch::channel(None);
43        (
44            Self {
45                live: Some(rx),
46                fallback: fallback.into(),
47            },
48            EndpointPublisher { tx },
49        )
50    }
51
52    /// The live origin, if one is published now.
53    pub fn live_origin(&self) -> Option<String> {
54        self.live.as_ref().and_then(|rx| rx.borrow().clone())
55    }
56
57    /// The live origin first, then the fallback, without duplicates.
58    pub fn current(&self) -> Vec<String> {
59        let mut origins: Vec<String> = Vec::with_capacity(self.fallback.len() + 1);
60        for origin in self
61            .live_origin()
62            .into_iter()
63            .chain(self.fallback.iter().cloned())
64        {
65            if !origins.iter().any(|known| same_origin(known, &origin)) {
66                origins.push(origin);
67            }
68        }
69        origins
70    }
71}
72
73impl EndpointPublisher {
74    /// Publish `origin` as the live one; `None` while it is down.
75    pub fn set(&self, origin: Option<String>) {
76        self.tx.send_replace(origin);
77    }
78}
79
80#[cfg(test)]
81mod tests {
82    use super::*;
83
84    #[test]
85    fn fixed_serves_config_origins() {
86        let source = EndpointSource::fixed(vec!["https://a.example.com".into()]);
87        assert_eq!(source.current(), vec!["https://a.example.com"]);
88        assert_eq!(source.live_origin(), None);
89    }
90
91    #[test]
92    fn live_origin_comes_first_and_is_deduplicated() {
93        let (source, publisher) = EndpointSource::live(vec![
94            "https://a.example.com".into(),
95            "https://b.example.com".into(),
96        ]);
97        assert_eq!(source.current().len(), 2);
98        publisher.set(Some("https://b.example.com/".into()));
99        assert_eq!(
100            source.current(),
101            vec!["https://b.example.com/", "https://a.example.com"]
102        );
103        let clone = source.clone();
104        publisher.set(None);
105        assert_eq!(
106            clone.current(),
107            vec!["https://a.example.com", "https://b.example.com"]
108        );
109    }
110
111    #[test]
112    fn source_outlives_its_publisher() {
113        let (source, publisher) = EndpointSource::live(vec![]);
114        publisher.set(Some("https://c.example.com".into()));
115        drop(publisher);
116        assert_eq!(source.current(), vec!["https://c.example.com"]);
117    }
118}