Expand description
§navree-http
HttpModule: Navree’s router and extractors, the default Tower layer
stack, JSON errors, controllers and route metadata.
Items hidden from this documentation are not public API: Navree’s own macros and crates use them, and they can change in any release.
- Modules contribute routes with
Controllers (ModuleBuilderHttpExt::controller); eachRouteDefcarries aRouteMetawith its access declaration, guards, throttle, timeout, body limit, audit action and OpenAPI metadata. Deny by default: a route withoutpublic,authenticated,roles,permissionsorcanfails the boot. - Modules serve any tower service under a path prefix with a
Mount(ModuleBuilderMountExt::mount), behind the same pipeline and access check as a route, and put a tower layer whose service can fail on the app withFallibleLayer. - Routes are matched by Navree’s
routing::Router: no path normalization (dot segments and backslashes are refused), strict percent-decoding of parameters, static before parameter before catch-all,HEAD,OPTIONSand 405 withAllow. Handlers are async functions whose arguments areextractors (Path,Query,Json,Form,Multipart,Extension,Scoped, …).wsturns a request into a WebSocket. - Responses are anything
IntoResponse(withHtml,Redirectand server-sent events), bodies are a boxedBodythat streams, andmiddlewareturns an async function into a Tower layer. build_routerassembles the app as anAppRouter, whichGlobalLayers wrap. Request pipeline, outermost first:LayerSlot::Edge(protocols that share the port but not the pipeline, such as gRPC) → request id → tracing and request log → CORS → panic catcher → timeout → security headers → compression (not fortext/event-stream) → error rendering → maintenance mode → per-IP rate limit → body limit →LayerSlot::Session→LayerSlot::AuthContext(the registeredAuthenticatorruns first) →LayerSlot::Uow→LayerSlot::Context→ router → per-route: authentication → per-user throttle →Guards →RouteAuthorizer→ route timeout → handler → audit action.serve()runs an app on a listener: HTTP/1 and HTTP/2 on hyper, with graceful shutdown and the limits ofServerOptions, so a client cannot hold a connection without finishing a request.listis the one query-string grammar of lists: filters with operators, sort, search, numbered and cursor pages, read strictly against an allow-list per resource by thelist::Listextractor.- Every error is an
AppErrorrendered in one JSON shape, asapplication/json:{"statusCode": 404, "message": "Not Found", "error": "Not Found", "code": "not_found"};codeis one of the stablecodes(or an app’s own) for front ends to translate, and validation errors are 400s whosemessagelists every field message and whoseerrorsmaps fields to their messages. This covers panics ("Internal server error", nothing leaked), timeouts, 404s and 405s, and extractor rejections (a body of the wrong shape is a 400), and every response carriesX-Request-Idand, for allowed origins, the CORS headers.
use std::sync::Arc;
use http::Method;
use navree_http::{Controller, Json, ModuleBuilderHttpExt, Path, RouteDef};
use navree_kernel::{BoxFuture, Injectable, KernelError, Module, ModuleBuilder, Resolver};
struct HelloController;
impl Injectable for HelloController {
fn construct(_r: Resolver) -> BoxFuture<'static, Result<Self, KernelError>> {
Box::pin(async { Ok(HelloController) })
}
}
impl Controller for HelloController {
fn prefix(&self) -> &'static str {
"/hello"
}
fn version(&self) -> Option<&'static str> {
Some("1")
}
fn routes(self: Arc<Self>) -> Vec<RouteDef> {
vec![
// GET /api/v1/hello/{name}
RouteDef::on(Method::GET, "/{name}", |Path(name): Path<String>| async move {
Json(serde_json::json!({ "hello": name }))
})
.public(),
]
}
}
struct HelloModule;
impl Module for HelloModule {
fn register(&self, m: &mut ModuleBuilder) {
m.controller::<HelloController>();
}
}Re-exports§
pub use extract::ClientIp;pub use extract::Extension;pub use extract::Form;pub use extract::Json;pub use extract::Multipart;pub use extract::MultipartLimits;pub use extract::Path;pub use extract::Query;pub use extract::RawQuery;pub use extract::Scoped;pub use handler::Handler;pub use response::Created;pub use response::IntoResponse;pub use response::NoContent;pub use response::Response;pub use routing::PathParams;pub use serve::serve;
Modules§
- body
- Request and response bodies:
Body,Bytes,to_bytes, and the request body limit (BodyLimit). - codes
- The framework’s stable error codes: the
codemember of the JSON error body. - csrf
- The names CSRF protection goes by, in one place: the session layer
(navree-session) sets and checks the token under them, and pages and
forms (navree-ui) carry it under them, so the two cannot drift apart. The
same goes for the token’s masked form: a page writes the token masked afresh
in every response (
page_token), and the check takes the token or a mask of it (token_matches). - extract
- Extractors: how a handler’s arguments are read from the request.
- handler
Handler: async functions as route endpoints, andEndpoint, a handler ready to mount.- list
- List queries: the one grammar every Navree list speaks.
- middleware
- Middleware from an async function:
from_fn,from_fn_with_stateandNext, the rest of the stack. - response
- Responses:
IntoResponse,Responseand the shapes handlers return most (Json,Created,NoContent,Html,Redirect,AppError, server-sent events insse). - routing
- Navree’s router: route patterns, matching, method dispatch and path parameters.
- serve
serve(): an app on aListener, over HTTP/1 and HTTP/2 on hyper, with graceful shutdown and the limits ofServerOptions.- ws
- WebSockets: the upgrade handshake, here, and frames on
tokio-tungstenite.
Structs§
- Access
Spec - Who may call a route. A route must declare at least one of these.
- ApiMeta
- OpenAPI metadata of a route (read by navree-api).
- AppError
- An HTTP error. Handlers, extractors, guards and layers return it; it
renders in Navree’s JSON error shape, as
application/json: - AppRouter
- The app as one
tower::Service:routing::Routeror any other service, wrapped in layers. - CanSpec
- An ability check:
actiononsubject, optionally on the record whose id is the path parameterfrom. - Compression
- The service
CompressionLayermakes. - Compression
Layer - A Tower layer that gzips responses for clients that accept it.
- Cors
- The service
CorsLayermakes. - Cors
Layer - A Tower layer that applies CORS rules. See the module documentation.
- Cors
Options - Cross-origin resource sharing: only the listed origins, with credentials,
and explicitly listed request and exposed headers (no wildcards). Applied
by
CorsLayer; an origin that is not listed gets no CORS headers. - Current
Principal - The authenticated principal of the request; 401 for guests.
- Error
Context - What the pipeline knows about the request that ended in an error.
- Error
Mapper - Maps errors of one type (anywhere in an
AppError’s source chain) to a specificAppError. Contributed withModuleBuilderHttpExt::map_error. - Error
Options - How error bodies are rendered (configuration section
http.errors). - Error
Pages Handle - An
ErrorPagesas a module contributes it. - Fallible
Layer - A tower layer whose service can fail, made into one the app can mount
(
AppRouter::layer,Endpoint::layer,Router::route_layer): the service’s error becomes a 500AppErrorwith the error as its source, so the app’s error mapping (m.map_error) and JSON error shape apply; its response body is taken as the app’s body. - Fallible
Service - What
FallibleLayermakes: a service withError = InfallibleandResponse = navree_http::response::Response. An error of the wrapped service, at its readiness or its call, answers asAppError::internalof that error. - Global
Layer - App-wide middleware contributed by a module with
ModuleBuilderHttpExt::http_layer.applywraps the router (router.layer(...)); layers in the same slot run in module dependency order (the first registered is outermost).applymay run more than once per app, so it should not have side effects, and it must only add layers: the router already has navree’s single 404 fallback. - Http
Module - The HTTP module: the server, default layer stack, JSON errors,
controllers. Global; provides and exports
HttpOptions,HttpServerandUrlSigner; registers the commandsserve,routes,downandup; and checks every route and every mount at boot (access declarations, duplicate routes, a mount’s prefix and what it overlaps, missing authenticator or authorizer), beforeservebinds a port. - Http
Options - HTTP server settings (configuration section
http; every key optional). - Http
Server - The HTTP server state shared by the commands and the pipeline: options,
maintenance mode and the address
serveis bound to. - Keyed
Rate Limiter - Allows
limitrequests perperand key, as a burst, refilling one request everyper / limit(generic cell rate algorithm: one timestamp per key). The keys are sharded, so concurrent requests from different keys rarely wait for each other. - Limited
- A refused request.
- Maintenance
Info - The contents of the maintenance file (written by the
downcommand). - Maintenance
Mode - Maintenance-mode state backed by a file, so
downin one process takes effect in a running server within a second. - Memory
Rate Limit Store - A
RateLimitStorein this process’s memory: the limits of every app it is registered in are counted together. For tests, and for several apps in one process. - Mount
- Any tower service under a path prefix, inside the app’s pipeline.
- Route
Def - One route: a method, a path, a
Handlerand its metadata. - Route
Errors - Every route problem found while building the router.
- Route
Meta - Everything known about a route besides its handler. The pipeline inserts
the matched route’s
Arc<RouteMeta>into the request and response extensions. - Server
Options - The limits on connections, enforced by
serveon every listener (configuration sectionhttp.server; every key optional). They bound what a client can hold without finishing anything, and the defaults are meant for production. - Throttle
- A rate limit:
limitrequests perper. - UrlSigner
- Signs URLs with HMAC-SHA256 so links (email verification, downloads) can
be trusted without a session. The signature covers the path, the query
and an
expirestimestamp. - Valid
Signature - A
Guardthat rejects requests without a valid, unexpired URL signature (401). Uses the app’sUrlSigneranddyn Clockwhen one is registered.
Enums§
- Layer
Slot - Where a
GlobalLayersits in the request pipeline, outermost first: the edge, then the session layer, then authentication context, then the unit of work, then the request context. Every slot butEdgeruns after the fixed layers (request id, tracing, CORS, panic catcher, timeout, security headers, compression, maintenance mode, per-IP rate limit, body limit) and before routing. - Preference
- What a client asked for in
Accept. - Route
Kind - How a route’s errors are shown (see
RouteDef::page).
Constants§
- DEFAULT_
IPV6_ PREFIX - The default IPv6 prefix length of a rate-limit key: a /64.
- ERROR_
CONTENT_ TYPE - The content type of every error response.
Traits§
- Authenticator
- Establishes who is making a request (implemented by navree-auth; fakes in
tests). Registered as
dyn Authenticatorand resolved withAppContext::try_get. - Controller
- A group of routes sharing a prefix and an API version (what
#[controller("/deals", version = "1")]implements). Controllers are singletons registered withModuleBuilderHttpExt::controller; handlers captureArc<Self>. - Error
Pages - Answers errors in another form than JSON.
- Guard
- A custom per-route check, run after authentication and throttling and before authorization and the handler. A guard alone is not an access declaration.
- Module
Builder Http Ext - HTTP registrations on a
ModuleBuilder. - Module
Builder Mount Ext - Mounting tower services on a
ModuleBuilder. - Rate
Limit Store - Where the per-IP limit and route throttles count their requests, when every process of the app must count them together: behind a load balancer N servers that each count on their own allow N times the limit.
- Request
Workspace - The workspace a request is in, as the app’s workspace module resolves it
(navree-workspace registers it as the
dyn RequestWorkspaceprovider). - Route
Authorizer - Checks a route’s roles, permissions and abilities (implemented by
navree-access). Registered as
dyn RouteAuthorizerand resolved withAppContext::try_get.
Functions§
- build_
router - Builds the app’s full router: every controller route and every
Mounton Navree’sRouterbehind its per-route pipeline, the single 404, the contributedGlobalLayers and the fixed global layers. Used byserveand by tests. - list_
spec - The list query
Rallows, usable as aListSpecFn(list_spec::<Deals>), so route macros never need navree-api. - may_
compress - Whether
responsemay be compressed at all, by this layer or by another compressor of the app (the UI toolkit’s brotli for pages and ops): not when its route opted out withno_compression, and not when it hasCache-Control: no-transform(in any case).http.compression = falseturns every compressor off as well; that is the app’s setting (HttpOptions::compression), not the response’s, so it is not read here. - preference
- What the
Acceptheader ofheadersprefers. - rate_
limit_ key - The key
ipis counted under: the address itself for IPv4 (and for IPv4-mapped IPv6 addresses, which are IPv4 clients behind a dual-stack socket), else the address with every bit after the firstipv6_prefixcleared, so the addresses of one network share one budget. A prefix of 0 is read as 1 and one above 128 as 128. - route_
table - Every route of the app with its mounted path and metadata, modules in
dependency order. Used by the
routescommand and navree-api. - schema_
fn - The OpenAPI schema of
Tas(name, JSON schema), usable as aSchemaFn(schema_fn::<CreateDeal>), so route macros never need navree-api.
Type Aliases§
- Apply
Layer - The function that wraps the app router in a
GlobalLayer. - List
Spec Fn - Returns the
ListSpecof a list query; seelist_spec. - Result
- The result type of handlers:
Result<T>fails with anAppError. - Schema
Fn - Returns
(schema name, JSON schema); seeschema_fn. - Store
Verdict - What a
RateLimitStoresays of a request: allowed (Ok), orLimited. The outer error is the store’s own: it could not count.