ddd_toolkit_core/projection_reliability.rs
1#![allow(clippy::type_complexity)]
2use crate::DomainEvent;
3use std::future::Future;
4use std::pin::Pin;
5
6/// **English:**<br>
7/// Owned cursor identifying progress in a projection's input stream.
8///
9/// The cursor type and meaning belong to the application. This container performs no ordering,
10/// monotonicity, or validity checks and does not store progress by itself.
11///
12/// Borrow a cursor for inspection, then recover its ownership without cloning.
13///
14/// **日本語:**<br>
15/// プロジェクションの入力ストリームにおける進捗を示す、所有されたカーソルです。
16///
17/// カーソルの型と意味はアプリケーションが定めます。このコンテナーは順序、単調性、妥当性を
18/// 検証せず、単体では進捗を保存しません。
19///
20/// カーソルを借用して確認した後、複製せずに所有権を取り出せます。
21///
22/// # Example / 使用例
23///
24/// ```rust
25/// use ddd_toolkit_core::ProjectionCheckpoint;
26///
27/// let checkpoint = ProjectionCheckpoint::new(String::from("partition-2:17"));
28/// assert_eq!(checkpoint.cursor(), "partition-2:17");
29/// let cursor = checkpoint.into_cursor();
30/// assert_eq!(cursor, "partition-2:17");
31/// ```
32#[derive(Clone, Debug, Eq, Hash, PartialEq)]
33pub struct ProjectionCheckpoint<C> {
34 cursor: C,
35}
36
37impl<C> ProjectionCheckpoint<C> {
38 /// **English:**<br>
39 /// Wraps `cursor` without validating its position or comparing previous progress.
40 ///
41 /// **日本語:**<br>
42 /// 位置の検証や以前の進捗との比較をせずに `cursor` を包みます。
43 pub fn new(cursor: C) -> Self {
44 Self { cursor }
45 }
46
47 /// **English:**<br>
48 /// Borrows the stored cursor without advancing it.
49 ///
50 /// **日本語:**<br>
51 /// 進めることなく、保存されたカーソルを借用します。
52 pub fn cursor(&self) -> &C {
53 &self.cursor
54 }
55
56 /// **English:**<br>
57 /// Consumes the checkpoint and returns its cursor by value.
58 ///
59 /// **日本語:**<br>
60 /// チェックポイントを消費し、カーソルを値として返します。
61 pub fn into_cursor(self) -> C {
62 self.cursor
63 }
64}
65
66/// **English:**<br>
67/// Successful outcome of [`IdempotentProjection::apply_once`] or
68/// [`AsyncIdempotentProjection::apply_once`], distinguishing application from a recognized duplicate.
69///
70/// **日本語:**<br>
71/// [`IdempotentProjection::apply_once`] または [`AsyncIdempotentProjection::apply_once`] の
72/// 成功結果であり、適用と認識済みの重複を区別します。
73#[derive(Clone, Copy, Debug, Eq, PartialEq)]
74pub enum ProjectionApplication {
75 /// **English:**<br>
76 /// The implementation reports that this call applied the event.
77 ///
78 /// **日本語:**<br>
79 /// この呼び出しでイベントを適用したことを実装が報告しています。
80 Applied,
81
82 /// **English:**<br>
83 /// The implementation recognized an already-applied input and skipped reapplication.
84 ///
85 /// **日本語:**<br>
86 /// 適用済みの入力を実装が認識し、再適用を省略しました。
87 AlreadyApplied,
88}
89
90/// **English:**<br>
91/// Synchronous persistence port for a projection's checkpoint.
92///
93/// With no projection identifier parameter, the store instance determines the checkpoint scope.
94/// Implementations define replacement, durability, concurrency, panic conditions, and whether
95/// saving progress is atomic with read-model updates. This trait supplies no monotonicity check.
96///
97/// **日本語:**<br>
98/// プロジェクションのチェックポイントを同期永続化するポートです。
99///
100/// プロジェクション識別子の引数がないため、保存対象の範囲はストアのインスタンスが定めます。
101/// 置換、永続性、並行処理、パニック条件、読み取りモデル更新との原子的な進捗保存は
102/// 実装が定めます。このトレイトは単調性の検証を提供しません。
103pub trait ProjectionCheckpointStore {
104 /// **English:**<br>
105 /// Application-defined position representation persisted by this store.
106 ///
107 /// **日本語:**<br>
108 /// このストアが永続化する、アプリケーション定義の位置表現です。
109 type Cursor;
110 /// **English:**<br>
111 /// Checkpoint storage failure reported by the adapter.
112 ///
113 /// **日本語:**<br>
114 /// アダプターが報告するチェックポイント保存先の障害です。
115 type Error;
116
117 /// **English:**<br>
118 /// Returns stored progress, `Ok(None)` for absence, or a storage error.
119 /// Absence is distinct from failing to read the checkpoint.
120 ///
121 /// **日本語:**<br>
122 /// 保存済み進捗、不在を表す `Ok(None)`、またはストレージエラーを返します。
123 /// 不在とチェックポイントの読み込み失敗は区別します。
124 fn load(&self) -> Result<Option<ProjectionCheckpoint<Self::Cursor>>, Self::Error>;
125
126 /// **English:**<br>
127 /// Consumes `checkpoint` to persist progress, returning `Ok(())` or a storage error.
128 /// The value is not returned on failure; retry and partial-write behavior depend on the adapter.
129 ///
130 /// **日本語:**<br>
131 /// `checkpoint` を消費して進捗を保存し、`Ok(())` またはストレージエラーを返します。
132 /// 失敗時に値は返されません。再試行と部分書き込みの挙動はアダプターに依存します。
133 fn save(&mut self, checkpoint: ProjectionCheckpoint<Self::Cursor>) -> Result<(), Self::Error>;
134}
135
136/// **English:**<br>
137/// Opt-in projection contract distinguishing new application from duplicate input.
138///
139/// This trait is independent of [`crate::Projection`] and [`ProjectionCheckpointStore`].
140/// Implementations supply duplicate detection, input identity, read-model changes, and any
141/// atomic checkpoint updates or locking. No deduplication algorithm is implemented here;
142/// adapters must define failure, retry, and panic behavior for their persistence boundary.
143///
144/// **日本語:**<br>
145/// 新規適用と重複入力を区別する、任意のプロジェクション契約です。
146///
147/// このトレイトは [`crate::Projection`] と [`ProjectionCheckpointStore`] から独立しています。
148/// 重複検出、入力の識別、読み取りモデルの変更、原子的なチェックポイント更新やロックは
149/// 実装が提供します。ここでは重複排除アルゴリズムを実装しません。永続化境界における
150/// 失敗、再試行、パニック時の挙動はアダプターが定める必要があります。
151pub trait IdempotentProjection {
152 /// **English:**<br>
153 /// Domain event inspected for application to the read model.
154 ///
155 /// **日本語:**<br>
156 /// 読み取りモデルへの適用を判断するドメインイベントです。
157 type Event: DomainEvent;
158 /// **English:**<br>
159 /// Position type used to associate input with projection progress.
160 ///
161 /// **日本語:**<br>
162 /// 入力とプロジェクションの進捗を関連付ける位置の型です。
163 type Cursor;
164 /// **English:**<br>
165 /// Error raised while detecting duplicates or applying an event.
166 ///
167 /// **日本語:**<br>
168 /// 重複の検出やイベント適用中に生じるエラーです。
169 type Error;
170
171 /// **English:**<br>
172 /// Borrows `event` and `checkpoint` and reports application or a recognized duplicate.
173 /// An error does not specify whether partial updates occurred. This call does not automatically
174 /// invoke a separate checkpoint store; checkpoint meaning and persistence belong to the implementation.
175 ///
176 /// **日本語:**<br>
177 /// `event` と `checkpoint` を借用し、適用または認識済みの重複を報告します。
178 /// エラーだけでは部分更新の有無は決まりません。別のチェックポイントストアを自動では
179 /// 呼び出さず、チェックポイントの意味と永続化は実装が定めます。
180 fn apply_once(
181 &mut self,
182 event: &Self::Event,
183 checkpoint: &ProjectionCheckpoint<Self::Cursor>,
184 ) -> Result<ProjectionApplication, Self::Error>;
185}
186
187/// **English:**<br>
188/// Checkpoint persistence port returning boxed `Send` futures tied to the store borrow.
189///
190/// The store instance determines the projection scope, as in [`ProjectionCheckpointStore`].
191/// The store must be `Send + Sync`, the cursor `Send + Sync`, and the error `Send`; these bounds
192/// do not provide locking, monotonic progress checks, or atomic read-model updates. Implementations
193/// define durability, concurrent replacement, partial failures, and panic conditions.
194///
195/// Dropping a returned future ends that operation's polling, but does not promise rollback or that
196/// no I/O occurred. Implementations may perform work before returning a future and must specify
197/// cancellation and retry behavior. This trait supplies no executor or transaction coordinator.
198///
199/// Await a write and then read its result; the adapter determines read-after-write consistency.
200/// This helper returns `None` if the subsequent load reports no stored checkpoint.
201///
202/// **日本語:**<br>
203/// ストアの借用期間に結び付いた、ボックス化された `Send` Future を返す進捗永続化ポートです。
204///
205/// [`ProjectionCheckpointStore`] と同様に、プロジェクションの範囲はストアのインスタンスが定めます。
206/// ストアには `Send + Sync`、カーソルには `Send + Sync`、エラーには `Send` が必要ですが、
207/// これらの境界はロック、単調な進捗の検査、読み取りモデルの原子的更新を提供しません。
208/// 永続性、並行する置換、部分失敗、パニック条件は実装が定めます。
209///
210/// 返された Future の破棄はその操作のポーリングを終了しますが、ロールバックや I/O が未実行であることを
211/// 保証しません。実装は Future を返す前にも処理でき、キャンセルと再試行の挙動を定める必要があります。
212/// このトレイトは実行器やトランザクション調整器を提供しません。
213///
214/// 書き込みを待ってから結果を読み込みます。書き込み後の読み取り整合性はアダプターが定めます。
215/// 後続の読み込みがチェックポイントの不在を報告した場合、このヘルパーは `None` を返します。
216///
217/// # Example / 使用例
218///
219/// ```rust
220/// use ddd_toolkit_core::{AsyncProjectionCheckpointStore, ProjectionCheckpoint};
221///
222/// async fn save_then_load<S: AsyncProjectionCheckpointStore>(
223/// store: &mut S,
224/// cursor: S::Cursor,
225/// ) -> Result<Option<S::Cursor>, S::Error> {
226/// store.save(ProjectionCheckpoint::new(cursor)).await?;
227/// Ok(store.load().await?.map(ProjectionCheckpoint::into_cursor))
228/// }
229/// ```
230pub trait AsyncProjectionCheckpointStore: Send + Sync {
231 /// **English:**<br>
232 /// Owned progress representation transferable and shareable across threads.
233 /// No ordering or clone bound is required.
234 ///
235 /// **日本語:**<br>
236 /// スレッド間で移動・共有できる、所有された進捗表現です。
237 /// 順序や複製の境界は要求しません。
238 type Cursor: Send + Sync;
239 /// **English:**<br>
240 /// Storage failure transferable with the future's result; no error trait bound is imposed.
241 ///
242 /// **日本語:**<br>
243 /// Future の結果とともに移動できるストレージの失敗です。エラートレイトの境界は課しません。
244 type Error: Send;
245
246 /// **English:**<br>
247 /// Borrows the store for `'a` and returns a future yielding owned stored progress.
248 /// `Ok(None)` means absence, while `Err` reports a read failure. Shared access permits multiple
249 /// load borrows but does not define snapshot isolation or freshness. Drop effects are adapter-defined.
250 ///
251 /// **日本語:**<br>
252 /// ストアを `'a` の間借用し、所有された保存済み進捗を返す Future を返します。
253 /// `Ok(None)` は不在を表し、`Err` は読み込み失敗を表します。共有参照で複数の読み込みを借用できますが、
254 /// スナップショット分離や鮮度は定めません。破棄による効果はアダプターが定めます。
255 fn load<'a>(
256 &'a self,
257 ) -> Pin<
258 Box<
259 dyn Future<Output = Result<Option<ProjectionCheckpoint<Self::Cursor>>, Self::Error>>
260 + Send
261 + 'a,
262 >,
263 >;
264
265 /// **English:**<br>
266 /// Takes ownership of `checkpoint` and exclusively borrows the store for `'a`.
267 /// The returned future reports `Ok(())` or a write failure, without returning the checkpoint
268 /// on error or cancellation. No rollback, retry, or atomic coordination with a projection is added.
269 ///
270 /// **日本語:**<br>
271 /// `checkpoint` の所有権を受け取り、ストアを `'a` の間排他的に借用します。
272 /// 返す Future は `Ok(())` または書き込み失敗を報告し、エラーやキャンセル時にチェックポイントを
273 /// 返しません。ロールバック、再試行、プロジェクションとの原子的な連携は追加しません。
274 fn save<'a>(
275 &'a mut self,
276 checkpoint: ProjectionCheckpoint<Self::Cursor>,
277 ) -> Pin<Box<dyn Future<Output = Result<(), Self::Error>> + Send + 'a>>;
278}
279
280/// **English:**<br>
281/// Asynchronous duplicate-aware projection independent of [`crate::AsyncProjection`]
282/// and [`AsyncProjectionCheckpointStore`].
283///
284/// Implementations provide input identity, duplicate detection, read-model updates, and any atomic
285/// checkpoint persistence. The trait itself implements no deduplication. The projection must be `Send`,
286/// its event `Sync`, its cursor `Send + Sync`, and its error `Send` for the boxed `Send` future.
287/// The projection need not be `Sync`; mutable borrowing prevents overlapping calls on the same value.
288///
289/// Dropping a future stops polling but does not establish whether changes occurred or were rolled back,
290/// even before the first poll: implementations may act during the method call. Adapters must document
291/// cancellation, retry, partial-update, and panic behavior at their persistence boundary.
292///
293/// **日本語:**<br>
294/// [`crate::AsyncProjection`] と [`AsyncProjectionCheckpointStore`] から独立した、
295/// 重複を区別する非同期プロジェクションです。
296///
297/// 入力の識別、重複検出、読み取りモデル更新、原子的なチェックポイント永続化は実装が提供します。
298/// トレイト自体は重複排除を実装しません。ボックス化された `Send` Future のため、
299/// プロジェクションには `Send`、イベントには `Sync`、カーソルには `Send + Sync`、エラーには `Send` が必要です。
300/// プロジェクション自体に `Sync` は不要です。同じ値への呼び出しの重複は可変借用が防ぎます。
301///
302/// Future の破棄はポーリングを止めますが、変更の有無やロールバックを保証しません。
303/// メソッド呼び出し中にも処理できるため、初回ポーリング前でも同様です。永続化境界における
304/// キャンセル、再試行、部分更新、パニックの挙動はアダプターが文書化する必要があります。
305pub trait AsyncIdempotentProjection: Send {
306 /// **English:**<br>
307 /// Domain event shareable through its borrowed reference in a `Send` future.
308 ///
309 /// **日本語:**<br>
310 /// `Send` Future 内の借用参照を通して共有できるドメインイベントです。
311 type Event: DomainEvent + Sync;
312 /// **English:**<br>
313 /// Progress representation used to associate the borrowed checkpoint with input.
314 ///
315 /// **日本語:**<br>
316 /// 借用したチェックポイントを入力に関連付ける進捗表現です。
317 type Cursor: Send + Sync;
318 /// **English:**<br>
319 /// Transferable failure from duplicate detection or read-model application.
320 ///
321 /// **日本語:**<br>
322 /// 重複検出や読み取りモデルへの適用で生じる、移動可能な失敗です。
323 type Error: Send;
324
325 /// **English:**<br>
326 /// Borrows the projection exclusively and the event and checkpoint jointly for `'a`.
327 /// The future reports [`ProjectionApplication::Applied`], [`ProjectionApplication::AlreadyApplied`],
328 /// or an error that does not rule out partial updates. It does not automatically call a checkpoint
329 /// store. Checkpoint interpretation and whether progress is persisted belong to the implementation.
330 ///
331 /// **日本語:**<br>
332 /// プロジェクションを排他的に、イベントとチェックポイントを共有で、いずれも `'a` の間借用します。
333 /// Future は [`ProjectionApplication::Applied`]、[`ProjectionApplication::AlreadyApplied`]、
334 /// または部分更新の可能性を排除しないエラーを返します。チェックポイントストアは自動では呼び出しません。
335 /// チェックポイントの解釈と進捗を永続化するかどうかは実装が定めます。
336 fn apply_once<'a>(
337 &'a mut self,
338 event: &'a Self::Event,
339 checkpoint: &'a ProjectionCheckpoint<Self::Cursor>,
340 ) -> Pin<Box<dyn Future<Output = Result<ProjectionApplication, Self::Error>> + Send + 'a>>;
341}