Skip to main content

capy_core/
events.rs

1//! Typed, ordered transaction participants. These are not a durable event broker.
2use crate::{AppConfig, AppContext, AppError, EventError, EventResult, Result, Services};
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.
26    pub config: &'a AppConfig,
27    /// The caller's uncommitted transaction. Listeners cannot commit or roll it back.
28    pub transaction: &'a DatabaseTransaction,
29    /// Typed application dependencies. Never perform external network I/O before commit.
30    pub services: &'a Services,
31}
32
33impl EventContext<'_> {
34    /// Access an application dependency for transactional work such as queued mail.
35    pub fn service<T: Send + Sync + 'static>(&self) -> Result<Arc<T>> {
36        self.services.get::<T>()
37    }
38}
39type Listener = Arc<
40    dyn for<'a> Fn(&'a (dyn Any + Send + Sync), EventContext<'a>) -> EventFuture<'a> + Send + Sync,
41>;
42/// Immutable, cheaply cloned registration snapshot. Each listener is called once per
43/// dispatch, in registration order. The first rejection/failure stops dispatch;
44/// the owner MUST roll back. Cancellation also requires rollback. Only explicit
45/// `EventError::Reject` values become public application errors. Unexpected errors
46/// and unwinding panics become a generic 500 (panic=abort still aborts the process).
47///
48/// Perform only transactional writes/enqueues here, never SMTP/network side effects.
49/// A listener is not an after-commit callback. Durable external work belongs in Jobs;
50/// those execute at least once. Retrying a transaction invokes its listeners again.
51#[derive(Clone, Default)]
52pub struct Events {
53    listeners: HashMap<TypeId, Vec<Listener>>,
54    services: Services,
55}
56impl Events {
57    /// Start an empty registry. No background task or global state is installed.
58    pub fn new() -> Self {
59        Self::default()
60    }
61    /// Supply the application factory's immutable dependency snapshot.
62    pub fn with_services(mut self, services: Services) -> Self {
63        self.services = services;
64        self
65    }
66    /// Append a typed listener. `Box::pin(async move { ... })` permits borrowing the
67    /// transaction without spawning or cloning it. Captured dependencies must be shared.
68    ///
69    /// ```
70    /// use capy_core::{Event, Events};
71    /// struct Created { id: i64 }
72    /// impl Event for Created {}
73    /// let events = Events::new().on::<Created>(|event, ctx| Box::pin(async move {
74    ///     let _ = (event.id, ctx.config, ctx.transaction);
75    ///     Ok(())
76    /// }));
77    /// ```
78    pub fn on<E: Event>(
79        mut self,
80        listener: impl for<'a> Fn(&'a E, EventContext<'a>) -> EventFuture<'a> + Send + Sync + 'static,
81    ) -> Self {
82        self.listeners
83            .entry(TypeId::of::<E>())
84            .or_default()
85            .push(Arc::new(move |event, ctx| {
86                // Registry key and value are constructed together; no unchecked casts.
87                match event.downcast_ref::<E>() {
88                    Some(event) => listener(event, ctx),
89                    None => Box::pin(async { Err(AppError::Lifecycle.into()) }),
90                }
91            }));
92        self
93    }
94    /// Participate in the caller's native transaction. Successful return does not
95    /// imply commit. Propagate failures and roll back the whole application transition.
96    /// This deliberately never dispatches using the pool outside a transaction.
97    pub async fn dispatch_in<E: Event>(
98        &self,
99        transaction: &DatabaseTransaction,
100        app: &AppContext,
101        event: E,
102    ) -> Result<()> {
103        if let Some(listeners) = self.listeners.get(&TypeId::of::<E>()) {
104            for (index, listener) in listeners.iter().enumerate() {
105                // Catch both a panic constructing the future and one polling it.
106                // Framework tracing/HTTP never expose panic payloads or native error text.
107                // The process-wide panic hook still follows application configuration.
108                let outcome = AssertUnwindSafe(async {
109                    listener(
110                        &event,
111                        EventContext {
112                            config: &app.config,
113                            transaction,
114                            services: &self.services,
115                        },
116                    )
117                    .await
118                })
119                .catch_unwind()
120                .await;
121                if let Ok(Err(EventError::Reject(problem))) = outcome {
122                    tracing::info!(
123                        event = "lifecycle.handler.rejected",
124                        event_type = std::any::type_name::<E>(),
125                        listener_index = index
126                    );
127                    return Err(problem.into());
128                }
129                if !matches!(outcome, Ok(Ok(()))) {
130                    let error_kind = match &outcome {
131                        Ok(Err(EventError::Failure(error))) => error.kind(),
132                        _ => "panic",
133                    };
134                    tracing::warn!(
135                        event = "lifecycle.handler.failed",
136                        event_type = std::any::type_name::<E>(),
137                        listener_index = index,
138                        error_kind
139                    );
140                    return Err(AppError::Lifecycle);
141                }
142            }
143        }
144        Ok(())
145    }
146}
147/// Extract the same registry installed by `App::on` for application-owned transitions.
148#[derive(Clone)]
149pub struct EventBus(pub Events);
150impl<S: Send + Sync> axum::extract::FromRequestParts<S> for EventBus {
151    type Rejection = AppError;
152    async fn from_request_parts(parts: &mut axum::http::request::Parts, _: &S) -> Result<Self> {
153        parts
154            .extensions
155            .get::<Events>()
156            .cloned()
157            .map(Self)
158            .ok_or_else(|| AppError::Configuration("Install App before using EventBus.".into()))
159    }
160}