1use std::net::SocketAddr;
2
3use axum::Router;
4use config::{File, FileFormat};
5use log::info;
6
7use fusion_core::{DataError, application::Application, configuration::ConfigRegistry};
8use mea::shutdown::ShutdownRecv;
9
10use crate::config::{DEFAULT_CONFIG_STR, WebConfig};
11
12pub struct WebServerBuilder {
13 router: Router,
14 shutdown_rx: Option<ShutdownRecv>,
15}
16
17impl WebServerBuilder {
18 pub fn new(router: Router) -> Self {
19 Self { router, shutdown_rx: None }
20 }
21
22 pub fn with_shutdown(mut self, shutdown_rx: ShutdownRecv) -> Self {
23 self.shutdown_rx = Some(shutdown_rx);
24 self
25 }
26
27 pub async fn build(self) -> Result<(), DataError> {
28 let app = Application::global();
29 app.config_registry().add_config_source(File::from_str(DEFAULT_CONFIG_STR, FileFormat::Toml))?;
30 let conf: WebConfig = app.get_config()?;
31 self.init_server_with_config(conf).await
32 }
33
34 async fn init_server_with_config(self, conf: WebConfig) -> Result<(), DataError> {
35 let listener = tokio::net::TcpListener::bind(&conf.server_addr).await.unwrap();
36 let local_addr = listener.local_addr()?;
37 info!("The Web Server listening on {}", local_addr);
38 let serve = if conf.enable_remote_addr {
39 let s = axum::serve(listener, self.router.into_make_service_with_connect_info::<SocketAddr>());
40 if let Some(shutdown_rx) = self.shutdown_rx {
41 s.with_graceful_shutdown(shutdown_rx.is_shutdown_owned()).await
42 } else {
43 s.await
44 }
45 } else {
46 let s = axum::serve(listener, self.router.into_make_service());
47 if let Some(shutdown_rx) = self.shutdown_rx {
48 s.with_graceful_shutdown(shutdown_rx.is_shutdown_owned()).await
49 } else {
50 s.await
51 }
52 };
53 serve.map_err(DataError::from)
54 }
55}