Skip to main content

Crate happenstance

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. Json is on by default; Postcard and Cbor arrive 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 its EventType and Tags. Its page carries the decode guard this first program leaves out.
  • DecisionModel — folds read events into decidable state and produces the matching Query, through Boundary. Its item page carries the program above over two variants. Composing several into one query — put them in a tuple, which is a Boundary too — is what makes a dynamic consistency boundary dynamic.
  • The command loop — read, decide, append, retry on ConditionViolated or Busy, bounded by a Retry you 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. apply is async (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.

featurewhat it turns on
json (default)Json — JSON payloads, readable in a console
postcardPostcard — compact binary, not self-describing
cborCbor — binary, and self-describing where postcard is not
std (default)the standard library, forwarded to the contract
memory (default)MemoryEventStore, forwarded to the contract
serdethe 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.
testingjson and memory
Given, when, then — a decision model tested without a database.

Structs§

AppendCondition
The consistency boundary an append is checked against.
Cborcbor
CBOR payloads: binary, and self-describing where postcard is not.
Chunk
How many events the projection runner applies between begin and commit.
Committed
What a committed command did: where it landed, and how hard it was.
ConditionViolated
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.
EventParts
The owned pieces of an Event, from Event::into_parts.
EventType
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.
Jsonjson
JSON payloads, on by default. Readable in a database console.
MemoryEventStorememory
The reference implementation of EventStore.
MemoryProjectionBatchmemory
An in-flight write against a MemoryProjectionStore.
MemoryProjectionStorememory
The reference implementation of ProjectionStore.
Postcardpostcard
Compact binary payloads, for an edge deployment that pays per byte.
Progressed
How far a run got, and how much it applied.
ProjectionId
Names a read model within a projection store.
QueryItem
One clause of a Query.
ReadOptions
How to traverse the matched events.
RecordedAt
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.
SequencePosition
An event’s place in the store’s total order.
SequencedEvent
An Event together 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§

AppendError
Why an append failed.
ApplyFailure
An event that could not be applied, as on_error is 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.
CodecError
Why a payload could not be turned into bytes, or bytes into a value.
CommandError
Why a command did not commit.
CommandOutcome
What a command did, when it did not fail.
CommitError
Why a commit failed.
InvalidCheckpointId
Why a checkpoint id could not be derived.
InvalidEventType
An EventType failed validation.
InvalidProjectionId
A ProjectionId failed validation (VT-35).
InvalidQuery
A Query or QueryItem failed validation.
InvalidTag
A Tag failed validation.
MemoryProjectionStoreErrormemory
MemoryProjectionStore’s error type, which is uninhabited.
MemoryStoreErrormemory
MemoryEventStore’s error type, which is uninhabited.
Policy
What the runner does with an event the projection could not take.
ProjectionError
Why a projection run stopped.
Query
A filter over the log.
ResetError
Why a reset failed.
StoreLimit
Which capacity limit an append exceeded.
ViewError
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 data payload 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.
ConvergentProjection
A projection whose read model is the same in any ingest order.
DecisionModel
Read events folded into state a decision can be taken on.
DomainEvent
A Rust type’s mapping to the event types and tags a store understands.
EventStore
A DCB-compliant event store.
Projection
A read model an application builds from its own decoded events.
ProjectionStore
A store that holds read models and their replay checkpoints.
SendEventStore
A DCB-compliant event store.
SendProjection
A read model an application builds from its own decoded events.
SendProjectionStore
A store that holds read models and their replay checkpoints.

Functions§

checkpoint_id
The id run_projection reads and commits this projection’s checkpoint under.
collect
Drains a read stream into a Vec, stopping at the first error.
commitjson
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 query and reports both the matching events and the position to use in a follow-up AppendCondition.
run_fan_out
Streams one read of the log into N views, each as run_projection would.
run_projection
Streams the events a projection nominates and applies them in chunks.