aidaemon_core/
endpoint.rs1use std::sync::Arc;
10
11use tokio::sync::watch;
12
13#[derive(Clone, Debug)]
15pub struct EndpointSource {
16 live: Option<watch::Receiver<Option<String>>>,
17 fallback: Arc<[String]>,
18}
19
20#[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 pub fn fixed(origins: Vec<String>) -> Self {
33 Self {
34 live: None,
35 fallback: origins.into(),
36 }
37 }
38
39 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 pub fn live_origin(&self) -> Option<String> {
54 self.live.as_ref().and_then(|rx| rx.borrow().clone())
55 }
56
57 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 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}