Skip to main content

Crate ddd_toolkit

Crate ddd_toolkit 

Source
Expand description

English:
Re-exports the traits and helpers from ddd-toolkit-core 0.4, including Entity, ValueObject, AggregateRoot, Repository, AsyncRepository, event publishing, CQRS, and event-sourcing contracts. Storage adapters and async runtimes are supplied by the application.

With the default derive feature, the ValueObject, Entity, DomainEvent, and AggregateRoot derive macros are also available at this crate’s root. Generated paths prefer a direct ddd-toolkit-core dependency, then this facade. Both dependencies may be renamed; a facade-only dependency suffices.

The optional serde feature enables core’s serde support and the serde derives needed by generated deserializers. Serialization is opt-in per value object with #[value_object(serde)]; put this flag last when combining options. Single-field tuple enum variants use Serde’s newtype format: Code(7) emits {"Code":7}. Macro 0.5 changes the old {"Code":[7]} output; migrate saved data by removing its outer tuple wrapper for affected variants before loading. Secret requires no feature and redacts formatting and zeroizes its contents on drop without a feature flag.

Validation returns an application-defined error; construction uses try_new rather than the removed TryFrom implementation.

日本語:
ddd-toolkit-core 0.4 のトレイトとヘルパーを再公開します。 Entity、ValueObject、AggregateRoot、Repository、 AsyncRepository、イベント発行、CQRS、イベントソーシングの契約を含みます。 ストレージのアダプターと非同期ランタイムはアプリケーションが提供します。

既定の derive feature では ValueObject、Entity、DomainEvent、 AggregateRoot の derive マクロもルートから利用できます。生成パスは直接依存の ddd-toolkit-core を優先し、なければファサードを使います。両者の依存名変更に 対応しており、ファサードだけの依存でも利用できます。

任意の serde feature はコアの serde 対応と生成された逆直列化に必要な serde の derive を有効にします。直列化は型ごとに #[value_object(serde)] で指定し、 他のオプションと併用するときはこのフラグを最後に置きます。単一フィールドの タプル型 enum variant は newtype 形式で、Code(7) は {"Code":7} を出力します。 マクロ 0.5 では旧出力 {"Code":[7]} から変わるため、保存済みの対象バリアントの 外側のタプルラッパーを除去してから読み込んでください。全 derive に直列化が 自動適用されるわけではありません。 Secret は feature 指定なしで使え、書式出力を秘匿化して破棄時に内容をゼロ化します。

検証はアプリケーション定義のエラーを返します。廃止された TryFrom 実装の代わりに try_new で構築します。

§Example / 使用例

#[derive(ddd_toolkit::ValueObject)]
#[value_object(validate = validate_email, error = &'static str)]
struct Email(String);

fn validate_email(value: &str) -> Result<(), &'static str> {
    if value.contains('@') { Ok(()) } else { Err("missing @") }
}

let email = Email::try_new("a@b.com".to_owned()).unwrap();
assert_eq!(email.as_inner(), "a@b.com");
assert_eq!(Email::try_new("invalid".to_owned()), Err("missing @"));
let key = ddd_toolkit::Secret::new("sekret".to_owned());
assert_eq!(format!("{key:?}"), "[REDACTED]");
assert_eq!(key.expose_secret(|value| value.len()), 6);

Structs§

AggregateSnapshot
English:
Owned aggregate state paired with the last event revision it represents. No identifier or schema version is added; include validation metadata in S when needed.
And
English:
Conjunction that evaluates the right rule only after the left returns Ok(true). A left Ok(false) or error is returned immediately; a right result is forwarded unchanged.
AppendResult
English:
Stream position reported after a successful append.
AsyncLifecycleContext
English:
Coordinates asynchronous aggregate persistence and event dispatch. Each operation may be attempted once; dropping an in-progress future consumes that attempt.
AsyncTransactionalOutboxLifecycleContext
English:
Single-attempt asynchronous enqueue tracking with exclusive aggregate and outbox borrows.
DeliveryMetadata
English:
Owned delivery identifiers, independent of the domain event payload.
EventIdentity
English:
Event name and schema version supplied by the application. Fields are public and unvalidated: an empty name or version zero is accepted. Equality compares both fields. This value supplies no registry, serialization format, or migration dispatch.
LifecycleContext
English:
Coordinates one synchronous aggregate save and event dispatch sequence.
NoStream
English:
Absence of a stream, distinct from an existing stream at revision 0.
Not
English:
Negation that evaluates its inner rule once, flips Ok(bool), and propagates Err unchanged.
Or
English:
Disjunction that evaluates the right rule only after the left returns Ok(false). A left Ok(true) or error short-circuits; errors are not treated as a negative match.
OutboxClaim
English:
Owned message identifier and event returned by an outbox claim.
OutboxMessageId
English:
Owned adapter-assigned identifier for an outbox message.
ProjectionCheckpoint
English:
Owned cursor identifying progress in a projection’s input stream.
RehydratedAggregate
English:
Reconstructed aggregate paired with the history’s final revision. This revision can be used as crate::ExpectedRevision::Revision for a subsequent append.
RevisionConflict
English:
Requested and observed stream states that prevented an append.
Secret
English:
Owns a value whose Zeroize::zeroize method is called before it is dropped.
SecretMetadata
English:
A zero-sized marker for metadata associated with a secret.
StreamHistory
English:
Non-empty, complete history in replay order starting at revision 0. Construction checks event count against the final revision, not event contents or identity.
StreamRevision
English:
Zero-based event position; the first event in a stream has revision 0.
TransactionalOutboxLifecycleContext
English:
Tracks one save-and-enqueue attempt while exclusively borrowing an aggregate and outbox.
Transition
English:
Owned next state and ordered effect descriptions returned by a ProcessManager. Construction and access do not execute effects or persist the state. Empty effects are valid; callers choose how to coordinate state storage and effect execution.
UpcasterChain
English:
Insertion-ordered sequence of upcasters of a single concrete type. Each stage consumes the preceding output. The chain does not select stages by event identity, sort versions, or restore an event after failure. Use an enum or another common upcaster type when stages need different behaviors. It stores no event value and adds no locking.

Enums§

AppendError
English:
Append failure; E carries an adapter-specific storage error.
AsyncTransactionalOutboxCompletionError
English:
Reason completion could not confirm a successful asynchronous enqueue.
AsyncTransactionalOutboxOperationError
English:
Failure of an asynchronous enqueue attempt or rejection of a repeated attempt.
CurrentRevision
English:
Stream state observed by an adapter during a revision conflict.
ExpectedRevision
English:
Stream state required by a caller when appending events.
LifecycleCompletionError
English:
Describes why a lifecycle context cannot be completed.
LifecycleOperationError
English:
An error returned when a lifecycle save or dispatch cannot be attempted or its adapter fails.
LoadResult
English:
Stream lookup result, separating absence from complete event history.
ProjectionApplication
English:
Successful outcome of IdempotentProjection::apply_once or AsyncIdempotentProjection::apply_once, distinguishing application from a recognized duplicate.
ReplayError
English:
First failure encountered during full-history reconstruction.
SnapshotLoadError
English:
Snapshot lookup failure, distinct from a missing snapshot.
SnapshotReplayError
English:
First failure during snapshot-assisted reconstruction; errors do not trigger fallback.
SnapshotSaveError
English:
Failure to persist a snapshot.
SnapshotUse
English:
Aggregate-defined snapshot classification used by crate::replay_with_optional_snapshot. Both Stale and Inapplicable trigger full replay; an older but usable snapshot may be Applicable.
StreamHistoryError
English:
Reason that event data cannot form a complete StreamHistory.
TransactionalOutboxCompletionError
English:
Reason that consuming a lifecycle context did not confirm successful enqueueing.
TransactionalOutboxOperationError
English:
Failure from an enqueue attempt or rejection of a repeated attempt.

Traits§

AggregateCreator
English:
Creates an aggregate from a command and runs the lifecycle callback before returning its output.
AggregateReplay
English:
Aggregate hooks for reconstructing state from stored events or a snapshot. Implementations should apply historical events without recording new pending events. The replay helpers do not clear queues, check aggregate identity, publish events, or catch panics from these hooks. Error and panic conditions are defined by each implementation.
AggregateRoot
English:
Represents an Entity that records domain events produced by state changes.
AsyncAggregateCreator
English:
Asynchronously creates an aggregate from a command and runs the lifecycle callback.
AsyncCommandHandler
English:
Asynchronously handles a command against an aggregate using a lifecycle callback.
AsyncDomainEventPublisher
English:
Publishes domain events asynchronously. Implementations define the event type and error type; publish borrows both the publisher and event until its returned future completes.
AsyncEventConsumer
English:
Handles borrowed domain events through boxed, Send futures.
AsyncEventStore
English:
Asynchronous event-stream storage using the result types of crate::EventStore.
AsyncIdempotentProjection
English:
Asynchronous duplicate-aware projection independent of crate::AsyncProjection and AsyncProjectionCheckpointStore.
AsyncLifecycleCallback
English:
Defines asynchronous work performed with a mutable asynchronous lifecycle context.
AsyncProjection
English:
Updates a read model through boxed, Send futures.
AsyncProjectionCheckpointStore
English:
Checkpoint persistence port returning boxed Send futures tied to the store borrow.
AsyncQueryHandler
English:
Handles a query asynchronously without requiring aggregate lifecycle operations.
AsyncRepository
English:
Provides asynchronous persistence operations for one aggregate type. Implementors supply storage behavior and its error type; returned futures borrow the repository and are Send.
AsyncSnapshotStore
English:
Asynchronous storage for snapshots, separate from event-stream appends.
AsyncTransactionalOutbox
English:
Asynchronous boundary for saving aggregates and staging events for delivery.
CommandHandler
English:
Loads an aggregate for a command, runs its lifecycle callback, and returns the callback output or an error.
DomainEvent
English:
Marks a type as an event that describes a meaningful domain occurrence.
DomainEventConversion
English:
Converts a domain event into an associated output type.
DomainEventDeliveryMetadata
English:
Opt-in access to delivery labels on a DomainEvent.
DomainEventMetadata
English:
Provides an event name, version, and optional metadata for a domain event.
DomainEventPublisher
English:
Publishes events that implement DomainEvent.
DomainFactory
English:
Constructs a domain product from owned input, reporting a typed construction error. Validation, identifier allocation, and side effects are chosen by the implementation; this trait does not require the product to be an aggregate or provide persistence. A shared receiver does not require Send, Sync, or side-effect-free construction.
DomainService
English:
Domain operation with owned input and implementation-selected output and error types. It supplies no transaction or retry logic. The shared receiver permits interior state; neither purity nor concurrent use is required by the trait.
Entity
English:
Identifies a domain object by an associated identifier type.
EventConsumer
English:
Handles a borrowed domain event synchronously.
EventStore
English:
Synchronous persistence boundary for aggregate event streams. Implementations define atomicity, durability, concurrent-writer coordination, and panic conditions; this trait supplies no storage or locking implementation.
EventUpcaster
English:
Fallible owned transformation from an event representation back to the same Rust type. Versions can be represented inside that type, but checking or advancing them is the implementation’s responsibility. No VersionedEvent bound or automatic version selection is used.
IdempotentProjection
English:
Opt-in projection contract distinguishing new application from duplicate input.
LifecycleCallback
English:
Defines work performed with a mutable lifecycle context. The callback result and error become the handler result and error.
Policy
English:
Fallible domain rule checked against a borrowed, possibly unsized context. Rejection and inability to evaluate are both represented by the implementation’s error type. This trait does not enforce the rule automatically at other domain boundaries.
ProcessManager
English:
Computes a next state and effect descriptions from borrowed state and event values. The caller owns persistence, event delivery, and effect execution. The signature does not enforce determinism, reentrancy, idempotency, or purity; shared access can still use interior mutability. Thread-safety bounds and panic behavior are left to implementations.
Projection
English:
Applies domain events to a read model synchronously.
ProjectionCheckpointStore
English:
Synchronous persistence port for a projection’s checkpoint.
QueryHandler
English:
Handles a query without requiring aggregate lifecycle operations.
Repository
English:
Defines persistence operations for one AggregateRoot type.
SnapshotStore
English:
Synchronous storage boundary for snapshots indexed by aggregate identifier. Implementations define replacement policy, durability, synchronization, and panic conditions. Saving a snapshot does not itself append events or validate the snapshot against an event stream.
Specification
English:
Fallible predicate over a borrowed candidate, with consuming boolean combinators. T may be unsized, but specification values must be sized. Combinations evaluate left to right, short-circuit on a decisive boolean, and propagate the first error without evaluating later rules. Implementations may use interior state; purity and thread safety are not required.
TransactionalOutbox
English:
Persistence boundary for saving an aggregate and staging events for delivery.
UnitOfWork
English:
Explicit registration, commit, and rollback operations for a set of changes. Implementations define transaction boundaries, atomicity, ordering, and whether repeated commits or rollback after commit are valid. This trait tracks no lifecycle state and provides no automatic rollback on drop or error. It imposes no Send or Sync bounds.
ValueObject
English:
Represents a domain value by wrapping an inner value.
VersionedEvent
English:
Type-level event identity independent of any particular event instance. No crate::DomainEvent bound is required, and the trait does not validate the returned identity.

Functions§

dispatch_events
English:
Publishes the events currently held by aggregate through publisher.
dispatch_events_async
English:
Asynchronously publishes the events currently held by aggregate, in the order returned by AggregateRoot::pull_events. On success, the events are removed. If publishing fails, all pulled events are recorded back into the aggregate before the publisher error is returned.
replay_aggregate
English:
Initializes A for id and applies every event in history in stored order. Returns the reconstructed aggregate and history revision. The first hook error is wrapped in ReplayError; the local aggregate is dropped on error. No storage or publishing is performed, and hook panics propagate. The caller must supply history belonging to id.
replay_with_optional_snapshot
English:
Reconstructs A using an optional snapshot and a complete history for id. With no snapshot, or a SnapshotUse::Stale or SnapshotUse::Inapplicable classification, initializes state and replays all events. For SnapshotUse::Applicable, selects events strictly after the snapshot revision, restores state, then applies that tail in order. A snapshot at the history’s final revision requires no event applications.

Type Aliases§

AsyncOutboxLifecycleCompletionError
English:
Alias for AsyncTransactionalOutboxCompletionError used for the final state check.
AsyncOutboxLifecycleContext
English:
Short alias for AsyncTransactionalOutboxLifecycleContext with the same cancellation rules.
AsyncOutboxLifecycleOperationError
English:
Alias for AsyncTransactionalOutboxOperationError covering enqueue and repeated-attempt errors.
OutboxLifecycleCompletionError
English:
Alias for TransactionalOutboxCompletionError used when checking lifecycle completion.
OutboxLifecycleContext
English:
Short name for TransactionalOutboxLifecycleContext with identical borrow and retry rules.
OutboxLifecycleOperationError
English:
Alias for TransactionalOutboxOperationError, including append failures and repeated attempts.

Derive Macros§

AggregateRoot
English:
Implements ddd_toolkit_core::AggregateRoot using a struct’s #[aggregate(events)] vector as its pending event queue.
DomainEvent
English:
Implements the empty ddd_toolkit_core::DomainEvent marker for a struct or enum, preserving its generic parameters and where clause.
Entity
English:
Implements ddd_toolkit_core::Entity, a borrowed inherent id() accessor, and PartialEq, Eq, and Hash using only the identifier field.
ValueObject
English:
Implements ddd_toolkit_core::ValueObject and value-based Debug, Clone, PartialEq, Eq, and Hash, with corresponding field bounds.