Skip to main content

Registry

Struct Registry 

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

Where the app and its modules register jobs, listeners, scheduled tasks and commands. Modules get it in Module::register.

Implementations§

Source§

impl Registry

Source

pub fn job<J: Job>(&mut self) -> &mut Self

Lets workers run jobs of type J.

Source

pub fn webhook<W: Webhook>(&mut self) -> &mut Self

Lets queue workers process W’s webhooks; pair it with Routes::webhook::<W>(path).

Source

pub fn listen<E, F, Fut>(&mut self, listener_fn: F) -> &mut Self
where E: Event, F: Fn(E, AppState) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result> + Send + 'static,

Runs listener whenever an E is emitted.

Source

pub fn command<F, Fut>(&mut self, name: &str, about: &str, run: F) -> &mut Self
where F: Fn(Args, AppState) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result> + Send + 'static,

Adds a command the app binary runs: my-app <name> [args]. See crate::command.

Source

pub fn typed_command<T: AppCommand>(&mut self) -> &mut Self

A command whose arguments are declared with clap; see AppCommand.

Source

pub fn templates( &mut self, hook: impl Fn(&mut Environment<'static>) + Send + Sync + 'static, ) -> &mut Self

Adds template functions, filters or globals, e.g. a euros filter that always writes cents the German way:

App::new().templates(|env| {
    env.add_filter("euros", |cents: i64| format!("{} €", renox::format_number(cents as f64 / 100.0, 2, "de")));
})

Built in: number ({{ price | number }} → 75.000 in German, number(2) for decimals) and date ({{ created_at | date("%d/%m/%Y") }}, in APP_TIMEZONE).

Source

pub fn asset( &mut self, path: &'static str, content_type: &'static str, body: &'static [u8], ) -> &mut Self

Serves body at path the way Renox serves its own scripts and styles: in front of sessions, CSRF and maintenance mode (no cookie is set), with a year-long immutable cache. For a module’s JavaScript, CSS or fonts, compiled into its crate; put a version or a hash of the content in path, so a new release gets a new address.

struct Charts;

impl Module for Charts {
    fn name(&self) -> &'static str { "charts" }

    fn register(&self, app: &mut Registry) {
        app.asset(
            "/_charts/charts-1.2.0.js",
            "text/javascript; charset=utf-8",
            b"console.log('charts')",
        );
    }
}

The path must start with /; two files at the same path stop the app at boot.

Source

pub fn share<F, Fut, T>(&mut self, key: &str, compute: F) -> &mut Self
where F: Fn(ViewContext) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<T>> + Send + 'static, T: Serialize,

Gives every view key, computed per request, e.g. the categories in a menu or the number of items in a cart. It runs for every rendered view, so keep it quick (cache what doesn’t change per request).

App::new().share("cart_count", |ctx: renox::view::ViewContext| async move {
    let Some(user) = ctx.user else { return Ok(0) };
    let n: i64 = renox::db::sql("SELECT COUNT(*) FROM cart_items WHERE user_id = ?")
        .bind(user.id)
        .scalar(&ctx.state.db)
        .await?;
    Ok(n)
})

Values a handler passes in context! win over shared ones.

Source

pub fn channel<F, Fut>(&mut self, name: &str, send: F) -> &mut Self
where F: Fn(Recipient, Value, AppState) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result> + Send + 'static,

Adds a notification channel, used by notifications that list Channel::Custom(name): send gets the recipient and the message Notification::to_channel built. See crate::auth::notifications.

Source

pub fn second_factor<F, Fut>( &mut self, challenge: &str, required: F, ) -> &mut Self
where F: Fn(User, AppState) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<bool>> + Send + 'static,

Adds a second step to logging in, such as two-factor authentication; see crate::auth::second_factor. After the right password, a user for whom required answers true isn’t logged in yet: the browser goes to the route named challenge, whose handler checks the code and calls crate::auth::complete_login. One module may set it; a second one is an error at boot.

Source

pub fn account_section<F, Fut>( &mut self, template: &str, order: i32, data: F, ) -> &mut Self
where F: Fn(User, AppState) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<Value>> + Send + 'static,

Adds a section to the Auth module’s /account page (with Auth::new().account()), such as two-factor authentication or linked logins. template is rendered with the page’s context; data runs for the logged-in user on every visit, and the template reads what it returns as section.data. Sections show in order (then in the order they were added), after the built-in cards and before “Delete account”.

struct Pin;

impl Module for Pin {
    fn name(&self) -> &'static str {
        "pin"
    }

    fn register(&self, app: &mut Registry) {
        app.templates(|env| {
            env.add_template(
                "pin/account.html",
                r#"<section id="pin">PIN {{ "on" if section.data.on else "off" }}</section>"#,
            )
            .unwrap();
        });
        app.account_section("pin/account.html", 10, |user, _state| async move {
            Ok(json!({ "on": user.extra.contains_key("pin") }))
        });
    }
}
Source

pub fn report<F, Fut>(&mut self, reporter: F) -> &mut Self
where F: Fn(ErrorReport, AppState) -> Fut + Send + Sync + 'static, Fut: Future<Output = ()> + Send + 'static,

Sends every error that needs a person to reporter; see crate::report.

Source

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

Makes value available everywhere the app runs, as App::provide does: Provided<T> in handlers, state.provided::<T>() in jobs, listeners, webhooks and commands. For a module’s settings that code without a request needs (a payment module’s plans in its webhook handler). One value per type; a value the app gives with App::provide wins.

struct Plans(Vec<&'static str>);

struct Billing;

impl Module for Billing {
    fn name(&self) -> &'static str {
        "billing"
    }

    fn register(&self, app: &mut Registry) {
        app.provide(Plans(vec!["basic", "pro"]));
    }
}

async fn in_a_job(state: AppState) {
    let plans = state.provided::<Plans>().expect("the Billing module is on");
}
Source

pub fn schedule(&mut self) -> &mut Schedule

The schedule, to add tasks to.

Trait Implementations§

Source§

impl Default for Registry

Source§

fn default() -> Self

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

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

Source§

type Output = T

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