pub struct App { /* private fields */ }Expand description
The application builder.
App collects application state, routers, and optional OpenAPI configuration,
then either finalizes into an AppInner via App::build or starts
serving via App::serve.
App is deliberately not generic over its state type: state is stored in a
type-erased StateMap, which is what lets router modules be defined without
any knowledge of the concrete state type.
Implementations§
Source§impl App
impl App
Sourcepub fn state<S: Send + Sync + 'static>(self, state: S) -> Self
pub fn state<S: Send + Sync + 'static>(self, state: S) -> Self
Registers an application state value, retrievable via the
State extractor.
Sourcepub fn logger(self, config: LoggerConfig) -> Self
pub fn logger(self, config: LoggerConfig) -> Self
Configures logging. Without this, logging is on by default with sensible
settings (a developer console on a terminal, JSON otherwise; level from
RUST_LOG or info).
Sourcepub fn cache(self, cache: Cache) -> Self
pub fn cache(self, cache: Cache) -> Self
Enables caching, making the Cache injectable into handlers
and services.
Pass a configured cache, for example Cache::in_memory() for the default
in-memory store. Without this call, injecting a Cache fails.
Sourcepub fn throttle(self, throttle: Throttle) -> Self
pub fn throttle(self, throttle: Throttle) -> Self
Enables rate limiting, defining the policies routes can apply with the
throttle attribute and (optionally) a global default.
App::new().throttle(
Throttle::new()
.policy("default", 100, 60)
.policy("strict", 5, 60)
.default("default"),
);Sourcepub fn include_router(self, router: Router) -> Self
pub fn include_router(self, router: Router) -> Self
Mounts a router’s routes on the application.
Sourcepub fn include(self, route: impl FnOnce() -> Route) -> Self
pub fn include(self, route: impl FnOnce() -> Route) -> Self
Mounts a single route, given the route factory generated for a handler.
A #[get] / #[post] / #[sse] / #[websocket] handler named handler
generates a handler() route factory, so App::new().include(handler)
registers it directly without building a Router.
Sourcepub fn openapi<P: OpenApiProvider>(self, provider: P) -> Self
pub fn openapi<P: OpenApiProvider>(self, provider: P) -> Self
Configures OpenAPI document generation and the documentation UI.
Sourcepub fn asyncapi<P: AsyncApiProvider>(self, provider: P) -> Self
pub fn asyncapi<P: AsyncApiProvider>(self, provider: P) -> Self
Configures AsyncAPI document generation for the SSE/WebSocket channels.
Sourcepub fn middleware<M: Middleware>(self, middleware: M) -> Self
pub fn middleware<M: Middleware>(self, middleware: M) -> Self
Registers a middleware layer.
Layers run in registration order, outermost first. Some middlewares may
only be registered once; see DuplicatePolicy.
Sourcepub fn lifespan<L: Lifespan>(self) -> Self
pub fn lifespan<L: Lifespan>(self) -> Self
Registers a lifespan: a resource container with typed startup/shutdown.
Lifespans start in registration order and stop in reverse order. Their
resources are registered for injection. Using a lifespan together with
on_startup or on_shutdown is a
configuration error.
Sourcepub fn on_startup<F, Fut>(self, hook: F) -> Self
pub fn on_startup<F, Fut>(self, hook: F) -> Self
Registers a startup hook (for apps that do not use a lifespan).
Sourcepub fn on_shutdown<F, Fut>(self, hook: F) -> Self
pub fn on_shutdown<F, Fut>(self, hook: F) -> Self
Registers a shutdown hook (for apps that do not use a lifespan).
Sourcepub fn on_ready<F, Fut>(self, hook: F) -> Self
pub fn on_ready<F, Fut>(self, hook: F) -> Self
Registers a hook that runs once the listener has bound.
Allowed in both lifespan and event-hook modes.
Sourcepub fn on_request<F, Fut>(self, hook: F) -> Self
pub fn on_request<F, Fut>(self, hook: F) -> Self
Registers an observe-only hook that runs when a request arrives.
Hooks run in registration order, before the middleware chain, and cannot alter the response. Use them for logging, metrics, or tracing.
Sourcepub fn on_response<F, Fut>(self, hook: F) -> Self
pub fn on_response<F, Fut>(self, hook: F) -> Self
Registers an observe-only hook that runs once a response is ready.
Hooks run in registration order, after the middleware chain, and observe the final status and elapsed time.
Sourcepub fn on_error<F, Fut>(self, hook: F) -> Self
pub fn on_error<F, Fut>(self, hook: F) -> Self
Registers an observe-only hook that runs for a non-validation error.
Validation failures (422) go to on_validation_error
instead; every other error fires this hook.
Sourcepub fn on_validation_error<F, Fut>(self, hook: F) -> Self
pub fn on_validation_error<F, Fut>(self, hook: F) -> Self
Registers an observe-only hook that runs for a request-body validation
failure (422).
Sourcepub fn on_panic<F, Fut>(self, hook: F) -> Self
pub fn on_panic<F, Fut>(self, hook: F) -> Self
Registers an observe-only hook that runs when a handler panic is caught.
Has no effect unless the panic boundary is enabled with
catch_panics.
Sourcepub fn websocket_config(self, config: WebSocketConfig) -> Self
pub fn websocket_config(self, config: WebSocketConfig) -> Self
Sets default WebSocket limits and timeouts for every #[websocket] route.
A route’s own #[websocket(...)] limits override these defaults.
Sourcepub fn max_sse_connections(self, limit: usize) -> Self
pub fn max_sse_connections(self, limit: usize) -> Self
Caps the number of concurrent Server-Sent Events streams the app will serve.
Each SSE connection holds a pinned stream and timers for its whole lifetime
(often hours), so an unbounded count can exhaust memory. Once the cap is
reached, further #[sse] requests are rejected with 503 Service Unavailable until a stream ends. With no cap set, SSE streams are unbounded.
Sourcepub fn idle_timeout(self, timeout: Duration) -> Self
pub fn idle_timeout(self, timeout: Duration) -> Self
Closes a connection after this long with no read or write activity.
Bounds slow or abandoned connections (and zombie keep-alive sockets). It is off by default, because a legitimately idle long-lived connection — an open WebSocket or a quiet Server-Sent Events stream — is normal; enable it only when your routes do not rely on long-lived idle connections, or set it comfortably above your SSE heartbeat interval.
Sourcepub fn reuse_port(self, enabled: bool) -> Self
pub fn reuse_port(self, enabled: bool) -> Self
Binds the listening socket with SO_REUSEPORT (Unix), so several processes
or instances can listen on the same address and the kernel load-balances new
connections across them.
Has no effect on non-Unix platforms. Off by default.
Sourcepub fn max_request_body_size(self, bytes: usize) -> Self
pub fn max_request_body_size(self, bytes: usize) -> Self
Sets the maximum size, in bytes, of a buffered request body.
Applies to the JSON, Valid<T>, and urlencoded Form<T> body extractors,
which enforce the cap incrementally as the body arrives (an oversized body is
rejected with 400 before it is fully buffered). Multipart uploads have their
own UploadConfig limits. Defaults to
MAX_BODY_BYTES (2 MiB).
Sourcepub fn header_read_timeout(self, timeout: Duration) -> Self
pub fn header_read_timeout(self, timeout: Duration) -> Self
Sets how long a client may take to send the complete request head (request line + headers) after its connection is accepted.
This bounds slowloris-style attacks where a client opens a connection and
dribbles header bytes to tie up a worker. Defaults to
DEFAULT_HEADER_READ_TIMEOUT
(30s); pass a longer duration to relax it. Applies to HTTP/1 connections.
Sourcepub fn without_header_read_timeout(self) -> Self
pub fn without_header_read_timeout(self) -> Self
Removes the request-head read deadline, letting a client take unlimited time to send its headers. Only do this behind a trusted proxy that already bounds slow clients.
Sourcepub fn http1(self, config: Http1Config) -> Self
pub fn http1(self, config: Http1Config) -> Self
Tunes HTTP/1 behavior (keep-alive, header count) for every connection.
Sourcepub fn http2(self, config: Http2Config) -> Self
pub fn http2(self, config: Http2Config) -> Self
Tunes HTTP/2 behavior (stream limits, keep-alive, flow control) for every connection. HTTP/2 is served automatically over a plaintext upgrade or over TLS via ALPN.
Sourcepub fn on_ws_connect<F, Fut>(self, hook: F) -> Self
pub fn on_ws_connect<F, Fut>(self, hook: F) -> Self
Registers an observe-only hook that runs when a WebSocket opens.
Sourcepub fn on_ws_disconnect<F, Fut>(self, hook: F) -> Self
pub fn on_ws_disconnect<F, Fut>(self, hook: F) -> Self
Registers an observe-only hook that runs when a WebSocket closes.
The event carries how long the connection was open and the close code.
Sourcepub fn upload_config(self, config: UploadConfig) -> Self
pub fn upload_config(self, config: UploadConfig) -> Self
Sets default multipart upload limits for every form/file route.
A route’s own #[post("/p", upload(...))] limits override these defaults.
Sourcepub fn catch_panics(self) -> Self
pub fn catch_panics(self) -> Self
Enables the panic boundary: a panic in a handler is caught and turned into
a 500 response instead of dropping the connection.
Enabled by default. A caught panic fires the on_panic
hooks. The boundary has no effect when the process is built with
panic = "abort".
Sourcepub fn propagate_panics(self) -> Self
pub fn propagate_panics(self) -> Self
Disables the panic boundary: handler panics propagate and tear down the
request task instead of becoming a 500 response.
Sourcepub fn exception_handler<E, F, Fut>(self, handler: F) -> Self
pub fn exception_handler<E, F, Fut>(self, handler: F) -> Self
Registers a handler that maps a typed error E into a response.
When an error carries a source of type E (for example one produced by a
#[derive(AppError)] type via ?), the registered handler receives the
recovered value and produces the response. Registering a handler for a type
again replaces the previous one.
Sourcepub async fn serve(self, addr: impl AsRef<str>) -> Result<()>
pub async fn serve(self, addr: impl AsRef<str>) -> Result<()>
Runs the application lifecycle and serves on addr until a shutdown signal.
Listens for SIGINT (Ctrl-C) and, on Unix, SIGTERM. The lifecycle runs
in order: startup (lifespans or on_startup hooks), bind, on_ready
hooks, the accept loop, drain, then shutdown (lifespans in reverse, or
on_shutdown hooks).
§Errors
Returns an error for a lifecycle misconfiguration, a failed startup, or a bind failure.
Sourcepub async fn serve_with_shutdown<S>(
self,
addr: impl AsRef<str>,
shutdown: S,
) -> Result<()>
pub async fn serve_with_shutdown<S>( self, addr: impl AsRef<str>, shutdown: S, ) -> Result<()>
Runs the lifecycle, stopping the accept loop when shutdown resolves.
Like serve but driven by a caller-supplied future instead
of SIGINT/SIGTERM, for custom graceful shutdown (and for tests).
Sourcepub async fn serve_unix(self, path: impl AsRef<Path>) -> Result<()>
pub async fn serve_unix(self, path: impl AsRef<Path>) -> Result<()>
Serves over a Unix-domain socket at path, until a SIGINT/SIGTERM.
Useful behind a reverse proxy on the same host. A stale socket file at
path is removed before binding. Unix only.
Sourcepub async fn serve_unix_with_shutdown<S>(
self,
path: impl AsRef<Path>,
shutdown: S,
) -> Result<()>
pub async fn serve_unix_with_shutdown<S>( self, path: impl AsRef<Path>, shutdown: S, ) -> Result<()>
Serves over a Unix-domain socket at path, stopping when shutdown
resolves. Unix only.
Sourcepub async fn build_test(self) -> Result<TestApp>
pub async fn build_test(self) -> Result<TestApp>
Builds the application for in-process testing.
Runs the startup phase (lifespans or on_startup hooks) and finalizes the
app without binding a socket, returning a TestApp that the
TestClient drives. The on_ready hooks are
not run, since there is no bound address.
Trait Implementations§
Auto Trait Implementations§
impl !RefUnwindSafe for App
impl !UnwindSafe for App
impl Freeze for App
impl Send for App
impl Sync for App
impl Unpin for App
impl UnsafeUnpin for App
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> Paint for Twhere
T: ?Sized,
impl<T> Paint for Twhere
T: ?Sized,
Source§fn fg(&self, value: Color) -> Painted<&T>
fn fg(&self, value: Color) -> Painted<&T>
Returns a styled value derived from self with the foreground set to
value.
This method should be used rarely. Instead, prefer to use color-specific
builder methods like red() and
green(), which have the same functionality but are
pithier.
§Example
Set foreground color to white using fg():
use yansi::{Paint, Color};
painted.fg(Color::White);Set foreground color to white using white().
use yansi::Paint;
painted.white();Source§fn bright_black(&self) -> Painted<&T>
fn bright_black(&self) -> Painted<&T>
Source§fn bright_red(&self) -> Painted<&T>
fn bright_red(&self) -> Painted<&T>
Source§fn bright_green(&self) -> Painted<&T>
fn bright_green(&self) -> Painted<&T>
Source§fn bright_yellow(&self) -> Painted<&T>
fn bright_yellow(&self) -> Painted<&T>
Source§fn bright_blue(&self) -> Painted<&T>
fn bright_blue(&self) -> Painted<&T>
Source§fn bright_magenta(&self) -> Painted<&T>
fn bright_magenta(&self) -> Painted<&T>
Source§fn bright_cyan(&self) -> Painted<&T>
fn bright_cyan(&self) -> Painted<&T>
Source§fn bright_white(&self) -> Painted<&T>
fn bright_white(&self) -> Painted<&T>
Source§fn bg(&self, value: Color) -> Painted<&T>
fn bg(&self, value: Color) -> Painted<&T>
Returns a styled value derived from self with the background set to
value.
This method should be used rarely. Instead, prefer to use color-specific
builder methods like on_red() and
on_green(), which have the same functionality but
are pithier.
§Example
Set background color to red using fg():
use yansi::{Paint, Color};
painted.bg(Color::Red);Set background color to red using on_red().
use yansi::Paint;
painted.on_red();Source§fn on_primary(&self) -> Painted<&T>
fn on_primary(&self) -> Painted<&T>
Source§fn on_magenta(&self) -> Painted<&T>
fn on_magenta(&self) -> Painted<&T>
Source§fn on_bright_black(&self) -> Painted<&T>
fn on_bright_black(&self) -> Painted<&T>
Source§fn on_bright_red(&self) -> Painted<&T>
fn on_bright_red(&self) -> Painted<&T>
Source§fn on_bright_green(&self) -> Painted<&T>
fn on_bright_green(&self) -> Painted<&T>
Source§fn on_bright_yellow(&self) -> Painted<&T>
fn on_bright_yellow(&self) -> Painted<&T>
Source§fn on_bright_blue(&self) -> Painted<&T>
fn on_bright_blue(&self) -> Painted<&T>
Source§fn on_bright_magenta(&self) -> Painted<&T>
fn on_bright_magenta(&self) -> Painted<&T>
Source§fn on_bright_cyan(&self) -> Painted<&T>
fn on_bright_cyan(&self) -> Painted<&T>
Source§fn on_bright_white(&self) -> Painted<&T>
fn on_bright_white(&self) -> Painted<&T>
Source§fn attr(&self, value: Attribute) -> Painted<&T>
fn attr(&self, value: Attribute) -> Painted<&T>
Enables the styling Attribute value.
This method should be used rarely. Instead, prefer to use
attribute-specific builder methods like bold() and
underline(), which have the same functionality
but are pithier.
§Example
Make text bold using attr():
use yansi::{Paint, Attribute};
painted.attr(Attribute::Bold);Make text bold using using bold().
use yansi::Paint;
painted.bold();Source§fn rapid_blink(&self) -> Painted<&T>
fn rapid_blink(&self) -> Painted<&T>
Source§fn quirk(&self, value: Quirk) -> Painted<&T>
fn quirk(&self, value: Quirk) -> Painted<&T>
Enables the yansi Quirk value.
This method should be used rarely. Instead, prefer to use quirk-specific
builder methods like mask() and
wrap(), which have the same functionality but are
pithier.
§Example
Enable wrapping using .quirk():
use yansi::{Paint, Quirk};
painted.quirk(Quirk::Wrap);Enable wrapping using wrap().
use yansi::Paint;
painted.wrap();Source§fn clear(&self) -> Painted<&T>
👎Deprecated since 1.0.1: renamed to resetting() due to conflicts with Vec::clear().
The clear() method will be removed in a future release.
fn clear(&self) -> Painted<&T>
renamed to resetting() due to conflicts with Vec::clear().
The clear() method will be removed in a future release.
Source§fn whenever(&self, value: Condition) -> Painted<&T>
fn whenever(&self, value: Condition) -> Painted<&T>
Conditionally enable styling based on whether the Condition value
applies. Replaces any previous condition.
See the crate level docs for more details.
§Example
Enable styling painted only when both stdout and stderr are TTYs:
use yansi::{Paint, Condition};
painted.red().on_yellow().whenever(Condition::STDOUTERR_ARE_TTY);