Skip to main content

AppState

Struct AppState 

Source
pub struct AppState(/* private fields */);
Expand description

Shared state available to every handler through State<AppState>.

One Arc around AppStateInner: every middleware layer, the request’s extensions and each handler’s State clone it, so a clone is one atomic increment (it was a struct of about 35 fields, cloned tens of times per request: #334). Read its parts as fields, through Deref: state.db, state.config, state.queue…

Implementations§

Source§

impl AppState

Source

pub fn broadcast(&self, event: &str, data: impl Serialize) -> Result

Sends the DOM event event, with data as its detail, to every page open in this process with a notification stream (the UI kit’s notification_bell or event_stream(), which need Auth::new().notifications()), whoever is logged in there.

Pages listen as to any DOM event on document: htmx with hx-trigger="order-updated from:document", Alpine with x-on:order-updated.document="…", a script with document.addEventListener("order-updated", e => e.detail). The event renox:toast with {"toasts": [toast]} shows toasts.

It is fire-and-forget: nothing is stored, and pages that aren’t connected at that moment (closed, reconnecting, open on another server, or a queue:work process sent it) never get it. Use a database notification (AppState::notify) for what must arrive.

state.broadcast("order-updated", json!({ "id": 7, "status": "paid" }))?;
// Only Ana's pages (any tab, any device on this server):
state.broadcast_to(user.id, "renox:toast", json!({ "toasts": [Toast::info("Export ready")] }))?;
Source

pub fn broadcast_to( &self, user_id: i64, event: &str, data: impl Serialize, ) -> Result

AppState::broadcast to the pages of one user (by id) only.

Source

pub async fn notify( &self, to: impl Into<Recipient>, notification: &impl Notification, ) -> Result

Delivers notification now to a user (&user) or to addresses (a Recipient), on each of its channels. The database row is written first and mail sent last, so a failure doesn’t leave a message behind that a retry would send again.

Source

pub async fn notify_later( &self, to: impl Into<Recipient>, notification: &impl Notification, ) -> Result

Like notify, but mail and the app’s channels are sent by queue workers, each channel as its own job with its own retries. The messages are built now; the database row is written now.

Source§

impl AppState

Source

pub async fn emit<E: Event>(&self, event: E) -> Result

Runs every listener of E in registration order: those added with App::listen first, then modules’ (registered at boot). All of them run even if one fails; the first error is returned.

Source§

impl AppState

Source

pub fn lang(&self, locale: &str) -> Lang

The texts of locale, for code without a request (a job, a mail to someone in another language).

Source

pub fn current_lang(&self) -> Lang

The texts of the current_locale.

Source§

impl AppState

Source

pub fn mail_view( &self, to: impl Into<String>, subject: impl Into<String>, view: &str, ctx: impl Serialize, ) -> Result<Mail>

Renders {view}.html into a mail, with {view}.txt as the text version when it exists (otherwise text made from the HTML). Templates see app (app.locale too) and t(key, …) in the current_locale besides ctx, can extend renox/mail/layout.html and import renox/mail/components.html (button, panel, table).

Source

pub fn mail_view_in( &self, locale: &str, to: impl Into<String>, subject: impl Into<String>, view: &str, ctx: impl Serialize, ) -> Result<Mail>

mail_view in locale (the recipient’s language).

Source

pub async fn queue_mail(&self, mail: Mail) -> Result<i64>

Sends mail from a queue worker, retrying up to five times.

Source

pub fn mailer_named(&self, name: &str) -> Result<&Mailer>

A mailer the app added with App::mailer, e.g. state.mailer_named("newsletter")?.send(mail); an unknown name is an error (500).

Source

pub async fn queue_mail_via(&self, mailer: &str, mail: Mail) -> Result<i64>

Like queue_mail, through the mailer named mailer.

Source§

impl AppState

Source

pub fn provided<T: Send + Sync + 'static>(&self) -> Option<Arc<T>>

A value given to App::provide, if one of type T was.

Source§

impl AppState

Source

pub async fn dispatch<J: Job>(&self, job: J) -> Result<i64>

Shorthand for state.queue.dispatch(job).

Source

pub async fn dispatch_sync<J: Job>(&self, job: J) -> Result

Runs job now, in this task, instead of queueing it (no retries, middleware or failed hook): the error, if any, is returned.

Source§

impl AppState

Source

pub fn signed_url( &self, name: &str, params: &[&dyn Display], ttl: Duration, ) -> Result<String>

An absolute URL to a named route, valid for ttl and signed with APP_KEY.

Source

pub fn sign_path(&self, path: &str, ttl: Duration) -> Result<String>

Like signed_url, for an already-encoded path such as /_renox/files/a.pdf.

Source

pub fn absolute_url( &self, name: &str, params: &[&dyn Display], ) -> Result<String>

An absolute URL to a named route.

Source§

impl AppState

Source

pub fn url(&self, name: &str, params: &[&dyn Display]) -> Result<String>

The URL path of a named route, e.g. state.url("products.show", &[&id]).

Source

pub fn encrypt(&self, plain: &str) -> String

Encrypts plain with APP_KEY (AES-256-GCM), e.g. an API secret a user saves, before storing it. The result is base64 text; only AppState::decrypt with the same key reads it back, and any change to it is detected. Rotating APP_KEY makes old values unreadable.

let sealed = state.encrypt("sk_live_123");
assert_eq!(state.decrypt(&sealed)?, "sk_live_123");
Source

pub fn decrypt(&self, sealed: &str) -> Result<String>

Reads a value from AppState::encrypt. Fails if it was changed or sealed with another key.

Source§

impl AppState

Source

pub fn disk_named(&self, name: &str) -> Result<&Storage>

A disk the app added with App::disk, e.g. state.disk_named("backups")?; an unknown name is an error (500).

Trait Implementations§

Source§

impl Clone for AppState

Source§

fn clone(&self) -> Self

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 Deref for AppState

Source§

type Target = AppStateInner

The resulting type after dereferencing.
Source§

fn deref(&self) -> &AppStateInner

Dereferences the value.
Source§

impl FromRef<AppState> for Db

Source§

fn from_ref(state: &AppState) -> Self

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

impl<T> FromRequest<AppState> for Valid<T>

Source§

type Rejection = Response<Body>

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, Response>

Perform the extraction.
Source§

impl FromRequestParts<AppState> for Cookies

Source§

type Rejection = !

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, Infallible>

Perform the extraction.
Source§

impl<T: Send + Sync + 'static> FromRequestParts<AppState> for Provided<T>

Source§

type Rejection = Error

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( _: &mut Parts, state: &AppState, ) -> Result<Self, Error>

Perform the extraction.

Auto Trait Implementations§

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

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

Source§

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

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> Fake for T

Source§

fn fake<U>(&self) -> U
where Self: FakeBase<U>,

Source§

fn fake_with_rng<U, R>(&self, rng: &mut R) -> U
where R: RngExt + ?Sized, Self: FakeBase<U>,

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<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,

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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. 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: Sized + 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: Sized + 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> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
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 = !

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

fn try_from(value: U) -> Result<T, !>

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