Skip to main content

Aggregate

Struct Aggregate 

Source
pub struct Aggregate<S> { /* private fields */ }
Expand description

An aggregate: how events change its state (apply) and which events a command produces (command). Handlers must be deterministic and free of side effects; they may run again. Create it with domain(...).aggregate(...); cloning gives another handle to the same aggregate. The registering methods return the aggregate, so they chain.

apply handlers change the state in place: cart_aggregate.apply("ItemAdded", |state, data: Item, _evt, _ctx| state.items += data.qty);. command handlers return the new events or a Rejected: cart_aggregate.command("AddItem", |state, data: Item, _cmd, _ctx| { if state.checked_out { return Err(Rejected::new("Cart is checked out")); } Ok(vec![NewEvent::new("ItemAdded", data)]) });. The type of data (here Item, any Deserialize type, or serde_json::Value) says how the payload is read; a payload that does not fit fails the command with handler_error. Handlers are synchronous and must not block.

Unique keys, facts and requirements reach across aggregates; the kernel checks them atomically when a command commits. unique declares a key computed from the state, which no two aggregates hold with the same value: customer_aggregate.unique("email", |s| s.email.clone(), Unique::tenant());. fact declares a condition of the state that other aggregates’ commands may require: vehicle_aggregate.fact("open", |s| !s.wound_up);. requires names the facts a command needs: account_aggregate.requires("OpenAccount", |_state, data: Open| [Requirement::new("funds", "vehicle", &data.vehicle_id, "open")]);. After every command, the worker sends the keys and facts of the new state, so an aggregate always holds exactly what its state yields.

Test without a kernel: cart_aggregate.fold([FoldEvent::new("ItemAdded", json!({ "qty": 2 }))], None)? returns the state, cart_aggregate.handle(&state, "AddItem", json!({ "qty": 1 }), &mut ctx) runs a command handler with a CommandContext::new, and cart_aggregate.index(&state)? and cart_aggregate.requirements(&state, "AddItem", json!({ "qty": 1 }))? compute the keys, facts and requirements.

Implementations§

Source§

impl<S: State> Aggregate<S>

Source

pub fn domain(&self) -> &Domain

The domain the aggregate belongs to.

Source

pub fn name(&self) -> &str

The aggregate’s name within its domain, e.g. cart.

Source

pub fn initial(&self) -> &S

The state before the first event.

Source

pub fn snapshot_every(&self, events: u64) -> Self

Sends a snapshot of the state every events events (default 100; 0 turns them off).

Source

pub fn schema(&self, schema: &str) -> Self

Version of the state format (default “1”). Change it when apply produces differently shaped state; older snapshots are then ignored and the state is rebuilt from the events.

Source

pub fn apply<D: DeserializeOwned>( &self, event_type: impl TypeKey<D>, f: impl Fn(&mut S, D, &EventMeta, &ApplyContext) + Send + Sync + 'static, ) -> Self

How an event of event_type changes the state: f(state, data, evt, ctx) changes state in place, or replaces it with *state = …. data is the event’s payload as D, upcast to the current version; evt is an EventMeta, ctx an ApplyContext. event_type is a name, or an event type’s constant (see crate::event), whose data D then is: order_aggregate.apply(OrderPlaced, |s, d, _evt, _ctx| ...). The same holds for command and requires. See Aggregate for an example.

Source

pub fn command<D: DeserializeOwned>( &self, command_type: impl TypeKey<D>, f: impl Fn(&S, D, &CommandMeta, &mut CommandContext) -> Result<Vec<NewEvent>, Rejected> + Send + Sync + 'static, ) -> Self

Which events a command_type command produces: f(state, data, cmd, ctx) returns them as Ok(vec![NewEvent::new(…)]), or Err(Rejected::new(…)). data is the command’s payload as D; cmd is a CommandMeta, ctx a CommandContext with the request context and deterministic now() and id(). See Aggregate for an example.

§Panics

If command_type starts with _reindex_: those are reserved for the built-in command of aggregates with unique keys or facts (see crate::reindex_type), and an aggregate cannot see the other aggregate types of its domain.

Source

pub fn unique<I: IntoIterator<Item = String>>( &self, name: &str, values: impl Fn(&S) -> I + Send + Sync + 'static, options: Unique<S>, ) -> Self

Declares a unique key named name: values(state) returns the values the aggregate holds in that state, as anything that iterates over Strings (values are strings by type; format numbers yourself): None (holds nothing), Some(value) (one value) or a Vec (several; repeated ones count once). No two aggregates of this type hold the same value of the key at the same time; a command that would make its aggregate hold a value another one holds is rejected with unique_taken. The value is compared as is: normalize it in values (e.g. lowercase an email); an empty string is a value like any other. options says where it is unique (within the tenant, or Unique::global) and whether the value is personal (Unique::personal). Example: customer_aggregate.unique("email", |s| s.email.as_ref().map(|e| e.to_lowercase()), Unique::tenant());.

The worker computes the keys from the state after every command, also one without events; values must be deterministic like apply, and one that panics fails the command with handler_error. An aggregate that had events before the key was declared holds none of its values until it runs a command: crate::Kernable::reindex runs one.

§Panics

If name is empty, longer than 128 bytes or holds . or *, or the aggregate declares a key named name already (a fact may have the same name).

Source

pub fn fact( &self, name: &str, holds: impl Fn(&S) -> bool + Send + Sync + 'static, ) -> Self

Declares a fact named name, which the aggregate holds while holds(state) is true. Commands of other aggregates of the tenant may require it (see Aggregate::requires). Computed like the keys (see Aggregate::unique). Example: vehicle_aggregate.fact("open", |s| !s.wound_up);.

§Panics

If name is empty, longer than 128 bytes or holds . or *, or the aggregate declares a fact named name already (a key may have the same name).

Source

pub fn requires<D: DeserializeOwned, I: IntoIterator<Item = Requirement>>( &self, command_type: impl TypeKey<D>, f: impl Fn(&S, D) -> I + Send + Sync + 'static, ) -> Self

Which facts of other aggregates of the tenant a command_type command requires: f(state, data) returns Requirements (anything that iterates over them), from the state before the command and its payload as D. The command commits only if each named aggregate holds its fact at that moment, otherwise it is rejected with requirement_missing; nothing is locked in between. Example: account_aggregate.requires("OpenAccount", |_state, data: Open| [Requirement::new("funds", "vehicle", &data.vehicle_id, "open")]);. A payload that is not a D, or an f that panics, fails the command with handler_error.

§Panics

If the aggregate has no command_type handler (declare it with Aggregate::command first).

Source

pub fn index(&self, state: &S) -> Result<Index, Error>

The unique keys and facts the aggregate holds in state, as the worker sends them after a command that leaves it in state; for tests without a kernel. Error::Config if a key or fact function panics.

Source

pub fn requirements( &self, state: &S, command_type: &str, data: impl Serialize, ) -> Result<Vec<Requirement>, Error>

The requirements of a command_type command with data on state (none if it declares none, see Aggregate::requires); for tests without a kernel. Error::Config if data is not the function’s D or it panics.

Source

pub fn fold( &self, history: impl IntoIterator<Item = FoldEvent>, from: Option<S>, ) -> Result<S, Error>

State after history, starting from from (default: the initial state). Events are upcast first; events without an apply are skipped. For tests without a kernel. Error::Config if an apply fails (also a payload that is not its D, or a panic) or an event’s schema is newer than known.

Source

pub fn handle( &self, state: &S, command_type: &str, data: impl Serialize, ctx: &mut CommandContext, ) -> Result<Vec<NewEvent>, Error>

Runs the command_type handler on state, e.g. in a unit test. The handler’s CommandMeta has the command ID of ctx, this aggregate’s domain and name, and an empty aggregate ID and tenant. Error::Rejected if the handler rejects the command, Error::Config if there is no handler for command_type or it fails otherwise.

Trait Implementations§

Source§

impl<S> Clone for Aggregate<S>

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<S> Forget for Aggregate<S>

§

impl<S> Freeze for Aggregate<S>
where *const ArcInner<AggregateInner<S>> is !null: Freeze, PhantomData<ArcInner<AggregateInner<S>>>: Freeze,

§

impl<S> Move for Aggregate<S>

§

impl<S> RefUnwindSafe for Aggregate<S>

§

impl<S> Send for Aggregate<S>
where Arc<AggregateInner<S>>: Send,

§

impl<S> Sync for Aggregate<S>
where Arc<AggregateInner<S>>: Sync,

§

impl<S> Unpin for Aggregate<S>
where Arc<AggregateInner<S>>: Unpin,

§

impl<S> UnsafeUnpin for Aggregate<S>
where *const ArcInner<AggregateInner<S>> is !null: UnsafeUnpin, PhantomData<ArcInner<AggregateInner<S>>>: UnsafeUnpin,

§

impl<S> UnwindSafe for Aggregate<S>
where Arc<AggregateInner<S>>: 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