Skip to main content

Crate ddd_toolkit_core

Crate ddd_toolkit_core 

Source
Expand description

English:
Core traits for modeling Domain-Driven Design entities and value objects.

Entity exposes a stable identifier by reference, while ValueObject exposes a wrapped value by reference or by value. Implement these traits on domain types to keep their domain-facing APIs independent from persistence details.

For event-sourced aggregates, EventStore loads complete StreamHistory values and appends events using ExpectedRevision. AggregateReplay supplies reconstruction hooks for replay_aggregate and replay_with_optional_snapshot. SnapshotStore persists AggregateSnapshot values separately; adapters define storage and concurrency behavior.

Secret wraps a value implementing zeroize::Zeroize, redacts its formatted output, and zeroizes it on drop. Access to the unredacted value is explicit; extracting it transfers responsibility for zeroization to the caller. SecretMetadata is a zero-sized marker and does not itself protect data.

AsyncEventStore and AsyncSnapshotStore expose boxed Send futures for event and snapshot persistence. EventConsumer and Projection separate event handling from read-model updates, with asynchronous counterparts AsyncEventConsumer and AsyncProjection. DomainEventDeliveryMetadata optionally exposes DeliveryMetadata. TransactionalOutbox separates save-and-enqueue, claim, and acknowledgement operations; adapters supply transactions and delivery policies, not this crate.

TransactionalOutboxLifecycleContext tracks a single save-and-enqueue attempt. It pulls pending events without restoring them on failure, rejects repeated attempts, and reports missing or unsuccessful enqueueing at completion. It does not implement a transaction.

AsyncTransactionalOutbox provides future-based outbox operations. AsyncTransactionalOutboxLifecycleContext consumes an attempt and pulls events before polling; dropping its future does not restore events. ProjectionCheckpoint carries application-defined progress for ProjectionCheckpointStore, while IdempotentProjection reports applied or duplicate input via ProjectionApplication. Implementations supply duplicate detection and coordination between checkpoint persistence and read-model changes.

AsyncProjectionCheckpointStore persists progress through boxed Send futures, and AsyncIdempotentProjection asynchronously distinguishes new application from duplicates. These independent ports do not coordinate transactions; dropping a future does not guarantee rollback or absence of side effects. Implementations define cancellation and retry semantics.

Specification composes fallible predicates with short-circuiting And, Or, and Not. DomainService, Policy, and DomainFactory define typed operation, rule-checking, and construction boundaries without prescribing persistence or thread safety. ProcessManager returns a Transition of state and effect descriptions for callers to store and execute. UnitOfWork exposes explicit registration, commit, and rollback ports; implementations define their transaction guarantees. EventIdentity and VersionedEvent describe event schemas, while UpcasterChain applies EventUpcaster stages in insertion order without automatically selecting versions.

日本語:
ドメイン駆動設計のエンティティと値オブジェクトを表現するためのコアトレイトを提供します。

Entity は安定した識別子を参照で公開し、ValueObject は内包値を参照または 値で公開します。永続化の詳細から独立したドメイン型の API を保つために、これらのトレイトを実装します。

イベントソーシングを使う集約では、EventStore が完全な StreamHistory を 読み込み、ExpectedRevision を条件にイベントを追加します。AggregateReplay は replay_aggregate と replay_with_optional_snapshot の復元フックを定めます。 SnapshotStore は AggregateSnapshot を別途永続化し、保存や並行処理の挙動は アダプターが定めます。

Secret は zeroize::Zeroize を実装する値を包み、書式出力を秘匿化し、 破棄時にゼロ化します。秘匿化していない値には明示的にアクセスし、値を取り出した後の ゼロ化は呼び出し側が管理します。SecretMetadata はサイズがゼロのマーカーであり、 それ自体はデータを保護しません。

AsyncEventStore と AsyncSnapshotStore はイベントとスナップショットの 永続化を、ボックス化された Send Future で公開します。EventConsumer と Projection はイベント処理と読み取りモデル更新を分け、非同期版の AsyncEventConsumer と AsyncProjection も提供します。DomainEventDeliveryMetadata は任意で DeliveryMetadata を公開します。TransactionalOutbox は保存・登録、取得、確認応答を 分離します。トランザクションと配信方針はこのクレートではなくアダプターが提供します。

TransactionalOutboxLifecycleContext は保存・登録の一回の試行を追跡します。 保留イベントを取り出して失敗時も復元せず、繰り返しの試行を拒否し、完了確認時に 未試行や未成功を報告します。トランザクション自体は実装しません。

AsyncTransactionalOutbox は Future によるアウトボックス操作を提供します。 AsyncTransactionalOutboxLifecycleContext はポーリング前に試行を消費してイベントを取り出し、 Future の破棄でも復元しません。ProjectionCheckpoint はアプリケーション定義の進捗を ProjectionCheckpointStore に渡し、IdempotentProjection は適用または重複を ProjectionApplication で報告します。重複検出と、チェックポイント永続化・読み取りモデル変更の 連携は実装が提供します。

AsyncProjectionCheckpointStore はボックス化された Send Future で進捗を永続化し、 AsyncIdempotentProjection は新規適用と重複を非同期に区別します。これらの独立したポートは トランザクションを調整せず、Future の破棄はロールバックや副作用の不在を保証しません。 キャンセルと再試行の意味は実装が定めます。

Specification は失敗し得る述語を、短絡評価する And、Or、Not で 結合します。DomainService、Policy、DomainFactory は永続化やスレッド安全性を 規定せず、型付きの操作、規則確認、構築の境界を定めます。ProcessManager は状態と 副作用の記述を Transition で返し、保存と実行は呼び出し側が担います。UnitOfWork は 明示的な登録、コミット、ロールバックのポートであり、トランザクションの保証は実装が定めます。 EventIdentity と VersionedEvent はイベントのスキーマを表し、UpcasterChain は バージョンを自動選択せず、EventUpcaster の段階を追加順に適用します。

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; earlier successful publishes are not undone, so a retry can publish duplicates.
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.