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/// Inside the pipeline the request extensions already hold the
112/// `AppContext`, the `navree_contracts::RequestId` and the [`ClientIp`](crate::ClientIp);
113/// from the `AuthContext` slot inward they also hold the
114/// `navree_contracts::AuthState`. Error responses should be [`AppError`]s, so
115/// they render in Navree's JSON error shape.
116///
117/// ```
118/// use navree_http::extract::Request;
119/// use navree_http::middleware::{self, Next};
120/// use navree_http::response::{IntoResponse, Response};
121/// use navree_http::{AppError, GlobalLayer, LayerSlot, ModuleBuilderHttpExt};
122/// use navree_kernel::{AppContext, Module, ModuleBuilder};
123///
124/// async fn unit_of_work(ctx: AppContext, request: Request, next: Next) -> Response {
125/// if request.extensions().get::<AppContext>().is_none() {
126/// return AppError::internal("outside the navree pipeline").into_response();
127/// }
128/// // open a transaction with `ctx`, run the request, commit or roll back
129/// let _ = ctx;
130/// next.run(request).await
131/// }
132///
133/// struct DatabaseModule;
134///
135/// impl Module for DatabaseModule {
136/// fn register(&self, m: &mut ModuleBuilder) {
137/// m.http_layer(GlobalLayer::new(LayerSlot::Uow, "uow", |ctx, router| {
138/// let ctx = ctx.clone();
139/// Ok(router.layer(middleware::from_fn(move |request: Request, next: Next| {
140/// unit_of_work(ctx.clone(), request, next)
141/// })))
142/// }));
143/// }
144/// }
145/// ```
146#[derive(Clone)]
147pub struct GlobalLayer {
148 /// The pipeline slot.
149 pub slot: LayerSlot,
150 /// A name for logs and `routes` output.
151 pub name: &'static str,
152 /// Wraps the router.
153 pub apply: ApplyLayer,
154}
155
156impl GlobalLayer {
157 /// A layer in `slot` applied by `apply`.
158 pub fn new<F>(slot: LayerSlot, name: &'static str, apply: F) -> Self
159 where
160 F: Fn(&AppContext, AppRouter) -> Result<AppRouter, BoxError> + Send + Sync + 'static,
161 {
162 Self {
163 slot,
164 name,
165 apply: Arc::new(apply),
166 }
167 }
168}
169
170impl fmt::Debug for GlobalLayer {
171 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172 f.debug_struct("GlobalLayer")
173 .field("slot", &self.slot)
174 .field("name", &self.name)
175 .finish_non_exhaustive()
176 }
177}
178
179/// HTTP registrations on a [`ModuleBuilder`].
180pub trait ModuleBuilderHttpExt {
181 /// Registers controller `C` as a singleton provider of this module and
182 /// mounts its routes.
183 fn controller<C: Controller + Injectable>(&mut self) -> &mut Self;
184
185 /// Adds app-wide middleware in a [`LayerSlot`].
186 fn http_layer(&mut self, layer: GlobalLayer) -> &mut Self;
187
188 /// Maps errors of type `E` found in a 500 [`AppError`]'s source chain to
189 /// a specific error (e.g. a database "record not found" to 404).
190 fn map_error<E: StdError + 'static>(&mut self, f: fn(&E) -> Option<AppError>) -> &mut Self;
191
192 /// Lets `pages` answer errors in another form than JSON: a page for a
193 /// browser, say. The app uses the first one contributed.
194 fn error_pages(&mut self, pages: impl crate::ErrorPages) -> &mut Self;
195}
196
197impl ModuleBuilderHttpExt for ModuleBuilder {
198 fn controller<C: Controller + Injectable>(&mut self) -> &mut Self {
199 let registration = ControllerRegistration::of::<C>(self.module_id());
200 self.provider::<C>().contribute(registration)
201 }
202
203 fn http_layer(&mut self, layer: GlobalLayer) -> &mut Self {
204 self.contribute(layer)
205 }
206
207 fn map_error<E: StdError + 'static>(&mut self, f: fn(&E) -> Option<AppError>) -> &mut Self {
208 self.contribute(ErrorMapper::new(f))
209 }
210
211 fn error_pages(&mut self, pages: impl crate::ErrorPages) -> &mut Self {
212 self.contribute(crate::ErrorPagesHandle::new(pages))
213 }
214}