Crate happenstance
Expand description
DCB-compliant event sourcing, with batteries.
Answers:
tutorial— How do I decide, write, and hold an invariant?
Guide-level documentation is the happenstance guide, which starts from events
and works up to dynamic consistency boundaries. Its source is docs/.
One enum of events, one struct that folds them, and one call that reads, decides, appends and retries:
use happenstance::{bytes::Bytes, Codec, CodecError, DecisionModel};
use happenstance::{DomainEvent, EventType, MemoryEventStore, Retry};
use happenstance::{Tags, commit};
use std::{convert::Infallible, error::Error};
#[derive(serde::Serialize, serde::Deserialize)]
enum Seat { Taken }
const SEAT_TAKEN: EventType = EventType::from_static("SeatTaken");
impl DomainEvent for Seat {
const EVENT_TYPES: &'static [EventType] = &[SEAT_TAKEN];
fn event_type(&self) -> EventType { SEAT_TAKEN }
fn tags(&self) -> Tags { Tags::empty() }
fn encode<C: Codec>(&self, c: &C) -> Result<Bytes, CodecError> {
c.encode(self)
}
fn decode<C: Codec>(c: &C, _t: &EventType, d: &Bytes)
-> Result<Self, CodecError> { c.decode(d) }
}
#[derive(Clone)]
struct Seats { scope: Tags, taken: u32 }
impl DecisionModel for Seats {
type Event = Seat;
fn scope(&self) -> &Tags { &self.scope }
fn apply(&mut self, event: Seat) {
match event { Seat::Taken => self.taken += 1 }
}
}
let store = MemoryEventStore::new();
let seats = Seats { scope: Tags::empty(), taken: 0 };
let retry = Retry::attempts(core::num::NonZeroU32::new(3).unwrap());
let take = |_: &Seats| Ok::<_, Infallible>(vec![Seat::Taken]);
let done = commit(&store, seats, retry, take).await?;
assert_eq!(done.committed().expect("a seat was taken").attempts, 1);To watch that boundary refuse a write instead, in three runnable steps: the opening encounter.
§Encoding lives here
The discriminator is encoding. happenstance_core deals in opaque
bytes on purpose — that is what keeps adapters free of domain knowledge and
lets replication forward events without deserialising them. Anything that
knows how a payload is shaped belongs here, so the contract crate never
grows a serde dependency in its default feature set.
ADR-0006
is why the bare name is here: an application programs against typed events
and decision models, so the crate it reaches for first should be the one it
uses. happenstance-core is what adapter authors pin, and they are the
ones who read version numbers carefully.
Everything the contract crate exports is available here under the same paths.
§The vocabulary
Every term below is an item you can use today. The last one asks for a feature first, and the feature is named after what is unfinished beneath it rather than after what it turns on.
Codec— payload encoding.Jsonis on by default;PostcardandCborarrive with the features below. Events carry a codec tag, so one store can hold more than one encoding at a time, which is what makes a payload migration possible.DomainEvent— a Rust type’s mapping to itsEventTypeandTags. Its page carries thedecodeguard this first program leaves out.DecisionModel— folds read events into decidable state and produces the matchingQuery, throughBoundary. Its item page carries the program above over two variants. Composing several into one query — put them in a tuple, which is aBoundarytoo — is what makes a dynamic consistency boundary dynamic.- The command loop — read, decide, append, retry on
ConditionViolatedorBusy, bounded by aRetryyou pass in and re-deciding from a pristine model on every attempt. Its own page carries the policy. - The typed projection runner — decoded events into
a read model, in chunks, with the rows and the checkpoint moving in one
commit.
applyisasync(ADR-0074), so it can await a live batch. One call drives one projection, or N views over one read, and never buffers the replay.
§Features
Every one of them adds. Turning any off leaves the rest compiling, and the three the contract crate also has mean there exactly what they mean here.
| feature | what it turns on |
|---|---|
json (default) | Json — JSON payloads, readable in a console |
postcard | Postcard — compact binary, not self-describing |
cbor | Cbor — binary, and self-describing where postcard is not |
std (default) | the standard library, forwarded to the contract |
memory (default) | MemoryEventStore, forwarded to the contract |
serde | the contract’s wire-format derives, for replication |
§Testing in memory
Does the domain model work and pick a database are two decisions, and
only the first is due now. happenstance::testing answers
it: given(model).event(a)?.when(..).await? folds your boundary over an
in-memory store and hands back a Decision to assert on — no connection
string, no fixture, one await.
For a store that misbehaves on demand — an append refused without naming
the conflict, positions that are not dense — add happenstance-testkit as a
dev-dependency. A test double belongs in a second crate rather than in an
application’s own dependency graph.
Adapter authors should depend on happenstance_core
directly rather than on this crate: it is the smaller semver surface, and
it is the one the conformance suite is written against.
Re-exports§
pub use bytes;pub use futures_core;pub use happenstance_core;
Modules§
- projection
- The projection store port.
- store
- The event store port, in two flavours.
- testing
jsonandmemory - Given, when, then — a decision model tested without a database.
Structs§
- Append
Condition - The consistency boundary an append is checked against.
- Cbor
cbor - CBOR payloads: binary, and self-describing where postcard is not.
- Chunk
- How many events the projection runner applies between
beginandcommit. - Committed
- What a committed command did: where it landed, and how hard it was.
- Condition
Violated - The specification-defined outcome of an append that was rejected because the
store already held an event matching the
AppendCondition. - Delivered
- One decoded event handed to
Projection::apply, and its identity. - Event
- An event on its way into the store.
- EventId
- A store-assigned event identity: which store first accepted the event, and at what position it did so.
- Event
Parts - The owned pieces of an
Event, fromEvent::into_parts. - Event
Type - The identifier a store filters on:
CourseDefined,StudentSubscribed, and so on. - FanOut
- What one fan-out run did to each view, and to the shared read.
- Guard
- One clause of an
AppendCondition: a query and the boundary it is checked from. - Json
json - JSON payloads, on by default. Readable in a database console.
- Memory
Event Store memory - The reference implementation of
EventStore. - Memory
Projection Batch memory - An in-flight write against a
MemoryProjectionStore. - Memory
Projection Store memory - The reference implementation of
ProjectionStore. - Postcard
postcard - Compact binary payloads, for an edge deployment that pays per byte.
- Progressed
- How far a run got, and how much it applied.
- Projection
Id - Names a read model within a projection store.
- Query
Item - One clause of a
Query. - Read
Options - How to traverse the matched events.
- Recorded
At - When the store accepted an event: milliseconds since the Unix epoch, UTC.
- Retry
- How many times a command may be attempted before it gives up.
- Sequence
Position - An event’s place in the store’s total order.
- Sequenced
Event - An
Eventtogether with the three facts its store assigned it. - StoreId
- Identifies one incarnation of a store’s persistent state.
- Tag
- A single domain-specific label attached to an
Event. - Tags
- A canonical set of
Tags: always sorted, always deduplicated.
Enums§
- Append
Error - Why an append failed.
- Apply
Failure - An event that could not be applied, as
on_erroris handed it. - Authority
- What a commit claims about the rows it leaves behind.
- Checkpoint
- Where a projection has been brought to, and whether its rows can be trusted.
- Codec
Error - Why a payload could not be turned into bytes, or bytes into a value.
- Command
Error - Why a command did not commit.
- Command
Outcome - What a command did, when it did not fail.
- Commit
Error - Why a
commitfailed. - Invalid
Checkpoint Id - Why a checkpoint id could not be derived.
- Invalid
Event Type - An
EventTypefailed validation. - Invalid
Projection Id - A
ProjectionIdfailed validation (VT-35). - Invalid
Query - A
QueryorQueryItemfailed validation. - Invalid
Tag - A
Tagfailed validation. - Memory
Projection Store Error memory MemoryProjectionStore’s error type, which is uninhabited.- Memory
Store Error memory MemoryEventStore’s error type, which is uninhabited.- Policy
- What the runner does with an event the projection could not take.
- Projection
Error - Why a projection run stopped.
- Query
- A filter over the log.
- Reset
Error - Why a
resetfailed. - Store
Limit - Which capacity limit an append exceeded.
- View
Error - Why one view of a fan-out run stopped.
Constants§
- MAX_
CHECKPOINT_ NAME_ LEN - The longest projection name a derived checkpoint id can carry.
- MAX_
EVENT_ TYPE_ LEN - Longest permitted event type, in bytes.
- MAX_
PROJECTION_ ID_ LEN - Longest permitted projection identifier, in bytes.
- MAX_
TAG_ LEN - Longest permitted tag, in bytes.
- MIN_
SUPPORTED_ EVENTS_ PER_ BATCH - Smallest number of events in one append every store must accept.
- MIN_
SUPPORTED_ EVENT_ DATA_ LEN - Smallest
datapayload every store must accept, in bytes. - MIN_
SUPPORTED_ QUERY_ ITEMS - Smallest number of query items every store must be able to evaluate.
- MIN_
SUPPORTED_ TAGS_ PER_ BATCH - Smallest total number of tags, summed over every event of one append, every store must accept (VT-36).
- MIN_
SUPPORTED_ TAGS_ PER_ EVENT - Smallest number of tags on one event every store must accept.
Traits§
- Boundary
- What a command loop consumes: a decision model, or a tuple of them.
- Codec
- Turns a serialisable value into payload bytes, and bytes back into a value.
- Convergent
Projection - A projection whose read model is the same in any ingest order.
- Decision
Model - Read events folded into state a decision can be taken on.
- Domain
Event - A Rust type’s mapping to the event types and tags a store understands.
- Event
Store - A DCB-compliant event store.
- Projection
- A read model an application builds from its own decoded events.
- Projection
Store - A store that holds read models and their replay checkpoints.
- Send
Event Store - A DCB-compliant event store.
- Send
Projection - A read model an application builds from its own decoded events.
- Send
Projection Store - A store that holds read models and their replay checkpoints.
Functions§
- checkpoint_
id - The id
run_projectionreads and commits this projection’s checkpoint under. - collect
- Drains a
readstream into aVec, stopping at the first error. - commit
json - Reads, decides, appends under a condition, and retries on contention.
- commit_
with - The command loop, with a codec of your own.
- read_
decision_ model - Reads
queryand reports both the matching events and the position to use in a follow-upAppendCondition. - run_
fan_ out - Streams one read of the log into N views, each as
run_projectionwould. - run_
projection - Streams the events a projection nominates and applies them in chunks.