redup_bootstrap/http/
surface.rs1use std::collections::HashMap;
8use std::fmt;
9use std::net::SocketAddr;
10use std::sync::{Arc, Mutex, MutexGuard};
11
12use axum::Router;
13
14#[derive(Clone)]
16pub(crate) struct Surface {
17 pub(crate) what: &'static str,
18 pub(crate) host: String,
19 pub(crate) port: u16,
20 pub(crate) router: Router,
21}
22
23impl Surface {
24 pub(crate) fn address(&self) -> String {
26 format!("{}:{}", self.host, self.port)
27 }
28}
29
30#[derive(Clone, Default)]
32pub(crate) struct HttpSurfaces {
33 inner: Arc<Mutex<Inner>>,
34}
35
36#[derive(Default)]
37struct Inner {
38 pending: Vec<Surface>,
39 addresses: HashMap<&'static str, SocketAddr>,
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum HttpError {
45 EmptyName,
47 Duplicate(&'static str),
49}
50
51impl fmt::Display for HttpError {
52 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
53 match self {
54 Self::EmptyName => formatter.write_str("the HTTP surface name is empty"),
55 Self::Duplicate(name) => {
56 write!(formatter, "the HTTP surface '{name}' is declared twice")
57 }
58 }
59 }
60}
61
62impl std::error::Error for HttpError {}
63
64#[derive(Clone)]
66pub struct Http {
67 surfaces: HttpSurfaces,
68}
69
70impl Http {
71 pub(crate) fn new(surfaces: HttpSurfaces) -> Self {
73 Self { surfaces }
74 }
75
76 pub fn surface(
85 &self,
86 what: &'static str,
87 host: impl Into<String>,
88 port: u16,
89 router: Router,
90 ) -> Result<(), HttpError> {
91 self.surfaces.register(Surface {
92 what,
93 host: host.into(),
94 port,
95 router,
96 })
97 }
98
99 pub fn address(&self, what: &str) -> Option<SocketAddr> {
101 self.surfaces.address(what)
102 }
103}
104
105impl HttpSurfaces {
106 pub(crate) fn register(&self, surface: Surface) -> Result<(), HttpError> {
108 if surface.what.is_empty() {
109 return Err(HttpError::EmptyName);
110 }
111 let mut inner = lock(&self.inner);
112 if inner.addresses.contains_key(surface.what)
113 || inner.pending.iter().any(|known| known.what == surface.what)
114 {
115 return Err(HttpError::Duplicate(surface.what));
116 }
117 inner.pending.push(surface);
118 Ok(())
119 }
120
121 pub(crate) fn take(&self) -> Vec<Surface> {
123 std::mem::take(&mut lock(&self.inner).pending)
124 }
125
126 pub(crate) fn address(&self, what: &str) -> Option<SocketAddr> {
128 lock(&self.inner).addresses.get(what).copied()
129 }
130
131 pub(crate) fn set_addresses(&self, surfaces: &[Surface], address: SocketAddr) {
133 let mut inner = lock(&self.inner);
134 for surface in surfaces {
135 inner.addresses.insert(surface.what, address);
136 }
137 }
138}
139
140fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
141 mutex
142 .lock()
143 .unwrap_or_else(|poisoned| poisoned.into_inner())
144}
145
146#[cfg(test)]
147mod tests {
148 use axum::Router;
149 use axum::routing::get;
150
151 use super::{Http, HttpError, HttpSurfaces};
152
153 fn router() -> Router {
154 Router::new().route("/ping", get(|| async { "pong" }))
155 }
156
157 #[test]
158 fn surface_is_taken_once() {
159 let surfaces = HttpSurfaces::default();
160 let http = Http::new(surfaces.clone());
161 http.surface("MCP", "0.0.0.0", 8082, router())
162 .expect("a surface");
163 assert_eq!(surfaces.take().len(), 1);
164 assert!(surfaces.take().is_empty());
165 }
166
167 #[test]
168 fn duplicate_name_is_rejected() {
169 let surfaces = HttpSurfaces::default();
170 let http = Http::new(surfaces);
171 http.surface("MCP", "0.0.0.0", 8082, router())
172 .expect("a surface");
173 assert_eq!(
174 http.surface("MCP", "0.0.0.0", 8083, router()),
175 Err(HttpError::Duplicate("MCP"))
176 );
177 }
178
179 #[test]
180 fn empty_name_is_rejected() {
181 let surfaces = HttpSurfaces::default();
182 let http = Http::new(surfaces);
183 assert_eq!(
184 http.surface("", "0.0.0.0", 8082, router()),
185 Err(HttpError::EmptyName)
186 );
187 }
188
189 #[test]
190 fn address_is_remembered_for_a_group() {
191 let surfaces = HttpSurfaces::default();
192 let http = Http::new(surfaces.clone());
193 http.surface("MCP", "0.0.0.0", 8082, router())
194 .expect("a surface");
195 let taken = surfaces.take();
196 let address = "127.0.0.1:8082".parse().expect("an address");
197 surfaces.set_addresses(&taken, address);
198 assert_eq!(http.address("MCP"), Some(address));
199 assert_eq!(http.address("other"), None);
200 }
201}