Skip to main content

MemoryEventStore

Struct MemoryEventStore 

Source
pub struct MemoryEventStore { /* private fields */ }
Available on crate feature memory only.
Expand description

The reference implementation of EventStore.

It exists for three reasons, in order of importance:

  1. it is the oracle the conformance suite is validated against, so that a failing adapter is known to be the adapter’s fault and not the suite’s;
  2. it makes this crate’s examples runnable, so the documentation cannot drift from the API;
  3. it lets application code be written and tested before any real adapter exists.

It is not built for scale. read snapshots the matching events under the lock and streams from that snapshot, so a read never holds the lock across a poll — correct, and deliberately simple. Snapshot cost: payloads are Bytes, so a snapshot bumps refcounts rather than copying data — but each event still costs t + 2.

Positions are dense and start at 1. The specification permits gaps, so nothing may depend on that.

§Examples

The full DCB loop — read a decision model, then append conditioned on it:

use happenstance_core::{
    AppendCondition, Event, EventStore, MemoryEventStore, Query, QueryItem, Tags,
    read_decision_model,
};

let store = MemoryEventStore::new();

// "Has course c1 already been defined?"
let query = Query::from_item(QueryItem::new(
    ["CourseDefined"],
    Tags::from_pairs([("course", "c1")])?,
)?);

let (events, last_seen) = read_decision_model(&store, &query).await?;
assert!(events.is_empty());

let defined = Event::new("CourseDefined", &b"{\"capacity\":2}"[..])?
    .with_tags(Tags::from_pairs([("course", "c1")])?);

// Append only if nothing matching has appeared since we looked.
let condition = AppendCondition::new(query.clone()).after_every_guard_opt(last_seen);
store.append(&[defined.clone()], Some(&condition)).await?;

// Replaying the same command now fails — the course exists.
let err = store.append(&[defined], Some(&condition)).await.unwrap_err();
assert!(err.is_condition_violated());

Implementations§

Source§

impl MemoryEventStore

Source

pub fn new() -> Self

Creates an empty store with a fresh incarnation identifier.

Examples found in repository?
examples/course-subscriptions/src/main.rs (line 30)
29async fn main() -> Result<()> {
30    let store = MemoryEventStore::new();
31
32    println!("== defining course c1 with capacity 2 ==");
33    define_course(&store, "c1", 2).await?;
34    println!("   defined");
35
36    println!("\n== defining course c1 again ==");
37    match define_course(&store, "c1", 5).await {
38        Ok(()) => bail!("a duplicate course definition should have been rejected"),
39        Err(err) => println!("   rejected: {err}"),
40    }
41
42    println!("\n== subscribing s1 and s2 ==");
43    subscribe(&store, "c1", "s1").await?;
44    subscribe(&store, "c1", "s2").await?;
45    println!("   both subscribed");
46
47    println!("\n== subscribing s1 again ==");
48    match subscribe(&store, "c1", "s1").await {
49        Ok(()) => bail!("a duplicate subscription should have been rejected"),
50        Err(err) => println!("   rejected: {err}"),
51    }
52
53    println!("\n== subscribing s3, which would exceed capacity ==");
54    match subscribe(&store, "c1", "s3").await {
55        Ok(()) => bail!("exceeding capacity should have been rejected"),
56        Err(err) => println!("   rejected: {err}"),
57    }
58
59    println!("\n== s1 unsubscribes, freeing a seat ==");
60    unsubscribe(&store, "c1", "s1").await?;
61    subscribe(&store, "c1", "s3").await?;
62    println!("   s3 subscribed into the freed seat");
63
64    println!("\n== final log ==");
65    for event in store.snapshot() {
66        println!(
67            "   {:>3}  {:<22} {:?}",
68            event.position.get(),
69            event.event_type().as_str(),
70            event.tags()
71        );
72    }
73
74    Ok(())
75}
Source

pub fn with_store_id(store_id: StoreId) -> Self

Creates an empty store with a caller-chosen incarnation.

Exists for the rule that a reopened store must not reissue an identity: “reopening” an in-memory store is constructing a new one, and the rule needs to distinguish “the same store again” from “a different store”.

Source

pub const fn store_id(&self) -> StoreId

The incarnation this store mints identities under.

Source

pub fn with_events(events: impl IntoIterator<Item = Event>) -> Self

Creates a store pre-loaded with events, assigned dense positions from 1.

Useful for arranging test fixtures without going through append.

Source

pub fn restore( store_id: StoreId, events: impl IntoIterator<Item = SequencedEvent>, ) -> Self

Reconstructs a store from a snapshot of what a durable medium held.

The counterpart of snapshot, and deliberately not with_events: that one arranges a store, assigning fresh positions, identities and a time, which is what a caller wants when seeding a fixture. This one reopens one, preserving every store-assigned fact on every event — which is what a real adapter’s open does, because it reads rows it wrote rather than re-accepting events. A store whose reopen restamps hands every auditor the time of the last restart.

§Examples
let store = MemoryEventStore::new();
store.append(&[Event::new("Issued", &b"{}"[..])?], None).await?;

// What a durable medium would have kept, and what reopening finds.
let reopened = MemoryEventStore::restore(store.store_id(), store.snapshot());
assert_eq!(reopened.snapshot(), store.snapshot());
Source

pub fn len(&self) -> usize

The number of events held.

Source

pub fn is_empty(&self) -> bool

Whether the store is empty.

Source

pub fn last_position(&self) -> Option<SequencePosition>

The position most recently assigned, or None if the store is empty.

Source

pub fn snapshot(&self) -> Vec<SequencedEvent>

A snapshot of every event held, in position order.

Examples found in repository?
examples/course-subscriptions/src/main.rs (line 65)
29async fn main() -> Result<()> {
30    let store = MemoryEventStore::new();
31
32    println!("== defining course c1 with capacity 2 ==");
33    define_course(&store, "c1", 2).await?;
34    println!("   defined");
35
36    println!("\n== defining course c1 again ==");
37    match define_course(&store, "c1", 5).await {
38        Ok(()) => bail!("a duplicate course definition should have been rejected"),
39        Err(err) => println!("   rejected: {err}"),
40    }
41
42    println!("\n== subscribing s1 and s2 ==");
43    subscribe(&store, "c1", "s1").await?;
44    subscribe(&store, "c1", "s2").await?;
45    println!("   both subscribed");
46
47    println!("\n== subscribing s1 again ==");
48    match subscribe(&store, "c1", "s1").await {
49        Ok(()) => bail!("a duplicate subscription should have been rejected"),
50        Err(err) => println!("   rejected: {err}"),
51    }
52
53    println!("\n== subscribing s3, which would exceed capacity ==");
54    match subscribe(&store, "c1", "s3").await {
55        Ok(()) => bail!("exceeding capacity should have been rejected"),
56        Err(err) => println!("   rejected: {err}"),
57    }
58
59    println!("\n== s1 unsubscribes, freeing a seat ==");
60    unsubscribe(&store, "c1", "s1").await?;
61    subscribe(&store, "c1", "s3").await?;
62    println!("   s3 subscribed into the freed seat");
63
64    println!("\n== final log ==");
65    for event in store.snapshot() {
66        println!(
67            "   {:>3}  {:<22} {:?}",
68            event.position.get(),
69            event.event_type().as_str(),
70            event.tags()
71        );
72    }
73
74    Ok(())
75}

Trait Implementations§

Source§

impl Debug for MemoryEventStore

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for MemoryEventStore

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl SendEventStore for MemoryEventStore

Source§

type Error = MemoryStoreError

How this adapter fails for its own reasons. Read more
Source§

fn read( &self, query: &Query, options: ReadOptions, ) -> impl Stream<Item = Result<SequencedEvent, Self::Error>> + Send

Reads the events matching query, in the order options asks for. Read more
Source§

async fn append( &self, events: &[Event], condition: Option<&AppendCondition>, ) -> Result<SequencePosition, AppendError<Self::Error>>

Atomically appends events, rejecting the write if condition matches. Read more
Source§

async fn head(&self) -> Result<Option<SequencePosition>, Self::Error>

The highest position currently visible in the store, or None when it holds nothing. Read more
Source§

async fn contains_event_id(&self, id: EventId) -> Result<bool, Self::Error>

Whether this store holds an event with id. Read more

Auto Trait Implementations§

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<TraitVariantBlanketType> EventStore for TraitVariantBlanketType
where TraitVariantBlanketType: SendEventStore,

Source§

type Error = <TraitVariantBlanketType as SendEventStore>::Error

How this adapter fails for its own reasons. Read more
Source§

fn read( &self, query: &Query, options: ReadOptions, ) -> impl Stream<Item = Result<SequencedEvent, <TraitVariantBlanketType as EventStore>::Error>>

Reads the events matching query, in the order options asks for. Read more
Source§

async fn append( &self, events: &[Event], condition: Option<&AppendCondition>, ) -> Result<SequencePosition, AppendError<<TraitVariantBlanketType as EventStore>::Error>>

Atomically appends events, rejecting the write if condition matches. Read more
Source§

async fn head( &self, ) -> Result<Option<SequencePosition>, <TraitVariantBlanketType as EventStore>::Error>

The highest position currently visible in the store, or None when it holds nothing. Read more
Source§

async fn contains_event_id( &self, id: EventId, ) -> Result<bool, <TraitVariantBlanketType as EventStore>::Error>

Whether this store holds an event with id. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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, 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.