capy-core 0.10.0

Typed configuration, application context, and errors for the Capy web framework.
Documentation
//! Typed, ordered transaction participants. These are not a durable event broker.
use crate::{AppConfig, AppContext, AppError, EventError, EventResult, Result, Services};
use futures_util::FutureExt;
use sea_orm::DatabaseTransaction;
use std::{
    any::{Any, TypeId},
    collections::HashMap,
    future::Future,
    panic::AssertUnwindSafe,
    pin::Pin,
    sync::Arc,
};

/// Explicit opt-in to transactional application events. No serialization is required.
/// Event values must not contain passwords, session/CSRF credentials or reset tokens.
pub trait Event: Send + Sync + 'static {}
/// A listener future borrowing the event, configuration and native transaction.
pub type EventFuture<'a> = Pin<Box<dyn Future<Output = EventResult> + Send + 'a>>;
/// Transaction-oriented services. No application pool is exposed. Reuse
/// `transaction` for repository calls and `ctx.jobs().dispatch(job)` (with the jobs
/// extension trait) for atomic enqueue. Avoid network I/O and capturing a pool:
/// reacquiring a connection can deadlock even on PostgreSQL when its pool is full.
#[derive(Clone, Copy)]
pub struct EventContext<'a> {
    /// Immutable application configuration.
    pub config: &'a AppConfig,
    /// The caller's uncommitted transaction. Listeners cannot commit or roll it back.
    pub transaction: &'a DatabaseTransaction,
    /// Typed application dependencies. Never perform external network I/O before commit.
    pub services: &'a Services,
}

impl EventContext<'_> {
    /// Access an application dependency for transactional work such as queued mail.
    pub fn service<T: Send + Sync + 'static>(&self) -> Result<Arc<T>> {
        self.services.get::<T>()
    }
}
type Listener = Arc<
    dyn for<'a> Fn(&'a (dyn Any + Send + Sync), EventContext<'a>) -> EventFuture<'a> + Send + Sync,
>;
/// Immutable, cheaply cloned registration snapshot. Each listener is called once per
/// dispatch, in registration order. The first rejection/failure stops dispatch;
/// the owner MUST roll back. Cancellation also requires rollback. Only explicit
/// `EventError::Reject` values become public application errors. Unexpected errors
/// and unwinding panics become a generic 500 (panic=abort still aborts the process).
///
/// Perform only transactional writes/enqueues here, never SMTP/network side effects.
/// A listener is not an after-commit callback. Durable external work belongs in Jobs;
/// those execute at least once. Retrying a transaction invokes its listeners again.
#[derive(Clone, Default)]
pub struct Events {
    listeners: HashMap<TypeId, Vec<Listener>>,
    services: Services,
}
impl Events {
    /// Start an empty registry. No background task or global state is installed.
    pub fn new() -> Self {
        Self::default()
    }
    /// Supply the application factory's immutable dependency snapshot.
    pub fn with_services(mut self, services: Services) -> Self {
        self.services = services;
        self
    }
    /// Append a typed listener. `Box::pin(async move { ... })` permits borrowing the
    /// transaction without spawning or cloning it. Captured dependencies must be shared.
    ///
    /// ```
    /// use capy_core::{Event, Events};
    /// struct Created { id: i64 }
    /// impl Event for Created {}
    /// let events = Events::new().on::<Created>(|event, ctx| Box::pin(async move {
    ///     let _ = (event.id, ctx.config, ctx.transaction);
    ///     Ok(())
    /// }));
    /// ```
    pub fn on<E: Event>(
        mut self,
        listener: impl for<'a> Fn(&'a E, EventContext<'a>) -> EventFuture<'a> + Send + Sync + 'static,
    ) -> Self {
        self.listeners
            .entry(TypeId::of::<E>())
            .or_default()
            .push(Arc::new(move |event, ctx| {
                // Registry key and value are constructed together; no unchecked casts.
                match event.downcast_ref::<E>() {
                    Some(event) => listener(event, ctx),
                    None => Box::pin(async { Err(AppError::Lifecycle.into()) }),
                }
            }));
        self
    }
    /// Participate in the caller's native transaction. Successful return does not
    /// imply commit. Propagate failures and roll back the whole application transition.
    /// This deliberately never dispatches using the pool outside a transaction.
    pub async fn dispatch_in<E: Event>(
        &self,
        transaction: &DatabaseTransaction,
        app: &AppContext,
        event: E,
    ) -> Result<()> {
        if let Some(listeners) = self.listeners.get(&TypeId::of::<E>()) {
            for (index, listener) in listeners.iter().enumerate() {
                // Catch both a panic constructing the future and one polling it.
                // Framework tracing/HTTP never expose panic payloads or native error text.
                // The process-wide panic hook still follows application configuration.
                let outcome = AssertUnwindSafe(async {
                    listener(
                        &event,
                        EventContext {
                            config: &app.config,
                            transaction,
                            services: &self.services,
                        },
                    )
                    .await
                })
                .catch_unwind()
                .await;
                if let Ok(Err(EventError::Reject(problem))) = outcome {
                    tracing::info!(
                        event = "lifecycle.handler.rejected",
                        event_type = std::any::type_name::<E>(),
                        listener_index = index
                    );
                    return Err(problem.into());
                }
                if !matches!(outcome, Ok(Ok(()))) {
                    let error_kind = match &outcome {
                        Ok(Err(EventError::Failure(error))) => error.kind(),
                        _ => "panic",
                    };
                    tracing::warn!(
                        event = "lifecycle.handler.failed",
                        event_type = std::any::type_name::<E>(),
                        listener_index = index,
                        error_kind
                    );
                    return Err(AppError::Lifecycle);
                }
            }
        }
        Ok(())
    }
}
/// Extract the same registry installed by `App::on` for application-owned transitions.
#[derive(Clone)]
pub struct EventBus(pub Events);
impl<S: Send + Sync> axum::extract::FromRequestParts<S> for EventBus {
    type Rejection = AppError;
    async fn from_request_parts(parts: &mut axum::http::request::Parts, _: &S) -> Result<Self> {
        parts
            .extensions
            .get::<Events>()
            .cloned()
            .map(Self)
            .ok_or_else(|| AppError::Configuration("Install App before using EventBus.".into()))
    }
}