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
impl Listener
Sourcepub fn domain(&self) -> &Domain
pub fn domain(&self) -> &Domain
The domain the listener belongs to: types without a domain are its.
Sourcepub fn order(&self, order: i32) -> Listener
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).
Sourcepub fn start(&self, position: u64) -> Listener
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.
Sourcepub fn live(&self) -> Listener
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.
Sourcepub fn instance(&self, id: &str) -> Listener
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).
Sourcepub fn single(&self, single: bool) -> Listener
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.
Sourcepub fn reconnect(&self, delay: Duration) -> Listener
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.
Sourcepub fn park_after(&self, attempts: u32) -> Listener
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.
Sourcepub fn store(&self, url: &str, schema: &str) -> Listener
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").
Sourcepub fn with_domain(&self, domain: &Domain) -> Listener
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.
Sourcepub fn on<D, F, Fut>(&self, event_type: impl TypeKey<D>, handler: F) -> Listenerwhere
D: DeserializeOwned + Send + 'static,
F: Fn(D, StoredEventMeta, ListenerContext) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), BoxError>> + Send + 'static,
pub fn on<D, F, Fut>(&self, event_type: impl TypeKey<D>, handler: F) -> Listenerwhere
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.
Sourcepub fn on_raw<D, F, Fut>(
&self,
event_type: impl TypeKey<D>,
handler: F,
) -> Listenerwhere
D: DeserializeOwned + Send + 'static,
F: Fn(D, StoredEventMeta, ListenerContext) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), BoxError>> + Send + 'static,
pub fn on_raw<D, F, Fut>(
&self,
event_type: impl TypeKey<D>,
handler: F,
) -> Listenerwhere
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).
Sourcepub fn also_on<D, F, Fut>(
&self,
event_type: impl TypeKey<D>,
handler: F,
) -> Listenerwhere
D: DeserializeOwned + Send + 'static,
F: Fn(D, StoredEventMeta, ListenerContext) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), BoxError>> + Send + 'static,
pub fn also_on<D, F, Fut>(
&self,
event_type: impl TypeKey<D>,
handler: F,
) -> Listenerwhere
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.
Sourcepub fn query<D, R, F, Fut>(
&self,
query_type: impl TypeKey<D>,
handler: F,
) -> Listener
pub fn query<D, R, F, Fut>( &self, query_type: impl TypeKey<D>, handler: F, ) -> Listener
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.
Sourcepub fn middleware<F, Fut>(
&self,
options: MiddlewareOptions,
handler: F,
) -> Listener
pub fn middleware<F, Fut>( &self, options: MiddlewareOptions, handler: F, ) -> Listener
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§
Auto Trait Implementations§
impl Forget for Listener
impl Freeze for Listener
impl Move for Listener
impl RefUnwindSafe for Listener
impl Send for Listener
impl Sync for Listener
impl Unpin for Listener
impl UnsafeUnpin for Listener
impl UnwindSafe for Listener
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
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
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> IntoRequest<T> for T
impl<T> IntoRequest<T> for T
Source§fn into_request(self) -> Request<T>
fn into_request(self) -> Request<T>
T in a tonic::Request