jaeb 0.4.0

simple snapshot-driven event bus
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;

use crate::deps::Deps;
use crate::error::{EventBusError, HandlerResult};
use crate::registry::{ErasedAsyncHandlerFn, ErasedSyncHandlerFn, EventType, ListenerEntry, ListenerKind};
use crate::subscription::Subscription;
use crate::types::Event;

/// Trait for **asynchronous** event handlers.
///
/// Implement this trait on a struct to receive events of type `E`
/// asynchronously. When an event is published:
/// - The event is cloned once per registered async listener (hence the
///   `E: Clone` bound).
/// - Each invocation is spawned as an independent Tokio task.
/// - [`EventBus::publish`](crate::EventBus::publish) returns once all async
///   handler tasks have been *spawned*, not necessarily *completed*.
///
/// # Examples
///
/// ```
/// use jaeb::{EventHandler, HandlerResult};
///
/// #[derive(Clone)]
/// struct OrderPlaced { id: u64 }
///
/// struct EmailNotifier;
///
/// impl EventHandler<OrderPlaced> for EmailNotifier {
///     async fn handle(&self, event: &OrderPlaced) -> HandlerResult {
///         // send email …
///         Ok(())
///     }
/// }
/// ```
pub trait EventHandler<E: Event + Clone>: Send + Sync + 'static {
    /// Handle a single published event.
    ///
    /// Called with a shared reference to the cloned event. Return `Ok(())`
    /// on success or a [`HandlerError`](crate::HandlerError) on failure.
    /// Failures are subject to the listener's
    /// [`SubscriptionPolicy`](crate::SubscriptionPolicy).
    fn handle(&self, event: &E) -> impl Future<Output = HandlerResult> + Send;

    /// Return an optional human-readable name for this listener.
    ///
    /// The name appears in [`HandlerInfo`](crate::HandlerInfo) (reported by
    /// [`EventBus::stats`](crate::EventBus::stats)) and in
    /// [`DeadLetter::handler_name`](crate::DeadLetter::handler_name).
    ///
    /// Defaults to `None`; the standalone `#[handler]` macro (feature
    /// `macros`) sets this automatically from the function name.
    fn name(&self) -> Option<&'static str> {
        None
    }
}

/// Trait for **synchronous** event handlers.
///
/// Implement this trait on a struct to receive events of type `E`
/// synchronously. When an event is published:
/// - The handler is called inline in a serialized per-event-type FIFO lane.
/// - [`EventBus::publish`](crate::EventBus::publish) waits for the handler to
///   return before proceeding.
/// - Sync handlers do **not** require `E: Clone` because the original event
///   reference is passed directly.
///
/// Sync handlers must use
/// [`SyncSubscriptionPolicy`](crate::SyncSubscriptionPolicy); passing a
/// [`SubscriptionPolicy`](crate::SubscriptionPolicy) for a sync handler is a
/// compile-time error.
///
/// # Examples
///
/// ```
/// use jaeb::{SyncEventHandler, HandlerResult};
///
/// #[derive(Clone)]
/// struct UserDeleted { id: u64 }
///
/// struct AuditLog;
///
/// impl SyncEventHandler<UserDeleted> for AuditLog {
///     fn handle(&self, event: &UserDeleted) -> HandlerResult {
///         // write to audit log …
///         Ok(())
///     }
/// }
/// ```
pub trait SyncEventHandler<E: Event>: Send + Sync + 'static {
    /// Handle a single published event synchronously.
    ///
    /// Called with a shared reference to the event. Return `Ok(())` on success
    /// or a [`HandlerError`](crate::HandlerError) on failure. On failure a
    /// [`DeadLetter`](crate::DeadLetter) is emitted if the listener's policy
    /// has `dead_letter` enabled.
    fn handle(&self, event: &E) -> HandlerResult;

    /// Return an optional human-readable name for this listener.
    ///
    /// See [`EventHandler::name`] for details.
    fn name(&self) -> Option<&'static str> {
        None
    }
}

/// Marker type that selects **async struct** dispatch for [`IntoHandler`].
///
/// Used as the `Mode` type parameter when a struct implementing
/// [`EventHandler<E>`] is passed to a `subscribe_*` method.
pub struct AsyncMode;
/// Marker type that selects **sync struct** dispatch for [`IntoHandler`].
///
/// Used as the `Mode` type parameter when a struct implementing
/// [`SyncEventHandler<E>`] is passed to a `subscribe_*` method.
pub struct SyncMode;
/// Marker type that selects **async function** dispatch for [`IntoHandler`].
///
/// Used as the `Mode` type parameter when a plain `async fn(E) -> HandlerResult`
/// function pointer or closure is passed to a `subscribe_*` method.
pub struct AsyncFnMode;
/// Marker type that selects **sync function** dispatch for [`IntoHandler`].
///
/// Used as the `Mode` type parameter when a plain `fn(&E) -> HandlerResult`
/// function pointer or closure is passed to a `subscribe_*` method.
pub struct SyncFnMode;

pub(crate) type RegisterFn = Box<dyn FnOnce(crate::types::SubscriptionId, crate::types::SubscriptionPolicy, bool) -> ListenerEntry + Send>;

pub(crate) struct RegisteredHandler {
    pub register: RegisterFn,
    pub name: Option<&'static str>,
    pub is_sync: bool,
}

/// Type-erases a concrete handler into the internal representation
/// expected by the bus registry.
///
/// This trait is implemented for:
/// - Structs implementing [`EventHandler<E>`] (selects [`AsyncMode`]).
/// - Structs implementing [`SyncEventHandler<E>`] (selects [`SyncMode`]).
/// - `async fn(E) -> HandlerResult` closures / function pointers (selects
///   [`AsyncFnMode`]).
/// - `fn(&E) -> HandlerResult` closures / function pointers (selects
///   [`SyncFnMode`]).
///
/// The `Mode` type parameter is inferred by the compiler from the concrete
/// handler type; callers never need to name it explicitly.
///
/// You do not need to implement this trait manually — it is a blanket
/// implementation over [`EventHandler`] and [`SyncEventHandler`].
#[allow(private_interfaces)]
pub trait IntoHandler<E: Event, Mode> {
    #[doc(hidden)]
    fn into_handler(self) -> RegisteredHandler;
}

#[allow(private_interfaces)]
impl<E, H> IntoHandler<E, AsyncMode> for H
where
    E: Event + Clone,
    H: EventHandler<E>,
{
    fn into_handler(self) -> RegisteredHandler {
        let name = self.name();
        let handler = Arc::new(self);
        let register: RegisterFn = Box::new(move |id, subscription_policy, once| {
            let typed_fn: ErasedAsyncHandlerFn = Arc::new(move |event: EventType| {
                let handler = Arc::clone(&handler);
                let event = event.downcast::<E>();
                Box::pin(async move {
                    let event = event.map_err(|_| "event type mismatch")?;
                    let event = (*event).clone();
                    handler.handle(&event).await
                })
            });
            ListenerEntry {
                id,
                kind: ListenerKind::Async(typed_fn),
                subscription_policy,
                name,
                once,
                fired: once.then(|| Arc::new(AtomicBool::new(false))),
            }
        });

        RegisteredHandler {
            register,
            name,
            is_sync: false,
        }
    }
}

#[allow(private_interfaces)]
impl<E, H> IntoHandler<E, SyncMode> for H
where
    E: Event,
    H: SyncEventHandler<E>,
{
    fn into_handler(self) -> RegisteredHandler {
        let name = self.name();
        let handler = Arc::new(self);
        let register: RegisterFn = Box::new(move |id, subscription_policy, once| {
            let typed_fn: ErasedSyncHandlerFn = Arc::new(move |event: &(dyn std::any::Any + Send + Sync)| {
                let Some(event) = event.downcast_ref::<E>() else {
                    return Err("event type mismatch".into());
                };
                handler.handle(event)
            });
            ListenerEntry {
                id,
                kind: ListenerKind::Sync(typed_fn),
                subscription_policy,
                name,
                once,
                fired: once.then(|| Arc::new(AtomicBool::new(false))),
            }
        });

        RegisteredHandler {
            register,
            name,
            is_sync: true,
        }
    }
}

#[allow(private_interfaces)]
impl<E, F> IntoHandler<E, SyncFnMode> for F
where
    E: Event,
    F: Fn(&E) -> HandlerResult + Send + Sync + 'static,
{
    fn into_handler(self) -> RegisteredHandler {
        let handler = Arc::new(self);
        let register: RegisterFn = Box::new(move |id, subscription_policy, once| {
            let typed_fn: ErasedSyncHandlerFn = Arc::new(move |event: &(dyn std::any::Any + Send + Sync)| {
                let Some(event) = event.downcast_ref::<E>() else {
                    return Err("event type mismatch".into());
                };
                handler(event)
            });
            ListenerEntry {
                id,
                kind: ListenerKind::Sync(typed_fn),
                subscription_policy,
                name: None,
                once,
                fired: once.then(|| Arc::new(AtomicBool::new(false))),
            }
        });

        RegisteredHandler {
            register,
            name: None,
            is_sync: true,
        }
    }
}

#[allow(private_interfaces)]
impl<E, F, Fut> IntoHandler<E, AsyncFnMode> for F
where
    E: Event + Clone,
    F: Fn(E) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = HandlerResult> + Send + 'static,
{
    fn into_handler(self) -> RegisteredHandler {
        let handler = Arc::new(self);
        let register: RegisterFn = Box::new(move |id, subscription_policy, once| {
            let typed_fn: ErasedAsyncHandlerFn = Arc::new(move |event: EventType| {
                let handler = Arc::clone(&handler);
                let event = event.downcast::<E>();
                Box::pin(async move {
                    let event = event.map_err(|_| "event type mismatch")?;
                    let event = (*event).clone();
                    handler(event).await
                })
            });
            ListenerEntry {
                id,
                kind: ListenerKind::Async(typed_fn),
                subscription_policy,
                name: None,
                once,
                fired: once.then(|| Arc::new(AtomicBool::new(false))),
            }
        });

        RegisteredHandler {
            register,
            name: None,
            is_sync: false,
        }
    }
}

// ── HandlerDescriptor / DeadLetterDescriptor ──────────────────────────────────

/// Trait for types that can register themselves as a handler on an [`EventBus`](crate::EventBus)
/// using dependencies supplied by a [`Deps`] container.
///
/// This is the primary extension point for the builder-first registration
/// pattern. Types implementing this trait are passed to
/// [`EventBusBuilder::handler`](crate::EventBusBuilder::handler) and are
/// registered during [`build`](crate::EventBusBuilder::build).
///
/// # Manual implementation
///
/// You rarely need to implement this by hand — the `#[handler]` macro (feature
/// `macros`) generates the implementation automatically. A manual implementation
/// looks like:
///
/// ```rust,ignore
/// use std::pin::Pin;
/// use std::sync::Arc;
/// use jaeb::{Deps, EventBus, EventHandler, HandlerDescriptor, HandlerResult, Subscription, EventBusError};
///
/// #[derive(Clone)]
/// struct OrderPlaced { pub id: u64 }
///
/// struct NotifyHandler;
///
/// impl EventHandler<OrderPlaced> for NotifyHandler {
///     async fn handle(&self, event: &OrderPlaced) -> HandlerResult { Ok(()) }
/// }
///
/// impl HandlerDescriptor for NotifyHandler {
///     fn register<'a>(
///         &'a self,
///         bus: &'a EventBus,
///         _deps: &'a Deps,
///     ) -> Pin<Box<dyn std::future::Future<Output = Result<Subscription, EventBusError>> + Send + 'a>> {
///         Box::pin(async move {
///             bus.subscribe::<OrderPlaced, _, _>(NotifyHandler).await
///         })
///     }
/// }
/// ```
pub trait HandlerDescriptor: Send + Sync + 'static {
    /// Register this handler on `bus`, resolving any dependencies from `deps`.
    ///
    /// Called once per descriptor during [`EventBusBuilder::build`](crate::EventBusBuilder::build).
    /// The returned [`Subscription`] is kept alive by the bus registry.
    fn register<'a>(
        &'a self,
        bus: &'a crate::bus::EventBus,
        deps: &'a Deps,
    ) -> Pin<Box<dyn Future<Output = Result<Subscription, EventBusError>> + Send + 'a>>;
}

/// Trait for types that register a **dead-letter** handler on an [`EventBus`](crate::EventBus).
///
/// This is a separate trait from [`HandlerDescriptor`] so that passing a
/// dead-letter handler to [`EventBusBuilder::handler`](crate::EventBusBuilder::handler)
/// — instead of the correct
/// [`EventBusBuilder::dead_letter`](crate::EventBusBuilder::dead_letter) — is
/// a **compile-time error**.
///
/// Dead-letter handlers must be **synchronous** (implement
/// [`SyncEventHandler<DeadLetter>`](crate::SyncEventHandler)). The `dead_letter`
/// flag on their subscription policy is forced to `false` to prevent infinite
/// recursion.
///
/// # Manual implementation
///
/// ```rust,ignore
/// use std::pin::Pin;
/// use jaeb::{DeadLetter, DeadLetterDescriptor, Deps, EventBus, EventBusError, HandlerResult, Subscription, SyncEventHandler};
///
/// struct LogDeadLetters;
///
/// impl SyncEventHandler<DeadLetter> for LogDeadLetters {
///     fn handle(&self, dl: &DeadLetter) -> HandlerResult {
///         eprintln!("dead letter: {:?}", dl);
///         Ok(())
///     }
/// }
///
/// impl DeadLetterDescriptor for LogDeadLetters {
///     fn register_dead_letter<'a>(
///         &'a self,
///         bus: &'a EventBus,
///         _deps: &'a Deps,
///     ) -> Pin<Box<dyn std::future::Future<Output = Result<Subscription, EventBusError>> + Send + 'a>> {
///         Box::pin(async move {
///             bus.subscribe_dead_letters(LogDeadLetters).await
///         })
///     }
/// }
/// ```
pub trait DeadLetterDescriptor: Send + Sync + 'static {
    /// Register this dead-letter handler on `bus`, resolving any dependencies
    /// from `deps`.
    ///
    /// Called once per descriptor during [`EventBusBuilder::build`](crate::EventBusBuilder::build).
    fn register_dead_letter<'a>(
        &'a self,
        bus: &'a crate::bus::EventBus,
        deps: &'a Deps,
    ) -> Pin<Box<dyn Future<Output = Result<Subscription, EventBusError>> + Send + 'a>>;
}