qubit-event-bus 0.6.3

A lightweight, thread-safe in-process event bus for Rust
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
/*******************************************************************************
 *
 *    Copyright (c) 2026 Haixing Hu.
 *
 *    SPDX-License-Identifier: Apache-2.0
 *
 *    Licensed under the Apache License, Version 2.0.
 *
 ******************************************************************************/
//! Subscriber interceptor chain handle.
// qubit-style: allow multiple-public-types
// qubit-style: allow coverage-cfg

use std::panic::{
    self,
    AssertUnwindSafe,
};
use std::sync::{
    Arc,
    Mutex,
};
use std::time::Duration;

#[cfg(coverage)]
use crate::Topic;
use crate::{
    EventBusError,
    EventBusResult,
    EventEnvelope,
};

type HandlerFn<T> = dyn Fn(EventEnvelope<T>) -> EventBusResult<()> + Send + Sync + 'static;
pub(crate) type DownstreamErrorSlot = Arc<Mutex<Vec<DownstreamErrorRecord>>>;

/// Recorded downstream failure provenance for one interceptor invocation.
pub(crate) struct DownstreamErrorRecord {
    fingerprint: ErrorFingerprint,
}

/// Identity of a downstream error value returned from `proceed`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ErrorFingerprint {
    NotStarted,
    StartFailed(OwnedStringFingerprint),
    InvalidArgument {
        field: &'static str,
        message: OwnedStringFingerprint,
    },
    MissingField {
        field: &'static str,
    },
    HandlerFailed(OwnedStringFingerprint),
    HandlerPanicked,
    InterceptorFailed {
        phase: &'static str,
        message: OwnedStringFingerprint,
    },
    ErrorHandlerFailed {
        phase: &'static str,
        message: OwnedStringFingerprint,
    },
    DeadLetterFailed(OwnedStringFingerprint),
    ExecutionRejected(OwnedStringFingerprint),
    ShutdownTimedOut {
        timeout: Duration,
    },
    LockPoisoned {
        resource: &'static str,
    },
    TypeMismatch {
        expected: &'static str,
        actual: &'static str,
    },
    UnsupportedOperation {
        operation: &'static str,
    },
}

/// Allocation identity for owned string payloads inside an error.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct OwnedStringFingerprint {
    ptr: usize,
    len: usize,
}

/// Chain handle passed to subscriber interceptors.
///
/// Calling [`proceed`](Self::proceed) invokes the next subscriber interceptor,
/// or the original subscriber handler when the current interceptor is the last
/// one in the chain.
///
/// The chain is a one-shot continuation. Calling `proceed` consumes the chain,
/// so an interceptor cannot accidentally invoke downstream processing twice.
///
/// ```compile_fail
/// # use qubit_event_bus::{
/// #     EventBusResult,
/// #     EventEnvelope,
/// #     SubscriberInterceptorChain,
/// # };
/// # fn interceptor(
/// #     event: EventEnvelope<String>,
/// #     chain: SubscriberInterceptorChain<String>,
/// # ) -> EventBusResult<()> {
/// let first = chain.proceed(event.clone());
/// let second = chain.proceed(event);
/// # first?;
/// # second
/// # }
/// ```
pub struct SubscriberInterceptorChain<T: Clone + Send + Sync + 'static> {
    next: Arc<HandlerFn<T>>,
    downstream_error: DownstreamErrorSlot,
}

/// Chain handle passed to global subscriber interceptors.
///
/// Calling [`proceed`](Self::proceed) invokes the next global interceptor,
/// typed interceptor, or original subscriber handler.
///
/// The chain is a one-shot continuation. Calling `proceed` consumes the chain,
/// so an interceptor cannot accidentally invoke downstream processing twice.
///
/// ```compile_fail
/// # use qubit_event_bus::{
/// #     EventBusResult,
/// #     SubscriberInterceptorAnyChain,
/// # };
/// # fn interceptor(chain: SubscriberInterceptorAnyChain) -> EventBusResult<()> {
/// let first = chain.proceed();
/// let second = chain.proceed();
/// # first?;
/// # second
/// # }
/// ```
pub struct SubscriberInterceptorAnyChain {
    next: Arc<dyn Fn() -> EventBusResult<()> + Send + Sync + 'static>,
    downstream_error: DownstreamErrorSlot,
}

impl SubscriberInterceptorAnyChain {
    /// Creates a chain handle sharing downstream error state with the wrapper.
    ///
    /// # Parameters
    /// - `next`: Handler or interceptor wrapper to invoke next.
    /// - `downstream_error`: Shared slot recording downstream failures.
    ///
    /// # Returns
    /// Chain handle for one global interceptor invocation.
    pub(crate) fn with_downstream_error(
        next: Arc<dyn Fn() -> EventBusResult<()> + Send + Sync + 'static>,
        downstream_error: DownstreamErrorSlot,
    ) -> Self {
        Self {
            next,
            downstream_error,
        }
    }

    /// Continues subscriber processing, consuming this one-shot chain handle.
    ///
    /// # Returns
    /// `Ok(())` when downstream processing succeeds.
    ///
    /// # Errors
    /// Returns the downstream handler or interceptor error. If the downstream
    /// handler panics, the panic is isolated and returned as
    /// [`EventBusError::HandlerPanicked`].
    pub fn proceed(self) -> EventBusResult<()> {
        match panic::catch_unwind(AssertUnwindSafe(|| (self.next)())) {
            Ok(Ok(())) => Ok(()),
            Ok(Err(error)) => {
                record_downstream_error(&self.downstream_error, &error);
                Err(error)
            }
            Err(_) => {
                let error = EventBusError::handler_panicked();
                record_downstream_error(&self.downstream_error, &error);
                Err(error)
            }
        }
    }
}

impl<T> SubscriberInterceptorChain<T>
where
    T: Clone + Send + Sync + 'static,
{
    /// Creates a chain handle sharing downstream error state with the wrapper.
    ///
    /// # Parameters
    /// - `next`: Handler or interceptor wrapper to invoke next.
    /// - `downstream_error`: Shared slot recording downstream failures.
    ///
    /// # Returns
    /// Chain handle for one interceptor invocation.
    pub(crate) fn with_downstream_error(
        next: Arc<dyn Fn(EventEnvelope<T>) -> EventBusResult<()> + Send + Sync + 'static>,
        downstream_error: DownstreamErrorSlot,
    ) -> Self {
        Self {
            next,
            downstream_error,
        }
    }

    /// Continues subscriber processing, consuming this one-shot chain handle.
    ///
    /// # Parameters
    /// - `envelope`: Envelope to pass to the next chain element.
    ///
    /// # Returns
    /// `Ok(())` when downstream processing succeeds.
    ///
    /// # Errors
    /// Returns the downstream handler or interceptor error. If the downstream
    /// handler panics, the panic is isolated and returned as
    /// [`EventBusError::HandlerPanicked`].
    pub fn proceed(self, envelope: EventEnvelope<T>) -> EventBusResult<()> {
        match panic::catch_unwind(AssertUnwindSafe(|| (self.next)(envelope))) {
            Ok(Ok(())) => Ok(()),
            Ok(Err(error)) => {
                record_downstream_error(&self.downstream_error, &error);
                Err(error)
            }
            Err(_) => {
                let error = EventBusError::handler_panicked();
                record_downstream_error(&self.downstream_error, &error);
                Err(error)
            }
        }
    }
}

/// Creates shared state for one interceptor invocation.
///
/// # Returns
/// Empty downstream error slot.
pub(crate) fn create_downstream_error_slot() -> DownstreamErrorSlot {
    Arc::new(Mutex::new(Vec::new()))
}

/// Returns whether an error came from the downstream chain.
///
/// # Parameters
/// - `downstream_error`: Slot filled by [`SubscriberInterceptorChain::proceed`]
///   or [`SubscriberInterceptorAnyChain::proceed`].
/// - `error`: Error returned by an interceptor.
///
/// # Returns
/// `true` when `error` has the same provenance as a recorded downstream failure.
pub(crate) fn is_recorded_downstream_error(
    downstream_error: &DownstreamErrorSlot,
    error: &EventBusError,
) -> bool {
    let fingerprint = ErrorFingerprint::from_error(error);
    downstream_error
        .lock()
        .map(|recorded| {
            recorded
                .iter()
                .any(|record| record.fingerprint == fingerprint)
        })
        .unwrap_or(false)
}

/// Records a downstream failure observed by a chain handle.
///
/// # Parameters
/// - `downstream_error`: Shared error slot.
/// - `error`: Downstream failure to record.
fn record_downstream_error(downstream_error: &DownstreamErrorSlot, error: &EventBusError) {
    let record = DownstreamErrorRecord::new(error);
    if let Ok(mut recorded) = downstream_error.lock()
        && !recorded
            .iter()
            .any(|existing| existing.fingerprint == record.fingerprint)
    {
        recorded.push(record);
    }
}

impl DownstreamErrorRecord {
    /// Creates a downstream provenance record from an error value.
    ///
    /// # Parameters
    /// - `error`: Error returned by downstream processing.
    ///
    /// # Returns
    /// Record used to recognize the same downstream error if it is propagated.
    fn new(error: &EventBusError) -> Self {
        Self {
            fingerprint: ErrorFingerprint::from_error(error),
        }
    }
}

impl ErrorFingerprint {
    /// Captures the internal identity of an event bus error.
    ///
    /// # Parameters
    /// - `error`: Error value to fingerprint.
    ///
    /// # Returns
    /// Fingerprint that preserves allocation provenance for owned messages.
    fn from_error(error: &EventBusError) -> Self {
        match error {
            EventBusError::NotStarted => Self::NotStarted,
            EventBusError::StartFailed { message } => {
                Self::StartFailed(OwnedStringFingerprint::new(message))
            }
            EventBusError::InvalidArgument { field, message } => Self::InvalidArgument {
                field,
                message: OwnedStringFingerprint::new(message),
            },
            EventBusError::MissingField { field } => Self::MissingField { field },
            EventBusError::HandlerFailed { message } => {
                Self::HandlerFailed(OwnedStringFingerprint::new(message))
            }
            EventBusError::HandlerPanicked => Self::HandlerPanicked,
            EventBusError::InterceptorFailed { phase, message } => Self::InterceptorFailed {
                phase,
                message: OwnedStringFingerprint::new(message),
            },
            EventBusError::ErrorHandlerFailed { phase, message } => Self::ErrorHandlerFailed {
                phase,
                message: OwnedStringFingerprint::new(message),
            },
            EventBusError::DeadLetterFailed { message } => {
                Self::DeadLetterFailed(OwnedStringFingerprint::new(message))
            }
            EventBusError::ExecutionRejected { message } => {
                Self::ExecutionRejected(OwnedStringFingerprint::new(message))
            }
            EventBusError::ShutdownTimedOut { timeout } => {
                Self::ShutdownTimedOut { timeout: *timeout }
            }
            EventBusError::LockPoisoned { resource } => Self::LockPoisoned { resource },
            EventBusError::TypeMismatch { expected, actual } => {
                Self::TypeMismatch { expected, actual }
            }
            EventBusError::UnsupportedOperation { operation } => {
                Self::UnsupportedOperation { operation }
            }
        }
    }
}

impl OwnedStringFingerprint {
    /// Captures the allocation identity of a string slice.
    ///
    /// # Parameters
    /// - `message`: Owned string contents stored in an error.
    ///
    /// # Returns
    /// Pointer-and-length identity for the current allocation.
    fn new(message: &str) -> Self {
        Self {
            ptr: message.as_ptr() as usize,
            len: message.len(),
        }
    }
}

/// Exercises coverage-only defensive branches for subscriber interceptor chains.
///
/// # Returns
/// Errors observed while exercising downstream provenance recording.
#[cfg(coverage)]
pub fn coverage_exercise_subscriber_interceptor_chain_defensive_paths() -> Vec<EventBusError> {
    let mut errors = Vec::new();
    let empty_slot = create_downstream_error_slot();
    assert!(!is_recorded_downstream_error(
        &empty_slot,
        &EventBusError::not_started()
    ));

    let any_ok = SubscriberInterceptorAnyChain::with_downstream_error(
        Arc::new(|| Ok(())),
        create_downstream_error_slot(),
    );
    assert!(any_ok.proceed().is_ok());

    let any_error_slot = create_downstream_error_slot();
    let any_error = SubscriberInterceptorAnyChain::with_downstream_error(
        Arc::new(|| Err(EventBusError::start_failed("coverage any failed"))),
        Arc::clone(&any_error_slot),
    )
    .proceed()
    .expect_err("coverage any chain should fail");
    assert!(is_recorded_downstream_error(&any_error_slot, &any_error));
    errors.push(any_error);

    let any_panic_slot = create_downstream_error_slot();
    let any_panic = SubscriberInterceptorAnyChain::with_downstream_error(
        Arc::new(|| panic!("coverage any panic")),
        Arc::clone(&any_panic_slot),
    )
    .proceed()
    .expect_err("coverage any chain should report panic");
    assert!(is_recorded_downstream_error(&any_panic_slot, &any_panic));
    errors.push(any_panic);

    let topic =
        Topic::<String>::try_new("coverage-subscriber-chain").expect("coverage topic should build");
    let typed_ok = SubscriberInterceptorChain::with_downstream_error(
        Arc::new(|_event: EventEnvelope<String>| Ok(())),
        create_downstream_error_slot(),
    );
    assert!(
        typed_ok
            .proceed(EventEnvelope::create(topic.clone(), "ok".to_string()))
            .is_ok()
    );

    let typed_error_slot = create_downstream_error_slot();
    let typed_error = SubscriberInterceptorChain::with_downstream_error(
        Arc::new(|_event: EventEnvelope<String>| {
            Err(EventBusError::handler_failed("coverage typed failed"))
        }),
        Arc::clone(&typed_error_slot),
    )
    .proceed(EventEnvelope::create(
        topic.clone(),
        "typed-error".to_string(),
    ))
    .expect_err("coverage typed chain should fail");
    assert!(is_recorded_downstream_error(
        &typed_error_slot,
        &typed_error
    ));
    errors.push(typed_error);

    let typed_panic_slot = create_downstream_error_slot();
    let typed_panic = SubscriberInterceptorChain::with_downstream_error(
        Arc::new(|_event: EventEnvelope<String>| panic!("coverage typed panic")),
        Arc::clone(&typed_panic_slot),
    )
    .proceed(EventEnvelope::create(topic, "typed-panic".to_string()))
    .expect_err("coverage typed chain should report panic");
    assert!(is_recorded_downstream_error(
        &typed_panic_slot,
        &typed_panic
    ));
    errors.push(typed_panic);

    let direct_slot = create_downstream_error_slot();
    let direct_errors = vec![
        EventBusError::not_started(),
        EventBusError::invalid_argument("field", "invalid"),
        EventBusError::missing_field("field"),
        EventBusError::interceptor_failed("phase", "interceptor"),
        EventBusError::error_handler_failed("phase", "handler"),
        EventBusError::dead_letter_failed("dead letter"),
        EventBusError::execution_rejected("execution"),
        EventBusError::shutdown_timed_out(Duration::from_millis(1)),
        EventBusError::lock_poisoned("lock"),
        EventBusError::type_mismatch("expected", "actual"),
        EventBusError::unsupported_operation("operation"),
    ];
    for error in direct_errors {
        record_downstream_error(&direct_slot, &error);
        record_downstream_error(&direct_slot, &error);
        assert!(is_recorded_downstream_error(&direct_slot, &error));
        errors.push(error);
    }
    errors
}