Skip to main content

Listener

Struct Listener 

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

A durable, named event listener of a domain: a read model (Domain::read_model) or a reactor (Domain::reactor). It defines what to handle; crate::Kernable::listener runs it. Events arrive in order, one at a time, after every listener with a lower order has processed them. Delivery is at least once: if a handler fails, the listener reconnects and the event is delivered again, until a reactor gives up on it and parks it (Listener::park_after).

Types without a domain (ItemAdded) are the listener’s own domain’s; other domains’ are qualified (identity.AccountRegistered). Handlers get event payloads upcast to the versions of the listener’s domain and of the domains it is given with with_domain. An event with a newer schema than known (a newer deployment wrote it) never reaches a handler, so it is never misread: a reactor that parks parks it at once (unknown_event), to be retried once it is updated; any other listener skips it, warns once per type and schema, and counts it (ListenerHandle::skipped). Raw handlers get it as stored. Cloning gives another handle to the same definition, and every configuring method returns one, so they chain.

Handlers are closures that return a future: Fn(data, meta, ctx) -> impl Future<Output = Result<_, BoxError>>. They are called again for every event, so they cannot own mutable state: share it as Arc<Mutex<…>>, clone the Arc into each closure with move, and lock it before the async block (do not hold a std::sync::MutexGuard across .await): let rows = Arc::new(Mutex::new(HashMap::<String, u32>::new())); let r = Arc::clone(&rows); carts_readmodel.on("ItemAdded", move |data: ItemAdded, evt, _ctx| { *r.lock().unwrap().entry(evt.aggregate_id).or_default() += data.qty; async { Ok(()) } });

A query handler returns its answer (any Serialize) or a Rejected as a BoxError: carts_readmodel.query("GetCart", move |q: GetCart, _qry, _ctx| { let row = r.lock().unwrap().get(&q.id).copied(); async move { Ok(row.ok_or_else(|| Rejected::new("no such cart").code("not_found"))?) } });

Implementations§

Source§

impl Listener

Source

pub fn name(&self) -> &str

The listener’s name: the kernel keeps its position under it.

Source

pub fn domain(&self) -> &Domain

The domain the listener belongs to: types without a domain are its.

Source

pub fn order(&self, order: i32) -> Listener

Listeners with a lower order process each event first; equal orders run in parallel. Defaults: 0 for read models, 10 for reactors. Negative orders are reserved for kernable’s kits (a grant of reserved_order).

Source

pub fn start(&self, position: u64) -> Listener

Position to start after on the first connect: 0 rebuilds from the beginning (default for read models). Reactors resume after the last acknowledged event unless given one, and a new one starts at the newest event, so it never reacts to what happened before it existed. Reconnects always resume after the last handled event.

Source

pub fn live(&self) -> Listener

Not registered with the kernel: no stored position, always starts at the newest event, nobody waits for it, and it is forgotten when it disconnects. For reactions that only matter while the process runs, e.g. pushing to connected browsers. Make it live before running it.

§Panics

If the listener is a middleware: a live listener cannot be one.

Source

pub fn instance(&self, id: &str) -> Listener

Runs this process’s listener as the instance id of a group under the listener’s name, e.g. one per node of a pair: 1 to 128 letters, digits, -, _ and .. Default: KERNABLE_INSTANCE, which kernable node sets; without either, the name has one connection. Read models are replicated: every instance gets every event and answers queries. Reactors are single (see Listener::single).

Source

pub fn single(&self, single: bool) -> Listener

Whether the instances take turns (default for reactors): one gets events, the others wait and the first of them takes over when it leaves, so a side effect happens once. false (default for read models): every instance gets every event, from its own position; such a listener cannot park events. Live listeners are never single.

Source

pub fn reconnect(&self, delay: Duration) -> Listener

Delay before reconnecting after the stream drops or a handler fails (default 1 s); twice as long after each further failed attempt, at most 30 s.

Source

pub fn park_after(&self, attempts: u32) -> Listener

How often a handler may fail on one event before the listener parks it and moves on (default 5 for reactors, 0 for read models; 0: never, the listener keeps getting the event and everything behind it waits). A Rejected (also a rejected ListenerContext::submit) parks at once; the kernel being unreachable or busy (UNAVAILABLE, DEADLINE_EXCEEDED, RESOURCE_EXHAUSTED, Error::NotSettled) or the store failing never does: the listener waits and tries again. The kernel keeps parked events with the rejection’s code and message (for other errors handler_error and handler failed; the log has the whole error) until an operator retries or dismisses them (kernable listeners retry). A read model should not park: it would miss the event’s change. With a store, a parked event’s writes are dropped, the rest of its batch kept. Live listeners never park, and no listener parks an event that erases a subject because its handler failed: the handler must get past it, so no personal data stays behind. An event newer than the code (unknown_event) is parked, erasing or not: no handler ran on it.

Source

pub fn store(&self, url: &str, schema: &str) -> Listener

Keeps the listener’s state in a store (sqlite:<path> or memory:) instead of memory: its data and position are written together per batch, and a restart continues after the stored position. schema is the version of the stored data’s format: change it when the handlers store data differently, and the store is cleared and rebuilt. Handlers get the store as ctx.store (ListenerContext::store, QueryContext::store). Example: shop_domain.read_model("carts").store("sqlite:carts.db", "1").

Source

pub fn with_domain(&self, domain: &Domain) -> Listener

Upcasts the events of another domain with its event schemas (see Domain::event); the listener’s own domain’s apply without it.

Source

pub fn on<D, F, Fut>(&self, event_type: impl TypeKey<D>, handler: F) -> Listener
where D: DeserializeOwned + Send + 'static, F: Fn(D, StoredEventMeta, ListenerContext) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<(), BoxError>> + Send + 'static,

Handles event_type events: a type of the listener’s domain (ItemAdded), of another domain (orders.OrderPlaced), a whole domain (orders.*), or an event type’s constant (see crate::event; query takes a query type’s likewise). handler(data, evt, ctx) gets the payload as D (serde_json::Value for any), a StoredEventMeta and a ListenerContext, and returns a future of Result<(), BoxError>. A payload that is not a D or an Err fails the batch: the listener reconnects and the event is delivered again, so handlers must be idempotent. See Listener for an example.

§Panics

If event_type is none of these.

Source

pub fn on_raw<D, F, Fut>( &self, event_type: impl TypeKey<D>, handler: F, ) -> Listener
where D: DeserializeOwned + Send + 'static, F: Fn(D, StoredEventMeta, ListenerContext) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<(), BoxError>> + Send + 'static,

Like on, but gets events as stored, without upcasting, whatever their schema (for archives and exports).

Source

pub fn also_on<D, F, Fut>( &self, event_type: impl TypeKey<D>, handler: F, ) -> Listener
where D: DeserializeOwned + Send + 'static, F: Fn(D, StoredEventMeta, ListenerContext) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<(), BoxError>> + Send + 'static,

Like on, but keeps a handler registered for the type already: this one runs after it, in the same delivery (a failing first one skips it). For code that adds to a listener it does not own, e.g. the kit’s visibility; register it after your own handlers.

Source

pub fn query<D, R, F, Fut>( &self, query_type: impl TypeKey<D>, handler: F, ) -> Listener
where D: DeserializeOwned + Send + 'static, R: Serialize, F: Fn(D, QueryMeta, QueryContext) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<R, BoxError>> + Send + 'static,

Answers query_type queries: a type of the listener’s domain (GetOrder) or of another one (orders.GetOrder), from this listener’s state: handler(data, qry, ctx) gets the query’s data as D, a QueryMeta and a QueryContext, and returns a future of the answer R (any Serialize). The kernel delivers queries in order with the events, so an answer reflects every event handled before it. Return a Rejected (as a BoxError) to refuse; any other error refuses with handler_error. A handler cannot query its own listener (the answer would wait behind itself): the kernel refuses it. See Listener for an example.

§Panics

If query_type is neither.

Source

pub fn middleware<F, Fut>( &self, options: MiddlewareOptions, handler: F, ) -> Listener
where F: Fn(Check) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<(), BoxError>> + Send + 'static,

Makes this listener a middleware: the kernel asks handler about every command, query, file and cache request of options.types (see MiddlewareOptions::types), before accepting or routing it (or after, see When), in chain order, and only once this listener has caught up with the events. Return a Rejected to refuse; any other error refuses too. After a request, the check carries its outcome (Check::outcome). The registration is stored: while this listener is away, the kernel refuses those requests (kernable listeners remove unregisters it). A listener has at most one middleware before and one after. The handler gets a Check and returns a future of Result<(), BoxError>: Ok(()) lets the request pass. Example: MiddlewareOptions::new(&["shop.*"]) with a handler that returns Err(Rejected::new("not allowed").code("forbidden").into()) unless check.request.sender_identity may send check.type_name.

§Panics

If a type is not *, a type, a qualified type or a domain, the listener has a middleware at options.when already, or it is live.

Trait Implementations§

Source§

impl Clone for Listener

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

Auto Trait Implementations§

§

impl Forget for Listener

§

impl Freeze for Listener
where *const ArcInner<ListenerInner> is !null: Freeze, PhantomData<ArcInner<ListenerInner>>: Freeze,

§

impl Move for Listener

§

impl RefUnwindSafe for Listener

§

impl Send for Listener
where Arc<ListenerInner>: Send,

§

impl Sync for Listener
where Arc<ListenerInner>: Sync,

§

impl Unpin for Listener
where Arc<ListenerInner>: Unpin,

§

impl UnsafeUnpin for Listener
where *const ArcInner<ListenerInner> is !null: UnsafeUnpin, PhantomData<ArcInner<ListenerInner>>: UnsafeUnpin,

§

impl UnwindSafe for Listener
where Arc<ListenerInner>: UnwindSafe,

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

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
Source§

impl<L> LayerExt<L> for L

Source§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in Layered.
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<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