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}
162
163pub(crate) type CustomHandlers = Vec<(Option<Method>, Arc<dyn Endpoint>)>;
164
165#[derive(Clone, Copy, Debug)]
166pub(crate) enum Target {
167    Page(usize),
168    Api(usize),
169    Custom(usize),
170}
171
172struct CustomRoute {
173    pattern: String,
174    method: Option<Method>,
175    endpoint: Arc<dyn Endpoint>,
176}
177
178pub(crate) struct Intercept {
179    pub page: usize,
180    pub target: Matcher<()>,
181    pub context: RoutePattern,
182}
183
184pub(crate) struct AppInner {
185    pub routes: Routes,
186    pub matcher: Matcher<Target>,
187    pub intercepts: Vec<Intercept>,
188    pub customs: Vec<CustomHandlers>,
189    pub config: Arc<Config>,
190    pub env: Environment,
191    pub public_dir: PathBuf,
192    pub client_dir: PathBuf,
193    pub dev_status_file: PathBuf,
194    /// Files compiled into the binary; `None` reads from disk.
195    pub embedded: Option<&'static crate::embed::Embedded>,
196    pub cache: Cache,
197    pub page_store: Arc<dyn CacheStore>,
198    pub global_stack: Arc<[Arc<dyn Middleware>]>,
199    pub page_stacks: Vec<Arc<[Arc<dyn Middleware>]>>,
200    pub api_stacks: Vec<Arc<[Arc<dyn Middleware>]>>,
201    pub actions: HashMap<String, usize>,
202    pub revalidating: Mutex<HashSet<String>>,
203    pub static_params: Mutex<HashMap<usize, Arc<Vec<Params>>>>,
204    pub plugins: Vec<Arc<dyn crate::plugin::Plugin>>,
205    pub public_env_json: Option<String>,
206}
207
208/// A configured application. Cheap to clone.
209#[derive(Clone)]
210pub struct App {
211    pub(crate) inner: Arc<AppInner>,
212}
213
214/// Builder returned by [`App::new`].
215pub struct AppBuilder {
216    routes: Routes,
217    config: Option<Config>,
218    env: Option<Environment>,
219    middleware: Vec<Arc<dyn Middleware>>,
220    cache: Option<Cache>,
221    page_store: Option<Arc<dyn CacheStore>>,
222    customs: Vec<CustomRoute>,
223    plugins: Vec<Arc<dyn crate::plugin::Plugin>>,
224}
225
226/// Convert `/users/:id`, `/files/*path` or `/users/[id]` into a pattern.
227pub fn parse_pattern(pattern: &str) -> std::result::Result<RoutePattern, String> {
228    let mut segs = Vec::new();
229    for part in pattern.split('/').filter(|p| !p.is_empty()) {
230        let seg = if let Some(name) = part.strip_prefix(':') {
231            PatternSegment::Dynamic(name.to_owned())
232        } else if let Some(name) = part.strip_prefix('*') {
233            match name.strip_suffix('?') {
234                Some(n) => PatternSegment::OptionalCatchAll(n.to_owned()),
235                None => PatternSegment::CatchAll(name.to_owned()),
236            }
237        } else {
238            match parse_segment(part)? {
239                Some(SegmentKind::Static(s)) => PatternSegment::Static(s),
240                Some(SegmentKind::Dynamic(s)) => PatternSegment::Dynamic(s),
241                Some(SegmentKind::CatchAll(s)) => PatternSegment::CatchAll(s),
242                Some(SegmentKind::OptionalCatchAll(s)) => PatternSegment::OptionalCatchAll(s),
243                _ => return Err(format!("unsupported segment `{part}` in pattern `{pattern}`")),
244            }
245        };
246        segs.push(seg);
247    }
248    Ok(RoutePattern(segs))
249}
250
251impl App {
252    /// Start building an application from generated routes.
253    #[allow(clippy::new_ret_no_self)]
254    pub fn new(routes: Routes) -> AppBuilder {
255        AppBuilder {
256            routes,
257            config: None,
258            env: None,
259            middleware: Vec::new(),
260            cache: None,
261            page_store: None,
262            customs: Vec::new(),
263            plugins: Vec::new(),
264        }
265    }
266
267    pub fn config(&self) -> &Config {
268        &self.inner.config
269    }
270
271    pub fn environment(&self) -> Environment {
272        self.inner.env
273    }
274
275    pub fn cache(&self) -> &Cache {
276        &self.inner.cache
277    }
278
279    /// Handle one request. This is the adapter surface: the built-in server,
280    /// tests and serverless adapters all call it.
281    pub async fn handle(&self, mut req: Request) -> Response {
282        let inner = self.inner.clone();
283        let nonce = crate::random_hex(16);
284        req.insert_extension(crate::CspNonce(nonce.clone()));
285        req.limit_body(inner.config.server.body_limit);
286
287        if let Some(res) = self.pre_routing(&mut req).await {
288            return self.finish(res, &req_cookies_placeholder(), &nonce, "");
289        }
290        let cookies = req.cookies().clone();
291        let path = req.path().to_owned();
292        let endpoint: Arc<dyn Endpoint> = Arc::new(RouteEndpoint { inner: inner.clone() });
293        let res = Next::new(inner.global_stack.clone(), endpoint).run(req).await;
294        self.finish(res, &cookies, &nonce, &path)
295    }
296
297    /// Framework assets, base path, configured redirects and trailing slashes.
298    async fn pre_routing(&self, req: &mut Request) -> Option<Response> {
299        let inner = &self.inner;
300        let config = &inner.config;
301
302        let base = config.app.base_path.as_str();
303        if !base.is_empty() {
304            let path = req.path().to_owned();
305            let stripped = if path == base {
306                "/".to_owned()
307            } else if let Some(rest) = path.strip_prefix(base).filter(|r| r.starts_with('/')) {
308                rest.to_owned()
309            } else {
310                return Some(Response::not_found());
311            };
312            let query = req.uri().query().map(|q| format!("?{q}")).unwrap_or_default();
313            if req.set_path(&format!("{stripped}{query}")).is_err() {
314                return Some(Response::status(400));
315            }
316        }
317
318        let path = req.path();
319        if path.starts_with("/_nr/")
320            && let Some(res) = crate::internal::handle(inner, req).await
321        {
322            return Some(res);
323        }
324
325        for rule in &config.redirects {
326            if let Some(dest) = crate::redirects::apply(&rule.source, &rule.destination, path) {
327                let query = req.uri().query().map(|q| format!("?{q}")).unwrap_or_default();
328                let location = if dest.contains('?') { dest } else { format!("{dest}{query}") };
329                return Some(if rule.permanent {
330                    Response::permanent_redirect(&location)
331                } else {
332                    Response::redirect(&location)
333                });
334            }
335        }
336
337        if path.len() > 1 {
338            let has_slash = path.ends_with('/');
339            let looks_like_file = path.rsplit('/').next().is_some_and(|last| last.contains('.'));
340            if has_slash != config.app.trailing_slash && !looks_like_file {
341                let fixed = if has_slash { path.trim_end_matches('/').to_owned() } else { format!("{path}/") };
342                let fixed = if fixed.is_empty() { "/".to_owned() } else { fixed };
343                let query = req.uri().query().map(|q| format!("?{q}")).unwrap_or_default();
344                return Some(Response::permanent_redirect(&format!("{base}{fixed}{query}")));
345            }
346        }
347        None
348    }
349
350    fn finish(&self, mut res: Response, cookies: &crate::Cookies, nonce: &str, path: &str) -> Response {
351        let config = &self.inner.config;
352        for value in cookies.set_cookie_headers() {
353            res.append_header("set-cookie", &value);
354        }
355        if !path.is_empty() {
356            for rule in &config.headers {
357                if crate::redirects::matches(&rule.source, path) {
358                    for (k, v) in &rule.headers {
359                        res.set_header(k, v);
360                    }
361                }
362            }
363        }
364        if config.security.headers {
365            crate::middleware::apply_security_headers(
366                &mut res,
367                config.security.csp.as_deref(),
368                nonce,
369                config.security.hsts_max_age,
370            );
371        }
372        res
373    }
374
375    /// Re-render `path` on its next request (ISR) and drop data-cache
376    /// entries stored under the same path key.
377    pub async fn revalidate_path(&self, path: &str) -> bool {
378        let path = if path.len() > 1 { path.trim_end_matches('/') } else { path };
379        let page = self.inner.page_store.delete(&next_rust_cache::CacheKey::page(path)).await.unwrap_or(false);
380        page | self.inner.cache.revalidate_path(path).await.unwrap_or(false)
381    }
382
383    /// Invalidate pages and data tagged with `tag`. Returns the number of entries removed.
384    pub async fn revalidate_tag(&self, tag: &str) -> usize {
385        self.inner.page_store.delete_tag(tag).await.unwrap_or(0)
386            + self.inner.cache.revalidate_tag(tag).await.unwrap_or(0)
387    }
388
389    /// Render every static route without keeping the result: used by
390    /// `next-rust build` to check that static generation succeeds.
391    pub async fn export(&self) -> std::result::Result<crate::export::ExportReport, String> {
392        crate::export::prerender(&self.inner, &MemoryStore::new(usize::MAX)).await
393    }
394
395    /// Render every static route into the page cache, so the first visitor
396    /// gets a cached page. Production servers do this in the background at
397    /// startup.
398    pub async fn prerender(&self) -> std::result::Result<crate::export::ExportReport, String> {
399        crate::export::prerender(&self.inner, self.inner.page_store.as_ref()).await
400    }
401
402    /// Route table as `(kind, pattern, source)` for diagnostics.
403    pub fn route_table(&self) -> Vec<(&'static str, &'static str, &'static str)> {
404        let r = &self.inner.routes;
405        let mut out: Vec<_> = r.pages.iter().map(|p| ("page", p.pattern, p.source)).collect();
406        out.extend(r.apis.iter().map(|a| ("api", a.pattern, a.source)));
407        out
408    }
409}
410
411fn req_cookies_placeholder() -> crate::Cookies {
412    crate::Cookies::default()
413}
414
415/// Find the configuration.
416///
417/// `NEXT_RUST_CONFIG` wins. A release binary then uses the configuration it
418/// was built with, rooted at the working directory, so it runs on its own.
419/// Otherwise the working directory (and its ancestors) is searched, then the
420/// project root recorded at build time, so `./target/debug/my-app` works from
421/// any directory.
422pub fn discover_config(
423    project_root: Option<&str>,
424    embedded: Option<&crate::embed::Embedded>,
425    toml: Option<next_rust_core::config::TomlParser>,
426) -> std::result::Result<Config, String> {
427    let start = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
428    if std::env::var_os("NEXT_RUST_CONFIG").is_none()
429        && let Some((text, json)) = embedded.and_then(|e| e.config)
430    {
431        let parsed = match (json, toml) {
432            (true, _) => Config::from_json_str(text),
433            (false, Some(parse)) => parse(text),
434            (false, None) => Err("embedded TOML configuration needs a TOML parser".to_owned()),
435        };
436        let mut config = parsed.map_err(|e| format!("embedded configuration: {e}"))?;
437        config.root = start;
438        config.apply_env_overrides();
439        return Ok(config);
440    }
441    let from_cwd = Config::discover_with(&start, toml).map_err(|e| e.to_string())?;
442    if from_cwd.source.is_some() || from_cwd.app_dir().is_dir() {
443        return Ok(from_cwd);
444    }
445    match project_root {
446        Some(root) if std::path::Path::new(root).is_dir() => {
447            Config::discover_with(root, toml).map_err(|e| e.to_string())
448        }
449        _ => Ok(from_cwd),
450    }
451}
452
453impl AppBuilder {
454    pub(crate) fn project_root(&self) -> Option<&'static str> {
455        self.routes.project_root
456    }
457
458    pub(crate) fn embedded(&self) -> Option<&'static crate::embed::Embedded> {
459        self.routes.embedded
460    }
461
462    pub(crate) fn toml_parser(&self) -> Option<next_rust_core::config::TomlParser> {
463        self.routes.toml
464    }
465
466    /// Use an explicit configuration instead of discovering `next-rust.toml`.
467    pub fn config(mut self, config: Config) -> Self {
468        self.config = Some(config);
469        self
470    }
471
472    pub fn environment(mut self, env: Environment) -> Self {
473        self.env = Some(env);
474        self
475    }
476
477    /// Add global middleware (runs before `middleware.rs` files, in order).
478    pub fn middleware(mut self, mw: impl Middleware) -> Self {
479        self.middleware.push(Arc::new(mw));
480        self
481    }
482
483    /// Data cache (default: in-memory).
484    pub fn cache(mut self, cache: Cache) -> Self {
485        self.cache = Some(cache);
486        self
487    }
488
489    /// Store for statically rendered pages (default: files in the build
490    /// output in production, memory in development).
491    pub fn page_store(mut self, store: impl CacheStore) -> Self {
492        self.page_store = Some(Arc::new(store));
493        self
494    }
495
496    pub fn plugin(mut self, plugin: impl crate::plugin::Plugin) -> Self {
497        self.plugins.push(Arc::new(plugin));
498        self
499    }
500
501    /// Register a handler programmatically for any method.
502    /// Patterns accept `/users/:id`, `/files/*path` or `/users/[id]`.
503    pub fn route<H, Fut, R>(self, method: Method, pattern: &str, handler: H) -> Self
504    where
505        H: Fn(Request) -> Fut + Send + Sync + 'static,
506        Fut: Future<Output = R> + Send + 'static,
507        R: IntoResponse,
508    {
509        self.custom(Some(method), pattern, handler)
510    }
511
512    pub fn get<H, Fut, R>(self, pattern: &str, handler: H) -> Self
513    where
514        H: Fn(Request) -> Fut + Send + Sync + 'static,
515        Fut: Future<Output = R> + Send + 'static,
516        R: IntoResponse,
517    {
518        self.custom(Some(Method::GET), pattern, handler)
519    }
520
521    pub fn post<H, Fut, R>(self, pattern: &str, handler: H) -> Self
522    where
523        H: Fn(Request) -> Fut + Send + Sync + 'static,
524        Fut: Future<Output = R> + Send + 'static,
525        R: IntoResponse,
526    {
527        self.custom(Some(Method::POST), pattern, handler)
528    }
529
530    /// WebSocket endpoint: `.ws("/socket", |socket| async move { .. })`.
531    #[cfg(feature = "websocket")]
532    pub fn ws<H, Fut>(self, pattern: &str, handler: H) -> Self
533    where
534        H: Fn(crate::ws::WebSocket) -> Fut + Clone + Send + Sync + 'static,
535        Fut: Future<Output = ()> + Send + 'static,
536    {
537        self.custom(Some(Method::GET), pattern, move |req: Request| {
538            let handler = handler.clone();
539            async move { crate::ws::upgrade(req, handler) }
540        })
541    }
542
543    fn custom<H, Fut, R>(mut self, method: Option<Method>, pattern: &str, handler: H) -> Self
544    where
545        H: Fn(Request) -> Fut + Send + Sync + 'static,
546        Fut: Future<Output = R> + Send + 'static,
547        R: IntoResponse,
548    {
549        let handler = Arc::new(handler);
550        let endpoint = move |req: Request| {
551            let handler = handler.clone();
552            async move { handler(req).await.into_response() }
553        };
554        self.customs.push(CustomRoute { pattern: pattern.to_owned(), method, endpoint: Arc::new(endpoint) });
555        self
556    }
557
558    /// Validate routes and build the application.
559    pub fn build(self) -> std::result::Result<App, String> {
560        let env = self.env.unwrap_or_else(Environment::from_env);
561        let config = match self.config {
562            Some(c) => c,
563            None => discover_config(self.routes.project_root, self.routes.embedded, self.routes.toml)?,
564        };
565        crate::set_dev(env.is_dev());
566        let json = match config.logging.format {
567            next_rust_core::config::LogFormat::Json => true,
568            next_rust_core::config::LogFormat::Pretty => false,
569            next_rust_core::config::LogFormat::Auto => !env.is_dev(),
570        };
571        // Production prints only errors unless `[logging]` says otherwise.
572        crate::log::configure(json, config.logging.level(env));
573        crate::set_trust_proxy(config.server.trust_proxy);
574
575        let mut matcher = Matcher::new();
576        let mut intercepts = Vec::new();
577        for (i, page) in self.routes.pages.iter().enumerate() {
578            let pattern = parse_pattern(page.pattern)?;
579            if let Some(from) = page.intercept_from {
580                let mut target = Matcher::new();
581                target.insert(pattern.segments(), ()).map_err(|e| format!("{}: {e}", page.source))?;
582                intercepts.push(Intercept { page: i, target, context: parse_pattern(from)? });
583                continue;
584            }
585            matcher
586                .insert(pattern.segments(), Target::Page(i))
587                .map_err(|e| format!("route {} ({}): {e}", page.pattern, page.source))?;
588        }
589        for (i, api) in self.routes.apis.iter().enumerate() {
590            let pattern = parse_pattern(api.pattern)?;
591            matcher
592                .insert(pattern.segments(), Target::Api(i))
593                .map_err(|e| format!("route {} ({}): {e}", api.pattern, api.source))?;
594        }
595        // Programmatic routes: group handlers by pattern.
596        let mut customs: Vec<CustomHandlers> = Vec::new();
597        let mut custom_index: HashMap<String, usize> = HashMap::new();
598        for c in self.customs {
599            let pattern = parse_pattern(&c.pattern)?;
600            let shape = pattern.shape();
601            let idx = match custom_index.get(&shape) {
602                Some(i) => *i,
603                None => {
604                    let i = customs.len();
605                    matcher
606                        .insert(pattern.segments(), Target::Custom(i))
607                        .map_err(|e| format!("route {}: {e} (conflicts with a file route)", c.pattern))?;
608                    customs.push(Vec::new());
609                    custom_index.insert(shape, i);
610                    i
611                }
612            };
613            customs[idx].push((c.method, c.endpoint));
614        }
615
616        let mut global: Vec<Arc<dyn Middleware>> = self.middleware;
617        for p in &self.plugins {
618            global.extend(p.middleware());
619        }
620        if let Some(mw) = self.routes.middleware {
621            global.push(Arc::new(FnMiddleware(mw)));
622        }
623        let stack_of = |fns: Vec<MiddlewareFn>| -> Arc<[Arc<dyn Middleware>]> {
624            fns.into_iter().map(|f| Arc::new(FnMiddleware(f)) as Arc<dyn Middleware>).collect::<Vec<_>>().into()
625        };
626        let page_stacks = self
627            .routes
628            .pages
629            .iter()
630            .map(|p| stack_of(p.segments.iter().filter_map(|s| s.middleware).collect()))
631            .collect();
632        let api_stacks = self.routes.apis.iter().map(|a| stack_of(a.middleware.clone())).collect();
633        let actions =
634            self.routes.actions.iter().enumerate().map(|(i, a)| (crate::actions::action_hash(a.id), i)).collect();
635
636        let output_dir = config.output_dir();
637        let page_store: Arc<dyn CacheStore> = match self.page_store {
638            Some(s) => s,
639            None if env.is_dev() => Arc::new(MemoryStore::new(1000)),
640            // Production keeps pages in memory: the binary writes no files.
641            None => Arc::new(MemoryStore::new(10_000)),
642        };
643        let cache = self.cache.unwrap_or_default();
644        next_rust_cache::install_global(cache.clone());
645        let _ = crate::PAGE_STORE.set(page_store.clone());
646
647        let public_env = next_rust_core::env::EnvVars::load(&config.root, env, &config.env.public_prefix)
648            .map(|e| e.public())
649            .unwrap_or_default();
650        let public_env_json = (!public_env.is_empty()).then(|| serde_json::to_string(&public_env).unwrap_or_default());
651
652        let inner = AppInner {
653            public_dir: config.public_dir(),
654            client_dir: config.root.join("client"),
655            dev_status_file: output_dir.join("dev/status.json"),
656            embedded: self.routes.embedded.filter(|e| !e.is_empty()),
657            routes: self.routes,
658            matcher,
659            intercepts,
660            customs,
661            env,
662            cache,
663            page_store,
664            global_stack: global.into(),
665            page_stacks,
666            api_stacks,
667            actions,
668            revalidating: Mutex::new(HashSet::new()),
669            static_params: Mutex::new(HashMap::new()),
670            plugins: self.plugins,
671            public_env_json,
672            config: Arc::new(config),
673        };
674        for p in &inner.plugins {
675            p.on_start(&inner.config);
676        }
677        Ok(App { inner: Arc::new(inner) })
678    }
679}
680
681/// Final endpoint of the global middleware chain: routing.
682struct RouteEndpoint {
683    inner: Arc<AppInner>,
684}
685
686impl Endpoint for RouteEndpoint {
687    fn call(&self, req: Request) -> BoxFuture<Response> {
688        let inner = self.inner.clone();
689        Box::pin(async move { dispatch(inner, req).await })
690    }
691}
692
693async fn dispatch(inner: Arc<AppInner>, mut req: Request) -> Response {
694    let path = req.path().to_owned();
695
696    if path.starts_with("/_nr/action/") {
697        return crate::actions::handle(&inner, req).await;
698    }
699    if req.method() == Method::GET || req.method() == Method::HEAD {
700        if path == "/sitemap.xml"
701            && let Some(f) = inner.routes.sitemap
702        {
703            return f().await.into_response();
704        }
705        if path == "/robots.txt"
706            && let Some(f) = inner.routes.robots
707        {
708            return f().await.into_response();
709        }
710    }
711
712    // Intercepting routes apply to client-side navigations only.
713    if let (Some(from), Some("1")) = (req.header("x-nr-from").map(str::to_owned), req.header("x-nr-nav")) {
714        for ic in &inner.intercepts {
715            if let Some(hit) = ic.target.at(&path)
716                && context_matches(&ic.context, &from)
717            {
718                req.set_params(hit.params);
719                let idx = ic.page;
720                // Tells the client runtime this HTML depends on the page it
721                // navigated from, so it isn't reused from other pages.
722                let mut res = run_page(&inner, idx, req).await;
723                res.set_header("x-nr-intercepted", "1");
724                return res;
725            }
726        }
727    }
728
729    let hit = inner.matcher.at(&path).map(|m| (*m.value, m.params));
730    match hit {
731        Some((Target::Page(i), params)) => {
732            if req.method() != Method::GET && req.method() != Method::HEAD {
733                return Response::text("Method Not Allowed").with_status(405).with_header("allow", "GET, HEAD");
734            }
735            req.set_params(params);
736            run_page(&inner, i, req).await
737        }
738        Some((Target::Api(i), params)) => {
739            req.set_params(params);
740            let stack = inner.api_stacks[i].clone();
741            let endpoint = ApiEndpoint { inner: inner.clone(), index: i };
742            Next::new(stack, Arc::new(endpoint)).run(req).await
743        }
744        Some((Target::Custom(i), params)) => {
745            req.set_params(params);
746            let handlers = &inner.customs[i];
747            let method = req.method().clone();
748            let found = handlers.iter().find(|(m, _)| {
749                m.as_ref().is_none_or(|m| *m == method || (method == Method::HEAD && *m == Method::GET))
750            });
751            match found {
752                Some((_, ep)) => {
753                    let head = method == Method::HEAD;
754                    let res = ep.call(req).await;
755                    if head { strip_body(res) } else { res }
756                }
757                None => method_not_allowed(handlers.iter().filter_map(|(m, _)| m.clone()).collect()),
758            }
759        }
760        None => {
761            if (req.method() == Method::GET || req.method() == Method::HEAD)
762                && let Some(res) = crate::static_files::serve_public(&inner, &req).await
763            {
764                return res;
765            }
766            crate::render::not_found_response(&inner, &req).await
767        }
768    }
769}
770
771fn context_matches(context: &RoutePattern, from: &str) -> bool {
772    let from = from.split('?').next().unwrap_or("");
773    let segs: Vec<&str> = from.split('/').filter(|s| !s.is_empty()).collect();
774    let n = context.segments().len();
775    if segs.len() < n {
776        return false;
777    }
778    let mut m = Matcher::new();
779    if m.insert(context.segments(), ()).is_err() {
780        return false;
781    }
782    m.at_segments(&segs[..n]).is_some()
783}
784
785async fn run_page(inner: &Arc<AppInner>, index: usize, req: Request) -> Response {
786    let stack = inner.page_stacks[index].clone();
787    let head = req.method() == Method::HEAD;
788    let endpoint = PageEndpoint { inner: inner.clone(), index };
789    let res = Next::new(stack, Arc::new(endpoint)).run(req).await;
790    if head { strip_body(res) } else { res }
791}
792
793struct PageEndpoint {
794    inner: Arc<AppInner>,
795    index: usize,
796}
797
798impl Endpoint for PageEndpoint {
799    fn call(&self, req: Request) -> BoxFuture<Response> {
800        let inner = self.inner.clone();
801        let index = self.index;
802        Box::pin(async move { crate::render::page_response(&inner, index, req).await })
803    }
804}
805
806struct ApiEndpoint {
807    inner: Arc<AppInner>,
808    index: usize,
809}
810
811impl Endpoint for ApiEndpoint {
812    fn call(&self, req: Request) -> BoxFuture<Response> {
813        let inner = self.inner.clone();
814        let index = self.index;
815        Box::pin(async move {
816            let api = &inner.routes.apis[index];
817            let method = req.method().clone();
818            if let Some((_, h)) = api.handlers.iter().find(|(m, _)| *m == method) {
819                return h(req).await;
820            }
821            if method == Method::HEAD
822                && let Some((_, h)) = api.handlers.iter().find(|(m, _)| *m == Method::GET)
823            {
824                return strip_body(h(req).await);
825            }
826            let mut allowed: Vec<Method> = api.handlers.iter().map(|(m, _)| m.clone()).collect();
827            if method == Method::OPTIONS {
828                allowed.push(Method::OPTIONS);
829                let list = allowed.iter().map(Method::as_str).collect::<Vec<_>>().join(", ");
830                return Response::status(204).with_header("allow", &list);
831            }
832            method_not_allowed(allowed)
833        })
834    }
835}
836
837fn method_not_allowed(allowed: Vec<Method>) -> Response {
838    let mut list: Vec<&str> = allowed.iter().map(Method::as_str).collect();
839    if list.contains(&"GET") && !list.contains(&"HEAD") {
840        list.push("HEAD");
841    }
842    Response::text("Method Not Allowed")
843        .with_status(StatusCode::METHOD_NOT_ALLOWED.as_u16())
844        .with_header("allow", &list.join(", "))
845}
846
847fn strip_body(mut res: Response) -> Response {
848    res.body = crate::response::Body::Empty;
849    res
850}