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