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