Skip to main content

webx_core/
handler.rs

1//! Handler traits: IRequestHandler and IEventHandler.
2//!
3//! ## IRequestHandler<T, R>
4//!
5//! Dual-type-parameter handler: `T` is the request type, `R` is the response type.
6//! The constraint `T: IRequest<R>` ensures type safety between request and response.
7//!
8//! `handle` takes `&mut self` so handlers that own a `DbContext` (resolved via
9//! `get_owned` — EFCore-style per-request unit-of-work) can call `ctx.set::<T>()`
10//! and `ctx.save_changes()` which require `&mut self`.
11//!
12//! ```ignore
13//! #[async_trait]
14//! impl IRequestHandler<GetUserRequest, UserModel> for GetUserHandler {
15//!     async fn handle(&mut self, req: GetUserRequest) -> Result<UserModel> { ... }
16//! }
17//! ```
18
19use crate::error::Result;
20use crate::mediator::{IEventRequest, IRequest};
21
22/// Handles a single `IRequest<R>`, producing its associated response `R`.
23///
24/// Authentication identity is not passed as a method parameter — this trait stays
25/// free of auth concerns. Requests that need the caller declare
26/// `#[fromclaim] user: IdentityUser`; the binder fills it before `handle` runs.
27///
28/// Register via `#[handler]` proc macro for compile-time collection,
29/// or use `register_handlers!` for manual DI registration.
30///
31/// `handle(&mut self, ...)` enables the EFCore-style owned-DbContext pattern:
32/// handlers declare a bare `ctx: DbContext` field, resolved per-request via
33/// `IServiceResolver::get_owned`, and mutate it directly without `Arc<Mutex>`.
34///
35/// ```ignore
36/// #[async_trait]
37/// impl IRequestHandler<GetUserRequest, UserModel> for GetUserHandler {
38///     async fn handle(&mut self, req: GetUserRequest) -> Result<UserModel> { ... }
39/// }
40/// ```
41#[async_trait::async_trait]
42pub trait IRequestHandler<T, R>: Send + Sync
43where
44    T: IRequest<R> + Send + 'static,
45    R: Send + 'static,
46{
47    /// Handle the request.
48    async fn handle(&mut self, req: T) -> Result<R>;
49}
50
51/// Handles a single `IEventRequest`, performing side effects.
52///
53/// ```ignore
54/// #[async_trait]
55/// impl IEventHandler<UserCreatedEvent> for SendWelcomeEmailHandler {
56///     async fn handle(&self, event: UserCreatedEvent) -> Result<()> { ... }
57/// }
58/// ```
59#[async_trait::async_trait]
60pub trait IEventHandler<T: IEventRequest>: Send + Sync {
61    async fn handle(&self, event: T) -> Result<()>;
62}
63
64/// Background service that is started when the host starts and
65/// stopped when the host performs a graceful shutdown.
66///
67/// Analogous to ASP.NET Core's IHostedService.
68///
69/// Use this for:
70/// - Data initialization / seeding at application startup
71/// - Background polling loops
72/// - Queue consumers
73/// - Connection pool warmup
74///
75/// # Example
76///
77/// ```ignore
78/// #[derive(Default)]
79/// struct DbInitService;
80///
81/// #[async_trait]
82/// impl IHostedService for DbInitService {
83///     async fn start(&self) -> Result<()> {
84///         tracing::info!("[DbInitService] Running migrations...");
85///         run_migrations().await?;
86///         tracing::info!("[DbInitService] Seeding data...");
87///         seed_data().await?;
88///         Ok(())
89///     }
90///
91///     async fn stop(&self) -> Result<()> {
92///         tracing::info!("[DbInitService] Shutting down...");
93///         Ok(())
94///     }
95/// }
96/// ```
97#[async_trait::async_trait]
98pub trait IHostedService: Send + Sync {
99    /// Called when the host starts.
100    ///
101    /// The host waits for all hosted services to finish `start()`
102    /// before beginning to accept incoming requests.
103    async fn start(&self) -> Result<()>;
104
105    /// Called during a graceful shutdown.
106    ///
107    /// The host calls `stop()` on all hosted services concurrently
108    /// after the HTTP server has stopped accepting new connections.
109    async fn stop(&self) -> Result<()> {
110        Ok(())
111    }
112}