Skip to main content

Crate navree_http

Crate navree_http 

Source
Expand description

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); each RouteDef carries a RouteMeta with its access declaration, guards, throttle, timeout, body limit, audit action and OpenAPI metadata. Deny by default: a route without public, authenticated, roles, permissions or can fails 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 with FallibleLayer.
  • 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, OPTIONS and 405 with Allow. Handlers are async functions whose arguments are extractors (Path, Query, Json, Form, Multipart, Extension, Scoped, …). ws turns a request into a WebSocket.
  • Responses are anything IntoResponse (with Html, Redirect and server-sent events), bodies are a boxed Body that streams, and middleware turns an async function into a Tower layer.
  • build_router assembles the app as an AppRouter, which GlobalLayers 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 for text/event-stream) → error rendering → maintenance mode → per-IP rate limit → body limit → LayerSlot::Session → LayerSlot::AuthContext (the registered Authenticator runs 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 of ServerOptions, so a client cannot hold a connection without finishing a request.
  • list is 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 the list::List extractor.
  • Every error is an AppError rendered in one JSON shape, as application/json: {"statusCode": 404, "message": "Not Found", "error": "Not Found", "code": "not_found"}; code is one of the stable codes (or an app’s own) for front ends to translate, and validation errors are 400s whose message lists every field message and whose errors maps 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 carries X-Request-Id and, 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 code member 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, and Endpoint, 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_state and Next, the rest of the stack.
response
Responses: IntoResponse, Response and the shapes handlers return most (Json, Created, NoContent, Html, Redirect, AppError, server-sent events in sse).
routing
Navree’s router: route patterns, matching, method dispatch and path parameters.
serve
serve(): an app on a Listener, over HTTP/1 and HTTP/2 on hyper, with graceful shutdown and the limits of ServerOptions.
ws
WebSockets: the upgrade handshake, here, and frames on tokio-tungstenite.

Structs§

AccessSpec
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::Router or any other service, wrapped in layers.
CanSpec
An ability check: action on subject, optionally on the record whose id is the path parameter from.
Compression
The service CompressionLayer makes.
CompressionLayer
A Tower layer that gzips responses for clients that accept it.
Cors
The service CorsLayer makes.
CorsLayer
A Tower layer that applies CORS rules. See the module documentation.
CorsOptions
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.
CurrentPrincipal
The authenticated principal of the request; 401 for guests.
ErrorContext
What the pipeline knows about the request that ended in an error.
ErrorMapper
Maps errors of one type (anywhere in an AppError’s source chain) to a specific AppError. Contributed with ModuleBuilderHttpExt::map_error.
ErrorOptions
How error bodies are rendered (configuration section http.errors).
ErrorPagesHandle
An ErrorPages as a module contributes it.
FallibleLayer
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 500 AppError with 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.
FallibleService
What FallibleLayer makes: a service with Error = Infallible and Response = navree_http::response::Response. An error of the wrapped service, at its readiness or its call, answers as AppError::internal of that error.
GlobalLayer
App-wide middleware contributed by a module with ModuleBuilderHttpExt::http_layer. apply wraps the router (router.layer(...)); layers in the same slot run in module dependency order (the first registered is outermost). apply may 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.
HttpModule
The HTTP module: the server, default layer stack, JSON errors, controllers. Global; provides and exports HttpOptions, HttpServer and UrlSigner; registers the commands serve, routes, down and up; 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), before serve binds a port.
HttpOptions
HTTP server settings (configuration section http; every key optional).
HttpServer
The HTTP server state shared by the commands and the pipeline: options, maintenance mode and the address serve is bound to.
KeyedRateLimiter
Allows limit requests per per and key, as a burst, refilling one request every per / 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.
MaintenanceInfo
The contents of the maintenance file (written by the down command).
MaintenanceMode
Maintenance-mode state backed by a file, so down in one process takes effect in a running server within a second.
MemoryRateLimitStore
A RateLimitStore in 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.
RouteDef
One route: a method, a path, a Handler and its metadata.
RouteErrors
Every route problem found while building the router.
RouteMeta
Everything known about a route besides its handler. The pipeline inserts the matched route’s Arc<RouteMeta> into the request and response extensions.
ServerOptions
The limits on connections, enforced by serve on every listener (configuration section http.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: limit requests per per.
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 expires timestamp.
ValidSignature
A Guard that rejects requests without a valid, unexpired URL signature (401). Uses the app’s UrlSigner and dyn Clock when one is registered.

Enums§

LayerSlot
Where a GlobalLayer sits 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 but Edge runs 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.
RouteKind
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 Authenticator and resolved with AppContext::try_get.
Controller
A group of routes sharing a prefix and an API version (what #[controller("/deals", version = "1")] implements). Controllers are singletons registered with ModuleBuilderHttpExt::controller; handlers capture Arc<Self>.
ErrorPages
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.
ModuleBuilderHttpExt
HTTP registrations on a ModuleBuilder.
ModuleBuilderMountExt
Mounting tower services on a ModuleBuilder.
RateLimitStore
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.
RequestWorkspace
The workspace a request is in, as the app’s workspace module resolves it (navree-workspace registers it as the dyn RequestWorkspace provider).
RouteAuthorizer
Checks a route’s roles, permissions and abilities (implemented by navree-access). Registered as dyn RouteAuthorizer and resolved with AppContext::try_get.

Functions§

build_router
Builds the app’s full router: every controller route and every Mount on Navree’s Router behind its per-route pipeline, the single 404, the contributed GlobalLayers and the fixed global layers. Used by serve and by tests.
list_spec
The list query R allows, usable as a ListSpecFn (list_spec::<Deals>), so route macros never need navree-api.
may_compress
Whether response may 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 with no_compression, and not when it has Cache-Control: no-transform (in any case). http.compression = false turns 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 Accept header of headers prefers.
rate_limit_key
The key ip is 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 first ipv6_prefix cleared, 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 routes command and navree-api.
schema_fn
The OpenAPI schema of T as (name, JSON schema), usable as a SchemaFn (schema_fn::<CreateDeal>), so route macros never need navree-api.

Type Aliases§

ApplyLayer
The function that wraps the app router in a GlobalLayer.
ListSpecFn
Returns the ListSpec of a list query; see list_spec.
Result
The result type of handlers: Result<T> fails with an AppError.
SchemaFn
Returns (schema name, JSON schema); see schema_fn.
StoreVerdict
What a RateLimitStore says of a request: allowed (Ok), or Limited. The outer error is the store’s own: it could not count.