Skip to main content

diode_http/
control_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;
17use crate::{HealthCheckRegistry, HealthClient, RouterBuilder};
18
19#[derive(Default)]
20struct ControlRouterRegistry {
21    routers: Vec<Arc<dyn RouterBuilder>>,
22    types: HashSet<TypeId>,
23}
24
25impl ControlRouterRegistry {
26    fn add_router<T: RouterBuilder + 'static>(&mut self, router: Arc<T>) {
27        if !self.types.insert(TypeId::of::<T>()) {
28            panic!("Router {} already added", type_name::<T>());
29        }
30        self.routers.push(router);
31    }
32
33    fn has_router<T: RouterBuilder + 'static>(&self) -> bool {
34        self.types.contains(&TypeId::of::<T>())
35    }
36
37    fn build_router(&self, app: &App) -> Router {
38        self.routers.iter().fold(Router::new(), |acc, v| {
39            acc.merge(v.clone().build_router(app))
40        })
41    }
42}
43
44struct ControlServerDaemon {
45    addr: SocketAddr,
46}
47
48impl Daemon for ControlServerDaemon {
49    async fn run(&self, app: &App, shutdown: CancellationToken) -> Result<(), StdError> {
50        let span = tracing::info_span!("control_server", addr = ?self.addr);
51        let router = app
52            .get_component_ref::<ControlRouterRegistry>()
53            .unwrap()
54            .build_router(app)
55            .layer(TracingLayer);
56        tracing::info!(parent: &span, "Control server starting");
57        defer! {
58            tracing::info!(parent: &span, "Control server stopped")
59        };
60        let listener = TcpListener::bind(self.addr).await.map_err(Box::new)?;
61        tracing::info!(parent: &span, "Control server started");
62        axum::serve(listener, router)
63            .with_graceful_shutdown(shutdown.cancelled_owned())
64            .await
65            .map_err(Box::new)?;
66        Ok(())
67    }
68}
69
70/// Configuration for the control HTTP server, read from the `control_server`
71/// config section.
72#[derive(Serialize, Deserialize)]
73#[config_section("control_server")]
74pub struct ControlServerConfig {
75    /// Socket address the control server binds and listens on.
76    pub addr: SocketAddr,
77}
78
79/// Plugin that runs the control HTTP server.
80///
81/// The control server is a separate, typically internal, server intended for
82/// operational endpoints (health, readiness, and so on). It serves the routers
83/// registered through [`AddControlRouterExt`] / [`AddControlRouterServiceExt`],
84/// hosts the health-check registry used by [`HealthRouter`](crate::HealthRouter),
85/// and exposes a [`HealthClient`] component pointed at its own `/health`
86/// endpoint. It binds the address from [`ControlServerConfig`] (config section
87/// `control_server`).
88pub struct ControlServerPlugin;
89
90impl Plugin for ControlServerPlugin {
91    async fn build(&self, ctx: &AppContext) -> Result<(), StdError> {
92        if !ctx.has_component::<ControlRouterRegistry>() {
93            ctx.add_component(ControlRouterRegistry::default());
94        }
95        if !ctx.has_component::<HealthCheckRegistry>() {
96            ctx.add_component(HealthCheckRegistry::default());
97        }
98        let config = ctx
99            .get_component_ref::<Config>()
100            .ok_or_else(|| "Config component is missing".to_string())?
101            .get::<ControlServerConfig>("control_server")?;
102        ctx.add_component(HealthClient::new(format!("http://{}/health", config.addr)));
103        ctx.add_daemon(ControlServerDaemon { addr: config.addr });
104        Ok(())
105    }
106}
107
108struct ControlRouterProvider<T>(PhantomData<T>);
109
110impl<T> Plugin for ControlRouterProvider<T>
111where
112    T: Service<Handle = Arc<T>> + RouterBuilder + 'static,
113{
114    async fn build(&self, ctx: &AppContext) -> Result<(), StdError> {
115        let component = ctx.get_component::<T::Handle>().unwrap();
116        ctx.get_component_mut::<ControlRouterRegistry>()
117            .unwrap()
118            .add_router(component);
119        Ok(())
120    }
121
122    fn dependencies(&self) -> Dependencies {
123        T::dependencies()
124            .service::<T>()
125            .plugin::<ControlServerPlugin>()
126    }
127}
128
129/// Registers concrete [`RouterBuilder`] instances on the control HTTP server.
130///
131/// The control-server counterpart of [`AddRouterExt`](crate::AddRouterExt).
132/// Lives on [`AppContext`], so routers can be registered while configuring the
133/// [`AppBuilder`] or from within a plugin's `build`. A router is identified by
134/// its type. Registration does not require [`ControlServerPlugin`]; without it
135/// the router is simply never served.
136pub trait AddControlRouterExt {
137    /// Registers `router` on the control HTTP server.
138    ///
139    /// # Panics
140    ///
141    /// Panics if a router of type `T` is already registered on the control
142    /// server. Guard with
143    /// [`has_control_router`](AddControlRouterExt::has_control_router) when the
144    /// same type may be registered more than once.
145    fn add_control_router<T>(&self, router: impl Into<Arc<T>>)
146    where
147        T: RouterBuilder + 'static;
148
149    /// Returns whether a router of type `T` is registered on the control server.
150    fn has_control_router<T>(&self) -> bool
151    where
152        T: RouterBuilder + 'static;
153}
154
155impl AddControlRouterExt for AppContext {
156    fn add_control_router<T>(&self, router: impl Into<Arc<T>>)
157    where
158        T: RouterBuilder + 'static,
159    {
160        if !self.has_component::<ControlRouterRegistry>() {
161            self.add_component(ControlRouterRegistry::default());
162        }
163        self.get_component_mut::<ControlRouterRegistry>()
164            .unwrap()
165            .add_router(router.into());
166    }
167
168    fn has_control_router<T>(&self) -> bool
169    where
170        T: RouterBuilder + 'static,
171    {
172        self.get_component_ref::<ControlRouterRegistry>()
173            .is_some_and(|registry| registry.has_router::<T>())
174    }
175}
176
177/// Registers routers resolved from the dependency-injection container on the
178/// control HTTP server.
179///
180/// The control-server counterpart of
181/// [`AddRouterServiceExt`](crate::AddRouterServiceExt): the router type `T` is a
182/// [`Service`], built by the container and registered as a [`RouterBuilder`].
183/// The service is added automatically if it is not already present.
184pub trait AddControlRouterServiceExt {
185    /// Registers the [`Service`] `T` and serves its routes on the control
186    /// server.
187    ///
188    /// # Panics
189    ///
190    /// Panics if `T` is already registered as a control router service. Building
191    /// the [`App`] additionally panics if `T` is registered both as a service
192    /// router and as an instance via [`AddControlRouterExt::add_control_router`].
193    fn add_control_router_service<T>(&mut self) -> &mut Self
194    where
195        T: Service<Handle = Arc<T>> + RouterBuilder + 'static;
196
197    /// Returns whether `T` is registered as a control router service.
198    fn has_control_router_service<T>(&self) -> bool
199    where
200        T: Service<Handle = Arc<T>> + RouterBuilder + 'static;
201}
202
203impl AddControlRouterServiceExt for AppBuilder {
204    fn add_control_router_service<T>(&mut self) -> &mut Self
205    where
206        T: Service<Handle = Arc<T>> + RouterBuilder + 'static,
207    {
208        if !self.has_service::<T>() {
209            self.add_service::<T>();
210        }
211        self.add_plugin(ControlRouterProvider::<T>(PhantomData));
212        self
213    }
214
215    fn has_control_router_service<T>(&self) -> bool
216    where
217        T: Service<Handle = Arc<T>> + RouterBuilder + 'static,
218    {
219        self.has_plugin::<ControlRouterProvider<T>>()
220    }
221}