ddd_toolkit_core/dispatch.rs
1use crate::event_restoration_guard::EventRestorationGuard;
2use crate::{AggregateRoot, DomainEventPublisher};
3
4/// **English:**<br>
5/// Publishes the events currently held by `aggregate` through `publisher`.
6///
7/// Events are passed to [`DomainEventPublisher::publish`] in the order returned by
8/// [`AggregateRoot::pull_events`]. If a publish operation returns an error, all events pulled at
9/// the start of this call are recorded back into the aggregate before that error is returned.
10/// If every publish succeeds, the events are removed from the aggregate and the function returns
11/// `Ok(())`.
12///
13/// If [`DomainEventPublisher::publish`] panics and unwinds, a Drop guard records all pulled events
14/// back into the aggregate before unwinding continues. Restoration does not undo external side
15/// effects of publishing, including publishes that already succeeded; retrying can publish
16/// duplicates. Restoration may fail if destructors do not run (for example, with `panic=abort`)
17/// or if [`AggregateRoot::record_event`] itself panics during restoration.
18///
19/// The function may panic if the aggregate's [`AggregateRoot::pull_events`] or
20/// [`AggregateRoot::record_event`] implementation panics. It does not impose additional
21/// synchronization; the aggregate and publisher must be mutably borrowed by the caller for the
22/// duration of the dispatch.
23///
24/// **日本語:**<br>
25/// `aggregate` が現在保持しているイベントを `publisher` 経由で発行します。
26///
27/// イベントは [`AggregateRoot::pull_events`] が返した順序で [`DomainEventPublisher::publish`]
28/// に渡されます。発行処理がエラーを返すと、この呼び出しの開始時に取り出したすべての
29/// イベントを集約へ記録し直してから、そのエラーを返します。すべての発行に成功した場合、
30/// イベントは集約から削除され、`Ok(())` を返します。
31///
32/// [`DomainEventPublisher::publish`] のパニックがアンワインドする場合、Dropガードが
33/// 取り出した全イベントを集約へ記録し直してから、アンワインドが継続します。復元は、
34/// すでに成功した発行を含め、発行による外部副作用を取り消しません。再試行すると重複発行
35/// される可能性があります。`panic=abort` などでデストラクタが実行されない場合や、
36/// 復元中に [`AggregateRoot::record_event`] 自体がパニックする場合、復元は保証されません。
37///
38/// 集約の [`AggregateRoot::pull_events`] または [`AggregateRoot::record_event`] の実装が
39/// パニックすると、この関数もパニックする可能性があります。この関数は追加の同期を
40/// 行わないため、呼び出し側はディスパッチ中、集約とパブリッシャーを可変借用します。
41pub fn dispatch_events<A, P>(aggregate: &mut A, publisher: &mut P) -> Result<(), P::Error>
42where
43 A: AggregateRoot,
44 P: DomainEventPublisher<Event = A::Event>,
45{
46 let snapshot = aggregate.pull_events();
47 let mut guard = EventRestorationGuard::new(aggregate, snapshot);
48
49 for event in guard.events() {
50 publisher.publish(event)?;
51 }
52
53 guard.commit();
54 Ok(())
55}