Skip to main content

sova_core/app/
hooks.rs

1use super::App;
2use crate::error::Result;
3use crate::handler::BoxFuture;
4use crate::request::Request;
5use crate::response::Response;
6use crate::router::{compile_router, CompiledRouter};
7use crate::service::BoxedService;
8use crate::state::StateMap;
9use crate::upgrade::UpgradeBudget;
10use bytes::Bytes;
11use http::Method;
12use std::sync::Arc;
13use std::time::Duration;
14use tokio::sync::Semaphore;
15
16pub(crate) type StartupHook =
17    Arc<dyn Fn(Arc<StateMap>) -> BoxFuture<Result<()>> + Send + Sync>;
18pub(crate) type ShutdownHook = Arc<dyn Fn() -> BoxFuture<()> + Send + Sync>;
19
20/// Compiled app ready to handle requests without recompiling the router.
21#[derive(Clone)]
22pub struct Server {
23    pub(crate) inner: Arc<AppInner>,
24    pub(crate) startups: Vec<StartupHook>,
25    pub(crate) shutdowns: Vec<ShutdownHook>,
26}
27
28impl Server {
29    /// Shared application state map (same as request `state`).
30    pub fn state(&self) -> Arc<StateMap> {
31        self.inner.state()
32    }
33
34    /// Run startup hooks without consuming them (safe to call multiple times).
35    #[cfg(any(test, feature = "testing"))]
36    pub async fn run_startup(&self) -> Result<Arc<StateMap>> {
37        let state = self.state();
38        for hook in &self.startups {
39            hook(Arc::clone(&state)).await?;
40        }
41        Ok(state)
42    }
43
44    /// Run shutdown hooks without consuming them.
45    #[cfg(any(test, feature = "testing"))]
46    pub async fn run_shutdown(&self) {
47        for hook in &self.shutdowns {
48            hook().await;
49        }
50    }
51
52    /// Handle a request (tests / embedded). Injects router state.
53    pub async fn handle(&self, mut req: Request) -> Response {
54        req.state = Arc::clone(&self.inner.compiled.state);
55        self.inner.compiled.dispatch(req).await
56    }
57
58    /// Convenience for unit tests without headers.
59    /// Custom headers: [`Request::builder`] + [`Self::handle`].
60    pub async fn handle_request(&self, method: Method, path: &str, body: &str) -> Response {
61        let req = Request::builder()
62            .method(method)
63            .path(path)
64            .body(Bytes::from(body.to_string()))
65            .build();
66        self.handle(req).await
67    }
68}
69
70pub(crate) struct ListenParts {
71    pub(crate) inner: AppInner,
72    pub(crate) startups: Vec<StartupHook>,
73    pub(crate) shutdowns: Vec<ShutdownHook>,
74    pub(crate) services: Vec<BoxedService>,
75    /// When false (CLI default), BackgroundServices are not started.
76    pub(crate) start_services: bool,
77}
78
79impl App {
80    fn validate_plugin_requires(&self) -> Result<()> {
81        if let Some((plugin, dep)) = self.missing_plugin_requires.first().copied() {
82            return Err(crate::error::Error::Internal(format!(
83                "plugin `{plugin}` requires `{dep}`; install `{dep}` before `{plugin}`"
84            )));
85        }
86        if let Some(id) = self.duplicate_plugin_ids.first().copied() {
87            return Err(crate::error::Error::Internal(format!(
88                "plugin `{id}` already installed; customize before first install or build App::new() with an explicit stack (re-install does not replace)"
89            )));
90        }
91        if let Some(msg) = self.plugin_sdk_errors.first() {
92            return Err(crate::error::Error::Internal(msg.clone()));
93        }
94        Ok(())
95    }
96
97    /// Compile routes once into a [`Server`]. Prefer this over repeated [`App::handle`].
98    pub fn build(&self) -> Result<Server> {
99        self.validate_plugin_requires()?;
100        let router = self.router.clone_for_compile();
101        router
102            .check_route_values(&self.router.state, &self.installed_plugins)
103            .map_err(crate::error::Error::Internal)?;
104        let explain = router.explain();
105        let route_count = router.route_entries().len();
106        let compiled = Arc::new(compile_router(router)?);
107        Ok(Server {
108            inner: Arc::new(AppInner::from_settings(
109                compiled,
110                route_count,
111                explain,
112                AppSettings::from(self),
113            )),
114            startups: self.on_startup.clone(),
115            shutdowns: self.on_shutdown.clone(),
116        })
117    }
118
119    pub(crate) fn into_listen_parts(mut self) -> Result<ListenParts> {
120        self.validate_plugin_requires()?;
121        let services = std::mem::take(&mut self.services);
122        let startups = self.on_startup.clone();
123        let shutdowns = self.on_shutdown.clone();
124        let start_services = !self.cli_mode || self.service_in_cli;
125
126        self.router
127            .check_route_values(&self.router.state, &self.installed_plugins)
128            .map_err(crate::error::Error::Internal)?;
129        let explain = self.router.explain();
130        let route_count = self.router.route_entries().len();
131        let settings = AppSettings::from(&self);
132        let router = self.router;
133        let compiled = Arc::new(compile_router(router)?);
134
135        Ok(ListenParts {
136            inner: AppInner::from_settings(compiled, route_count, explain, settings),
137            startups,
138            shutdowns,
139            services,
140            start_services,
141        })
142    }
143}
144
145pub(crate) struct AppSettings {
146    pub max_body_size: usize,
147    pub max_connections: usize,
148    pub max_upgraded_connections: usize,
149    pub max_concurrent_streams: usize,
150    pub max_headers: usize,
151    pub max_buf_size: Option<usize>,
152    pub request_timeout: Option<Duration>,
153    pub header_read_timeout: Duration,
154    pub idle_timeout: Duration,
155    pub drain_timeout: Duration,
156    pub keep_alive: bool,
157    pub trust_proxy: bool,
158    pub reuseport: bool,
159    pub hsts: bool,
160    pub alt_svc: Option<String>,
161}
162
163impl From<&App> for AppSettings {
164    fn from(app: &App) -> Self {
165        Self {
166            max_body_size: app.max_body_size,
167            max_connections: app.max_connections,
168            max_upgraded_connections: app.max_upgraded_connections,
169            max_concurrent_streams: app.max_concurrent_streams,
170            max_headers: app.max_headers,
171            max_buf_size: app.max_buf_size,
172            request_timeout: app.request_timeout,
173            header_read_timeout: app.header_read_timeout,
174            idle_timeout: app.idle_timeout,
175            drain_timeout: app.drain_timeout,
176            keep_alive: app.keep_alive,
177            trust_proxy: app.trust_proxy,
178            reuseport: app.reuseport,
179            hsts: app.hsts,
180            alt_svc: app.alt_svc.clone(),
181        }
182    }
183}
184
185pub(crate) struct AppInner {
186    pub(crate) compiled: Arc<CompiledRouter>,
187    pub(crate) max_body_size: usize,
188    pub(crate) max_connections: usize,
189    pub(crate) max_upgraded: UpgradeBudget,
190    pub(crate) max_concurrent_streams: usize,
191    pub(crate) max_headers: usize,
192    pub(crate) max_buf_size: Option<usize>,
193    pub(crate) request_timeout: Option<Duration>,
194    pub(crate) header_read_timeout: Duration,
195    pub(crate) idle_timeout: Duration,
196    pub(crate) drain_timeout: Duration,
197    pub(crate) keep_alive: bool,
198    pub(crate) trust_proxy: bool,
199    pub(crate) reuseport: bool,
200    pub(crate) hsts: bool,
201    pub(crate) alt_svc: Option<String>,
202    pub(crate) route_count: usize,
203    pub(crate) explain: String,
204}
205
206impl AppInner {
207    fn from_settings(
208        compiled: Arc<CompiledRouter>,
209        route_count: usize,
210        explain: String,
211        s: AppSettings,
212    ) -> Self {
213        Self {
214            compiled,
215            max_body_size: s.max_body_size,
216            max_connections: s.max_connections,
217            max_upgraded: UpgradeBudget(Arc::new(Semaphore::new(s.max_upgraded_connections))),
218            max_concurrent_streams: s.max_concurrent_streams,
219            max_headers: s.max_headers,
220            max_buf_size: s.max_buf_size,
221            request_timeout: s.request_timeout,
222            header_read_timeout: s.header_read_timeout,
223            idle_timeout: s.idle_timeout,
224            drain_timeout: s.drain_timeout,
225            keep_alive: s.keep_alive,
226            trust_proxy: s.trust_proxy,
227            reuseport: s.reuseport,
228            hsts: s.hsts,
229            alt_svc: s.alt_svc,
230            route_count,
231            explain,
232        }
233    }
234
235    pub(crate) async fn handle(&self, req: Request) -> Response {
236        self.compiled.dispatch(req).await
237    }
238
239    pub(crate) fn state(&self) -> Arc<StateMap> {
240        Arc::clone(&self.compiled.state)
241    }
242
243    pub(crate) fn conn_header_timeout(&self) -> Duration {
244        self.header_read_timeout.min(self.idle_timeout)
245    }
246}