Skip to main content

guardrail_proxy/
state.rs

1//! Shared server state and lifecycle handle.
2//!
3//! Kept separate from request-handling logic (`crate::handler`) and the
4//! listener loop ([`crate::server`]) so each module has a single, obvious
5//! responsibility: this one just defines *what data* every connection
6//! handler needs, with no behavior of its own.
7
8use std::net::SocketAddr;
9use std::sync::Arc;
10
11use guardrail_config::ConfigHandle;
12
13use crate::metrics::Metrics;
14
15/// Shared application state, cloned (cheaply, via `Arc`) into every
16/// connection handler.
17pub(crate) struct AppState {
18    pub(crate) config: Arc<ConfigHandle>,
19    pub(crate) http_client: reqwest::Client,
20    pub(crate) metrics: Metrics,
21    /// One permit per request allowed at once
22    /// (`server.max_concurrent_requests`); `None` when unlimited.
23    pub(crate) admission: Option<Arc<tokio::sync::Semaphore>>,
24}
25
26/// A handle to a running server, returned by [`crate::run_server`].
27///
28/// Dropping this handle does **not** stop the server; call
29/// [`ServerHandle::shutdown`] to request graceful shutdown.
30pub struct ServerHandle {
31    pub(crate) addr: SocketAddr,
32    pub(crate) shutdown_tx: tokio::sync::watch::Sender<bool>,
33}
34
35impl ServerHandle {
36    /// The address the server is bound to. Useful when `listen_addr` uses
37    /// port `0` and the OS assigns a port.
38    pub fn local_addr(&self) -> SocketAddr {
39        self.addr
40    }
41
42    /// Request graceful shutdown. In-flight requests are allowed to complete.
43    pub fn shutdown(&self) {
44        let _ = self.shutdown_tx.send(true);
45    }
46}