capy_core/events.rs
1//! Typed, ordered transaction participants. These are not a durable event broker.
2use crate::{AppConfig, AppContext, AppError, EventError, EventResult, Result};
3use futures_util::FutureExt;
4use sea_orm::DatabaseTransaction;
5use std::{
6 any::{Any, TypeId},
7 collections::HashMap,
8 future::Future,
9 panic::AssertUnwindSafe,
10 pin::Pin,
11 sync::Arc,
12};
13
14/// Explicit opt-in to transactional application events. No serialization is required.
15/// Event values must not contain passwords, session/CSRF credentials or reset tokens.
16pub trait Event: Send + Sync + 'static {}
17/// A listener future borrowing the event, configuration and native transaction.
18pub type EventFuture<'a> = Pin<Box<dyn Future<Output = EventResult> + Send + 'a>>;
19/// Transaction-oriented services. No application pool is exposed. Reuse
20/// `transaction` for repository calls and `ctx.jobs().dispatch(job)` (with the jobs
21/// extension trait) for atomic enqueue. Avoid network I/O and capturing a pool:
22/// reacquiring a connection can deadlock even on PostgreSQL when its pool is full.
23#[derive(Clone, Copy)]
24pub struct EventContext<'a> {
25 /// Immutable application configuration; capture other non-database services explicitly.
26 pub config: &'a AppConfig,
27 /// The caller's uncommitted transaction. Listeners cannot commit or roll it back.
28 pub transaction: &'a DatabaseTransaction,
29}
30type Listener = Arc<
31 dyn for<'a> Fn(&'a (dyn Any + Send + Sync), EventContext<'a>) -> EventFuture<'a> + Send + Sync,
32>;
33/// Immutable, cheaply cloned registration snapshot. Each listener is called once per
34/// dispatch, in registration order. The first rejection/failure stops dispatch;
35/// the owner MUST roll back. Cancellation also requires rollback. Only explicit
36/// `EventError::Reject` values become public application errors. Unexpected errors
37/// and unwinding panics become a generic 500 (panic=abort still aborts the process).
38///
39/// Perform only transactional writes/enqueues here, never SMTP/network side effects.
40/// A listener is not an after-commit callback. Durable external work belongs in Jobs;
41/// those execute at least once. Retrying a transaction invokes its listeners again.
42#[derive(Clone, Default)]
43pub struct Events {
44 listeners: HashMap<TypeId, Vec<Listener>>,
45}
46impl Events {
47 /// Start an empty registry. No background task or global state is installed.
48 pub fn new() -> Self {
49 Self::default()
50 }
51 /// Append a typed listener. `Box::pin(async move { ... })` permits borrowing the
52 /// transaction without spawning or cloning it. Captured dependencies must be shared.
53 ///
54 /// ```
55 /// use capy_core::{Event, Events};
56 /// struct Created { id: i64 }
57 /// impl Event for Created {}
58 /// let events = Events::new().on::<Created>(|event, ctx| Box::pin(async move {
59 /// let _ = (event.id, ctx.config, ctx.transaction);
60 /// Ok(())
61 /// }));
62 /// ```
63 pub fn on<E: Event>(
64 mut self,
65 listener: impl for<'a> Fn(&'a E, EventContext<'a>) -> EventFuture<'a> + Send + Sync + 'static,
66 ) -> Self {
67 self.listeners
68 .entry(TypeId::of::<E>())
69 .or_default()
70 .push(Arc::new(move |event, ctx| {
71 // Registry key and value are constructed together; no unchecked casts.
72 match event.downcast_ref::<E>() {
73 Some(event) => listener(event, ctx),
74 None => Box::pin(async { Err(AppError::Lifecycle.into()) }),
75 }
76 }));
77 self
78 }
79 /// Participate in the caller's native transaction. Successful return does not
80 /// imply commit. Propagate failures and roll back the whole application transition.
81 /// This deliberately never dispatches using the pool outside a transaction.
82 pub async fn dispatch_in<E: Event>(
83 &self,
84 transaction: &DatabaseTransaction,
85 app: &AppContext,
86 event: E,
87 ) -> Result<()> {
88 if let Some(listeners) = self.listeners.get(&TypeId::of::<E>()) {
89 for (index, listener) in listeners.iter().enumerate() {
90 // Catch both a panic constructing the future and one polling it.
91 // Framework tracing/HTTP never expose panic payloads or native error text.
92 // The process-wide panic hook still follows application configuration.
93 let outcome = AssertUnwindSafe(async {
94 listener(
95 &event,
96 EventContext {
97 config: &app.config,
98 transaction,
99 },
100 )
101 .await
102 })
103 .catch_unwind()
104 .await;
105 if let Ok(Err(EventError::Reject(problem))) = outcome {
106 tracing::info!(
107 event = "lifecycle.handler.rejected",
108 event_type = std::any::type_name::<E>(),
109 listener_index = index
110 );
111 return Err(problem.into());
112 }
113 if !matches!(outcome, Ok(Ok(()))) {
114 let error_kind = match &outcome {
115 Ok(Err(EventError::Failure(error))) => error.kind(),
116 _ => "panic",
117 };
118 tracing::warn!(
119 event = "lifecycle.handler.failed",
120 event_type = std::any::type_name::<E>(),
121 listener_index = index,
122 error_kind
123 );
124 return Err(AppError::Lifecycle);
125 }
126 }
127 }
128 Ok(())
129 }
130}
131/// Extract the same registry installed by `App::on` for application-owned transitions.
132#[derive(Clone)]
133pub struct EventBus(pub Events);
134impl<S: Send + Sync> axum::extract::FromRequestParts<S> for EventBus {
135 type Rejection = AppError;
136 async fn from_request_parts(parts: &mut axum::http::request::Parts, _: &S) -> Result<Self> {
137 parts
138 .extensions
139 .get::<Events>()
140 .cloned()
141 .map(Self)
142 .ok_or_else(|| AppError::Configuration("Install App before using EventBus.".into()))
143 }
144}