diode_http/
control_router.rs1use 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#[derive(Serialize, Deserialize)]
73#[config_section("control_server")]
74pub struct ControlServerConfig {
75 pub addr: SocketAddr,
77}
78
79pub 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
129pub trait AddControlRouterExt {
137 fn add_control_router<T>(&self, router: impl Into<Arc<T>>)
146 where
147 T: RouterBuilder + 'static;
148
149 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
177pub trait AddControlRouterServiceExt {
185 fn add_control_router_service<T>(&mut self) -> &mut Self
194 where
195 T: Service<Handle = Arc<T>> + RouterBuilder + 'static;
196
197 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}