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