pub struct MemoryEventStore { /* private fields */ }memory only.Expand description
The reference implementation of EventStore.
It exists for three reasons, in order of importance:
- 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;
- it makes this crate’s examples runnable, so the documentation cannot drift from the API;
- 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
impl MemoryEventStore
Sourcepub fn new() -> Self
pub fn new() -> Self
Creates an empty store with a fresh incarnation identifier.
Examples found in repository?
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}Sourcepub fn with_store_id(store_id: StoreId) -> Self
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”.
Sourcepub fn with_events(events: impl IntoIterator<Item = Event>) -> Self
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.
Sourcepub fn restore(
store_id: StoreId,
events: impl IntoIterator<Item = SequencedEvent>,
) -> Self
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());Sourcepub fn last_position(&self) -> Option<SequencePosition>
pub fn last_position(&self) -> Option<SequencePosition>
The position most recently assigned, or None if the store is empty.
Sourcepub fn snapshot(&self) -> Vec<SequencedEvent>
pub fn snapshot(&self) -> Vec<SequencedEvent>
A snapshot of every event held, in position order.
Examples found in repository?
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
impl Debug for MemoryEventStore
Source§impl Default for MemoryEventStore
impl Default for MemoryEventStore
Source§impl SendEventStore for MemoryEventStore
impl SendEventStore for MemoryEventStore
Source§type Error = MemoryStoreError
type Error = MemoryStoreError
Source§fn read(
&self,
query: &Query,
options: ReadOptions,
) -> impl Stream<Item = Result<SequencedEvent, Self::Error>> + Send
fn read( &self, query: &Query, options: ReadOptions, ) -> impl Stream<Item = Result<SequencedEvent, Self::Error>> + Send
Source§async 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>>
Auto Trait Implementations§
impl !Freeze for MemoryEventStore
impl RefUnwindSafe for MemoryEventStore
impl Send for MemoryEventStore
impl Sync for MemoryEventStore
impl Unpin for MemoryEventStore
impl UnsafeUnpin for MemoryEventStore
impl UnwindSafe for MemoryEventStore
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<TraitVariantBlanketType> EventStore for TraitVariantBlanketTypewhere
TraitVariantBlanketType: SendEventStore,
impl<TraitVariantBlanketType> EventStore for TraitVariantBlanketTypewhere
TraitVariantBlanketType: SendEventStore,
Source§type Error = <TraitVariantBlanketType as SendEventStore>::Error
type Error = <TraitVariantBlanketType as SendEventStore>::Error
Source§fn read(
&self,
query: &Query,
options: ReadOptions,
) -> impl Stream<Item = Result<SequencedEvent, <TraitVariantBlanketType as EventStore>::Error>>
fn read( &self, query: &Query, options: ReadOptions, ) -> impl Stream<Item = Result<SequencedEvent, <TraitVariantBlanketType as EventStore>::Error>>
Source§async fn append(
&self,
events: &[Event],
condition: Option<&AppendCondition>,
) -> Result<SequencePosition, AppendError<<TraitVariantBlanketType as EventStore>::Error>>
async fn append( &self, events: &[Event], condition: Option<&AppendCondition>, ) -> Result<SequencePosition, AppendError<<TraitVariantBlanketType as EventStore>::Error>>
Source§async fn head(
&self,
) -> Result<Option<SequencePosition>, <TraitVariantBlanketType as EventStore>::Error>
async fn head( &self, ) -> Result<Option<SequencePosition>, <TraitVariantBlanketType as EventStore>::Error>
None when it
holds nothing. Read moreSource§async fn contains_event_id(
&self,
id: EventId,
) -> Result<bool, <TraitVariantBlanketType as EventStore>::Error>
async fn contains_event_id( &self, id: EventId, ) -> Result<bool, <TraitVariantBlanketType as EventStore>::Error>
id. Read more