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§
- Aggregate
Snapshot - English:
Owned aggregate state paired with the last event revision it represents. No identifier or schema version is added; include validation metadata inSwhen needed. - And
- English:
Conjunction that evaluates the right rule only after the left returnsOk(true). A leftOk(false)or error is returned immediately; a right result is forwarded unchanged. - Append
Result - English:
Stream position reported after a successful append. - Async
Lifecycle Context - English:
Coordinates asynchronous aggregate persistence and event dispatch. Each operation may be attempted once; dropping an in-progress future consumes that attempt. - Async
Transactional Outbox Lifecycle Context - English:
Single-attempt asynchronous enqueue tracking with exclusive aggregate and outbox borrows. - Delivery
Metadata - English:
Owned delivery identifiers, independent of the domain event payload. - Event
Identity - 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. - Lifecycle
Context - English:
Coordinates one synchronous aggregate save and event dispatch sequence. - NoStream
- English:
Absence of a stream, distinct from an existing stream at revision0. - Not
- English:
Negation that evaluates its inner rule once, flipsOk(bool), and propagatesErrunchanged. - Or
- English:
Disjunction that evaluates the right rule only after the left returnsOk(false). A leftOk(true)or error short-circuits; errors are not treated as a negative match. - Outbox
Claim - English:
Owned message identifier and event returned by an outbox claim. - Outbox
Message Id - English:
Owned adapter-assigned identifier for an outbox message. - Projection
Checkpoint - English:
Owned cursor identifying progress in a projection’s input stream. - Rehydrated
Aggregate - English:
Reconstructed aggregate paired with the history’s final revision. This revision can be used ascrate::ExpectedRevision::Revisionfor a subsequent append. - Revision
Conflict - English:
Requested and observed stream states that prevented an append. - Secret
- English:
Owns a value whoseZeroize::zeroizemethod is called before it is dropped. - Secret
Metadata - English:
A zero-sized marker for metadata associated with a secret. - Stream
History - English:
Non-empty, complete history in replay order starting at revision0. Construction checks event count against the final revision, not event contents or identity. - Stream
Revision - English:
Zero-based event position; the first event in a stream has revision0. - Transactional
Outbox Lifecycle Context - 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 aProcessManager. 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. - Upcaster
Chain - 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§
- Append
Error - English:
Append failure;Ecarries an adapter-specific storage error. - Async
Transactional Outbox Completion Error - English:
Reason completion could not confirm a successful asynchronous enqueue. - Async
Transactional Outbox Operation Error - English:
Failure of an asynchronous enqueue attempt or rejection of a repeated attempt. - Current
Revision - English:
Stream state observed by an adapter during a revision conflict. - Expected
Revision - English:
Stream state required by a caller when appending events. - Lifecycle
Completion Error - English:
Describes why a lifecycle context cannot be completed. - Lifecycle
Operation Error - English:
An error returned when a lifecycle save or dispatch cannot be attempted or its adapter fails. - Load
Result - English:
Stream lookup result, separating absence from complete event history. - Projection
Application - English:
Successful outcome ofIdempotentProjection::apply_onceorAsyncIdempotentProjection::apply_once, distinguishing application from a recognized duplicate. - Replay
Error - English:
First failure encountered during full-history reconstruction. - Snapshot
Load Error - English:
Snapshot lookup failure, distinct from a missing snapshot. - Snapshot
Replay Error - English:
First failure during snapshot-assisted reconstruction; errors do not trigger fallback. - Snapshot
Save Error - English:
Failure to persist a snapshot. - Snapshot
Use - English:
Aggregate-defined snapshot classification used bycrate::replay_with_optional_snapshot. BothStaleandInapplicabletrigger full replay; an older but usable snapshot may beApplicable. - Stream
History Error - English:
Reason that event data cannot form a completeStreamHistory. - Transactional
Outbox Completion Error - English:
Reason that consuming a lifecycle context did not confirm successful enqueueing. - Transactional
Outbox Operation Error - English:
Failure from an enqueue attempt or rejection of a repeated attempt.
Traits§
- Aggregate
Creator - English:
Creates an aggregate from a command and runs the lifecycle callback before returning its output. - Aggregate
Replay - 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. - Aggregate
Root - English:
Represents anEntitythat records domain events produced by state changes. - Async
Aggregate Creator - English:
Asynchronously creates an aggregate from a command and runs the lifecycle callback. - Async
Command Handler - English:
Asynchronously handles a command against an aggregate using a lifecycle callback. - Async
Domain Event Publisher - English:
Publishes domain events asynchronously. Implementations define the event type and error type;publishborrows both the publisher and event until its returned future completes. - Async
Event Consumer - English:
Handles borrowed domain events through boxed,Sendfutures. - Async
Event Store - English:
Asynchronous event-stream storage using the result types ofcrate::EventStore. - Async
Idempotent Projection - English:
Asynchronous duplicate-aware projection independent ofcrate::AsyncProjectionandAsyncProjectionCheckpointStore. - Async
Lifecycle Callback - English:
Defines asynchronous work performed with a mutable asynchronous lifecycle context. - Async
Projection - English:
Updates a read model through boxed,Sendfutures. - Async
Projection Checkpoint Store - English:
Checkpoint persistence port returning boxedSendfutures tied to the store borrow. - Async
Query Handler - English:
Handles a query asynchronously without requiring aggregate lifecycle operations. - Async
Repository - English:
Provides asynchronous persistence operations for one aggregate type. Implementors supply storage behavior and its error type; returned futures borrow the repository and areSend. - Async
Snapshot Store - English:
Asynchronous storage for snapshots, separate from event-stream appends. - Async
Transactional Outbox - English:
Asynchronous boundary for saving aggregates and staging events for delivery. - Command
Handler - English:
Loads an aggregate for a command, runs its lifecycle callback, and returns the callback output or an error. - Domain
Event - English:
Marks a type as an event that describes a meaningful domain occurrence. - Domain
Event Conversion - English:
Converts a domain event into an associated output type. - Domain
Event Delivery Metadata - English:
Opt-in access to delivery labels on aDomainEvent. - Domain
Event Metadata - English:
Provides an event name, version, and optional metadata for a domain event. - Domain
Event Publisher - English:
Publishes events that implementDomainEvent. - Domain
Factory - 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 requireSend,Sync, or side-effect-free construction. - Domain
Service - 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. - Event
Consumer - English:
Handles a borrowed domain event synchronously. - Event
Store - 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. - Event
Upcaster - 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. NoVersionedEventbound or automatic version selection is used. - Idempotent
Projection - English:
Opt-in projection contract distinguishing new application from duplicate input. - Lifecycle
Callback - 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. - Process
Manager - 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. - Projection
Checkpoint Store - English:
Synchronous persistence port for a projection’s checkpoint. - Query
Handler - English:
Handles a query without requiring aggregate lifecycle operations. - Repository
- English:
Defines persistence operations for oneAggregateRoottype. - Snapshot
Store - 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.Tmay 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. - Transactional
Outbox - English:
Persistence boundary for saving an aggregate and staging events for delivery. - Unit
OfWork - 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 noSendorSyncbounds. - Value
Object - English:
Represents a domain value by wrapping an inner value. - Versioned
Event - English:
Type-level event identity independent of any particular event instance. Nocrate::DomainEventbound is required, and the trait does not validate the returned identity.
Functions§
- dispatch_
events - English:
Publishes the events currently held byaggregatethroughpublisher. - dispatch_
events_ async - English:
Asynchronously publishes the events currently held byaggregate, in the order returned byAggregateRoot::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:
InitializesAforidand applies every event inhistoryin stored order. Returns the reconstructed aggregate and history revision. The first hook error is wrapped inReplayError; the local aggregate is dropped on error. No storage or publishing is performed, and hook panics propagate. The caller must supply history belonging toid. - replay_
with_ optional_ snapshot - English:
ReconstructsAusing an optional snapshot and a completehistoryforid. With no snapshot, or aSnapshotUse::StaleorSnapshotUse::Inapplicableclassification, initializes state and replays all events. ForSnapshotUse::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§
- Async
Outbox Lifecycle Completion Error - English:
Alias forAsyncTransactionalOutboxCompletionErrorused for the final state check. - Async
Outbox Lifecycle Context - English:
Short alias forAsyncTransactionalOutboxLifecycleContextwith the same cancellation rules. - Async
Outbox Lifecycle Operation Error - English:
Alias forAsyncTransactionalOutboxOperationErrorcovering enqueue and repeated-attempt errors. - Outbox
Lifecycle Completion Error - English:
Alias forTransactionalOutboxCompletionErrorused when checking lifecycle completion. - Outbox
Lifecycle Context - English:
Short name forTransactionalOutboxLifecycleContextwith identical borrow and retry rules. - Outbox
Lifecycle Operation Error - English:
Alias forTransactionalOutboxOperationError, including append failures and repeated attempts.