Skip to main content

Kernable

Struct Kernable 

Source
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

Source

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

Source

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")?.

Source

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

Source

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.

Source

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.

Source

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

Source

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

Source

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.

Source

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

Source

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

Source

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.

Source

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.

Source

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.

Source

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

Source

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

Source

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.

Source

pub fn subscribe<F, Fut>( &self, options: SubscribeOptions, handler: F, ) -> Subscription
where F: Fn(StoredEvent) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<(), BoxError>> + Send + 'static,

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§

Source§

impl Clone for Kernable

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 !Freeze for Kernable

§

impl !RefUnwindSafe for Kernable

§

impl !UnwindSafe for Kernable

§

impl Forget for Kernable

§

impl Move for Kernable

§

impl Send for Kernable
where Arc<Channels>: Send, Arc<Partitions>: Send, Arc<SigningKey>: Send, RawVecInner: Send, Bytes: Send, Arc<str>: Send, NodeRef<Owned, String, String, LeafOrInternal>: Send, BoxRaw<(String, String)>: Send, Arc<RwLock<HashMap<String, Domain>>>: Send,

§

impl Sync for Kernable
where Arc<Channels>: Sync, Arc<Partitions>: Sync, Arc<SigningKey>: Sync, RawVecInner: Sync, Bytes: Sync, Arc<str>: Sync, NodeRef<Owned, String, String, LeafOrInternal>: Sync, BoxRaw<(String, String)>: Sync, Arc<RwLock<HashMap<String, Domain>>>: Sync,

§

impl Unpin for Kernable
where 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 Kernable
where *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> 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