ddd_toolkit_core/transactional_outbox.rs
1#![allow(clippy::type_complexity)]
2
3use crate::{AggregateRoot, AppendError, AppendResult, ExpectedRevision};
4
5/// **English:** Owned adapter-assigned identifier for an outbox message.
6///
7/// The string is not validated or generated here. It need not equal a domain event's
8/// delivery identifier; uniqueness and identifier scope belong to the outbox adapter.
9///
10/// **日本語:** アダプターが割り当てる、所有されたアウトボックスメッセージ識別子です。
11///
12/// ここでは文字列を検証・生成しません。ドメインイベントの配信識別子と同じである
13/// 必要はなく、一意性と識別子のスコープはアウトボックスアダプターが定めます。
14#[derive(Clone, Debug, Eq, Hash, PartialEq)]
15pub struct OutboxMessageId(String);
16
17impl OutboxMessageId {
18 /// **English:** Converts `value` to the stored string, accepting empty strings as well.
19 ///
20 /// **日本語:** `value` を保存用の文字列へ変換します。空文字列も受け付けます。
21 pub fn new(value: impl Into<String>) -> Self {
22 Self(value.into())
23 }
24
25 /// **English:** Borrows the message identifier without cloning its string.
26 ///
27 /// **日本語:** 文字列を複製せずにメッセージ識別子を借用します。
28 pub fn as_str(&self) -> &str {
29 &self.0
30 }
31
32 /// **English:** Consumes the identifier and returns its owned string.
33 ///
34 /// **日本語:** 識別子を消費し、所有された文字列を返します。
35 pub fn into_inner(self) -> String {
36 self.0
37 }
38}
39
40/// **English:** Owned message identifier and event returned by an outbox claim.
41///
42/// Constructing or dropping this container does not reserve, acknowledge, or release a message.
43/// Leases, redelivery, and acknowledgement effects are adapter responsibilities.
44///
45/// **日本語:** アウトボックスの取得操作が返す、所有されたメッセージ識別子とイベントです。
46///
47/// このコンテナーの構築や破棄は、メッセージの予約、確認応答、解放を行いません。
48/// リース、再配信、確認応答の効果はアダプターの責務です。
49///
50/// **English:** Split a claim to transfer its identifier and payload independently.
51///
52/// **日本語:** 識別子とペイロードを別々に渡すために取得結果を分解します。
53///
54/// ```rust
55/// use ddd_toolkit_core::{OutboxClaim, OutboxMessageId};
56///
57/// let claim = OutboxClaim::new(OutboxMessageId::new("message-1"), 42_u32);
58/// assert_eq!(claim.message_id().as_str(), "message-1");
59/// assert_eq!(*claim.event(), 42);
60/// let (id, event) = claim.into_parts();
61/// assert_eq!(id.into_inner(), "message-1");
62/// assert_eq!(event, 42);
63/// ```
64#[derive(Debug, Eq, PartialEq)]
65pub struct OutboxClaim<E> {
66 message_id: OutboxMessageId,
67 event: E,
68}
69
70impl<E> OutboxClaim<E> {
71 /// **English:** Pairs `message_id` with `event` without contacting an outbox adapter.
72 ///
73 /// **日本語:** アウトボックスアダプターにアクセスせず、`message_id` と `event` を組にします。
74 pub fn new(message_id: OutboxMessageId, event: E) -> Self {
75 Self { message_id, event }
76 }
77
78 /// **English:** Borrows the identifier used to acknowledge this message.
79 ///
80 /// **日本語:** このメッセージの確認応答に使う識別子を借用します。
81 pub fn message_id(&self) -> &OutboxMessageId {
82 &self.message_id
83 }
84
85 /// **English:** Borrows the claimed payload without removing it from this container.
86 ///
87 /// **日本語:** このコンテナーから取り出さずに、取得したペイロードを借用します。
88 pub fn event(&self) -> &E {
89 &self.event
90 }
91
92 /// **English:** Consumes the claim and returns the identifier and event without cloning.
93 /// This does not acknowledge the message.
94 ///
95 /// **日本語:** 取得結果を消費し、複製せずに識別子とイベントを返します。
96 /// この操作はメッセージの確認応答を行いません。
97 pub fn into_parts(self) -> (OutboxMessageId, E) {
98 (self.message_id, self.event)
99 }
100}
101
102/// **English:** Persistence boundary for saving an aggregate and staging events for delivery.
103///
104/// An adapter supplies the transaction joining aggregate persistence and outbox insertion;
105/// this trait contains no transaction implementation. Adapters must describe atomicity,
106/// durability, concurrent claims, claim order, retry/lease policy, and panic conditions.
107/// Claiming and acknowledging are separate from saving; no exactly-once delivery mechanism
108/// is supplied, so consumers may need to handle duplicate events.
109///
110/// **日本語:** 集約の保存と配信対象イベントの登録を行う永続化境界です。
111///
112/// 集約の永続化とアウトボックス挿入を結ぶトランザクションはアダプターが提供し、
113/// このトレイト自体には実装しません。原子性、永続性、並行取得、取得順序、再試行・
114/// リース方針、パニック条件はアダプターが記述する必要があります。取得と確認応答は
115/// 保存から分離されています。厳密に一度だけ配信する機構は提供しないため、
116/// コンシューマー側で重複イベントへの対応が必要になる場合があります。
117pub trait TransactionalOutbox {
118 /// **English:** Aggregate whose state and associated events are staged together.
119 ///
120 /// **日本語:** 状態と関連イベントをまとめて登録する対象の集約です。
121 type Aggregate: AggregateRoot;
122 /// **English:** Adapter failure used by save, claim, and acknowledgement operations.
123 ///
124 /// **日本語:** 保存、取得、確認応答が使うアダプター障害です。
125 type Error;
126
127 /// **English:** Borrows `aggregate` and consumes `events` to save and enqueue under `expected`.
128 /// Returns the resulting stream revision, or [`AppendError`] for an empty batch, conflict,
129 /// revision exhaustion, or adapter failure. Events are supplied explicitly; this signature
130 /// does not pull or clear the aggregate's pending events. The batch is not returned on error;
131 /// consult the adapter's transaction contract before retrying.
132 ///
133 /// **日本語:** `aggregate` を借用し、`events` を消費して `expected` を条件に保存・登録します。
134 /// 結果のストリームリビジョン、または空バッチ、競合、リビジョン枯渇、アダプター障害を
135 /// 示す [`AppendError`] を返します。イベントは明示的に渡します。このシグネチャは
136 /// 集約の保留イベントを取り出したり消去したりしません。エラー時にバッチは返されないため、
137 /// 再試行する前にアダプターのトランザクション契約を確認してください。
138 fn save_and_enqueue(
139 &mut self,
140 aggregate: &Self::Aggregate,
141 expected: ExpectedRevision,
142 events: Vec<<Self::Aggregate as AggregateRoot>::Event>,
143 ) -> Result<AppendResult, AppendError<Self::Error>>;
144
145 /// **English:** Claims an available message, returning its owned identifier and event.
146 /// `Ok(None)` means no message is available to this call; adapter failures use `Self::Error`.
147 /// Reservation duration and eligibility for redelivery are not represented by [`OutboxClaim`].
148 ///
149 /// **日本語:** 利用可能なメッセージを取得し、所有された識別子とイベントを返します。
150 /// `Ok(None)` はこの呼び出しで取得できるものがないことを表し、障害は `Self::Error` です。
151 /// 予約期間と再配信の条件は [`OutboxClaim`] では表現しません。
152 fn claim(
153 &mut self,
154 ) -> Result<Option<OutboxClaim<<Self::Aggregate as AggregateRoot>::Event>>, Self::Error>;
155
156 /// **English:** Reports completed handling of `message_id`, returning an adapter error on failure.
157 /// Unknown IDs, repeated acknowledgements, and removal or retention of acknowledged messages
158 /// follow the adapter's policy. No claim token or ownership proof is required by this API.
159 ///
160 /// **日本語:** `message_id` の処理完了を通知し、失敗時にアダプターエラーを返します。
161 /// 未知の識別子、確認応答の繰り返し、応答済みメッセージの削除・保持はアダプターの
162 /// 方針に従います。この API は取得トークンや所有権の証明を要求しません。
163 fn acknowledge(&mut self, message_id: &OutboxMessageId) -> Result<(), Self::Error>;
164}