Skip to main content

App

Struct App 

Source
pub struct App { /* private fields */ }
Expand description

An HTTP application: routes, state, middleware, lifespan and metadata.

Implementations§

Source§

impl App

Source

pub fn new() -> Self

Create an empty application.

Source

pub fn title(self, title: impl Into<String>) -> Self

Set the API title.

Source

pub fn version(self, version: impl Into<String>) -> Self

Set the API version.

Source

pub fn description(self, description: impl Into<String>) -> Self

Set the API description.

Source

pub fn docs(self, docs: DocsConfig) -> Self

Configure documentation endpoints.

Source

pub fn meta(&self) -> &AppMeta

The application metadata.

Source

pub fn route(self, path: &str, methods: MethodRouter) -> Self

Register methods at path (use {param} for path parameters).

Source

pub fn routes(self, routes: impl IntoIterator<Item = Route>) -> Self

Register routes produced by route macros (see routes![]).

Source

pub fn mount(self, prefix: &str, app: App) -> Self

Mount app under prefix (e.g. /api/v1); / merges its routes into this app. See the module docs.

Source

pub fn nest(self, prefix: &str, app: App) -> Self

Alias of App::mount.

Source

pub fn with_state<T: Send + Sync + 'static>(self, state: T) -> Self

Make state available to handlers through State<T>.

Applies to every route of this app regardless of call order.

Source

pub fn database(self, alias: impl Into<String>, db: Db) -> Self

Register db under alias ("default", "replica", …).

Every registered database is available to handlers as State<Databases>; a router set with App::databases is kept.

Source

pub fn databases(self, databases: Databases) -> Self

Replace the whole database registry (aliases and router).

Source

pub fn database_registry(&self) -> Option<&Databases>

The registered databases, if any.

Source

pub fn openapi(&self) -> Result<OpenApi, OpenApiError>

Generate the OpenAPI 3.1 document for this app and its mounts.

§Errors

Returns OpenApiError on duplicate operations/ids or schema name conflicts.

Source

pub fn into_router_service(self) -> Result<RouterService, ServerError>

Convert into an in-process tower::Service (used by the testkit). Lifespan hooks are not run.

§Errors

Returns ServerError::Configuration if the app is misconfigured.

Source

pub fn into_service_with_lifespan( self, ) -> Result<(RouterService, Lifespan), ServerError>

Like App::into_router_service, but also returns the Lifespan so the caller can run startup and shutdown hooks around the service without binding a socket (used by the testkit).

§Errors

Returns ServerError::Configuration if the app is misconfigured.

Source

pub async fn run(self, addr: &str) -> Result<(), ServerError>

Serve until Ctrl-C or Unix SIGTERM, then drain and clean up resources.

Args: addr: Address to bind.

Returns: Success after shutdown and resource cleanup.

§Errors

Configuration, startup, bind, serving or shutdown errors.

Source

pub async fn run_until<F>( self, addr: &str, shutdown: F, ) -> Result<(), ServerError>
where F: Future<Output = ()> + Send + 'static,

Serve until a caller-supplied shutdown future completes.

Startup cancellation and bind failure clean initialized resources. HTTP draining and teardown share one deadline. Connection, stream and WebSocket workers are cancelled before resource teardown.

Args: addr: Address to bind. shutdown: Future requesting graceful termination.

Returns: Success after serving and cleanup finish.

§Errors

Configuration/startup/I/O errors or exceeded shutdown deadline.

Source§

impl App

Source

pub fn background_tasks(self, limits: BackgroundTaskLimits) -> Self

Configure admission and execution limits for this app’s task queue.

Args: limits: Positive limits within Tokio semaphore capacity.

Returns: Configured app; invalid limits become a configuration error.

Source§

impl App

Source

pub fn provide<T: Send + Sync + 'static>(self, value: T) -> Self

Share value with every request of this app (and its mounts). See the module docs.

Source

pub fn provide_arc<T: Send + Sync + 'static>(self, value: Arc<T>) -> Self

Like App::provide for a value that is already shared, so the caller can keep a handle to it.

Source

pub fn override_dependency<T, F, Fut>(self, f: F) -> Self
where T: Dependency, F: Fn(RequestHead) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<T, ApiError>> + Send + 'static,

Replace T::resolve with f (also for nested resolution). f gets an owned RequestHead because a borrowed request cannot cross the returned future.

Source

pub fn override_value<T: Dependency + Clone>(self, value: T) -> Self

Replace T::resolve with a clone of value.

Source

pub fn dependency<T: Dependency>(self) -> Self

Resolve T before every routed request; its error short-circuits. The value stays cached, so handlers asking for Depends<T> reuse it.

Source§

impl App

Source

pub fn shutdown_timeout(self, budget: Duration) -> Self

Set the total graceful-shutdown budget, including resource teardown.

Args: budget: Positive, representable duration (default: 30 seconds).

Returns: The configured application; invalid budgets fail validation.

Source

pub fn on_startup<F, Fut>(self, hook: F) -> Self
where F: FnOnce() -> Fut + Send + 'static, Fut: Future<Output = Result<(), ApiError>> + Send + 'static,

Run hook at startup (before the socket is bound).

Source

pub fn on_shutdown<F, Fut>(self, hook: F) -> Self
where F: FnOnce() -> Fut + Send + 'static, Fut: Future<Output = Result<(), ApiError>> + Send + 'static,

Run hook at shutdown (hooks run in reverse registration order).

Source

pub fn lifespan_resource<T, F, Fut, C>(self, init: F) -> Self
where T: Send + Sync + 'static, F: FnOnce() -> Fut + Send + 'static, Fut: Future<Output = Result<(T, C), ApiError>> + Send + 'static, C: Future<Output = Result<(), ApiError>> + Send + 'static,

Create a resource at startup and tear it down at shutdown.

init returns the value and a teardown future (which may capture clones of whatever it needs to close). Handlers receive the value via Resource<T>. Resources are torn down in reverse registration order.

Source§

impl App

Source

pub fn layer<L>(self, layer: L) -> Self
where L: Layer<BoxService> + Clone + Send + Sync + 'static, L::Service: Service<Request, Response = Response, Error = Infallible> + Clone + Send + Sync + 'static, <L::Service as Service<Request>>::Future: Send + 'static,

Wrap the application in layer. See the module docs for the ordering rules.

Source

pub fn cors(self, cors: Cors) -> Self

Add Cors middleware.

Source

pub fn compression(self, compression: Compression) -> Self

Add Compression middleware.

Source

pub fn csrf_origin(self, csrf: CsrfOrigin) -> Self

Add CsrfOrigin middleware.

Source

pub fn trusted_hosts(self, hosts: TrustedHosts) -> Self

Add TrustedHosts middleware.

Source

pub fn https_redirect(self, redirect: HttpsRedirect) -> Self

Add HttpsRedirect middleware.

Source

pub fn request_id(self) -> Self

Add request-id middleware with default settings.

Source

pub fn request_logging(self) -> Self

Add RequestLogging middleware.

Source

pub fn timeout(self, limit: Duration) -> Self

Add a Timeout (504 by default).

Source

pub fn concurrency_limit(self, max: usize) -> Self

Source

pub fn body_limit(self, max_bytes: usize) -> Self

Add a BodyLimit of max_bytes.

Source

pub fn rate_limit(self, limit: RateLimit) -> Self

Add a RateLimit.

Source§

impl App

Source

pub fn server_limits(self, limits: ServerLimits) -> Self

Configure bounded transport admission before binding the server.

Args: limits: Accepted socket and per-connection HTTP/2 limits.

Returns: This application; invalid bounds become configuration errors.

Source§

impl App

Source

pub fn static_files(self, prefix: &str, dir: impl Into<PathBuf>) -> Self

Serve files from dir under URL prefix (for example /assets).

The mount is not documented in OpenAPI. Path traversal (.. segments) is rejected by tower-http’s ServeDir. A root prefix (/ or empty) serves dir as the fallback for every path no route matches.

Source

pub fn spa(self, prefix: &str, dir: impl Into<PathBuf>) -> Self

Serve a single-page application from dir under prefix (/ for the whole site): files as they are, and dir/index.html for browser navigations to any other path below prefix, so client side routes (/app/settings) load the app.

Explicit routes still win. The fallback applies only to GET and HEAD requests accepting text/html whose last path segment has no extension; a missing asset, an API-style request or a missing index.html answer with the 404 problem document, and other methods with 405. Paths are resolved inside the canonical dir (no .., encoded or not, and no symbolic link leading out). The mount is not documented in OpenAPI.

Trait Implementations§

Source§

impl Debug for App

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for App

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for App

§

impl !Sync for App

§

impl !UnwindSafe for App

§

impl Freeze for App

§

impl Send for App

§

impl Unpin for App

§

impl UnsafeUnpin for App

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
§

impl<T> ServiceExt for T

§

fn compression(self) -> Compression<Self>
where Self: Sized,

Compresses response bodies. Read more
§

fn trace_for_http(self) -> Trace<Self, SharedClassifier<ServerErrorsAsFailures>>
where Self: Sized,

High level tracing that classifies responses using HTTP status codes. Read more
§

fn trace_for_grpc(self) -> Trace<Self, SharedClassifier<GrpcErrorsAsFailures>>
where Self: Sized,

High level tracing that classifies responses using gRPC headers. Read more
§

fn override_request_header<M>( self, header_name: HeaderName, make: M, ) -> SetRequestHeader<Self, M>
where Self: Sized,

Insert a header into the request. Read more
§

fn append_request_header<M>( self, header_name: HeaderName, make: M, ) -> SetRequestHeader<Self, M>
where Self: Sized,

Append a header into the request. Read more
§

fn insert_request_header_if_not_present<M>( self, header_name: HeaderName, make: M, ) -> SetRequestHeader<Self, M>
where Self: Sized,

Insert a header into the request, if the header is not already present. Read more
§

fn override_response_header<M>( self, header_name: HeaderName, make: M, ) -> SetResponseHeader<Self, M>
where Self: Sized,

Insert a header into the response. Read more
§

fn append_response_header<M>( self, header_name: HeaderName, make: M, ) -> SetResponseHeader<Self, M>
where Self: Sized,

Append a header into the response. Read more
§

fn insert_response_header_if_not_present<M>( self, header_name: HeaderName, make: M, ) -> SetResponseHeader<Self, M>
where Self: Sized,

Insert a header into the response, if the header is not already present. Read more
§

fn set_request_id<M>( self, header_name: HeaderName, make_request_id: M, ) -> SetRequestId<Self, M>
where Self: Sized, M: MakeRequestId,

Add request id header and extension. Read more
§

fn set_x_request_id<M>(self, make_request_id: M) -> SetRequestId<Self, M>
where Self: Sized, M: MakeRequestId,

Add request id header and extension, using x-request-id as the header name. Read more
§

fn propagate_request_id( self, header_name: HeaderName, ) -> PropagateRequestId<Self>
where Self: Sized,

Propgate request ids from requests to responses. Read more
§

fn propagate_x_request_id(self) -> PropagateRequestId<Self>
where Self: Sized,

Propgate request ids from requests to responses, using x-request-id as the header name. Read more
§

fn request_body_limit(self, limit: usize) -> RequestBodyLimit<Self>
where Self: Sized,

Intercept requests with over-sized payloads and convert them into 413 Payload Too Large responses. Read more
§

fn trim_trailing_slash(self) -> NormalizePath<Self>
where Self: Sized,

Remove trailing slashes from paths. Read more
§

fn append_trailing_slash(self) -> NormalizePath<Self>
where Self: Sized,

Append trailing slash to paths. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more