Skip to main content

redup_bootstrap/http/
surface.rs

1//! HTTP-поверхности интеграций: общий роутер инстанса и адреса слушателей.
2//!
3//! Модуль-интеграция добавляет свой роутер на порт. Поверхности одного порта сливаются в общий
4//! роутер; совпадение маршрутов — ошибка старта. Поверхность на порту встроенного слушателя
5//! (REST, транскодинг) садится на него, иначе инстанс поднимает отдельный слушатель.
6
7use std::collections::HashMap;
8use std::fmt;
9use std::net::SocketAddr;
10use std::sync::{Arc, Mutex, MutexGuard};
11
12use axum::Router;
13
14/// Заявка поверхности: имя, адрес и роутер.
15#[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    /// Адрес заявки в записи `host:port`.
25    pub(crate) fn address(&self) -> String {
26        format!("{}:{}", self.host, self.port)
27    }
28}
29
30/// Реестр HTTP-поверхностей интеграций.
31#[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/// Ошибка заявки HTTP-поверхности.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum HttpError {
45    /// Имя поверхности пустое.
46    EmptyName,
47    /// Поверхность с таким именем уже заявлена.
48    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/// Ручка модуля для заявки HTTP-поверхности.
65#[derive(Clone)]
66pub struct Http {
67    surfaces: HttpSurfaces,
68}
69
70impl Http {
71    /// Ручка поверх реестра.
72    pub(crate) fn new(surfaces: HttpSurfaces) -> Self {
73        Self { surfaces }
74    }
75
76    /// Заявить поверхность `what` на адресе `host:port`.
77    ///
78    /// Поверхности одного порта сливаются в общий роутер. Имя уникально в инстансе: по нему
79    /// модуль узнаёт адрес слушателя.
80    ///
81    /// # Ошибки
82    ///
83    /// [`HttpError`] — имя пустое или уже занято.
84    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    /// Адрес поверхности `what`, если её слушатель уже поднят.
100    pub fn address(&self, what: &str) -> Option<SocketAddr> {
101        self.surfaces.address(what)
102    }
103}
104
105impl HttpSurfaces {
106    /// Добавить поверхность.
107    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    /// Забрать все заявки: инстанс раздаёт их слушателям при запуске.
122    pub(crate) fn take(&self) -> Vec<Surface> {
123        std::mem::take(&mut lock(&self.inner).pending)
124    }
125
126    /// Адрес поднятого слушателя поверхности.
127    pub(crate) fn address(&self, what: &str) -> Option<SocketAddr> {
128        lock(&self.inner).addresses.get(what).copied()
129    }
130
131    /// Запомнить адрес слушателя для всех поверхностей группы.
132    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}