rust-webx-core 1.1.0

rust-webx core traits: IRequest, IRequestHandler, IMiddleware, IHttpContext, IMediator, and more
Documentation
//! Handler traits: IRequestHandler and IEventHandler.
//!
//! ## IRequestHandler<T, R>
//!
//! Dual-type-parameter handler: `T` is the request type, `R` is the response type.
//! The constraint `T: IRequest<R>` ensures type safety between request and response.
//!
//! `handle` takes `&mut self` so handlers that own a `DbContext` (resolved via
//! `get_owned` — EFCore-style per-request unit-of-work) can call `ctx.set::<T>()`
//! and `ctx.save_changes()` which require `&mut self`.
//!
//! ```ignore
//! #[async_trait]
//! impl IRequestHandler<GetUserRequest, UserModel> for GetUserHandler {
//!     async fn handle(&mut self, req: GetUserRequest) -> ActionResult<UserModel> { ... }
//! }
//! ```

use crate::error::{ActionResult, Result};
use crate::mediator::{IEventRequest, IRequest};

/// Handles a single `IRequest<R>`, producing its associated response `R`.
///
/// Authentication identity is not passed as a method parameter — this trait stays
/// free of auth concerns. Requests that need the caller declare
/// `#[fromclaim] user: IdentityUser`; the binder fills it before `handle` runs.
///
/// Register via `#[handler]` proc macro for compile-time collection; for
/// non-HTTP Mediator use, register the handler in DI with rust-dix's
/// `#[rust_dix::inject]` attribute (trait-impl registration) or
/// `ServiceCollection::singleton`.
///
/// `handle(&mut self, ...)` enables the EFCore-style owned-DbContext pattern:
/// handlers declare a bare `ctx: DbContext` field, resolved per-request via
/// `IServiceResolver::get_owned`, and mutate it directly without `Arc<Mutex>`.
///
/// ```ignore
/// #[async_trait]
/// impl IRequestHandler<GetUserRequest, UserModel> for GetUserHandler {
///     async fn handle(&mut self, req: GetUserRequest) -> ActionResult<UserModel> { ... }
/// }
/// ```
#[async_trait::async_trait]
pub trait IRequestHandler<T, R>: Send + Sync
where
    T: IRequest<R> + Send + 'static,
    R: Send + 'static,
{
    /// Handle the request.
    async fn handle(&mut self, req: T) -> ActionResult<R>;
}

/// Handles a single `IEventRequest`, performing side effects.
///
/// ```ignore
/// #[async_trait]
/// impl IEventHandler<UserCreatedEvent> for SendWelcomeEmailHandler {
///     async fn handle(&self, event: UserCreatedEvent) -> Result<()> { ... }
/// }
/// ```
#[async_trait::async_trait]
pub trait IEventHandler<T: IEventRequest>: Send + Sync {
    async fn handle(&self, event: T) -> Result<()>;
}

/// Background service that is started when the host starts and
/// stopped when the host performs a graceful shutdown.
///
/// Analogous to ASP.NET Core's IHostedService.
///
/// Use this for:
/// - Data initialization / seeding at application startup
/// - Background polling loops
/// - Queue consumers
/// - Connection pool warmup
///
/// # Example
///
/// ```ignore
/// #[derive(Default)]
/// struct DbInitService;
///
/// #[async_trait]
/// impl IHostedService for DbInitService {
///     async fn start(&self) -> Result<()> {
///         tracing::info!("[DbInitService] Running migrations...");
///         run_migrations().await?;
///         tracing::info!("[DbInitService] Seeding data...");
///         seed_data().await?;
///         Ok(())
///     }
///
///     async fn stop(&self) -> Result<()> {
///         tracing::info!("[DbInitService] Shutting down...");
///         Ok(())
///     }
/// }
/// ```
#[async_trait::async_trait]
pub trait IHostedService: Send + Sync {
    /// Called when the host starts.
    ///
    /// Services start in registration order and the host waits for all of them
    /// before accepting requests. There is **no ambient DI context**: a hosted
    /// service that needs scoped dependencies (DbContext, transactions, ...)
    /// takes rust-dix's built-in `#[inject] services: Arc<dyn ScopeFactory>`
    /// field and opens its own scope
    /// (`let scope = services.create_scope();`), disposed with the scope.
    /// If one `start()` fails, the services that already started are stopped
    /// again in reverse order before the host reports the error.
    async fn start(&self) -> Result<()>;

    /// Called during a graceful shutdown.
    ///
    /// The host stops the services that started, in **reverse** start order
    /// (the last dependency to start is the first to stop), with a timeout per
    /// service so one stuck service cannot block the process forever. Like
    /// `start()`, each `stop()` runs inside a fresh DI scope.
    async fn stop(&self) -> Result<()> {
        Ok(())
    }
}