Skip to main content

ProjectionStore

Trait ProjectionStore 

Source
pub trait ProjectionStore {
    type Error: Error + 'static;
    type Batch;

    // Required methods
    async fn begin(&self) -> Result<Self::Batch, Self::Error>;
    async fn checkpoint(
        &self,
        id: &ProjectionId,
    ) -> Result<Checkpoint, Self::Error>;
    async fn commit(
        &self,
        batch: Self::Batch,
        id: &ProjectionId,
        position: SequencePosition,
        authority: Authority,
    ) -> Result<(), CommitError<Self::Error>>;
    async fn reset(
        &self,
        batch: Self::Batch,
        id: &ProjectionId,
    ) -> Result<(), ResetError<Self::Error>>;
    async fn rollback(&self, batch: Self::Batch) -> Result<(), Self::Error>;
}
Expand description

A store that holds read models and their replay checkpoints.

See the module documentation for the transactional invariant this shape exists to enforce, for why the batch is owned, and for how its freeze was earned.

Two traits, one set of doc attributes. trait_variant derives SendProjectionStore from ProjectionStore and copies this block onto it, so every sentence here is written to hold on whichever of the two pages you opened. ProjectionStore states no Send requirement and is what generic code binds; SendProjectionStore adds it and hands back ProjectionStore free. The same split as EventStore, for the same reason.

§Implementing it

The whole port, on a store small enough to read at a glance. Note what is absent: there is no Self::Batch<'_> anywhere, because there is no lifetime to spell. An implementer writes type Batch = MyBatch; and then async fn commit(&self, batch: MyBatch, …), and it compiles.

That used to be the trap that explained why this port had no adapters. While Batch was a generic associated type, the trait declared batch: Self::Batch<'_>, so naming the concrete type in the impl declared a different set of lifetime generics and rustc answered error[E0195]: lifetime parameters or bounds on method 'commit' do not match the trait declaration — with nothing in the workspace saying the literal Self::Batch<'_> was required, and nothing to copy. This example is the disposition of that trap: it compiles on every CI run, so it cannot rot back.

use happenstance_core::{
    Authority, Checkpoint, CommitError, ProjectionId, ProjectionStore, ResetError,
    SequencePosition,
};

/// The adapter's own batch. Owned, and not a live transaction.
#[derive(Debug, Default)]
struct ToyBatch {
    rows: Vec<(String, u64)>,
}

#[derive(Debug, Default)]
struct ToyStore {
    committed: std::cell::RefCell<Vec<(String, u64)>>,
    checkpoint: std::cell::Cell<Option<SequencePosition>>,
}

impl ProjectionStore for ToyStore {
    type Error = ToyError;

    // No lifetime, and no `where Self: 'a`.
    type Batch = ToyBatch;

    // `async` and fallible on the port because a batch that is a live
    // transaction has a round trip and a failure here. A buffer has neither:
    // this body never yields and never fails, and costs what it looks like.
    async fn begin(&self) -> Result<ToyBatch, ToyError> {
        Ok(ToyBatch::default())
    }

    async fn checkpoint(&self, _id: &ProjectionId) -> Result<Checkpoint, ToyError> {
        Ok(match self.checkpoint.get() {
            None => Checkpoint::NeverRun,
            Some(through) => Checkpoint::Live { through },
        })
    }

    // The concrete type, spelled straight out. This is the line that used
    // to be `error[E0195]`.
    async fn commit(
        &self,
        batch: ToyBatch,
        _id: &ProjectionId,
        position: SequencePosition,
        _authority: Authority,
    ) -> Result<(), CommitError<ToyError>> {
        // The rows and the checkpoint, or neither.
        self.committed.borrow_mut().extend(batch.rows);
        self.checkpoint.set(Some(position));
        Ok(())
    }

    async fn reset(
        &self,
        batch: ToyBatch,
        _id: &ProjectionId,
    ) -> Result<(), ResetError<ToyError>> {
        // The caller's batch carries the deletes; this store's whole read
        // model is the vector, so clearing it is the same unit of work.
        drop(batch);
        self.committed.borrow_mut().clear();
        self.checkpoint.set(None);
        Ok(())
    }

    async fn rollback(&self, batch: ToyBatch) -> Result<(), ToyError> {
        drop(batch);
        Ok(())
    }
}

#[derive(Debug)]
struct ToyError;
impl core::fmt::Display for ToyError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str("the toy store failed")
    }
}
impl core::error::Error for ToyError {}

let store = ToyStore::default();
let id = ProjectionId::new("toy")?;

let mut batch = store.begin().await?;
batch.rows.push(("depot-7".to_owned(), 12));
store
    .commit(batch, &id, SequencePosition::FIRST, Authority::Live)
    .await?;

assert_eq!(
    store.checkpoint(&id).await?,
    Checkpoint::Live { through: SequencePosition::FIRST },
);

Required Associated Types§

Source

type Error: Error + 'static

How this adapter fails.

Source

type Batch

The adapter’s write set.

Owned, and not required to be a live transaction. Only the adapter knows what it is: a SQL transaction, a buffered statement list, a graph write set. Applying an event mutates it; it becomes durable only when handed to commit or reset.

No Send bound is written here, and it is not an oversight. SendProjectionStore transitively requires Batch: Send, but trait_variant copies associated-type bounds verbatim into the bare flavour — so type Batch: Send; would impose Send on the flavour that exists for wasm32, where nothing is. The requirement is documented here and written by the caller as S::Batch: Send when they need it.

Required Methods§

Source

async fn begin(&self) -> Result<Self::Batch, Self::Error>

Opens a write set.

async and fallible, and it was neither until ADR-0062. The old shape argued that an async fn begin() -> Result<…> implies a round trip, which an adapter on a one-shot HTTP transport cannot afford. It does not imply one: an async fn whose body never awaits is a future that is ready at its first poll, and Ok(Vec::new()) is what every buffering adapter in this workspace writes here. What the old shape forbade was a batch that is a live transaction, because every route to a real driver’s transaction is async and fallible — sqlx’s Pool::begin().await? has no synchronous spelling and private fields — and PS-6’s own falsifier, an adapter that must reserve something from the server before the first write, is exactly that BEGIN.

The discipline the old signature enforced is now the implementer’s: an adapter with nothing to reserve MUST NOT spend a round trip here. A transport that can count its requests can assert it, and happenstance-neon does.

§Errors

Returns the adapter’s error if a write set could not be opened — a connection that could not be acquired, a BEGIN that was refused. A buffering adapter has no failing path and returns Ok unconditionally.

Source

async fn checkpoint(&self, id: &ProjectionId) -> Result<Checkpoint, Self::Error>

How far this projection has been brought, and whether its rows are authoritative.

Returns a Checkpoint, never an Option<SequencePosition>; the reason the tuple form lost is recorded on that type. Resume a replay by feeding through to ReadOptions::from after advancing past it.

PS-38, frozen: the answer reflects every commit this store has acknowledged, through any handle onto it, and an adapter over replicated storage answers from the primary, never from a replica that may lag it — a runner that resumes from a stale checkpoint applies again what it already committed. No conformance rule can observe a lagging replica in process, so this is documented rather than checked, and if PS-38’s falsifier fires the obligation narrows to reads through the same handle.

§Errors

Returns the adapter’s error if the checkpoint cannot be read.

Source

async fn commit( &self, batch: Self::Batch, id: &ProjectionId, position: SequencePosition, authority: Authority, ) -> Result<(), CommitError<Self::Error>>

Applies batch and moves id’s checkpoint to position, as one unit.

position is the position considered, not the position applied, so a batch that wrote nothing still advances the checkpoint. authority is the claim this commit makes about the rows it leaves behind.

§Errors

Returns CommitError::ForeignBatch if batch was begun on a different store instance, CommitError::CheckpointRegression if position is below the checkpoint already recorded, and CommitError::Store if the adapter itself failed. The batch is consumed either way, and a failed commit leaves both the read model and the checkpoint unchanged.

Source

async fn reset( &self, batch: Self::Batch, id: &ProjectionId, ) -> Result<(), ResetError<Self::Error>>

Applies batch and returns id to Checkpoint::NeverRun, as one unit.

The dual of commit: the caller’s own batch carries the deletes, because the port has no idea what the read model is. The alternative — a reset that clears the rows itself — would oblige the adapter to know which tables belong to a ProjectionId, which is exactly the knowledge this port keeps out.

§Errors

Returns ResetError::ForeignBatch if batch was begun on a different store instance, ResetError::Refused if this store declines to reset this projection, and ResetError::Store if the adapter itself failed. A refusal, like a failure, leaves both halves unchanged.

Source

async fn rollback(&self, batch: Self::Batch) -> Result<(), Self::Error>

Discards the batch without committing.

Exists because Drop cannot await: an adapter holding a real resource needs somewhere to release it. Dropping a batch bare must also roll back and leave the store usable.

§Errors

Returns the adapter’s error if the rollback fails.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§

Source§

impl<TraitVariantBlanketType: SendProjectionStore> ProjectionStore for TraitVariantBlanketType

Source§

type Error = <TraitVariantBlanketType as SendProjectionStore>::Error

Source§

type Batch = <TraitVariantBlanketType as SendProjectionStore>::Batch