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
18pub trait RouterBuilder: Send + Sync {
28 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#[derive(Serialize, Deserialize)]
86#[config_section("http_server")]
87pub struct HttpServerConfig {
88 pub addr: SocketAddr,
90}
91
92pub 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
135pub trait AddRouterExt {
145 fn add_router<T>(&self, router: impl Into<Arc<T>>)
157 where
158 T: RouterBuilder + 'static;
159
160 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
188pub trait AddRouterServiceExt {
196 fn add_router_service<T>(&mut self) -> &mut Self
207 where
208 T: Service<Handle = Arc<T>> + RouterBuilder + 'static;
209
210 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}