Skip to main content

navree_http/
controller.rs

1//! [`Controller`], [`GlobalLayer`] and [`ModuleBuilderHttpExt`]: how modules
2//! contribute routes, global middleware and error mappings.
3
4use std::error::Error as StdError;
5use std::fmt;
6use std::sync::Arc;
7
8use navree_kernel::{
9    AppContext, BoxError, BoxFuture, Injectable, KernelError, ModuleBuilder, ModuleId, Resolver,
10};
11
12use crate::{AppError, AppRouter, ErrorMapper, RouteDef};
13
14/// A group of routes sharing a prefix and an API version (what
15/// `#[controller("/deals", version = "1")]` implements). Controllers are
16/// singletons registered with [`ModuleBuilderHttpExt::controller`]; handlers
17/// capture `Arc<Self>`.
18///
19/// Routes mount at `{api_prefix}/v{version}{prefix}{path}`; a prefix or a
20/// route path starting with `!` is absolute (no API prefix, no version).
21pub trait Controller: Send + Sync + 'static {
22    /// The path prefix, e.g. `/deals`.
23    fn prefix(&self) -> &'static str;
24
25    /// The API version (`"1"` mounts under `/v1`).
26    fn version(&self) -> Option<&'static str> {
27        None
28    }
29
30    /// The routes, with paths relative to the prefix.
31    fn routes(self: Arc<Self>) -> Vec<RouteDef>;
32}
33
34/// The routes of one controller, resolved from its module.
35pub(crate) struct ControllerRoutes {
36    pub(crate) type_name: &'static str,
37    pub(crate) prefix: &'static str,
38    pub(crate) version: Option<&'static str>,
39    pub(crate) routes: Vec<RouteDef>,
40}
41
42type ResolveRoutes = Arc<
43    dyn Fn(Resolver) -> BoxFuture<'static, Result<ControllerRoutes, KernelError>> + Send + Sync,
44>;
45
46/// A controller registered by a module (a contribution).
47#[derive(Clone)]
48pub(crate) struct ControllerRegistration {
49    pub(crate) module: ModuleId,
50    pub(crate) resolve: ResolveRoutes,
51}
52
53impl ControllerRegistration {
54    fn of<C: Controller + Injectable>(module: ModuleId) -> Self {
55        Self {
56            module,
57            resolve: Arc::new(|r: Resolver| {
58                Box::pin(async move {
59                    let controller = r.get::<C>().await?;
60                    Ok(ControllerRoutes {
61                        type_name: std::any::type_name::<C>(),
62                        prefix: controller.prefix(),
63                        version: controller.version(),
64                        routes: controller.routes(),
65                    })
66                })
67            }),
68        }
69    }
70}
71
72/// Where a [`GlobalLayer`] sits in the request pipeline, outermost first:
73/// the edge, then the session layer, then authentication context, then the
74/// unit of work, then the request context. Every slot but
75/// [`Edge`](LayerSlot::Edge) runs after the fixed layers (request id,
76/// tracing, CORS, panic catcher, timeout, security headers, compression,
77/// maintenance mode, per-IP rate limit, body limit) and before routing.
78#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
79#[non_exhaustive]
80pub enum LayerSlot {
81    /// Around the whole app, before every fixed layer: for protocols that
82    /// share the HTTP port but not the HTTP pipeline (navree-grpc sends
83    /// gRPC calls to its own). Requests here have no request id, app
84    /// context or client IP yet, and a response an edge layer returns
85    /// itself gets none of the fixed layers' treatment.
86    Edge,
87    /// Session and CSRF (navree-session).
88    Session,
89    /// Authentication: navree-http runs the `Authenticator` first in this slot.
90    AuthContext,
91    /// The unit of work (navree-db).
92    Uow,
93    /// Request context for handlers, innermost (navree-i18n's locale). The
94    /// unit-of-work layer runs the rest of the request in a task of its
95    /// own, so a layer that sets a Tokio task-local for handlers belongs
96    /// here, inside it.
97    Context,
98}
99
100/// The function that wraps the app router in a [`GlobalLayer`].
101pub type ApplyLayer =
102    Arc<dyn Fn(&AppContext, AppRouter) -> Result<AppRouter, BoxError> + Send + Sync>;
103
104/// App-wide middleware contributed by a module with
105/// [`ModuleBuilderHttpExt::http_layer`]. `apply` wraps the router
106/// (`router.layer(...)`); layers in the same slot run in module dependency
107/// order (the first registered is outermost). `apply` may run more than once
108/// per app, so it should not have side effects, and it must only add
109/// layers: the router already has navree's single 404 fallback.
110///
111/// Only the app adds middleware that runs on every request: a module of a
112/// plugin that is not one of the framework's own packages stops the boot
113/// when it contributes one.
114///
115/// Inside the pipeline the request extensions already hold the
116/// `AppContext`, the `navree_contracts::RequestId` and the [`ClientIp`](crate::ClientIp);
117/// from the `AuthContext` slot inward they also hold the
118/// `navree_contracts::AuthState`. Error responses should be [`AppError`]s, so
119/// they render in Navree's JSON error shape.
120///
121/// ```
122/// use navree_http::extract::Request;
123/// use navree_http::middleware::{self, Next};
124/// use navree_http::response::{IntoResponse, Response};
125/// use navree_http::{AppError, GlobalLayer, LayerSlot, ModuleBuilderHttpExt};
126/// use navree_kernel::{AppContext, Module, ModuleBuilder};
127///
128/// async fn unit_of_work(ctx: AppContext, request: Request, next: Next) -> Response {
129///     if request.extensions().get::<AppContext>().is_none() {
130///         return AppError::internal("outside the navree pipeline").into_response();
131///     }
132///     // open a transaction with `ctx`, run the request, commit or roll back
133///     let _ = ctx;
134///     next.run(request).await
135/// }
136///
137/// struct DatabaseModule;
138///
139/// impl Module for DatabaseModule {
140///     fn register(&self, m: &mut ModuleBuilder) {
141///         m.http_layer(GlobalLayer::new(LayerSlot::Uow, "uow", |ctx, router| {
142///             let ctx = ctx.clone();
143///             Ok(router.layer(middleware::from_fn(move |request: Request, next: Next| {
144///                 unit_of_work(ctx.clone(), request, next)
145///             })))
146///         }));
147///     }
148/// }
149/// ```
150#[derive(Clone)]
151pub struct GlobalLayer {
152    /// The pipeline slot.
153    pub slot: LayerSlot,
154    /// A name for logs and `routes` output.
155    pub name: &'static str,
156    /// Wraps the router.
157    pub apply: ApplyLayer,
158}
159
160impl GlobalLayer {
161    /// A layer in `slot` applied by `apply`.
162    pub fn new<F>(slot: LayerSlot, name: &'static str, apply: F) -> Self
163    where
164        F: Fn(&AppContext, AppRouter) -> Result<AppRouter, BoxError> + Send + Sync + 'static,
165    {
166        Self {
167            slot,
168            name,
169            apply: Arc::new(apply),
170        }
171    }
172}
173
174impl fmt::Debug for GlobalLayer {
175    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176        f.debug_struct("GlobalLayer")
177            .field("slot", &self.slot)
178            .field("name", &self.name)
179            .finish_non_exhaustive()
180    }
181}
182
183/// HTTP registrations on a [`ModuleBuilder`].
184pub trait ModuleBuilderHttpExt {
185    /// Registers controller `C` as a singleton provider of this module and
186    /// mounts its routes.
187    fn controller<C: Controller + Injectable>(&mut self) -> &mut Self;
188
189    /// Adds app-wide middleware in a [`LayerSlot`].
190    ///
191    /// Only the app adds middleware that runs on every request: a module of a
192    /// plugin that is not one of the framework's own packages stops the boot
193    /// when it calls this. A plugin ships its layer as a function, the app
194    /// adds it with one line, and a plugin's own routes and mounts may carry
195    /// layers of their own (`Endpoint::layer`, `Mount`).
196    fn http_layer(&mut self, layer: GlobalLayer) -> &mut Self;
197
198    /// Maps errors of type `E` found in a 500 [`AppError`]'s source chain to
199    /// a specific error (e.g. a database "record not found" to 404).
200    ///
201    /// The mapping answers every such error of the app. A module of a plugin
202    /// that is not one of the framework's own packages maps only the error
203    /// types of the plugin's crate: another crate's stops the boot, and the
204    /// app registers such a mapping from a module of its own.
205    fn map_error<E: StdError + 'static>(&mut self, f: fn(&E) -> Option<AppError>) -> &mut Self;
206
207    /// Lets `pages` answer errors in another form than JSON: a page for a
208    /// browser, say. The app uses the first one contributed.
209    ///
210    /// A module of a plugin that is not one of the framework's own packages
211    /// may not call this: [`build_router`](crate::build_router) refuses it,
212    /// which stops the boot, and the app registers such a plugin's pages from
213    /// a module of its own.
214    fn error_pages(&mut self, pages: impl crate::ErrorPages) -> &mut Self;
215}
216
217impl ModuleBuilderHttpExt for ModuleBuilder {
218    fn controller<C: Controller + Injectable>(&mut self) -> &mut Self {
219        let registration = ControllerRegistration::of::<C>(self.module_id());
220        self.provider::<C>().contribute(registration)
221    }
222
223    fn http_layer(&mut self, layer: GlobalLayer) -> &mut Self {
224        self.contribute(layer)
225    }
226
227    fn map_error<E: StdError + 'static>(&mut self, f: fn(&E) -> Option<AppError>) -> &mut Self {
228        self.contribute(ErrorMapper::new(f))
229    }
230
231    fn error_pages(&mut self, pages: impl crate::ErrorPages) -> &mut Self {
232        self.contribute(crate::ErrorPagesHandle::new(pages))
233    }
234}