Skip to main content

diode_http/
router.rs

1use std::any::{TypeId, type_name};
2use std::collections::HashSet;
3use std::marker::PhantomData;
4use std::net::SocketAddr;
5use std::sync::Arc;
6
7use axum::Router;
8use diode::{
9    AddServiceExt as _, App, AppBuilder, AppContext, Dependencies, Plugin, Service,
10    ServiceDependencyExt as _, StdError,
11};
12use diode_base::{AddDaemonExt as _, CancellationToken, Config, Daemon, config_section, defer};
13use serde::{Deserialize, Serialize};
14use tokio::net::TcpListener;
15
16use crate::tracing::TracingLayer;
17
18/// Builds the [`axum::Router`] contributed by a type to an HTTP server.
19///
20/// Implement this for any value that exposes routes. The builder is handed the
21/// fully built [`App`], so it can resolve other components (services,
22/// registries, configuration) while assembling its routes.
23///
24/// Register an implementor with [`AddRouterExt::add_router`] (a concrete
25/// instance) or [`AddRouterServiceExt::add_router_service`] (resolved from a
26/// [`Service`]). The server merges every registered router into one.
27pub trait RouterBuilder: Send + Sync {
28    /// Builds this type's routes into a [`Router`].
29    fn build_router(self: Arc<Self>, app: &App) -> Router;
30}
31
32#[derive(Default)]
33struct RouterRegistry {
34    routers: Vec<Arc<dyn RouterBuilder>>,
35    types: HashSet<TypeId>,
36}
37
38impl RouterRegistry {
39    fn add_router<T: RouterBuilder + 'static>(&mut self, router: Arc<T>) {
40        if !self.types.insert(TypeId::of::<T>()) {
41            panic!("Router {} already added", type_name::<T>());
42        }
43        self.routers.push(router);
44    }
45
46    fn has_router<T: RouterBuilder + 'static>(&self) -> bool {
47        self.types.contains(&TypeId::of::<T>())
48    }
49
50    fn build_router(&self, app: &App) -> Router {
51        self.routers.iter().fold(Router::new(), |acc, v| {
52            acc.merge(v.clone().build_router(app))
53        })
54    }
55}
56
57struct ServerDaemon {
58    addr: SocketAddr,
59}
60
61impl Daemon for ServerDaemon {
62    async fn run(&self, app: &App, shutdown: CancellationToken) -> Result<(), StdError> {
63        let span = tracing::info_span!("http_server", addr = ?self.addr);
64        let router = app
65            .get_component_ref::<RouterRegistry>()
66            .unwrap()
67            .build_router(app)
68            .layer(TracingLayer);
69        tracing::info!(parent: &span, "Server starting");
70        defer! {
71            tracing::info!(parent: &span, "Server stopped")
72        };
73        let listener = TcpListener::bind(self.addr).await.map_err(Box::new)?;
74        tracing::info!(parent: &span, "Server started");
75        axum::serve(listener, router)
76            .with_graceful_shutdown(shutdown.cancelled_owned())
77            .await
78            .map_err(Box::new)?;
79        Ok(())
80    }
81}
82
83/// Configuration for the public HTTP server, read from the `http_server`
84/// config section.
85#[derive(Serialize, Deserialize)]
86#[config_section("http_server")]
87pub struct HttpServerConfig {
88    /// Socket address the server binds and listens on.
89    pub addr: SocketAddr,
90}
91
92/// Plugin that runs the public HTTP server.
93///
94/// Add it to the [`AppBuilder`] to serve every router registered through
95/// [`AddRouterExt`] / [`AddRouterServiceExt`]. The server binds the address from
96/// [`HttpServerConfig`] (config section `http_server`) and runs as a [`Daemon`],
97/// shutting down gracefully when its cancellation token fires.
98pub struct HttpServerPlugin;
99
100impl Plugin for HttpServerPlugin {
101    async fn build(&self, ctx: &AppContext) -> Result<(), StdError> {
102        if !ctx.has_component::<RouterRegistry>() {
103            ctx.add_component(RouterRegistry::default());
104        }
105        let config = ctx
106            .get_component_ref::<Config>()
107            .ok_or_else(|| "Config component is missing".to_string())?
108            .get::<HttpServerConfig>("http_server")?;
109        ctx.add_daemon(ServerDaemon { addr: config.addr });
110        Ok(())
111    }
112}
113
114struct RouterProvider<T>(PhantomData<T>);
115
116impl<T> Plugin for RouterProvider<T>
117where
118    T: Service<Handle = Arc<T>> + RouterBuilder + 'static,
119{
120    async fn build(&self, ctx: &AppContext) -> Result<(), StdError> {
121        let component = ctx.get_component::<T::Handle>().unwrap();
122        ctx.get_component_mut::<RouterRegistry>()
123            .unwrap()
124            .add_router(component);
125        Ok(())
126    }
127
128    fn dependencies(&self) -> Dependencies {
129        T::dependencies()
130            .service::<T>()
131            .plugin::<HttpServerPlugin>()
132    }
133}
134
135/// Registers concrete [`RouterBuilder`] instances on the public HTTP server.
136///
137/// This extension lives on [`AppContext`], so routers can be registered both
138/// while configuring the [`AppBuilder`] and from within a plugin's `build`. A
139/// router is identified by its type: at most one instance of a given type may be
140/// registered.
141///
142/// Registration does not require [`HttpServerPlugin`]; if the plugin is never
143/// added the router is simply never served.
144pub trait AddRouterExt {
145    /// Registers `router` on the public HTTP server.
146    ///
147    /// The router is stored under its concrete type `T`. To expose several
148    /// distinct sets of routes use distinct types; a single type that needs many
149    /// routes should build them all in its [`RouterBuilder`] implementation.
150    ///
151    /// # Panics
152    ///
153    /// Panics if a router of type `T` is already registered on this server.
154    /// Guard with [`has_router`](AddRouterExt::has_router) when the same type may
155    /// be registered more than once (for example from several bundles).
156    fn add_router<T>(&self, router: impl Into<Arc<T>>)
157    where
158        T: RouterBuilder + 'static;
159
160    /// Returns whether a router of type `T` is registered on the public server.
161    fn has_router<T>(&self) -> bool
162    where
163        T: RouterBuilder + 'static;
164}
165
166impl AddRouterExt for AppContext {
167    fn add_router<T>(&self, router: impl Into<Arc<T>>)
168    where
169        T: RouterBuilder + 'static,
170    {
171        if !self.has_component::<RouterRegistry>() {
172            self.add_component(RouterRegistry::default());
173        }
174        self.get_component_mut::<RouterRegistry>()
175            .unwrap()
176            .add_router(router.into());
177    }
178
179    fn has_router<T>(&self) -> bool
180    where
181        T: RouterBuilder + 'static,
182    {
183        self.get_component_ref::<RouterRegistry>()
184            .is_some_and(|registry| registry.has_router::<T>())
185    }
186}
187
188/// Registers routers resolved from the dependency-injection container on the
189/// public HTTP server.
190///
191/// Unlike [`AddRouterExt`], the router type `T` is a [`Service`]: it is built by
192/// the container (together with its dependencies) and its handle is then
193/// registered as a [`RouterBuilder`]. The service is added automatically if it
194/// is not already present.
195pub trait AddRouterServiceExt {
196    /// Registers the [`Service`] `T` and serves its routes on the public server.
197    ///
198    /// # Panics
199    ///
200    /// Panics if `T` is already registered as a router service (its provider
201    /// plugin would be added twice); guard with
202    /// [`has_router_service`](AddRouterServiceExt::has_router_service) when this
203    /// can happen. Building the [`App`] additionally panics if `T` is registered
204    /// both as a service router and as an instance via
205    /// [`AddRouterExt::add_router`], since a type may back at most one router.
206    fn add_router_service<T>(&mut self) -> &mut Self
207    where
208        T: Service<Handle = Arc<T>> + RouterBuilder + 'static;
209
210    /// Returns whether `T` is registered as a router service on the public
211    /// server.
212    fn has_router_service<T>(&self) -> bool
213    where
214        T: Service<Handle = Arc<T>> + RouterBuilder + 'static;
215}
216
217impl AddRouterServiceExt for AppBuilder {
218    fn add_router_service<T>(&mut self) -> &mut Self
219    where
220        T: Service<Handle = Arc<T>> + RouterBuilder + 'static,
221    {
222        if !self.has_service::<T>() {
223            self.add_service::<T>();
224        }
225        self.add_plugin(RouterProvider::<T>(PhantomData));
226        self
227    }
228
229    fn has_router_service<T>(&self) -> bool
230    where
231        T: Service<Handle = Arc<T>> + RouterBuilder + 'static,
232    {
233        self.has_plugin::<RouterProvider<T>>()
234    }
235}