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