Skip to main content

Crate ddd_cqrs_es

Crate ddd_cqrs_es 

Source
Expand description

§ddd_cqrs_es

A lightweight framework for building Domain-Driven Design, CQRS, and Event Sourcing applications in Rust.

The crate provides explicit building blocks for aggregate command handling, optimistic concurrency, event replay, projections, process managers, snapshots, and pluggable persistence backends. The included in-memory store is intended for tests, examples, and local development.

§Example

use ddd_cqrs_es::{Aggregate, DomainEvent, InMemoryEventStore, Metadata, Repository};

#[derive(Clone)]
enum CounterEvent {
    Created,
    Incremented(u64),
}

impl DomainEvent for CounterEvent {
    fn event_type(&self) -> &'static str {
        match self {
            CounterEvent::Created => "counter_created",
            CounterEvent::Incremented(_) => "counter_incremented",
        }
    }
}

enum CounterCommand {
    Create,
    Increment(u64),
}

#[derive(Default)]
struct Counter {
    exists: bool,
    value: u64,
    revision: u64,
}

#[derive(Debug)]
enum CounterError {
    AlreadyCreated,
    NotCreated,
}

impl Aggregate for Counter {
    type Id = String;
    type Command = CounterCommand;
    type Event = CounterEvent;
    type Error = CounterError;

    fn aggregate_type() -> &'static str { "counter" }
    fn revision(&self) -> u64 { self.revision }
    fn new() -> Self { Self::default() }

    fn apply(&mut self, event: &Self::Event) {
        match event {
            CounterEvent::Created => self.exists = true,
            CounterEvent::Incremented(by) => self.value += by,
        }
        self.revision += 1;
    }

    fn handle(&self, command: Self::Command) -> Result<Vec<Self::Event>, Self::Error> {
        match command {
            CounterCommand::Create if self.exists => Err(CounterError::AlreadyCreated),
            CounterCommand::Create => Ok(vec![CounterEvent::Created]),
            CounterCommand::Increment(_) if !self.exists => Err(CounterError::NotCreated),
            CounterCommand::Increment(by) => Ok(vec![CounterEvent::Incremented(by)]),
        }
    }
}

let store = InMemoryEventStore::<Counter>::new();
let repo = Repository::new(store);
let counter_id = "counter-1".to_owned();

repo.execute(&counter_id, CounterCommand::Create, Metadata::default())?;
repo.execute(&counter_id, CounterCommand::Increment(5), Metadata::default())?;
let loaded = repo.load(&counter_id)?;

assert_eq!(loaded.state.value, 5);

Re-exports§

pub use aggregate::Aggregate;
pub use aggregate::LoadedAggregate;
pub use command::CommandBus;
pub use command::CommandHandler;
pub use command::QueryHandler;
pub use error::ConcurrencyError;
pub use error::EventStoreError;
pub use error::EventStoreFailure;
pub use error::RepositoryError;
pub use event::DomainEvent;
pub use event::EventEnvelope;
pub use event::EventId;
pub use event::EventType;
pub use event::ExpectedRevision;
pub use event::NewEvent;
pub use event::Revision;
pub use event::INITIAL_REVISION;
pub use event_store::AtomicIdempotentEventStore;
pub use event_store::EventStore;
pub use event_store::EventStream;
pub use event_store::IdempotentAppendError;
pub use event_store::StandardEventStore;
pub use idempotency::IdempotencyKey;
pub use idempotency::IdempotencyState;
pub use idempotency::IdempotencyStore;
pub use idempotency::IdempotencyWaitConfig;
pub use idempotency::IdempotentRepositoryError;
pub use idempotency::InMemoryIdempotencyError;
pub use idempotency::InMemoryIdempotencyStore;
pub use idempotency::DEFAULT_IDEMPOTENCY_PENDING_TIMEOUT;
pub use idempotency::DEFAULT_IDEMPOTENCY_POLL_INTERVAL;
pub use memory::InMemoryEventStore;
pub use metadata::Metadata;
pub use process_manager::ProcessManager;
pub use process_manager::ProcessManagerRunner;
pub use process_manager::ProcessManagerRunnerError;
pub use projection::CheckpointStore;
pub use projection::CheckpointedProjection;
pub use projection::CheckpointedProjectionRunner;
pub use projection::InMemoryProjectionRunner;
pub use projection::PersistedProjectionRunner;
pub use projection::Projection;
pub use projection::ProjectionBatchConfig;
pub use projection::ProjectionBatchOutcome;
pub use projection::ProjectionRunnerError;
pub use projection::TransactionalCheckpointedProjection;
pub use projection::TransactionalCheckpointedProjectionRunner;
pub use projection::DEFAULT_PROJECTION_BATCH_SIZE;
pub use repository::AtomicIdempotentRepositoryResult;
pub use repository::CommittedEvents;
pub use repository::ExecutionOutcome;
pub use repository::IdempotentRepositoryResult;
pub use repository::Repository;
pub use repository::RepositoryResult;
pub use repository::SnapshotRepositoryResult;
pub use schema::SchemaMigration;
pub use schema::SchemaMigrator;
pub use schema::SqlDialect;
pub use schema::SqlSchemaConfig;
pub use snapshot::InMemorySnapshotError;
pub use snapshot::InMemorySnapshotStore;
pub use snapshot::Snapshot;
pub use snapshot::SnapshotRepositoryError;
pub use snapshot::SnapshotStore;
pub use testing::assert_checkpoint_store_contract;
pub use testing::assert_event_store_contract;
pub use testing::assert_event_store_global_replay_contract;
pub use testing::assert_idempotency_store_contract;
pub use testing::assert_snapshot_store_contract;
pub use testing::AggregateFixture;
pub use testing::EventStoreContractOptions;
pub use upcast::ErasedUpcaster;
pub use upcast::EventUpcaster;
pub use upcast::UpcasterRegistry;

Modules§

aggregate
command
error
event
event_store
idempotency
memory
In-memory event store implementation used by tests, examples, and local development. It preserves stream/revision behavior for API compatibility while remaining non-durable.
metadata
process_manager
projection
repository
schema
Versioned Schema Migration System
snapshot
testing
upcast