Skip to main content

navree_http/
lib.rs

1//! # navree-http
2//!
3//! `HttpModule`: Navree's router and extractors, the default Tower layer
4//! stack, JSON errors, controllers and route metadata.
5//!
6//! Items hidden from this documentation are not public API: Navree's own
7//! macros and crates use them, and they can change in any release.
8//!
9//! - Modules contribute routes with [`Controller`]s
10//!   ([`ModuleBuilderHttpExt::controller`]); each [`RouteDef`] carries a
11//!   [`RouteMeta`] with its access declaration, guards, throttle, timeout,
12//!   body limit, audit action and OpenAPI metadata. **Deny by default:** a
13//!   route without [`public`](RouteDef::public),
14//!   [`authenticated`](RouteDef::authenticated), [`roles`](RouteDef::roles),
15//!   [`permissions`](RouteDef::permissions) or [`can`](RouteDef::can) fails
16//!   the boot.
17//! - Modules serve any tower service under a path prefix with a [`Mount`]
18//!   ([`ModuleBuilderMountExt::mount`]), behind the same pipeline and access
19//!   check as a route, and put a tower layer whose service can fail on the
20//!   app with [`FallibleLayer`].
21//! - Routes are matched by Navree's [`routing::Router`]: no path
22//!   normalization (dot segments and backslashes are refused), strict
23//!   percent-decoding of parameters, static before parameter before
24//!   catch-all, `HEAD`, `OPTIONS` and 405 with `Allow`. Handlers are async
25//!   functions whose arguments are [`extract`]ors ([`Path`], [`Query`],
26//!   [`Json`], [`Form`], [`Multipart`], [`Extension`], [`Scoped`], ...).
27//!   [`ws`] turns a request into a WebSocket.
28//! - Responses are anything [`IntoResponse`] (with
29//!   [`Html`](response::Html), [`Redirect`](response::Redirect) and
30//!   [server-sent events](response::sse)), bodies are a boxed
31//!   [`Body`](body::Body) that streams, and [`middleware`] turns an async
32//!   function into a Tower layer.
33//! - [`build_router`] assembles the app as an [`AppRouter`], which
34//!   [`GlobalLayer`]s wrap. Request pipeline, outermost first:
35//!   [`LayerSlot::Edge`] (protocols that share the port but not the
36//!   pipeline, such as gRPC) → request id → tracing and request log → CORS
37//!   → panic catcher → timeout →
38//!   security headers → compression (not for `text/event-stream`) →
39//!   error rendering → maintenance mode → per-IP rate limit → body limit →
40//!   [`LayerSlot::Session`] → [`LayerSlot::AuthContext`] (the registered
41//!   [`Authenticator`] runs first) → [`LayerSlot::Uow`] →
42//!   [`LayerSlot::Context`] → router → per-route:
43//!   authentication → per-user throttle → [`Guard`]s → [`RouteAuthorizer`]
44//!   → route timeout → handler → audit action.
45//! - [`serve()`] runs an app on a listener: HTTP/1 and HTTP/2 on hyper, with
46//!   graceful shutdown and the limits of [`ServerOptions`], so a client
47//!   cannot hold a connection without finishing a request.
48//! - [`list`] is the one query-string grammar of lists: filters with
49//!   operators, sort, search, numbered and cursor pages, read strictly
50//!   against an allow-list per resource by the [`list::List`] extractor.
51//! - Every error is an [`AppError`] rendered in one JSON shape, as
52//!   `application/json`: `{"statusCode": 404, "message": "Not Found",
53//!   "error": "Not Found", "code": "not_found"}`; `code` is one of the
54//!   stable [`codes`] (or an app's own) for front ends to translate, and
55//!   validation errors are 400s whose `message` lists every field message
56//!   and whose `errors` maps fields to their messages.
57//!   This covers panics (`"Internal server error"`, nothing leaked),
58//!   timeouts, 404s and 405s, and extractor rejections (a body of the wrong
59//!   shape is a 400), and every response carries `X-Request-Id` and, for
60//!   allowed origins, the CORS headers.
61//!
62//! ```
63//! use std::sync::Arc;
64//!
65//! use http::Method;
66//! use navree_http::{Controller, Json, ModuleBuilderHttpExt, Path, RouteDef};
67//! use navree_kernel::{BoxFuture, Injectable, KernelError, Module, ModuleBuilder, Resolver};
68//!
69//! struct HelloController;
70//!
71//! impl Injectable for HelloController {
72//!     fn construct(_r: Resolver) -> BoxFuture<'static, Result<Self, KernelError>> {
73//!         Box::pin(async { Ok(HelloController) })
74//!     }
75//! }
76//!
77//! impl Controller for HelloController {
78//!     fn prefix(&self) -> &'static str {
79//!         "/hello"
80//!     }
81//!
82//!     fn version(&self) -> Option<&'static str> {
83//!         Some("1")
84//!     }
85//!
86//!     fn routes(self: Arc<Self>) -> Vec<RouteDef> {
87//!         vec![
88//!             // GET /api/v1/hello/{name}
89//!             RouteDef::on(Method::GET, "/{name}", |Path(name): Path<String>| async move {
90//!                 Json(serde_json::json!({ "hello": name }))
91//!             })
92//!             .public(),
93//!         ]
94//!     }
95//! }
96//!
97//! struct HelloModule;
98//!
99//! impl Module for HelloModule {
100//!     fn register(&self, m: &mut ModuleBuilder) {
101//!         m.controller::<HelloController>();
102//!     }
103//! }
104//! ```
105#![forbid(unsafe_code)]
106#![cfg_attr(docsrs, feature(doc_cfg))]
107
108mod app;
109mod auth;
110pub mod body;
111pub mod codes;
112mod compression;
113mod controller;
114mod cors;
115pub mod csrf;
116mod declared;
117mod error;
118mod error_pages;
119pub mod extract;
120mod fallible;
121pub mod handler;
122mod limiter;
123pub mod list;
124mod maintenance;
125pub mod middleware;
126mod module;
127mod mount;
128mod network;
129mod options;
130mod pipeline;
131pub mod response;
132mod route;
133mod router;
134pub mod routing;
135pub mod serve;
136mod signed;
137mod workspace;
138pub mod ws;
139
140pub use app::AppRouter;
141pub use auth::{Authenticator, CurrentPrincipal, Guard, RouteAuthorizer};
142pub use compression::{Compression, CompressionLayer, may_compress};
143pub use controller::{ApplyLayer, Controller, GlobalLayer, LayerSlot, ModuleBuilderHttpExt};
144pub use cors::{Cors, CorsLayer};
145pub use error::{AppError, ERROR_CONTENT_TYPE, ErrorMapper, Result};
146pub use error_pages::{
147    ErrorContext, ErrorPages, ErrorPagesHandle, Preference, RouteKind, preference,
148};
149pub use extract::{
150    ClientIp, Extension, Form, Json, Multipart, MultipartLimits, Path, Query, RawQuery, Scoped,
151};
152pub use fallible::{FallibleLayer, FallibleService};
153pub use handler::Handler;
154pub use limiter::{KeyedRateLimiter, Limited, MemoryRateLimitStore, RateLimitStore, StoreVerdict};
155pub use maintenance::{MaintenanceInfo, MaintenanceMode};
156pub use module::{HttpModule, HttpServer};
157pub use mount::{ModuleBuilderMountExt, Mount};
158pub use network::{DEFAULT_IPV6_PREFIX, rate_limit_key};
159pub use options::{CorsOptions, ErrorOptions, HttpOptions, ServerOptions};
160pub use response::{Created, IntoResponse, NoContent, Response};
161pub use route::{
162    AccessSpec, ApiMeta, CanSpec, ListSpecFn, RouteDef, RouteMeta, SchemaFn, Throttle, list_spec,
163    schema_fn,
164};
165pub use router::{RouteErrors, build_router, route_table};
166pub use routing::PathParams;
167pub use serve::serve;
168pub use signed::{UrlSigner, ValidSignature};
169pub use workspace::RequestWorkspace;
170
171/// Items Navree's own crates use; not public API.
172#[doc(hidden)]
173pub mod __private {
174    pub use crate::declared::{AccessDeclarations, DeclaredAccess, declared_access};
175    pub use crate::error::mappers_of_plugins;
176    pub use crate::router::layers_of_plugins;
177}