Skip to main content

capy_core/
events.rs

1//! Typed, ordered transaction participants. These are not a durable event broker.
2use crate::{AppContext, AppError, Result};
3use sea_orm::DatabaseTransaction;
4use std::{
5    any::{Any, TypeId},
6    collections::HashMap,
7    future::Future,
8    pin::Pin,
9    sync::Arc,
10};
11
12/// Explicit opt-in to transactional application events. No serialization is required.
13/// Event values must not contain passwords, session/CSRF credentials or reset tokens.
14pub trait Event: Send + Sync + 'static {}
15/// A listener future borrowing the event, application context and native transaction.
16pub type EventFuture<'a> = Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>;
17/// Services available during a transaction. Use `transaction` for all database writes
18/// and job enqueues. Accessing `app.db` opens a separate connection and can deadlock
19/// a one-connection SQLite pool. Capture additional application dependencies explicitly.
20#[derive(Clone, Copy)]
21pub struct EventContext<'a> {
22    /// Existing application configuration and pool; never an implicit service locator.
23    pub app: &'a AppContext,
24    /// The caller's uncommitted transaction. Listeners cannot commit or roll it back.
25    pub transaction: &'a DatabaseTransaction,
26}
27type Listener = Arc<
28    dyn for<'a> Fn(&'a (dyn Any + Send + Sync), EventContext<'a>) -> EventFuture<'a> + Send + Sync,
29>;
30/// Immutable, cheaply cloned registration snapshot. Each listener is called once per
31/// dispatch, in registration order. The first error stops dispatch and returns a safe
32/// internal error; the owner MUST roll back. Cancellation also requires rollback.
33///
34/// Perform only transactional writes/enqueues here, never SMTP/network side effects.
35/// A listener is not an after-commit callback. Durable external work belongs in Jobs;
36/// those execute at least once. Retrying a transaction invokes its listeners again.
37#[derive(Clone, Default)]
38pub struct Events {
39    listeners: HashMap<TypeId, Vec<Listener>>,
40}
41impl Events {
42    /// Start an empty registry. No background task or global state is installed.
43    pub fn new() -> Self {
44        Self::default()
45    }
46    /// Append a typed listener. `Box::pin(async move { ... })` permits borrowing the
47    /// transaction without spawning or cloning it. Captured dependencies must be shared.
48    ///
49    /// ```
50    /// use capy_core::{Event, Events};
51    /// struct Created { id: i64 }
52    /// impl Event for Created {}
53    /// let events = Events::new().on::<Created>(|event, ctx| Box::pin(async move {
54    ///     let _ = (event.id, &ctx.app.config, ctx.transaction);
55    ///     Ok(())
56    /// }));
57    /// ```
58    pub fn on<E: Event>(
59        mut self,
60        listener: impl for<'a> Fn(&'a E, EventContext<'a>) -> EventFuture<'a> + Send + Sync + 'static,
61    ) -> Self {
62        self.listeners
63            .entry(TypeId::of::<E>())
64            .or_default()
65            .push(Arc::new(move |event, ctx| {
66                // Registry key and value are constructed together; no unchecked casts.
67                match event.downcast_ref::<E>() {
68                    Some(event) => listener(event, ctx),
69                    None => Box::pin(async { Err(AppError::Lifecycle) }),
70                }
71            }));
72        self
73    }
74    /// Participate in the caller's native transaction. Successful return does not
75    /// imply commit. Propagate failures and roll back the whole application transition.
76    /// This deliberately never dispatches using the pool outside a transaction.
77    pub async fn dispatch_in<E: Event>(
78        &self,
79        transaction: &DatabaseTransaction,
80        app: &AppContext,
81        event: E,
82    ) -> Result<()> {
83        if let Some(listeners) = self.listeners.get(&TypeId::of::<E>()) {
84            for (index, listener) in listeners.iter().enumerate() {
85                if let Err(error) = listener(&event, EventContext { app, transaction }).await {
86                    tracing::warn!(
87                        event = "lifecycle.handler.failed",
88                        event_type = std::any::type_name::<E>(),
89                        listener_index = index,
90                        error_kind = error.kind()
91                    );
92                    return Err(AppError::Lifecycle);
93                }
94            }
95        }
96        Ok(())
97    }
98}
99/// Extract the same registry installed by `App::on` for application-owned transitions.
100#[derive(Clone)]
101pub struct EventBus(pub Events);
102impl<S: Send + Sync> axum::extract::FromRequestParts<S> for EventBus {
103    type Rejection = AppError;
104    async fn from_request_parts(parts: &mut axum::http::request::Parts, _: &S) -> Result<Self> {
105        parts
106            .extensions
107            .get::<Events>()
108            .cloned()
109            .map(Self)
110            .ok_or_else(|| AppError::Configuration("Install App before using EventBus.".into()))
111    }
112}