Skip to main content

rust_web_server/app/
mod.rs

1#[cfg(test)]
2mod tests;
3
4pub mod controller;
5
6use std::sync::Arc;
7
8use crate::app::controller::favicon::FaviconController;
9use crate::app::controller::health::HealthController;
10use crate::app::controller::ready::ReadyController;
11use crate::app::controller::metrics::MetricsController;
12use crate::app::controller::file::initiate::FileUploadInitiateController;
13use crate::app::controller::form::get_method::FormGetMethodController;
14use crate::app::controller::form::multipart_enctype_post_method::FormMultipartEnctypePostMethodController;
15use crate::app::controller::form::url_encoded_enctype_post_method::FormUrlEncodedEnctypePostMethodController;
16use crate::app::controller::index::IndexController;
17use crate::app::controller::not_found::NotFoundController;
18use crate::app::controller::script::ScriptController;
19use crate::app::controller::static_resource::StaticResourceController;
20use crate::app::controller::style::StyleController;
21use crate::application::Application;
22use crate::controller::Controller;
23use crate::core::New;
24use crate::header::Header;
25use crate::mcp::McpServer;
26use crate::middleware::{Middleware, WithMiddleware};
27use crate::request::Request;
28use crate::response::{Response, STATUS_CODE_REASON_PHRASE};
29use crate::server::ConnectionInfo;
30use crate::server_config::ServerConfig;
31use crate::state::AppWithState;
32
33/// A pair of function pointers representing one entry in the controller chain.
34struct ControllerEntry {
35    is_matching: fn(&Request, &ConnectionInfo) -> bool,
36    process: fn(&Request, Response, &ConnectionInfo) -> Response,
37}
38
39/// Build a [`ControllerEntry`] from any type that implements [`Controller`].
40fn entry<C: Controller>() -> ControllerEntry {
41    ControllerEntry {
42        is_matching: C::is_matching,
43        process: C::process,
44    }
45}
46
47/// The built-in HTTP application. Serves static files, favicons, forms,
48/// file uploads, health probes, metrics, and a 404 fallback.
49///
50/// Use as-is or compose with the framework's building blocks:
51///
52/// ```rust,no_run
53/// use rust_web_server::app::App;
54/// use rust_web_server::middleware::{WithMiddleware, RateLimitLayer};
55/// use rust_web_server::core::New;
56///
57/// // Middleware stack around the built-in app
58/// let app = App::new().wrap(RateLimitLayer);
59/// ```
60///
61/// For user-defined routes with shared state, call [`App::with_state`]:
62///
63/// ```rust,no_run
64/// use rust_web_server::app::App;
65/// use rust_web_server::response::{Response, STATUS_CODE_REASON_PHRASE};
66/// use rust_web_server::core::New;
67///
68/// struct State { version: &'static str }
69///
70/// let app = App::with_state(State { version: "1.0" })
71///     .get("/version", |_req, _params, _conn, state| {
72///         let mut r = Response::new();
73///         r.status_code = *STATUS_CODE_REASON_PHRASE.n200_ok.status_code;
74///         r.reason_phrase = STATUS_CODE_REASON_PHRASE.n200_ok.reason_phrase.to_string();
75///         r
76///     });
77/// ```
78///
79/// # Per-instance configuration
80///
81/// By default `App::new()` reads CORS, CSP, and other settings from
82/// environment variables on each request (matching the current process state,
83/// including hot-reloaded values). Call [`App::with_config`] to pin the
84/// configuration to a specific [`ServerConfig`] — this is the recommended
85/// pattern for parallel integration tests, which should not touch environment
86/// variables at all.
87///
88/// ```rust,ignore
89/// use rust_web_server::app::App;
90/// use rust_web_server::server_config::ServerConfig;
91/// use rust_web_server::test_client::TestClient;
92///
93/// // No env writes, no lock needed — safe to run in parallel.
94/// let app = App::with_config(ServerConfig {
95///     cors_allow_all: false,
96///     cors_allow_origins: "https://trusted.example.com".to_string(),
97///     ..ServerConfig::default()
98/// });
99/// let client = TestClient::new(app);
100/// ```
101#[derive(Clone)]
102pub struct App {
103    /// When `Some`, every request is served using this fixed config.
104    /// When `None`, config is read from environment variables on each request
105    /// (supports hot-reload via SIGHUP / `POST /admin/config/reload`).
106    config: Option<Arc<ServerConfig>>,
107}
108
109impl New for App {
110    fn new() -> Self {
111        App { config: None }
112    }
113}
114
115impl App {
116    /// Create an `App` pinned to an explicit [`ServerConfig`].
117    ///
118    /// All CORS, CSP, and other header settings are taken from `config` rather
119    /// than from environment variables. The configuration is fixed for the
120    /// lifetime of the `App` instance — SIGHUP / hot-reload do not affect it.
121    ///
122    /// This is the preferred constructor for integration tests: build a
123    /// [`ServerConfig`] with the exact settings under test, pass it here, and
124    /// use [`TestClient`] to drive requests. No environment writes and no
125    /// [`test_env::lock()`] are needed.
126    ///
127    /// [`TestClient`]: crate::test_client::TestClient
128    /// [`test_env::lock()`]: crate::test_env::lock
129    pub fn with_config(config: ServerConfig) -> Self {
130        App { config: Some(Arc::new(config)) }
131    }
132}
133
134impl Application for App {
135    fn execute(&self, request: &Request, connection: &ConnectionInfo) -> Result<Response, String> {
136        let config = match &self.config {
137            Some(c) => (**c).clone(),
138            None => ServerConfig::from_env(),
139        };
140        let header_list = Header::get_header_list_with_config(request, &config);
141        let response = Response::get_response(
142            STATUS_CODE_REASON_PHRASE.n501_not_implemented,
143            Some(header_list),
144            None,
145        );
146
147        let controllers = [
148            entry::<IndexController>(),
149            entry::<StyleController>(),
150            entry::<ScriptController>(),
151            entry::<FileUploadInitiateController>(),
152            entry::<FormUrlEncodedEnctypePostMethodController>(),
153            entry::<FormGetMethodController>(),
154            entry::<FormMultipartEnctypePostMethodController>(),
155            entry::<HealthController>(),
156            entry::<ReadyController>(),
157            entry::<MetricsController>(),
158            entry::<FaviconController>(),
159            entry::<StaticResourceController>(),
160            entry::<NotFoundController>(),
161        ];
162
163        for c in &controllers {
164            if (c.is_matching)(request, connection) {
165                return Ok((c.process)(request, response, connection));
166            }
167        }
168
169        Ok(response)
170    }
171}
172
173impl App {
174    /// Dispatch `request` through the controller chain and return the response.
175    ///
176    /// This is a convenience wrapper over [`Application::execute`] that uses a
177    /// synthetic loopback [`ConnectionInfo`]. Use it in tests or when no real
178    /// connection context is available. Prefer [`TestClient`] for structured
179    /// test code.
180    ///
181    /// [`TestClient`]: crate::test_client::TestClient
182    pub fn handle_request(request: Request) -> (Response, Request) {
183        use crate::server::Address;
184        let conn = ConnectionInfo {
185            client: Address { ip: "127.0.0.1".to_string(), port: 0 },
186            server: Address { ip: "127.0.0.1".to_string(), port: 7878 },
187            request_size: 16000,
188            sni_hostname: None,
189        };
190        let app = App::new();
191        let response = app.execute(&request, &conn).unwrap_or_else(|_| {
192            let header_list = Header::get_header_list_with_config(&request, &ServerConfig::from_env());
193            Response::get_response(
194                STATUS_CODE_REASON_PHRASE.n500_internal_server_error,
195                Some(header_list),
196                None,
197            )
198        });
199        (response, request)
200    }
201
202    /// Create a state-aware application. Routes registered on the returned
203    /// [`AppWithState<S>`] are tried first; unmatched requests fall through to
204    /// the built-in controller chain (static files, health probes, etc.).
205    ///
206    /// The state is stored as `Arc<S>` and shared across all handlers.
207    ///
208    /// # Example
209    ///
210    /// ```rust,no_run
211    /// use rust_web_server::app::App;
212    /// use rust_web_server::response::{Response, STATUS_CODE_REASON_PHRASE};
213    /// use rust_web_server::core::New;
214    ///
215    /// struct Db { url: String }
216    ///
217    /// let app = App::with_state(Db { url: "postgres://...".to_string() })
218    ///     .get("/ping", |_req, _params, _conn, db| {
219    ///         let mut r = Response::new();
220    ///         r.status_code = *STATUS_CODE_REASON_PHRASE.n200_ok.status_code;
221    ///         r.reason_phrase = STATUS_CODE_REASON_PHRASE.n200_ok.reason_phrase.to_string();
222    ///         r
223    ///     });
224    /// ```
225    pub fn with_state<S: Send + Sync + 'static>(state: S) -> AppWithState<S> {
226        AppWithState::new(state)
227    }
228
229    /// Wrap this application in a middleware layer.
230    ///
231    /// Returns a [`WithMiddleware<App>`] that runs `layer` before every
232    /// request. Chain `.wrap()` calls to stack multiple layers:
233    ///
234    /// ```rust,no_run
235    /// use rust_web_server::app::App;
236    /// use rust_web_server::middleware::RateLimitLayer;
237    /// use rust_web_server::core::New;
238    ///
239    /// let app = App::new().wrap(RateLimitLayer);
240    /// ```
241    pub fn wrap<M: Middleware + 'static>(self, layer: M) -> WithMiddleware<App> {
242        WithMiddleware::new(self).wrap(layer)
243    }
244
245    /// Attach an MCP server to this application. Tools, resources, and
246    /// prompts are registered on the returned [`McpServer`]; requests that
247    /// do not match the MCP endpoint are forwarded to `self` (static files,
248    /// health probes, any custom routes registered before this call).
249    ///
250    /// ```rust,no_run
251    /// use rust_web_server::app::App;
252    /// use rust_web_server::mcp::{McpContent, extract_arg};
253    /// use rust_web_server::core::New;
254    ///
255    /// // Pure MCP — unmatched paths handled by built-in App
256    /// let app = App::new()
257    ///     .mcp("my-server", "1.0")
258    ///     .tool(
259    ///         "echo",
260    ///         "Echo text back",
261    ///         r#"{"type":"object","properties":{"text":{"type":"string"}}}"#,
262    ///         |args| Ok(McpContent::text(extract_arg(args, "text").unwrap_or_default())),
263    ///     );
264    /// ```
265    ///
266    /// To combine with custom HTTP routes, start from [`App::with_state`]:
267    ///
268    /// ```rust,no_run
269    /// use rust_web_server::app::App;
270    /// use rust_web_server::mcp::McpContent;
271    /// use rust_web_server::response::{Response, STATUS_CODE_REASON_PHRASE};
272    /// use rust_web_server::core::New;
273    ///
274    /// let app = App::with_state(())
275    ///     .get("/api/ping", |_, _, _, _| {
276    ///         let mut r = Response::new();
277    ///         r.status_code = *STATUS_CODE_REASON_PHRASE.n200_ok.status_code;
278    ///         r.reason_phrase = STATUS_CODE_REASON_PHRASE.n200_ok.reason_phrase.to_string();
279    ///         r
280    ///     })
281    ///     .mcp("my-server", "1.0")
282    ///     .tool("ping", "Ping the server", "{}", |_| Ok(McpContent::text("pong")));
283    /// ```
284    pub fn mcp(self, name: impl Into<String>, version: impl Into<String>) -> McpServer {
285        McpServer::new(name, version).wrap(self)
286    }
287
288    /// Create an async state-aware application (requires the `http2` feature).
289    ///
290    /// Handlers are `async fn` closures that can `await` database queries,
291    /// HTTP clients, or any other async I/O. Unmatched routes fall through to
292    /// the built-in controller chain.
293    ///
294    /// # Example
295    ///
296    /// ```rust,no_run
297    /// use std::sync::Arc;
298    /// use rust_web_server::app::App;
299    /// use rust_web_server::response::{Response, STATUS_CODE_REASON_PHRASE};
300    /// use rust_web_server::core::New;
301    ///
302    /// struct Db { url: String }
303    ///
304    /// let app = App::with_async_state(Db { url: "postgres://...".to_string() })
305    ///     .get("/ping", |_req, _params, _conn, state| async move {
306    ///         // state: Arc<Db>
307    ///         let mut r = Response::new();
308    ///         r.status_code = *STATUS_CODE_REASON_PHRASE.n200_ok.status_code;
309    ///         r.reason_phrase = STATUS_CODE_REASON_PHRASE.n200_ok.reason_phrase.to_string();
310    ///         r
311    ///     });
312    /// ```
313    #[cfg(feature = "http2")]
314    pub fn with_async_state<S: Send + Sync + 'static>(state: S) -> crate::async_state::AsyncAppWithState<S> {
315        crate::async_state::AsyncAppWithState::new(state)
316    }
317}