pub trait EventStore {
type Error: Error + 'static;
// Required methods
fn read(
&self,
query: &Query,
options: ReadOptions,
) -> impl Stream<Item = Result<SequencedEvent, Self::Error>>;
async fn append(
&self,
events: &[Event],
condition: Option<&AppendCondition>,
) -> Result<SequencePosition, AppendError<Self::Error>>;
async fn head(&self) -> Result<Option<SequencePosition>, Self::Error>;
async fn contains_event_id(&self, id: EventId) -> Result<bool, Self::Error>;
}Expand description
A DCB-compliant event store.
Two traits, one set of doc attributes. trait_variant derives
SendEventStore from EventStore and copies this block onto it, so
every sentence here is written to hold on whichever of the two pages you
opened. EventStore states no Send requirement and is what generic code
binds; SendEventStore adds it and hands back EventStore free. The
module documentation has the reason the split exists.
§Implementing this trait
Implement SendEventStore where the store can be shared across threads,
which is every native adapter; implement EventStore only where Send
cannot be had at all, as on wasm32.
The specification’s requirements are obligations on the implementer, and
happenstance-testkit checks every one of
them. An adapter is not finished until it passes that suite.
For a runnable end-to-end example see MemoryEventStore, which the memory
feature provides. It is not linked because this item exists without that
feature and the link would not resolve (D13).
§Deletion is outside the port
This port has no delete, truncate, compact, redact or tombstone method, and
no 1.x release adds one. A store that has lost events by some means outside
the port still owes every promise about the events it holds. It never
reuses a position, and Query::all means every event it holds
(specification ES-38). What a condition over removed history does is on
AppendCondition: it passes vacuously (ES-40). Nothing here reports what
a store no longer holds.
§Writing generic code over a store
Bound on EventStore, not SendEventStore, unless you need to cross a
thread boundary:
use happenstance_core::{EventStore, Query, ReadOptions, collect};
async fn count_all<S: EventStore>(store: &S) -> Result<usize, S::Error> {
let events = collect(store.read(&Query::all(), ReadOptions::new())).await?;
Ok(events.len())
}Required Associated Types§
Sourcetype Error: Error + 'static
type Error: Error + 'static
How this adapter fails for its own reasons.
Append-condition violations do not belong here — they are reported
through AppendError::ConditionViolated, so that callers can tell
“retry the decision” from “something broke” without knowing which
adapter they hold.
Required Methods§
Sourcefn read(
&self,
query: &Query,
options: ReadOptions,
) -> impl Stream<Item = Result<SequencedEvent, Self::Error>>
fn read( &self, query: &Query, options: ReadOptions, ) -> impl Stream<Item = Result<SequencedEvent, Self::Error>>
Reads the events matching query, in the order options asks for.
Evaluated against one state sampled no later than the first poll; laziness
is permitted, never required. An adapter issuing more than one statement per
read must capture a position ceiling no later than that poll and bound every
later statement by it. Failures surface as Err items rather than up front.
This method is not async because putting the stream at the top level of the
return type is what allows SendEventStore to mark the stream Send, not
merely the future that produces it, and it is what lets an adapter stream a
million-event replay without buffering it. Use collect for a Vec.
§Ordering
Ascending by SequencePosition unless
ReadOptions::backwards is set.
ReadOptions::from is inclusive.
Sourceasync fn append(
&self,
events: &[Event],
condition: Option<&AppendCondition>,
) -> Result<SequencePosition, AppendError<Self::Error>>
async fn append( &self, events: &[Event], condition: Option<&AppendCondition>, ) -> Result<SequencePosition, AppendError<Self::Error>>
Atomically appends events, rejecting the write if condition matches.
Returns the position assigned to the last appended event. The specification does not require this, but it is what checkpointing and reporting need, and only the store knows it.
It is not a sound after for a follow-up condition unless the
caller has already read up to it. Positions may have gaps and another
writer may hold one below this value that this caller never saw, so a
condition anchored here silently excludes exactly the events a condition
exists to catch. The sound after comes from a read:
read_decision_model returns the last position actually observed,
which is what
AppendCondition::after_every_guard_opt
expects.
§Atomicity
Either every event lands or none does. A rejected append must leave the store byte-identical.
§Cancellation
Dropping this future does not cancel the append. An adapter MAY
commit a batch whose future was dropped, and a caller MUST NOT read a
dropped future as evidence that nothing landed. There is deliberately no
error value for it — a dropped future produces no Result at all, so
the outcome has nowhere to go, and the contract states the absence of a
promise rather than inventing a variant that could never be delivered.
What is promised is # Atomicity, which bounds what the silence can
cost: whichever the adapter does, the batch is applied in full or not at
all and never in part. Each adapter MUST state which of the two it does.
At the edge this is the ordinary termination path rather than an exotic
one — a client disconnect, a CPU limit, a Durable Object or pod
eviction. The shape that looks cancellation-safe and is not: a pooled
rusqlite adapter doing its work in spawn_blocking. Dropping the
JoinHandle does not cancel the closure, the COMMIT runs, the caller
is told nothing, and an operator retries a payment that already went
out.
§Resolving an unknown outcome
A conditional append is at-most-once under verbatim reissue. Where
the events being appended are themselves matched by the condition’s
query, reissuing the identical batch resolves what a dropped future left
unknown: AppendError::ConditionViolated means the first attempt
landed, Ok means it had not and now has. Either way the store holds
exactly one copy. No identity, no idempotency key and no extra operation
— the guarantee falls out of the condition the caller already wrote.
It has three limits, stated here because a guarantee whose limits are unstated gets read as universal:
- An unconditional append has no such property. Reissuing it appends a second copy, and nothing in this port can prevent that.
- A conditional append whose query does not match its own events has
none either: conditioning on
CourseCapacityChangedwhile appendingStudentSubscribedleaves the reissue indistinguishable from a first attempt. That is the common shape, not a corner — it is what a decision that reads one thing and writes another looks like. - The reissue must be verbatim. This is not the
ConditionViolatedre-decide path, where the correct response is to re-read, rebuild the decision model and produce different events. The two arrive as the same error value and mean opposite things — one says “your write already happened”, the other says “the world moved, decide again” — and collapsing them is the mistake this section exists to prevent.
A caller needing at-most-once for the second and third shapes supplies
its own dedup in the domain. A natural key in the tags is the mechanism,
and it is queryable; an identity buried in
Event::metadata is not, because a query
matches on type and tags only.
§Errors
AppendError::NoEventswheneventsis empty. The specification defines a batch as non-empty, so there is no position to return. This check MUST precede the condition check: an empty batch is the caller’s own bug and retrying cannot fix it, whereasConditionViolatedmeans “retry”, so reporting the violation for an empty batch puts a correct client into a loop that never terminates.AppendError::ConditionViolatedwhen the store already holds an event matchingcondition. This is routine under contention: rebuild the decision model and retry.AppendError::Busywhen the store refused for a transient reason before the batch took any effect. Nothing was written, so taking the decision again is safe. An adapter that cannot vouch for that reportsStoreinstead.AppendError::Storefor adapter-specific failures, including any outcome the adapter cannot vouch for.
Sourceasync fn head(&self) -> Result<Option<SequencePosition>, Self::Error>
async fn head(&self) -> Result<Option<SequencePosition>, Self::Error>
The highest position currently visible in the store, or None when it
holds nothing.
§Why this is required rather than provided
A provided body would have to be
read(&Query::all(), backwards().limit(1)), which is a scan on any store
that cannot push the ordering down, and a blanket implementation cannot
be overridden per adapter. A SQLite adapter wants SELECT max(position).
The cost of required is a body in every implementation; the cost of
provided is a fast path no adapter can install.
There is a second reason, and it is the one that settles it: the only
provided form holds &self across an await, which needs
where Self: Sync — and the !Send edge adapter that the bare flavour
exists for is not Sync, so the convenience body would fail to compile
for exactly the adapter it was meant to spare.
§What it is for
Answering “am I caught up?” — a projection runner compares its checkpoint with this for equality or ordering. Do not subtract two positions and read the difference as a count of outstanding events: positions are an opaque ordering key and the specification permits gaps, so the difference is not a number of anything.
§Errors
Returns the adapter’s error if the head cannot be determined.
Sourceasync fn contains_event_id(&self, id: EventId) -> Result<bool, Self::Error>
async fn contains_event_id(&self, id: EventId) -> Result<bool, Self::Error>
Whether this store holds an event with id.
The membership question a replicating peer must be able to ask without
constructing a Query and without parsing any payload — which is why
EventId is deliberately outside the query language.
§Why every store can answer this cheaply
Every store already holds at most one event per EventId, so the index
that answers this exists wherever the contract is honoured, and no
adapter is taxed with a new one. A store that has never ingested anything
can answer without an index at all: if the identifier’s store half is not
its own incarnation the answer is false, and if it is, the question
reduces to whether that position exists.
false means this store does not hold the event. It does not say
whether the store never held it or no longer does.
§Errors
Returns the adapter’s error if the lookup fails.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".