Skip to main content

AppState

Struct AppState 

Source
#[non_exhaustive]
pub struct AppState { /* private fields */ }
Expand description

Shared application state passed to all route handlers.

Holds framework-managed resources such as the database connection pool. Axum requires handler state to be Clone, so internal resources use Arc or are already cheaply cloneable (deadpool::Pool is Arc-wrapped internally).

This struct is normally constructed by crate::app::AppBuilder::run and should not need to be created manually. It is public so that custom Axum extractors can access framework resources via State<AppState>.

§Examples

use autumn_web::AppState;

// State without a database (e.g., for testing)
let state = AppState::for_test().with_profile("dev");

Implementations§

Source§

impl AppState

Source

pub fn insert_extension<T>(&self, value: T)
where T: Any + Send + Sync + 'static,

Install or replace a typed runtime extension.

Integrations use this to publish typed runtime resources, such as background-worker handles or dedicated storage pools, after startup.

§Panics

Panics if the internal extension map mutex is poisoned.

Source

pub fn extension<T>(&self) -> Option<Arc<T>>
where T: Any + Send + Sync + 'static,

Borrow a typed runtime extension if it has been installed.

The returned Arc is cloned out of the internal registry so callers do not hold the state mutex while using the value.

§Panics

Panics if the internal extension map mutex is poisoned.

Source

pub const fn pool(&self) -> Option<&Pool<AsyncPgConnection>>

Returns the database connection pool.

Source

pub const fn replica_pool(&self) -> Option<&Pool<AsyncPgConnection>>

Returns the read-replica database connection pool, if configured.

Source

pub fn read_pool(&self) -> Option<&Pool<AsyncPgConnection>>

Returns the pool used for read-only work.

Source

pub const fn metrics(&self) -> &MetricsCollector

Returns the metrics collector.

Source

pub const fn log_levels(&self) -> &LogLevels

Returns the log levels configuration.

Source

pub const fn task_registry(&self) -> &TaskRegistry

Returns the task registry.

Source

pub const fn job_registry(&self) -> &JobRegistry

Returns the job registry.

Source

pub const fn config_props(&self) -> &ConfigProperties

Returns the config properties.

Source

pub const fn probes(&self) -> &ProbeState

Returns the shared probe lifecycle state.

Source

pub fn mark_startup_complete(&self)

Mark startup as complete so readiness can become healthy.

Source

pub fn begin_shutdown(&self)

Mark the application as draining so readiness flips unhealthy.

Source

pub fn with_pool(self, pool: Pool<AsyncPgConnection>) -> Self

Sets the database pool.

Source

pub fn with_replica_pool(self, pool: Pool<AsyncPgConnection>) -> Self

Sets the read-replica database pool.

Source

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

Install a typed runtime extension while building test or ad-hoc state.

Source

pub fn cache(&self) -> Option<Arc<dyn Cache>>

Returns the registered global cache backend, if any.

Checks the extension map first (populated at runtime by startup hooks via Self::set_cache) so that a plugin replacing a build-time backend is always visible. Falls back to shared_cache (set at build time via Self::with_cache).

Source

pub fn with_cache(self, cache: Arc<dyn Cache>) -> Self

Register a global cache backend (builder / test helper, build-time).

Source

pub fn set_cache(&self, cache: Arc<dyn Cache>)

Install or replace the global cache backend at runtime (e.g. from a startup hook).

Updates both the process-level global (used by #[cached] functions) and the extension map (used by CacheResponseLayer::from_app and state.cache()).

Source

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

Sets the active profile.

Source

pub const fn policy_registry(&self) -> &PolicyRegistry

Returns a reference to the PolicyRegistry.

Source

pub fn policy<R: Send + Sync + 'static>(&self) -> Option<Arc<dyn Policy<R>>>

Resolve the registered Policy for resource R, if any.

Source

pub fn scope<R: Send + Sync + 'static>(&self) -> Option<Arc<dyn Scope<R>>>

Resolve the registered Scope for resource R, if any.

Source

pub const fn forbidden_response(&self) -> ForbiddenResponse

Configured deny-response shape. See ForbiddenResponse for the trade-off between 403 and 404 defaults.

Source

pub fn auth_session_key(&self) -> &str

Session key used to resolve the authenticated user id for PolicyContext.

Source

pub fn profile(&self) -> &str

Returns the active profile name, or "default" if none is set.

Source

pub fn uptime(&self) -> Duration

Returns how long the application has been running.

Source

pub fn uptime_display(&self) -> String

Format uptime as a human-readable string (e.g., “2h 15m”).

Source

pub const fn channels(&self) -> &Channels

Returns a reference to the broadcast channel registry.

Shorthand for accessing self.channels directly.

Source

pub fn broadcast(&self) -> Broadcast

Returns a high-level broadcast facade for raw and htmx HTML payloads.

Source

pub fn shutdown_token(&self) -> CancellationToken

Returns a child cancellation token for the server shutdown signal.

WebSocket handlers should select on this to clean up when the server is shutting down.

Source

pub fn detached() -> Self

Create a minimal detached AppState without an HTTP server.

This is useful for background runtimes or helper processes that still need framework-managed resources such as typed extensions, metrics, or WebSocket channel registries.

Source

pub fn for_test() -> Self

Create an AppState suitable for testing, with sensible defaults for all fields. Database pool is None.

Trait Implementations§

Source§

impl Clone for AppState

Source§

fn clone(&self) -> AppState

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl DbState for AppState

Available on crate feature db only.
Source§

fn pool(&self) -> Option<&Pool<AsyncPgConnection>>

Returns the database connection pool, if configured.
Source§

fn replica_pool(&self) -> Option<&Pool<AsyncPgConnection>>

Returns the read/replica connection pool, if configured.
Source§

fn read_pool(&self) -> Option<&Pool<AsyncPgConnection>>

Returns the pool used for read-only work. Read more
Source§

impl Debug for AppState

Source§

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

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

impl FromRequest<AppState> for SignedWebhook

Source§

type Rejection = AutumnError

If the extractor fails it’ll use this “rejection” type. A rejection is a kind of error that can be converted into a response.
Source§

async fn from_request( req: Request, state: &AppState, ) -> Result<Self, Self::Rejection>

Perform the extraction.
Source§

impl FromRequestParts<AppState> for AutumnConfig

Source§

type Rejection = AutumnError

If the extractor fails it’ll use this “rejection” type. A rejection is a kind of error that can be converted into a response.
Source§

async fn from_request_parts( _parts: &mut Parts, state: &AppState, ) -> Result<Self, Self::Rejection>

Perform the extraction.
Source§

impl FromRequestParts<AppState> for Mailer

Source§

type Rejection = AutumnError

If the extractor fails it’ll use this “rejection” type. A rejection is a kind of error that can be converted into a response.
Source§

async fn from_request_parts( _parts: &mut Parts, state: &AppState, ) -> Result<Self, Self::Rejection>

Perform the extraction.
Source§

impl ProvideActuatorState for AppState

Source§

fn metrics(&self) -> &MetricsCollector

Returns a reference to the crate::middleware::MetricsCollector tracking current HTTP traffic metrics.
Source§

fn log_levels(&self) -> &LogLevels

Returns a reference to the dynamic LogLevels configuration allowing runtime adjustment of tracing filters.
Source§

fn task_registry(&self) -> &TaskRegistry

Returns a reference to the TaskRegistry holding status and metadata for async scheduled background tasks.
Source§

fn job_registry(&self) -> &JobRegistry

Returns a reference to the JobRegistry holding queue and failure information for ad-hoc background jobs.
Source§

fn config_props(&self) -> &ConfigProperties

Returns a reference to the ConfigProperties snapshot, providing active configuration state for the environment endpoint.
Source§

fn profile(&self) -> &str

Returns the currently active execution profile (e.g. “dev”, “prod”) which modifies what sensitive endpoints are exposed.
Source§

fn uptime_display(&self) -> String

Returns a human-readable string displaying how long the application has been running (e.g., “2d 4h 13m”).
Source§

fn channels(&self) -> &Channels

Returns a reference to the system crate::channels::Channels which broadcasts operational events to WebSocket streams.
Source§

fn shutdown_token(&self) -> CancellationToken

Returns the main cancellation token that triggers a graceful framework shutdown.
Source§

fn pool(&self) -> Option<&Pool<AsyncPgConnection>>

Returns an optional reference to the database connection pool, used to expose database connection metrics in the /actuator/metrics endpoint.
Source§

fn a11y_posture(&self) -> A11yPosture

Returns the scaffold-level accessibility posture reported by /actuator/a11y. Read more
Source§

impl ProvideProbeState for AppState

Source§

fn probes(&self) -> &ProbeState

Returns a reference to the shared ProbeState that tracks lifecycle phases (startup, ready, draining).
Source§

fn health_detailed(&self) -> bool

Returns whether detailed health information (e.g., uptime, pool stats) should be included in the response.
Source§

fn profile(&self) -> &str

Returns the currently active execution profile (e.g. “dev”, “prod”).
Source§

fn uptime_display(&self) -> String

Returns a human-readable string displaying how long the application has been running (e.g., “2d 4h 13m”).
Source§

fn pool(&self) -> Option<&Pool<AsyncPgConnection>>

Returns an optional reference to the database connection pool, used to evaluate database connectivity during a readiness check.
Source§

fn replica_pool(&self) -> Option<&Pool<AsyncPgConnection>>

Returns an optional read-replica pool for readiness checks.
Source§

fn mark_startup_complete(&self)

Helper method to mark the application startup as complete. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> AggregateExpressionMethods for T

Source§

fn aggregate_distinct(self) -> Self::Output
where Self: DistinctDsl,

DISTINCT modifier for aggregate functions Read more
Source§

fn aggregate_all(self) -> Self::Output
where Self: AllDsl,

ALL modifier for aggregate functions Read more
Source§

fn aggregate_filter<P>(self, f: P) -> Self::Output
where P: AsExpression<Bool>, Self: FilterDsl<<P as AsExpression<Bool>>::Expression>,

Add an aggregate function filter Read more
Source§

fn aggregate_order<O>(self, o: O) -> Self::Output
where Self: OrderAggregateDsl<O>,

Add an aggregate function order Read more
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
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Converts Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Converts &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSend for T
where T: Any + Send,

Source§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_sync(self: Box<T>) -> Box<dyn Any + Send + Sync>

Converts Box<Trait> (where Trait: DowncastSync) to Box<dyn Any + Send + Sync>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Send + Sync>

Converts Arc<Trait> (where Trait: DowncastSync) to Arc<Any>, which can then be downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> Instrument for T

Source§

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

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

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.

Source§

impl<T> IntoSql for T

Source§

fn into_sql<T>(self) -> Self::Expression

Convert self to an expression for Diesel’s query builder. Read more
Source§

fn as_sql<'a, T>(&'a self) -> <&'a Self as AsExpression<T>>::Expression
where &'a Self: AsExpression<T>, T: SqlType + TypedExpressionType,

Convert &self to an expression for Diesel’s query builder. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

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

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> RepositoryHooksClone for T
where T: Clone,

Source§

fn autumn_clone(&self) -> T

Clone hook state for generated repository values.
Source§

impl<T, Conn> RunQueryDsl<Conn> for T

Source§

fn execute<'conn, 'query>( self, conn: &'conn mut Conn, ) -> <Conn as AsyncConnectionCore>::ExecuteFuture<'conn, 'query>
where Conn: AsyncConnectionCore + Send, Self: ExecuteDsl<Conn> + 'query,

Executes the given command, returning the number of rows affected. Read more
Source§

fn load<'query, 'conn, U>( self, conn: &'conn mut Conn, ) -> AndThen<Self::LoadFuture<'conn>, TryCollect<Self::Stream<'conn>, Vec<U>>>
where U: Send, Conn: AsyncConnectionCore, Self: LoadQuery<'query, Conn, U> + 'query,

Executes the given query, returning a Vec with the returned rows. Read more
Source§

fn load_stream<'conn, 'query, U>( self, conn: &'conn mut Conn, ) -> Self::LoadFuture<'conn>
where Conn: AsyncConnectionCore, U: 'conn, Self: LoadQuery<'query, Conn, U> + 'query,

Executes the given query, returning a [Stream] with the returned rows. Read more
Source§

fn get_result<'query, 'conn, U>( self, conn: &'conn mut Conn, ) -> AndThen<Self::LoadFuture<'conn>, LoadNext<Pin<Box<Self::Stream<'conn>>>>>
where U: Send + 'conn, Conn: AsyncConnectionCore, Self: LoadQuery<'query, Conn, U> + 'query,

Runs the command, and returns the affected row. Read more
Source§

fn get_results<'query, 'conn, U>( self, conn: &'conn mut Conn, ) -> AndThen<Self::LoadFuture<'conn>, TryCollect<Self::Stream<'conn>, Vec<U>>>
where U: Send, Conn: AsyncConnectionCore, Self: LoadQuery<'query, Conn, U> + 'query,

Runs the command, returning an Vec with the affected rows. Read more
Source§

fn first<'query, 'conn, U>( self, conn: &'conn mut Conn, ) -> AndThen<<Self::Output as LoadQuery<'query, Conn, U>>::LoadFuture<'conn>, LoadNext<Pin<Box<<Self::Output as LoadQuery<'query, Conn, U>>::Stream<'conn>>>>>
where U: Send + 'conn, Conn: AsyncConnectionCore, Self: LimitDsl, Self::Output: LoadQuery<'query, Conn, U> + Send + 'query,

Attempts to load a single record. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> Scoped for T
where T: Send + Sync + 'static,

Source§

fn scope(ctx: &PolicyContext) -> ScopeQuery<'_, Self>

Open a deferred ScopeQuery for this type. Resolves the registered scope at .load() time, not here.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. 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.
Source§

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

Source§

fn vzip(self) -> V

Source§

impl<T> WindowExpressionMethods for T

Source§

fn over(self) -> Self::Output
where Self: OverDsl,

Turn a function call into a window function call Read more
Source§

fn window_filter<P>(self, f: P) -> Self::Output
where P: AsExpression<Bool>, Self: FilterDsl<<P as AsExpression<Bool>>::Expression>,

Add a filter to the current window function Read more
Source§

fn partition_by<E>(self, expr: E) -> Self::Output
where Self: PartitionByDsl<E>,

Add a partition clause to the current window function Read more
Source§

fn window_order<E>(self, expr: E) -> Self::Output
where Self: OrderWindowDsl<E>,

Add a order clause to the current window function Read more
Source§

fn frame_by<E>(self, expr: E) -> Self::Output
where Self: FrameDsl<E>,

Add a frame clause to the current window function Read more
Source§

impl<T> WithSubscriber for T

Source§

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
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

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

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,