Skip to main content

next_rust_server/
app.rs

1//! Route definitions, application builder and request dispatch.
2//!
3//! The types in the first half of this module are the contract between the
4//! build-time code generator and the runtime. Application code normally never
5//! constructs them by hand: `next_rust::routes!()` expands to generated code
6//! that does.
7
8use std::collections::{HashMap, HashSet};
9use std::future::Future;
10use std::path::PathBuf;
11use std::sync::{Arc, Mutex};
12
13use http::{Method, StatusCode};
14use next_rust_cache::{Cache, CacheStore, MemoryStore};
15use next_rust_core::{Config, Environment};
16use next_rust_router::{Matcher, Params, PatternSegment, RoutePattern, SegmentKind, parse_segment};
17use next_rust_view::{Children, Metadata, Node, Slots};
18
19use crate::context::Ctx;
20use crate::error::Result;
21use crate::middleware::{BoxFuture, Endpoint, FnMiddleware, Middleware, Next};
22use crate::request::Request;
23use crate::response::{IntoResponse, Response};
24use crate::seo::{Robots, Sitemap};
25
26pub type RenderFn = fn(Ctx) -> BoxFuture<Result<Node>>;
27pub type LayoutFn = fn(Ctx, Children, Slots) -> BoxFuture<Result<Node>>;
28pub type LoadingFn = fn(Ctx) -> Node;
29pub type ErrorFn = fn(Ctx, ErrorInfo) -> Node;
30pub type MetadataFn = fn(Ctx) -> BoxFuture<Result<Metadata>>;
31pub type MiddlewareFn = fn(Request, Next) -> BoxFuture<Response>;
32pub type HandlerFn = fn(Request) -> BoxFuture<Response>;
33pub type ParamsFn = fn() -> BoxFuture<Result<Vec<Params>>>;
34pub type SitemapFn = fn() -> BoxFuture<Sitemap>;
35pub type RobotsFn = fn() -> BoxFuture<Robots>;
36
37/// Rendering mode declared by a page: `pub const RENDERING: Rendering = Rendering::Dynamic;`
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
39pub enum Rendering {
40    #[default]
41    Auto,
42    Static,
43    Dynamic,
44}
45
46/// Information passed to `error.rs` / `global-error.rs`.
47#[derive(Debug, Clone)]
48pub struct ErrorInfo {
49    pub status: u16,
50    /// User-safe message in production, detailed message in development.
51    pub message: String,
52    /// Random identifier that is also written to the server log.
53    pub digest: String,
54}
55
56impl ErrorInfo {
57    pub(crate) fn from_error(e: &crate::Error, dev: bool) -> Self {
58        let digest = crate::random_hex(6);
59        let status = e.status().as_u16();
60        if status >= 500 {
61            crate::log::error(&format!("render error [{digest}]: {}", e.detailed_message()));
62        }
63        ErrorInfo { status, message: if dev { e.detailed_message() } else { e.public_message() }, digest }
64    }
65}
66
67/// Files attached to one route segment (directory).
68#[derive(Clone, Default)]
69pub struct SegmentDef {
70    pub layout: Option<LayoutFn>,
71    pub template: Option<LayoutFn>,
72    pub loading: Option<LoadingFn>,
73    pub error: Option<ErrorFn>,
74    pub not_found: Option<RenderFn>,
75    pub metadata: Option<MetadataFn>,
76    /// Nested `middleware.rs` (never the app-root one, which is global).
77    pub middleware: Option<MiddlewareFn>,
78    pub slots: Vec<SlotDef>,
79    /// Identity of `layout` (its file, relative to the project), used to
80    /// recognize a layout the browser already shows.
81    pub layout_id: &'static str,
82    /// The build found that `layout` (and its `load`) reads nothing from the
83    /// request, so client navigations may keep it on screen instead of
84    /// rendering it again.
85    pub layout_reusable: bool,
86    /// `layout` reads route parameters (`Params` / `Path`): it is only reused
87    /// while every parameter keeps its value.
88    pub layout_uses_params: bool,
89}
90
91#[derive(Clone)]
92pub struct SlotDef {
93    pub name: &'static str,
94    /// The matching slot page or its `default.rs`.
95    pub render: Option<RenderFn>,
96}
97
98pub enum PageBody {
99    Rust(RenderFn),
100    /// Contents of `page.html`.
101    Html(&'static str),
102}
103
104pub struct PageDef {
105    /// Filesystem-style pattern, e.g. `/blog/[slug]`.
106    pub pattern: &'static str,
107    pub source: &'static str,
108    pub body: PageBody,
109    /// Root → leaf segments.
110    pub segments: Vec<SegmentDef>,
111    pub metadata: Option<MetadataFn>,
112    /// Resolved by the build (`Auto` is treated as `Dynamic`).
113    pub rendering: Rendering,
114    pub revalidate: Option<u64>,
115    pub generate_params: Option<ParamsFn>,
116    /// Render params not returned by `generate_params` on demand.
117    pub dynamic_params: bool,
118    /// Cache tags for `revalidate_tag`.
119    pub tags: &'static [&'static str],
120    /// Set for intercepting routes: the URL pattern they intercept from.
121    pub intercept_from: Option<&'static str>,
122}
123
124pub struct ApiDef {
125    pub pattern: &'static str,
126    pub source: &'static str,
127    pub handlers: Vec<(Method, HandlerFn)>,
128    pub middleware: Vec<MiddlewareFn>,
129}
130
131pub struct ActionDef {
132    /// Stable identifier (`module::path::fn_name`).
133    pub id: &'static str,
134    pub handler: HandlerFn,
135}
136
137/// Everything discovered in the app directory.
138#[derive(Default)]
139pub struct Routes {
140    pub pages: Vec<PageDef>,
141    pub apis: Vec<ApiDef>,
142    pub actions: Vec<ActionDef>,
143    /// `not-found.rs` / `layout.rs` / `metadata` of the app root, used for unmatched URLs.
144    pub root: SegmentDef,
145    /// App-root `middleware.rs`: runs for every request, before routing.
146    pub middleware: Option<MiddlewareFn>,
147    pub global_error: Option<ErrorFn>,
148    pub sitemap: Option<SitemapFn>,
149    pub robots: Option<RobotsFn>,
150    /// Absolute project root recorded at build time (fallback for config discovery).
151    pub project_root: Option<&'static str>,
152    /// Configuration and static files compiled into release binaries.
153    pub embedded: Option<&'static crate::embed::Embedded>,
154    /// Changes whenever the application's source changes. Part of every layout
155    /// key, so a browser never keeps a layout from an older deployment.
156    pub build_id: &'static str,
157    /// Reads `next-rust.toml` at runtime. Set by the generated code for
158    /// development builds; release builds embed their configuration as JSON
159    /// and leave this `None`, so no TOML parser is linked.
160    pub toml: Option<next_rust_core::config::TomlParser>,
161    /// Stylesheets added to every page, such as the generated Tailwind CSS.
162    pub stylesheets: &'static [&'static next_rust_view::Stylesheet],
163}
164
165pub(crate) type CustomHandlers = Vec<(Option<Method>, Arc<dyn Endpoint>)>;
166
167#[derive(Clone, Copy, Debug)]
168pub(crate) enum Target {
169    Page(usize),
170    Api(usize),
171    Custom(usize),
172}
173
174struct CustomRoute {
175    pattern: String,
176    method: Option<Method>,
177    endpoint: Arc<dyn Endpoint>,
178}
179
180pub(crate) struct Intercept {
181    pub page: usize,
182    pub target: Matcher<()>,
183    pub context: RoutePattern,
184}
185
186pub(crate) struct AppInner {
187    pub routes: Routes,
188    pub matcher: Matcher<Target>,
189    pub intercepts: Vec<Intercept>,
190    pub customs: Vec<CustomHandlers>,
191    pub config: Arc<Config>,
192    pub env: Environment,
193    pub public_dir: PathBuf,
194    pub client_dir: PathBuf,
195    pub dev_status_file: PathBuf,
196    /// Files compiled into the binary; `None` reads from disk.
197    pub embedded: Option<&'static crate::embed::Embedded>,
198    pub cache: Cache,
199    pub page_store: Arc<dyn CacheStore>,
200    pub global_stack: Arc<[Arc<dyn Middleware>]>,
201    pub page_stacks: Vec<Arc<[Arc<dyn Middleware>]>>,
202    pub api_stacks: Vec<Arc<[Arc<dyn Middleware>]>>,
203    pub actions: HashMap<String, usize>,
204    pub revalidating: Mutex<HashSet<String>>,
205    pub static_params: Mutex<HashMap<usize, Arc<Vec<Params>>>>,
206    pub plugins: Vec<Arc<dyn crate::plugin::Plugin>>,
207    pub public_env_json: Option<String>,
208}
209
210/// A configured application. Cheap to clone.
211#[derive(Clone)]
212pub struct App {
213    pub(crate) inner: Arc<AppInner>,
214}
215
216/// Builder returned by [`App::new`].
217pub struct AppBuilder {
218    routes: Routes,
219    config: Option<Config>,
220    env: Option<Environment>,
221    middleware: Vec<Arc<dyn Middleware>>,
222    cache: Option<Cache>,
223    page_store: Option<Arc<dyn CacheStore>>,
224    customs: Vec<CustomRoute>,
225    plugins: Vec<Arc<dyn crate::plugin::Plugin>>,
226}
227
228/// Convert `/users/:id`, `/files/*path` or `/users/[id]` into a pattern.
229pub fn parse_pattern(pattern: &str) -> std::result::Result<RoutePattern, String> {
230    let mut segs = Vec::new();
231    for part in pattern.split('/').filter(|p| !p.is_empty()) {
232        let seg = if let Some(name) = part.strip_prefix(':') {
233            PatternSegment::Dynamic(name.to_owned())
234        } else if let Some(name) = part.strip_prefix('*') {
235            match name.strip_suffix('?') {
236                Some(n) => PatternSegment::OptionalCatchAll(n.to_owned()),
237                None => PatternSegment::CatchAll(name.to_owned()),
238            }
239        } else {
240            match parse_segment(part)? {
241                Some(SegmentKind::Static(s)) => PatternSegment::Static(s),
242                Some(SegmentKind::Dynamic(s)) => PatternSegment::Dynamic(s),
243                Some(SegmentKind::CatchAll(s)) => PatternSegment::CatchAll(s),
244                Some(SegmentKind::OptionalCatchAll(s)) => PatternSegment::OptionalCatchAll(s),
245                _ => return Err(format!("unsupported segment `{part}` in pattern `{pattern}`")),
246            }
247        };
248        segs.push(seg);
249    }
250    Ok(RoutePattern(segs))
251}
252
253impl App {
254    /// Start building an application from generated routes.
255    #[allow(clippy::new_ret_no_self)]
256    pub fn new(routes: Routes) -> AppBuilder {
257        AppBuilder {
258            routes,
259            config: None,
260            env: None,
261            middleware: Vec::new(),
262            cache: None,
263            page_store: None,
264            customs: Vec::new(),
265            plugins: Vec::new(),
266        }
267    }
268
269    pub fn config(&self) -> &Config {
270        &self.inner.config
271    }
272
273    pub fn environment(&self) -> Environment {
274        self.inner.env
275    }
276
277    pub fn cache(&self) -> &Cache {
278        &self.inner.cache
279    }
280
281    /// Handle one request. This is the adapter surface: the built-in server,
282    /// tests and serverless adapters all call it.
283    pub async fn handle(&self, mut req: Request) -> Response {
284        let inner = self.inner.clone();
285        let nonce = crate::random_hex(16);
286        req.insert_extension(crate::CspNonce(nonce.clone()));
287        req.limit_body(inner.config.server.body_limit);
288
289        if let Some(res) = self.pre_routing(&mut req).await {
290            return self.finish(res, &req_cookies_placeholder(), &nonce, "");
291        }
292        let cookies = req.cookies().clone();
293        let path = req.path().to_owned();
294        let endpoint: Arc<dyn Endpoint> = Arc::new(RouteEndpoint { inner: inner.clone() });
295        let res = Next::new(inner.global_stack.clone(), endpoint).run(req).await;
296        self.finish(res, &cookies, &nonce, &path)
297    }
298
299    /// Framework assets, base path, configured redirects and trailing slashes.
300    async fn pre_routing(&self, req: &mut Request) -> Option<Response> {
301        let inner = &self.inner;
302        let config = &inner.config;
303
304        let base = config.app.base_path.as_str();
305        if !base.is_empty() {
306            let path = req.path().to_owned();
307            let stripped = if path == base {
308                "/".to_owned()
309            } else if let Some(rest) = path.strip_prefix(base).filter(|r| r.starts_with('/')) {
310                rest.to_owned()
311            } else {
312                return Some(Response::not_found());
313            };
314            let query = req.uri().query().map(|q| format!("?{q}")).unwrap_or_default();
315            if req.set_path(&format!("{stripped}{query}")).is_err() {
316                return Some(Response::status(400));
317            }
318        }
319
320        let path = req.path();
321        if path.starts_with("/_nr/")
322            && let Some(res) = crate::internal::handle(inner, req).await
323        {
324            return Some(res);
325        }
326
327        for rule in &config.redirects {
328            if let Some(dest) = crate::redirects::apply(&rule.source, &rule.destination, path) {
329                let query = req.uri().query().map(|q| format!("?{q}")).unwrap_or_default();
330                let location = if dest.contains('?') { dest } else { format!("{dest}{query}") };
331                return Some(if rule.permanent {
332                    Response::permanent_redirect(&location)
333                } else {
334                    Response::redirect(&location)
335                });
336            }
337        }
338
339        if path.len() > 1 {
340            let has_slash = path.ends_with('/');
341            let looks_like_file = path.rsplit('/').next().is_some_and(|last| last.contains('.'));
342            if has_slash != config.app.trailing_slash && !looks_like_file {
343                let fixed = if has_slash { path.trim_end_matches('/').to_owned() } else { format!("{path}/") };
344                let fixed = if fixed.is_empty() { "/".to_owned() } else { fixed };
345                let query = req.uri().query().map(|q| format!("?{q}")).unwrap_or_default();
346                return Some(Response::permanent_redirect(&format!("{base}{fixed}{query}")));
347            }
348        }
349        None
350    }
351
352    fn finish(&self, mut res: Response, cookies: &crate::Cookies, nonce: &str, path: &str) -> Response {
353        let config = &self.inner.config;
354        for value in cookies.set_cookie_headers() {
355            res.append_header("set-cookie", &value);
356        }
357        if !path.is_empty() {
358            for rule in &config.headers {
359                if crate::redirects::matches(&rule.source, path) {
360                    for (k, v) in &rule.headers {
361                        res.set_header(k, v);
362                    }
363                }
364            }
365        }
366        if config.security.headers {
367            crate::middleware::apply_security_headers(
368                &mut res,
369                config.security.csp.as_deref(),
370                nonce,
371                config.security.hsts_max_age,
372            );
373        }
374        res
375    }
376
377    /// Re-render `path` on its next request (ISR) and drop data-cache
378    /// entries stored under the same path key.
379    pub async fn revalidate_path(&self, path: &str) -> bool {
380        let path = if path.len() > 1 { path.trim_end_matches('/') } else { path };
381        let page = self.inner.page_store.delete(&next_rust_cache::CacheKey::page(path)).await.unwrap_or(false);
382        page | self.inner.cache.revalidate_path(path).await.unwrap_or(false)
383    }
384
385    /// Invalidate pages and data tagged with `tag`. Returns the number of entries removed.
386    pub async fn revalidate_tag(&self, tag: &str) -> usize {
387        self.inner.page_store.delete_tag(tag).await.unwrap_or(0)
388            + self.inner.cache.revalidate_tag(tag).await.unwrap_or(0)
389    }
390
391    /// Render every static route without keeping the result: used by
392    /// `next-rust build` to check that static generation succeeds.
393    pub async fn export(&self) -> std::result::Result<crate::export::ExportReport, String> {
394        crate::export::prerender(&self.inner, &MemoryStore::new(usize::MAX)).await
395    }
396
397    /// Render every static route into the page cache, so the first visitor
398    /// gets a cached page. Production servers do this in the background at
399    /// startup.
400    pub async fn prerender(&self) -> std::result::Result<crate::export::ExportReport, String> {
401        crate::export::prerender(&self.inner, self.inner.page_store.as_ref()).await
402    }
403
404    /// Route table as `(kind, pattern, source)` for diagnostics.
405    pub fn route_table(&self) -> Vec<(&'static str, &'static str, &'static str)> {
406        let r = &self.inner.routes;
407        let mut out: Vec<_> = r.pages.iter().map(|p| ("page", p.pattern, p.source)).collect();
408        out.extend(r.apis.iter().map(|a| ("api", a.pattern, a.source)));
409        out
410    }
411}
412
413fn req_cookies_placeholder() -> crate::Cookies {
414    crate::Cookies::default()
415}
416
417/// Find the configuration.
418///
419/// `NEXT_RUST_CONFIG` wins. A release binary then uses the configuration it
420/// was built with, rooted at the working directory, so it runs on its own.
421/// Otherwise the working directory (and its ancestors) is searched, then the
422/// project root recorded at build time, so `./target/debug/my-app` works from
423/// any directory.
424pub fn discover_config(
425    project_root: Option<&str>,
426    embedded: Option<&crate::embed::Embedded>,
427    toml: Option<next_rust_core::config::TomlParser>,
428) -> std::result::Result<Config, String> {
429    let start = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
430    if std::env::var_os("NEXT_RUST_CONFIG").is_none()
431        && let Some((text, json)) = embedded.and_then(|e| e.config)
432    {
433        let parsed = match (json, toml) {
434            (true, _) => Config::from_json_str(text),
435            (false, Some(parse)) => parse(text),
436            (false, None) => Err("embedded TOML configuration needs a TOML parser".to_owned()),
437        };
438        let mut config = parsed.map_err(|e| format!("embedded configuration: {e}"))?;
439        config.root = start;
440        config.apply_env_overrides();
441        return Ok(config);
442    }
443    let from_cwd = Config::discover_with(&start, toml).map_err(|e| e.to_string())?;
444    if from_cwd.source.is_some() || from_cwd.app_dir().is_dir() {
445        return Ok(from_cwd);
446    }
447    match project_root {
448        Some(root) if std::path::Path::new(root).is_dir() => {
449            Config::discover_with(root, toml).map_err(|e| e.to_string())
450        }
451        _ => Ok(from_cwd),
452    }
453}
454
455impl AppBuilder {
456    pub(crate) fn project_root(&self) -> Option<&'static str> {
457        self.routes.project_root
458    }
459
460    pub(crate) fn embedded(&self) -> Option<&'static crate::embed::Embedded> {
461        self.routes.embedded
462    }
463
464    pub(crate) fn toml_parser(&self) -> Option<next_rust_core::config::TomlParser> {
465        self.routes.toml
466    }
467
468    /// Use an explicit configuration instead of discovering `next-rust.toml`.
469    pub fn config(mut self, config: Config) -> Self {
470        self.config = Some(config);
471        self
472    }
473
474    pub fn environment(mut self, env: Environment) -> Self {
475        self.env = Some(env);
476        self
477    }
478
479    /// Add global middleware (runs before `middleware.rs` files, in order).
480    pub fn middleware(mut self, mw: impl Middleware) -> Self {
481        self.middleware.push(Arc::new(mw));
482        self
483    }
484
485    /// Data cache (default: in-memory).
486    pub fn cache(mut self, cache: Cache) -> Self {
487        self.cache = Some(cache);
488        self
489    }
490
491    /// Store for statically rendered pages (default: files in the build
492    /// output in production, memory in development).
493    pub fn page_store(mut self, store: impl CacheStore) -> Self {
494        self.page_store = Some(Arc::new(store));
495        self
496    }
497
498    pub fn plugin(mut self, plugin: impl crate::plugin::Plugin) -> Self {
499        self.plugins.push(Arc::new(plugin));
500        self
501    }
502
503    /// Register a handler programmatically for any method.
504    /// Patterns accept `/users/:id`, `/files/*path` or `/users/[id]`.
505    pub fn route<H, Fut, R>(self, method: Method, pattern: &str, handler: H) -> Self
506    where
507        H: Fn(Request) -> Fut + Send + Sync + 'static,
508        Fut: Future<Output = R> + Send + 'static,
509        R: IntoResponse,
510    {
511        self.custom(Some(method), pattern, handler)
512    }
513
514    pub fn get<H, Fut, R>(self, pattern: &str, handler: H) -> Self
515    where
516        H: Fn(Request) -> Fut + Send + Sync + 'static,
517        Fut: Future<Output = R> + Send + 'static,
518        R: IntoResponse,
519    {
520        self.custom(Some(Method::GET), pattern, handler)
521    }
522
523    pub fn post<H, Fut, R>(self, pattern: &str, handler: H) -> Self
524    where
525        H: Fn(Request) -> Fut + Send + Sync + 'static,
526        Fut: Future<Output = R> + Send + 'static,
527        R: IntoResponse,
528    {
529        self.custom(Some(Method::POST), pattern, handler)
530    }
531
532    /// WebSocket endpoint: `.ws("/socket", |socket| async move { .. })`.
533    #[cfg(feature = "websocket")]
534    pub fn ws<H, Fut>(self, pattern: &str, handler: H) -> Self
535    where
536        H: Fn(crate::ws::WebSocket) -> Fut + Clone + Send + Sync + 'static,
537        Fut: Future<Output = ()> + Send + 'static,
538    {
539        self.custom(Some(Method::GET), pattern, move |req: Request| {
540            let handler = handler.clone();
541            async move { crate::ws::upgrade(req, handler) }
542        })
543    }
544
545    fn custom<H, Fut, R>(mut self, method: Option<Method>, pattern: &str, handler: H) -> Self
546    where
547        H: Fn(Request) -> Fut + Send + Sync + 'static,
548        Fut: Future<Output = R> + Send + 'static,
549        R: IntoResponse,
550    {
551        let handler = Arc::new(handler);
552        let endpoint = move |req: Request| {
553            let handler = handler.clone();
554            async move { handler(req).await.into_response() }
555        };
556        self.customs.push(CustomRoute { pattern: pattern.to_owned(), method, endpoint: Arc::new(endpoint) });
557        self
558    }
559
560    /// Validate routes and build the application.
561    pub fn build(self) -> std::result::Result<App, String> {
562        let env = self.env.unwrap_or_else(Environment::from_env);
563        let config = match self.config {
564            Some(c) => c,
565            None => discover_config(self.routes.project_root, self.routes.embedded, self.routes.toml)?,
566        };
567        crate::set_dev(env.is_dev());
568        let json = match config.logging.format {
569            next_rust_core::config::LogFormat::Json => true,
570            next_rust_core::config::LogFormat::Pretty => false,
571            next_rust_core::config::LogFormat::Auto => !env.is_dev(),
572        };
573        // Production prints only errors unless `[logging]` says otherwise.
574        crate::log::configure(json, config.logging.level(env));
575        crate::set_trust_proxy(config.server.trust_proxy);
576
577        let mut matcher = Matcher::new();
578        let mut intercepts = Vec::new();
579        for (i, page) in self.routes.pages.iter().enumerate() {
580            let pattern = parse_pattern(page.pattern)?;
581            if let Some(from) = page.intercept_from {
582                let mut target = Matcher::new();
583                target.insert(pattern.segments(), ()).map_err(|e| format!("{}: {e}", page.source))?;
584                intercepts.push(Intercept { page: i, target, context: parse_pattern(from)? });
585                continue;
586            }
587            matcher
588                .insert(pattern.segments(), Target::Page(i))
589                .map_err(|e| format!("route {} ({}): {e}", page.pattern, page.source))?;
590        }
591        for (i, api) in self.routes.apis.iter().enumerate() {
592            let pattern = parse_pattern(api.pattern)?;
593            matcher
594                .insert(pattern.segments(), Target::Api(i))
595                .map_err(|e| format!("route {} ({}): {e}", api.pattern, api.source))?;
596        }
597        // Programmatic routes: group handlers by pattern.
598        let mut customs: Vec<CustomHandlers> = Vec::new();
599        let mut custom_index: HashMap<String, usize> = HashMap::new();
600        for c in self.customs {
601            let pattern = parse_pattern(&c.pattern)?;
602            let shape = pattern.shape();
603            let idx = match custom_index.get(&shape) {
604                Some(i) => *i,
605                None => {
606                    let i = customs.len();
607                    matcher
608                        .insert(pattern.segments(), Target::Custom(i))
609                        .map_err(|e| format!("route {}: {e} (conflicts with a file route)", c.pattern))?;
610                    customs.push(Vec::new());
611                    custom_index.insert(shape, i);
612                    i
613                }
614            };
615            customs[idx].push((c.method, c.endpoint));
616        }
617
618        let mut global: Vec<Arc<dyn Middleware>> = self.middleware;
619        for p in &self.plugins {
620            global.extend(p.middleware());
621        }
622        if let Some(mw) = self.routes.middleware {
623            global.push(Arc::new(FnMiddleware(mw)));
624        }
625        let stack_of = |fns: Vec<MiddlewareFn>| -> Arc<[Arc<dyn Middleware>]> {
626            fns.into_iter().map(|f| Arc::new(FnMiddleware(f)) as Arc<dyn Middleware>).collect::<Vec<_>>().into()
627        };
628        let page_stacks = self
629            .routes
630            .pages
631            .iter()
632            .map(|p| stack_of(p.segments.iter().filter_map(|s| s.middleware).collect()))
633            .collect();
634        let api_stacks = self.routes.apis.iter().map(|a| stack_of(a.middleware.clone())).collect();
635        let actions =
636            self.routes.actions.iter().enumerate().map(|(i, a)| (crate::actions::action_hash(a.id), i)).collect();
637
638        let output_dir = config.output_dir();
639        let page_store: Arc<dyn CacheStore> = match self.page_store {
640            Some(s) => s,
641            None if env.is_dev() => Arc::new(MemoryStore::new(1000)),
642            // Production keeps pages in memory: the binary writes no files.
643            None => Arc::new(MemoryStore::new(10_000)),
644        };
645        let cache = self.cache.unwrap_or_default();
646        next_rust_cache::install_global(cache.clone());
647        let _ = crate::PAGE_STORE.set(page_store.clone());
648
649        let public_env = next_rust_core::env::EnvVars::load(&config.root, env, &config.env.public_prefix)
650            .map(|e| e.public())
651            .unwrap_or_default();
652        let public_env_json = (!public_env.is_empty()).then(|| serde_json::to_string(&public_env).unwrap_or_default());
653
654        let inner = AppInner {
655            public_dir: config.public_dir(),
656            client_dir: config.root.join("client"),
657            dev_status_file: output_dir.join("dev/status.json"),
658            embedded: self.routes.embedded.filter(|e| !e.is_empty()),
659            routes: self.routes,
660            matcher,
661            intercepts,
662            customs,
663            env,
664            cache,
665            page_store,
666            global_stack: global.into(),
667            page_stacks,
668            api_stacks,
669            actions,
670            revalidating: Mutex::new(HashSet::new()),
671            static_params: Mutex::new(HashMap::new()),
672            plugins: self.plugins,
673            public_env_json,
674            config: Arc::new(config),
675        };
676        for p in &inner.plugins {
677            p.on_start(&inner.config);
678        }
679        Ok(App { inner: Arc::new(inner) })
680    }
681}
682
683/// Final endpoint of the global middleware chain: routing.
684struct RouteEndpoint {
685    inner: Arc<AppInner>,
686}
687
688impl Endpoint for RouteEndpoint {
689    fn call(&self, req: Request) -> BoxFuture<Response> {
690        let inner = self.inner.clone();
691        Box::pin(async move { dispatch(inner, req).await })
692    }
693}
694
695async fn dispatch(inner: Arc<AppInner>, mut req: Request) -> Response {
696    let path = req.path().to_owned();
697
698    if path.starts_with("/_nr/action/") {
699        return crate::actions::handle(&inner, req).await;
700    }
701    if req.method() == Method::GET || req.method() == Method::HEAD {
702        if path == "/sitemap.xml"
703            && let Some(f) = inner.routes.sitemap
704        {
705            return f().await.into_response();
706        }
707        if path == "/robots.txt"
708            && let Some(f) = inner.routes.robots
709        {
710            return f().await.into_response();
711        }
712    }
713
714    // Intercepting routes apply to client-side navigations only.
715    if let (Some(from), Some("1")) = (req.header("x-nr-from").map(str::to_owned), req.header("x-nr-nav")) {
716        for ic in &inner.intercepts {
717            if let Some(hit) = ic.target.at(&path)
718                && context_matches(&ic.context, &from)
719            {
720                req.set_params(hit.params);
721                let idx = ic.page;
722                // Tells the client runtime this HTML depends on the page it
723                // navigated from, so it isn't reused from other pages.
724                let mut res = run_page(&inner, idx, req).await;
725                res.set_header("x-nr-intercepted", "1");
726                return res;
727            }
728        }
729    }
730
731    let hit = inner.matcher.at(&path).map(|m| (*m.value, m.params));
732    match hit {
733        Some((Target::Page(i), params)) => {
734            if req.method() != Method::GET && req.method() != Method::HEAD {
735                return Response::text("Method Not Allowed").with_status(405).with_header("allow", "GET, HEAD");
736            }
737            req.set_params(params);
738            run_page(&inner, i, req).await
739        }
740        Some((Target::Api(i), params)) => {
741            req.set_params(params);
742            let stack = inner.api_stacks[i].clone();
743            let endpoint = ApiEndpoint { inner: inner.clone(), index: i };
744            Next::new(stack, Arc::new(endpoint)).run(req).await
745        }
746        Some((Target::Custom(i), params)) => {
747            req.set_params(params);
748            let handlers = &inner.customs[i];
749            let method = req.method().clone();
750            let found = handlers.iter().find(|(m, _)| {
751                m.as_ref().is_none_or(|m| *m == method || (method == Method::HEAD && *m == Method::GET))
752            });
753            match found {
754                Some((_, ep)) => {
755                    let head = method == Method::HEAD;
756                    let res = ep.call(req).await;
757                    if head { strip_body(res) } else { res }
758                }
759                None => method_not_allowed(handlers.iter().filter_map(|(m, _)| m.clone()).collect()),
760            }
761        }
762        None => {
763            if (req.method() == Method::GET || req.method() == Method::HEAD)
764                && let Some(res) = crate::static_files::serve_public(&inner, &req).await
765            {
766                return res;
767            }
768            crate::render::not_found_response(&inner, &req).await
769        }
770    }
771}
772
773fn context_matches(context: &RoutePattern, from: &str) -> bool {
774    let from = from.split('?').next().unwrap_or("");
775    let segs: Vec<&str> = from.split('/').filter(|s| !s.is_empty()).collect();
776    let n = context.segments().len();
777    if segs.len() < n {
778        return false;
779    }
780    let mut m = Matcher::new();
781    if m.insert(context.segments(), ()).is_err() {
782        return false;
783    }
784    m.at_segments(&segs[..n]).is_some()
785}
786
787async fn run_page(inner: &Arc<AppInner>, index: usize, req: Request) -> Response {
788    let stack = inner.page_stacks[index].clone();
789    let head = req.method() == Method::HEAD;
790    let endpoint = PageEndpoint { inner: inner.clone(), index };
791    let res = Next::new(stack, Arc::new(endpoint)).run(req).await;
792    if head { strip_body(res) } else { res }
793}
794
795struct PageEndpoint {
796    inner: Arc<AppInner>,
797    index: usize,
798}
799
800impl Endpoint for PageEndpoint {
801    fn call(&self, req: Request) -> BoxFuture<Response> {
802        let inner = self.inner.clone();
803        let index = self.index;
804        Box::pin(async move { crate::render::page_response(&inner, index, req).await })
805    }
806}
807
808struct ApiEndpoint {
809    inner: Arc<AppInner>,
810    index: usize,
811}
812
813impl Endpoint for ApiEndpoint {
814    fn call(&self, req: Request) -> BoxFuture<Response> {
815        let inner = self.inner.clone();
816        let index = self.index;
817        Box::pin(async move {
818            let api = &inner.routes.apis[index];
819            let method = req.method().clone();
820            if let Some((_, h)) = api.handlers.iter().find(|(m, _)| *m == method) {
821                return h(req).await;
822            }
823            if method == Method::HEAD
824                && let Some((_, h)) = api.handlers.iter().find(|(m, _)| *m == Method::GET)
825            {
826                return strip_body(h(req).await);
827            }
828            let mut allowed: Vec<Method> = api.handlers.iter().map(|(m, _)| m.clone()).collect();
829            if method == Method::OPTIONS {
830                allowed.push(Method::OPTIONS);
831                let list = allowed.iter().map(Method::as_str).collect::<Vec<_>>().join(", ");
832                return Response::status(204).with_header("allow", &list);
833            }
834            method_not_allowed(allowed)
835        })
836    }
837}
838
839fn method_not_allowed(allowed: Vec<Method>) -> Response {
840    let mut list: Vec<&str> = allowed.iter().map(Method::as_str).collect();
841    if list.contains(&"GET") && !list.contains(&"HEAD") {
842        list.push("HEAD");
843    }
844    Response::text("Method Not Allowed")
845        .with_status(StatusCode::METHOD_NOT_ALLOWED.as_u16())
846        .with_header("allow", &list.join(", "))
847}
848
849fn strip_body(mut res: Response) -> Response {
850    res.body = crate::response::Body::Empty;
851    res
852}