datum-persistence 0.11.3

Event sourcing, durable state, and CQRS persistence for Datum
Documentation

datum-persistence

datum-persistence provides event-sourced and durable-state actor behaviors, byte-oriented storage SPIs, schema adapters, CQRS query capabilities, and production PostgreSQL and RocksDB backends for Datum. Behavior construction is side-effect-free; recovery and storage I/O begin at spawn.

Features

Feature Default Provides
protobuf Yes ProstSerializer for explicit-id, explicit-manifest prost::Message payloads
postgres No PostgresPersistence: journal, snapshots, and durable state through SQLx/Tokio
rocksdb No RocksDbBackend: embedded journal, snapshots, and durable state with configurable WAL durability
cassandra No CassandraPersistence: journal, snapshots, and LWT durable state over the async scylla CQL driver
sharding No sharding::EventSourcedEntity::register integration with datum-cluster-sharding

Minimal event-sourced behavior

use std::sync::Arc;

use datum_persistence::{
    Effect, EventSourcedBehavior, EventSourcedRuntime, IdentityAdapter, MemoryJournal,
    PersistenceError, PersistenceId, PersistenceResult, PersistenceSerializer, SerializerCatalog,
    SerializerId,
};

#[derive(Clone, Copy)]
struct I64Serializer;

impl PersistenceSerializer<i64> for I64Serializer {
    fn serializer_id(&self) -> SerializerId {
        SerializerId::new(41)
    }

    fn manifest(&self, _value: &i64) -> String {
        "counter-i64-v1".into()
    }

    fn serialize(&self, value: &i64) -> PersistenceResult<Vec<u8>> {
        Ok(value.to_be_bytes().to_vec())
    }

    fn deserialize(&self, manifest: &str, payload: &[u8]) -> PersistenceResult<i64> {
        if manifest != "counter-i64-v1" || payload.len() != 8 {
            return Err(PersistenceError::Serialization("invalid counter frame".into()));
        }
        let mut bytes = [0_u8; 8];
        bytes.copy_from_slice(payload);
        Ok(i64::from_be_bytes(bytes))
    }
}

#[tokio::main]
async fn main() -> PersistenceResult<()> {
    let behavior = EventSourcedBehavior::new(
        PersistenceId::new("counter", "counter-1")?,
        0_i64,
        |_state, delta: i64| Effect::persist(delta),
        |state: &i64, event: &i64| state + event,
    )
    .with_event_adapter(
        IdentityAdapter,
        SerializerCatalog::new(I64Serializer),
    );

    let handle = behavior
        .spawn(EventSourcedRuntime::new(Arc::new(MemoryJournal::new())))
        .await?;
    handle.tell(2)?;
    handle.tell(3)?;

    let current = handle.state().await?;
    assert_eq!(current.state, 5);
    assert_eq!(current.sequence_nr.as_u64(), 2);
    handle.stop();
    Ok(())
}

See the Persistence guides for event sourcing, durable state, backend setup, read-side projections, schema evolution, and cookbook recipes.