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>
impl<S: State> Aggregate<S>
Sourcepub fn snapshot_every(&self, events: u64) -> Self
pub fn snapshot_every(&self, events: u64) -> Self
Sends a snapshot of the state every events events (default 100; 0 turns them off).
Sourcepub fn schema(&self, schema: &str) -> Self
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.
Sourcepub fn apply<D: DeserializeOwned>(
&self,
event_type: impl TypeKey<D>,
f: impl Fn(&mut S, D, &EventMeta, &ApplyContext) + Send + Sync + 'static,
) -> Self
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.
Sourcepub 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
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.
Sourcepub fn unique<I: IntoIterator<Item = String>>(
&self,
name: &str,
values: impl Fn(&S) -> I + Send + Sync + 'static,
options: Unique<S>,
) -> Self
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).
Sourcepub fn fact(
&self,
name: &str,
holds: impl Fn(&S) -> bool + Send + Sync + 'static,
) -> Self
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).
Sourcepub fn requires<D: DeserializeOwned, I: IntoIterator<Item = Requirement>>(
&self,
command_type: impl TypeKey<D>,
f: impl Fn(&S, D) -> I + Send + Sync + 'static,
) -> Self
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).
Sourcepub fn index(&self, state: &S) -> Result<Index, Error>
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.
Sourcepub fn requirements(
&self,
state: &S,
command_type: &str,
data: impl Serialize,
) -> Result<Vec<Requirement>, Error>
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.
Sourcepub fn fold(
&self,
history: impl IntoIterator<Item = FoldEvent>,
from: Option<S>,
) -> Result<S, Error>
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.
Sourcepub fn handle(
&self,
state: &S,
command_type: &str,
data: impl Serialize,
ctx: &mut CommandContext,
) -> Result<Vec<NewEvent>, Error>
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§
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>where
Atomic<usize>: RefUnwindSafe,
RwLock<HashMap<String, EventDef>>: RefUnwindSafe,
RwLock<HashMap<String, VaultFields>>: RefUnwindSafe,
RwLock<HashMap<String, Option<QueryTarget>>>: RefUnwindSafe,
RwLock<Vec<Arc<dyn Runnable>>>: RefUnwindSafe,
RwLock<Vec<Listener>>: RefUnwindSafe,
RwLock<Vec<Process>>: RefUnwindSafe,
RwLock<HashSet<String>>: RefUnwindSafe,
S: RefUnwindSafe,
Mutex<(u64, String)>: RefUnwindSafe,
RwLock<HashMap<String, Arc<dyn Fn(&mut S, Value, &EventMeta, &ApplyContext) -> Result<(), Box<dyn Error + Sync + Send>> + Sync + Send>>>: RefUnwindSafe,
RwLock<HashMap<String, Arc<dyn Fn(&S, Value, &CommandMeta, &mut CommandContext) -> Result<Vec<NewEvent>, Failure> + Sync + Send>>>: RefUnwindSafe,
RwLock<Vec<KeyDef<S>>>: RefUnwindSafe,
RwLock<Vec<(String, Arc<dyn Fn(&S) -> bool + Sync + Send>)>>: RefUnwindSafe,
RwLock<HashMap<String, Arc<dyn Fn(&S, Value) -> Result<Vec<Requirement>, Failure> + Sync + Send>>>: RefUnwindSafe,
impl<S> Send for Aggregate<S>
impl<S> Sync for Aggregate<S>
impl<S> Unpin for Aggregate<S>
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> 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