use std::collections::HashMap;
use std::fmt;
use std::net::SocketAddr;
use std::sync::{Arc, Mutex, MutexGuard};
use axum::Router;
#[derive(Clone)]
pub(crate) struct Surface {
pub(crate) what: &'static str,
pub(crate) host: String,
pub(crate) port: u16,
pub(crate) router: Router,
}
impl Surface {
pub(crate) fn address(&self) -> String {
format!("{}:{}", self.host, self.port)
}
}
#[derive(Clone, Default)]
pub(crate) struct HttpSurfaces {
inner: Arc<Mutex<Inner>>,
}
#[derive(Default)]
struct Inner {
pending: Vec<Surface>,
addresses: HashMap<&'static str, SocketAddr>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HttpError {
EmptyName,
Duplicate(&'static str),
}
impl fmt::Display for HttpError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::EmptyName => formatter.write_str("the HTTP surface name is empty"),
Self::Duplicate(name) => {
write!(formatter, "the HTTP surface '{name}' is declared twice")
}
}
}
}
impl std::error::Error for HttpError {}
#[derive(Clone)]
pub struct Http {
surfaces: HttpSurfaces,
}
impl Http {
pub(crate) fn new(surfaces: HttpSurfaces) -> Self {
Self { surfaces }
}
pub fn surface(
&self,
what: &'static str,
host: impl Into<String>,
port: u16,
router: Router,
) -> Result<(), HttpError> {
self.surfaces.register(Surface {
what,
host: host.into(),
port,
router,
})
}
pub fn address(&self, what: &str) -> Option<SocketAddr> {
self.surfaces.address(what)
}
}
impl HttpSurfaces {
pub(crate) fn register(&self, surface: Surface) -> Result<(), HttpError> {
if surface.what.is_empty() {
return Err(HttpError::EmptyName);
}
let mut inner = lock(&self.inner);
if inner.addresses.contains_key(surface.what)
|| inner.pending.iter().any(|known| known.what == surface.what)
{
return Err(HttpError::Duplicate(surface.what));
}
inner.pending.push(surface);
Ok(())
}
pub(crate) fn take(&self) -> Vec<Surface> {
std::mem::take(&mut lock(&self.inner).pending)
}
pub(crate) fn address(&self, what: &str) -> Option<SocketAddr> {
lock(&self.inner).addresses.get(what).copied()
}
pub(crate) fn set_addresses(&self, surfaces: &[Surface], address: SocketAddr) {
let mut inner = lock(&self.inner);
for surface in surfaces {
inner.addresses.insert(surface.what, address);
}
}
}
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
#[cfg(test)]
mod tests {
use axum::Router;
use axum::routing::get;
use super::{Http, HttpError, HttpSurfaces};
fn router() -> Router {
Router::new().route("/ping", get(|| async { "pong" }))
}
#[test]
fn surface_is_taken_once() {
let surfaces = HttpSurfaces::default();
let http = Http::new(surfaces.clone());
http.surface("MCP", "0.0.0.0", 8082, router())
.expect("a surface");
assert_eq!(surfaces.take().len(), 1);
assert!(surfaces.take().is_empty());
}
#[test]
fn duplicate_name_is_rejected() {
let surfaces = HttpSurfaces::default();
let http = Http::new(surfaces);
http.surface("MCP", "0.0.0.0", 8082, router())
.expect("a surface");
assert_eq!(
http.surface("MCP", "0.0.0.0", 8083, router()),
Err(HttpError::Duplicate("MCP"))
);
}
#[test]
fn empty_name_is_rejected() {
let surfaces = HttpSurfaces::default();
let http = Http::new(surfaces);
assert_eq!(
http.surface("", "0.0.0.0", 8082, router()),
Err(HttpError::EmptyName)
);
}
#[test]
fn address_is_remembered_for_a_group() {
let surfaces = HttpSurfaces::default();
let http = Http::new(surfaces.clone());
http.surface("MCP", "0.0.0.0", 8082, router())
.expect("a surface");
let taken = surfaces.take();
let address = "127.0.0.1:8082".parse().expect("an address");
surfaces.set_addresses(&taken, address);
assert_eq!(http.address("MCP"), Some(address));
assert_eq!(http.address("other"), None);
}
}