Skip to main content

WithholdingStore

Struct WithholdingStore 

pub struct WithholdingStore<S> { /* private fields */ }
Expand description

Wraps a store so that it holds only part of its own log: a suffix, or a scattered subset with survivors between the holes.

Rejects: a reader that infers completeness from a port value. A pruned store and a young store are the same value at every seam the port exposes (CF-27, ES-39), so a projection runner or an ingest path that reads “the log starts here” from head, from the lowest position it read, or from a condition that passed, is wrong, and this is the store that shows it.

Every event it withholds behaves as removed: read never yields it, head skips it, contains_event_id answers false for it, and an append condition that only it would violate passes. What it withholds is reported through withheld, its own inherent method, and never through an EventStore method (ADR-0028).

With nothing withheld it is transparent: every call is delegated with the same arguments. Cloning it produces a second handle onto the same withheld set.

Cost. Each conditional append made while anything is withheld first reads the inner log up to the highest withheld position, which is what an instrument can afford and an adapter could not.

§What it cannot model

  • Ingest deduplication. The inner store still holds what is withheld, so an ingest path over the inner store would deduplicate a re-delivered withheld event where a physically pruned store would admit it again.
  • Position reuse. The inner store forgets nothing, so the instrument never reuses a position (ES-38) by delegation. That rule’s teeth are the real adapters, removing outside the port.

It implements the bare EventStore flavour only, as FaultyStore does, and for the same coherence reason a Send sibling would be a second type.

§Examples

use happenstance_core::{AppendCondition, Event, EventStore, MemoryEventStore};
use happenstance_core::{Query, QueryItem, ReadOptions, Tags, collect};
use happenstance_testkit::{WithholdingStore, block_on};

let claimed = |claim: &str| -> Result<Event, Box<dyn core::error::Error>> {
    let tags = Tags::from_pairs([("claim", claim)])?;
    Ok(Event::new("Claimed", &b"{}"[..])?.with_tags(tags))
};
let store = WithholdingStore::new(MemoryEventStore::new());

block_on(async {
    for claim in ["first", "middle", "last"] {
        store.append(&[claimed(claim)?], None).await?;
    }
    let all = collect(store.read(&Query::all(), ReadOptions::new())).await?;
    let middle = all.get(1).ok_or("three were appended")?.position;

    store.withhold(&[middle]).await?;

    // `read` skips it, and the report names it.
    let now = collect(store.read(&Query::all(), ReadOptions::new())).await?;
    assert_eq!(now.len(), all.len() - 1);
    assert!(now.iter().all(|event| event.position != middle));
    assert!(store.withheld().contains(&middle));

    // A condition only the withheld event would violate admits the append.
    let only_middle =
        Query::from_item(QueryItem::tagged(Tags::from_pairs([("claim", "middle")])?)?);
    let landed = store
        .append(&[claimed("middle")?], Some(&AppendCondition::new(only_middle)))
        .await?;
    assert!(landed > middle);
    Ok::<(), Box<dyn core::error::Error>>(())
})?;

Implementations§

§

impl<S> WithholdingStore<S>

pub fn new(inner: S) -> Self

Wraps inner, withholding nothing.

pub fn withheld(&self) -> BTreeSet<SequencePosition>

Every position this instrument withholds, ascending: the report.

An owned snapshot rather than a borrowing iterator, because the set lives behind a lock that cannot be held while a caller iterates, and a concurrent withhold may change it meanwhile.

§

impl<S: EventStore> WithholdingStore<S>

pub async fn withhold( &self, positions: &[SequencePosition], ) -> Result<(), WithholdError<S::Error>>

Withholds the events the inner store holds at positions, all or nothing.

Withholding an already-withheld position again is a no-op, and an empty slice withholds nothing and succeeds.

§Errors

WithholdError::NotHeld, naming the lowest such position, if the inner store yields no event at one of positions; and WithholdError::Store if reading the inner store fails. Either way nothing is withheld.

pub async fn withhold_where( &self, select: impl FnMut(&SequencedEvent) -> bool, ) -> Result<Vec<SequencePosition>, WithholdError<S::Error>>

Withholds every held, not yet withheld event that select picks, and returns the positions it withheld, ascending.

The suffix is |event| event.position <= cut, a purge is a predicate on tags, and |_| true withholds everything held.

§Errors

WithholdError::Store if reading the inner store fails, in which case nothing is withheld.

§Examples
use happenstance_core::{Event, EventStore, MemoryEventStore, Query, ReadOptions, collect};
use happenstance_testkit::{WithholdingStore, block_on};

let store = WithholdingStore::new(MemoryEventStore::new());
block_on(async {
    let mut assigned = Vec::new();
    for _ in 0..4 {
        assigned.push(store.append(&[Event::new("Ticked", &b"{}"[..])?], None).await?);
    }
    let cut = *assigned.get(1).ok_or("four were appended")?;

    // Withhold a prefix of history: the store now holds only a suffix.
    let withheld = store.withhold_where(|event| event.position <= cut).await?;
    assert_eq!(withheld, assigned.get(..2).ok_or("four were appended")?);

    let retained = collect(store.read(&Query::all(), ReadOptions::new())).await?;
    assert!(retained.iter().all(|event| event.position > cut));
    Ok::<(), Box<dyn core::error::Error>>(())
})?;

Trait Implementations§

§

impl<S: Clone> Clone for WithholdingStore<S>

§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl<S: Debug> Debug for WithholdingStore<S>

§

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

Formats the value using the given formatter. Read more
§

impl<S: EventStore> EventStore for WithholdingStore<S>

§

type Error = <S as EventStore>::Error

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

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. Read more
§

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
§

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
§

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§

§

impl<S> Freeze for WithholdingStore<S>
where S: Freeze,

§

impl<S> RefUnwindSafe for WithholdingStore<S>
where S: RefUnwindSafe,

§

impl<S> Send for WithholdingStore<S>
where S: Send,

§

impl<S> Sync for WithholdingStore<S>
where S: Sync,

§

impl<S> Unpin for WithholdingStore<S>
where S: Unpin,

§

impl<S> UnsafeUnpin for WithholdingStore<S>
where S: UnsafeUnpin,

§

impl<S> UnwindSafe for WithholdingStore<S>
where S: UnwindSafe,

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
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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.

§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V