pub struct Kernable { /* private fields */ }Expand description
A connection to the kernel: submits commands, asks queries, and runs workers and listeners. Cloning gives another handle to the same connection.
The calls to the kernel are async and need a Tokio runtime (#[tokio::main]). Workers,
listeners and apps run until stopped: run().await them, or tokio::spawn them and wait
for ready(). Workers and listeners print connection lines to stderr up to the level
KERNABLE_LOG names (off, error, warn, info (default), debug). Example:
let kernable = Kernable::new("app.key")?; let outcome = kernable.submit(Submit::new("shop", "cart", "c1", "AddItem").data(json!({ "qty": 2 }))).await?;
Implementations§
Source§impl Kernable
impl Kernable
Sourcepub async fn reindex(
&self,
reindex: Reindex,
) -> Result<Vec<(String, Outcome)>, Error>
pub async fn reindex( &self, reindex: Reindex, ) -> Result<Vec<(String, Outcome)>, Error>
Stores the unique keys and facts of aggregates as their current state yields them:
submits the built-in _reindex_<aggregate_type> command (reindex_type; no events)
to each ID in turn and returns each ID with its outcome. Run it after declaring a key or fact on an aggregate that has events
already: until an aggregate runs a command, it holds what its last command left. An ID
without events holds nothing and commits. A rejection is an outcome, e.g.
unique_taken if another aggregate holds one of its keys (a duplicate from before the
key was declared). Error as for Kernable::submit, for the first ID that fails;
the ones before it are done. Needs the submit grant for
<domain>._reindex_<aggregate_type>. Example:
kernable.reindex(Reindex::new("shop", "customer", ["k1", "k2"])).await?.
Source§impl Kernable
impl Kernable
Sourcepub fn new(options: impl Into<Options>) -> Result<Kernable, Error>
pub fn new(options: impl Into<Options>) -> Result<Kernable, Error>
A client for the kernel options names, or with only a key file’s path, for the default
kernel; Options::default() takes everything from the environment (see Options). It
connects on first use and again after the connection drops. Needs a Tokio runtime.
Error::Config if the key, grant or TLS files cannot be read, only some of the TLS
variables are set, or the URL or the deployment is invalid. Example: Kernable::new("app.key")?.
Sourcepub fn with_domain(&self, domain: &Domain) -> Kernable
pub fn with_domain(&self, domain: &Domain) -> Kernable
Seals the vault fields of this domain’s commands when submitting them (see
Domain::command) and sends the target of its queries asked by name (see
Domain::query). Returns another handle to this connection, so it chains:
Kernable::new("app.key")?.with_domain(&shop_domain).
Sourcepub fn worker<S: State>(&self, aggregate: &Aggregate<S>) -> Worker
pub fn worker<S: State>(&self, aggregate: &Aggregate<S>) -> Worker
A worker that runs the commands of aggregate; add more with Worker::aggregate. It
belongs to this connection’s service (see Options::service). Nothing runs until
Worker::run is awaited: kernable.worker(&cart_aggregate).run().await.
Sourcepub fn listener(&self, listener: &Listener) -> ListenerHandle
pub fn listener(&self, listener: &Listener) -> ListenerHandle
Runs listener (a read model or reactor of a domain) on this connection: the handle
processes its events with run(). Each call gives a new handle. The listener belongs to
this connection’s service (see Options::service). Example:
kernable.listener(&carts_readmodel).run().await.
Sourcepub fn data(&self) -> Files
pub fn data(&self) -> Files
Files of the default tenant: bytes up to 16 MiB per key, kept by the kernel outside the
signed event log; see Files. Example:
kernable.data().put("shop", "invoices/c1.pdf", bytes, "application/pdf").await?.
Sourcepub fn cache(&self) -> Cache
pub fn cache(&self) -> Cache
The kernel’s cache for the default tenant: values up to 1 MiB per key, optionally with a
TTL, lost when the kernel restarts; see Cache. Example:
kernable.cache().set("shop", "rate:c1", "3", Some(Duration::from_secs(60))).await?.
Sourcepub async fn apply(&self, manifest: Manifest) -> Result<(), Error>
pub async fn apply(&self, manifest: Manifest) -> Result<(), Error>
Replaces the membership of a service (default: this connection’s, see
Options::service): the workers, listeners and middlewares the kernel waits for, plus
free metadata. Apply it once per deploy (e.g. from a deploy script), not from every
process: the newest apply wins, and an older one that arrives late is refused. The key needs the manage grant for the service. A
middleware the new membership no longer lists stops checking. It names the deployment
that serves the service (Manifest::deployment, default this connection’s, see
Options::deployment): its workers run the commands and its read models answer. A
membership that names another deployment than the serving one switches to it as
Manifest::switch says: by default only once that deployment has caught up, refused
before with not_caught_up, and never back to one that served before (served_before;
Error::waits_for_switch). Example:
kernable.apply(Manifest::new().service("shop").worker(&cart_aggregate).listener(&carts_readmodel)).await?.
Error::Config if neither the manifest nor the connection names a service, or the
deployment is invalid, Error::Status if the kernel refuses it.
Sourcepub async fn register_process(
&self,
process: &Process,
) -> Result<Registered, Error>
pub async fn register_process( &self, process: &Process, ) -> Result<Registered, Error>
Registers a business process with the kernel (see process): its model, signed. The
kernel numbers the versions: a model equal to the newest version registers nothing
(process::Registered::new is false), a different one becomes the next version;
running cases finish on the version they started with. An app registers its domains’
processes itself (Kernable::app). The key needs the process grant for the process,
and submit, query and listen for the commands, queries and events it names.
Error::Config if the model is invalid (Process::model), Error::Status if the
kernel refuses it (INVALID_ARGUMENT names the step and why).
Sourcepub async fn process_act(
&self,
name: &str,
context: RequestContext,
) -> Result<bool, Error>
pub async fn process_act( &self, name: &str, context: RequestContext, ) -> Result<bool, Error>
Sets as whom the process name (qualified: shop.fulfilment) acts: the request context
its commands and queries carry (sender tenant, identity, session), instead of
process:<name>. The kernel keeps it with the process, replicated to every partition.
The kernable kit calls it for every process it gives an identity and an API key. Returns
whether it changed (false: it acted so already). The key needs the process grant for
the process; Error::Status if the kernel refuses (NOT_FOUND: no such process).
Sourcepub fn app(&self, app: App) -> Result<AppHandle, Error>
pub fn app(&self, app: App) -> Result<AppHandle, Error>
An app made of whole domains: AppHandle::run applies the service’s membership (the
domains’ aggregates as workers, their read models and reactors as listeners, those that
check requests as middlewares; live ones are not listed, and the metadata is version
and description, when given, then the app’s other metadata; the domains’ business
processes), then runs one worker for all the aggregates and every listener, live ones
too, all in the app’s service, and registers the processes once the worker is ready
(Kernable::register_process; the key then needs the process grant for them).
Example: kernable.app(App::new().service("shop").version("1.0.0").domain(&shop_domain))?.run().await?.
Every start applies the membership, so the key needs the manage grant for the service.
One service is one app: two processes with the same service would replace each other’s
membership. Error::Config if neither the app nor the connection names a service.
Sourcepub async fn submit(&self, submit: Submit) -> Result<Outcome, Error>
pub async fn submit(&self, submit: Submit) -> Result<Outcome, Error>
Runs a command and returns its outcome: Outcome::Committed with the new events, or
Outcome::Rejected if a handler, a middleware or the kernel rejected it (a rejection
is Ok, not an error); the kernel rejects with unknown_history a command whose
aggregate holds events the serving deployment’s worker does not know (after a
rollback, see Manifest::deployment). By default it waits until every listener that counts has processed the
events; see Submit::wait. Error::NotSettled if they did not in time (the
command is committed), Error::Status if the kernel refuses the call (no grant,
unknown aggregate type, timeout). Example: kernable.submit(Submit::new("shop", "cart", "c1", "AddItem").data(json!({ "sku": "apple", "qty": 2 }))).await?.
A scheduled command (Submit::at) has no outcome yet: enqueue it
(Kernable::enqueue); submitting it is Error::Config. Submitted again by its ID
without at, it waits for the scheduled command’s outcome; Error::NotDue if the
kernel answers that it is not due yet.
Sourcepub async fn enqueue(&self, submit: Submit) -> Result<String, Error>
pub async fn enqueue(&self, submit: Submit) -> Result<String, Error>
Stores the command in the kernel’s queue and returns its ID without waiting for it to
run. Submit it again with the same id (Submit::id) to get the outcome; its wait
is ignored. With Submit::at, a scheduled command: it runs at that time, e.g. a
reminder in 24 hours, kernable.enqueue(Submit::command(Remind {}, "o1") .at(SystemTime::now() + Duration::from_secs(86_400))).await?; cancel it with
Kernable::cancel.
Sourcepub async fn cancel(&self, cancel: Cancel) -> Result<CancelOutcome, Error>
pub async fn cancel(&self, cancel: Cancel) -> Result<CancelOutcome, Error>
Cancels a scheduled command (Submit::at) before it is due: it completes as rejected
cancelled, which a submit of its ID answers from then on. Needs the submit grant for
the command’s type; middlewares check it as a cancel of that type (CheckKind::Cancel).
Returns CancelOutcome::Cancelled (also when it was cancelled before), or
CancelOutcome::Rejected with too_late (due, running or done already), not_found,
or a middleware’s code. Example: kernable.cancel(Cancel::new(&id)).await?.
Sourcepub async fn query<T: DeserializeOwned>(&self, query: Query) -> Result<T, Error>
pub async fn query<T: DeserializeOwned>(&self, query: Query) -> Result<T, Error>
Asks the read model that answers domain.type and returns its answer, deserialized as
T (serde_json::Value for any). Queries always go through the kernel, also within one
process. A refusal by the read model or a middleware is Error::Rejected; the
kernel’s own (no grant, no read model connected) is Error::Status; an answer that is
not a T is Error::Json. Example: let cart: Value = kernable.query(Query::new("shop", "GetCart").data(json!({ "id": "c1" }))).await?;
Sourcepub async fn ask<Q: QueryType>(
&self,
query: Q,
options: impl FnOnce(Query) -> Query,
) -> Result<Q::Answer, Error>
pub async fn ask<Q: QueryType>( &self, query: Q, options: impl FnOnce(Query) -> Query, ) -> Result<Q::Answer, Error>
Asks a query of a message type and returns its typed answer: kernable.ask(GetOrder { id }, |q| q.tenant(t)).await?; options sets what Query’s methods set.
Sourcepub fn subscribe<F, Fut>(
&self,
options: SubscribeOptions,
handler: F,
) -> Subscription
pub fn subscribe<F, Fut>( &self, options: SubscribeOptions, handler: F, ) -> Subscription
Streams committed events after options.after (backlog first, then live) to handler,
one at a time. Reconnects and resumes after the last handled event; if the handler
fails, that event is delivered again. Persist the position yourself to resume across
restarts. Needs the subscribe grant for the types. Unlike a listener, a subscription is
not registered with the kernel: nobody waits for it, and its events carry no vault values
(vault fields are null and listed in redacted). It runs in a Tokio task from the
call on; Subscription::stop ends it.
Trait Implementations§
Auto Trait Implementations§
impl !Freeze for Kernable
impl !RefUnwindSafe for Kernable
impl !UnwindSafe for Kernable
impl Forget for Kernable
impl Move for Kernable
impl Send for Kernable
impl Sync for Kernable
impl Unpin for Kernablewhere
Arc<Channels>: Unpin,
Arc<Partitions>: Unpin,
Arc<SigningKey>: Unpin,
*const u8 is !null: Unpin,
*const u8: Unpin,
Align8<*mut ()>: Unpin,
&'static Vtable: Unpin,
Arc<str>: Unpin,
*const LeafNode<String, String> is !null: Unpin,
Box<(String, String)>: Unpin,
Arc<RwLock<HashMap<String, Domain>>>: Unpin,
impl UnsafeUnpin for Kernablewhere
*const ArcInner<Channels> is !null: UnsafeUnpin,
PhantomData<ArcInner<Channels>>: UnsafeUnpin,
*const ArcInner<Partitions> is !null: UnsafeUnpin,
PhantomData<ArcInner<Partitions>>: UnsafeUnpin,
*const ArcInner<SigningKey> is !null: UnsafeUnpin,
PhantomData<ArcInner<SigningKey>>: UnsafeUnpin,
*const u8 is !null: UnsafeUnpin,
PhantomData<u8>: UnsafeUnpin,
*const u8: UnsafeUnpin,
Align8<*mut ()>: UnsafeUnpin,
&'static Vtable: UnsafeUnpin,
PhantomData<Ascii>: UnsafeUnpin,
*const ArcInner<str> is !null: UnsafeUnpin,
PhantomData<ArcInner<str>>: UnsafeUnpin,
*const LeafNode<String, String> is !null: UnsafeUnpin,
PhantomData<(Owned, LeafOrInternal)>: UnsafeUnpin,
PhantomData<Box<(String, String)>>: UnsafeUnpin,
*const ArcInner<RwLock<HashMap<String, Domain>>> is !null: UnsafeUnpin,
PhantomData<ArcInner<RwLock<HashMap<String, Domain>>>>: UnsafeUnpin,
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