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) -> ActionResult<UserModel> { ... }
16//! }
17//! ```
18
19use crate::error::{ActionResult, 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; for
29/// non-HTTP Mediator use, register the handler in DI with rust-dix's
30/// `#[rust_dix::inject]` attribute (trait-impl registration) or
31/// `ServiceCollection::singleton`.
32///
33/// `handle(&mut self, ...)` enables the EFCore-style owned-DbContext pattern:
34/// handlers declare a bare `ctx: DbContext` field, resolved per-request via
35/// `IServiceResolver::get_owned`, and mutate it directly without `Arc<Mutex>`.
36///
37/// ```ignore
38/// #[async_trait]
39/// impl IRequestHandler<GetUserRequest, UserModel> for GetUserHandler {
40///     async fn handle(&mut self, req: GetUserRequest) -> ActionResult<UserModel> { ... }
41/// }
42/// ```
43#[async_trait::async_trait]
44pub trait IRequestHandler<T, R>: Send + Sync
45where
46    T: IRequest<R> + Send + 'static,
47    R: Send + 'static,
48{
49    /// Handle the request.
50    async fn handle(&mut self, req: T) -> ActionResult<R>;
51}
52
53/// Handles a single `IEventRequest`, performing side effects.
54///
55/// ```ignore
56/// #[async_trait]
57/// impl IEventHandler<UserCreatedEvent> for SendWelcomeEmailHandler {
58///     async fn handle(&self, event: UserCreatedEvent) -> Result<()> { ... }
59/// }
60/// ```
61#[async_trait::async_trait]
62pub trait IEventHandler<T: IEventRequest>: Send + Sync {
63    async fn handle(&self, event: T) -> Result<()>;
64}
65
66/// Background service that is started when the host starts and
67/// stopped when the host performs a graceful shutdown.
68///
69/// Analogous to ASP.NET Core's IHostedService.
70///
71/// Use this for:
72/// - Data initialization / seeding at application startup
73/// - Background polling loops
74/// - Queue consumers
75/// - Connection pool warmup
76///
77/// # Example
78///
79/// ```ignore
80/// #[derive(Default)]
81/// struct DbInitService;
82///
83/// #[async_trait]
84/// impl IHostedService for DbInitService {
85///     async fn start(&self) -> Result<()> {
86///         tracing::info!("[DbInitService] Running migrations...");
87///         run_migrations().await?;
88///         tracing::info!("[DbInitService] Seeding data...");
89///         seed_data().await?;
90///         Ok(())
91///     }
92///
93///     async fn stop(&self) -> Result<()> {
94///         tracing::info!("[DbInitService] Shutting down...");
95///         Ok(())
96///     }
97/// }
98/// ```
99#[async_trait::async_trait]
100pub trait IHostedService: Send + Sync {
101    /// Called when the host starts.
102    ///
103    /// Services start in registration order and the host waits for all of them
104    /// before accepting requests. There is **no ambient DI context**: a hosted
105    /// service that needs scoped dependencies (DbContext, transactions, ...)
106    /// takes rust-dix's built-in `#[inject] services: Arc<dyn ScopeFactory>`
107    /// field and opens its own scope
108    /// (`let scope = services.create_scope();`), disposed with the scope.
109    /// If one `start()` fails, the services that already started are stopped
110    /// again in reverse order before the host reports the error.
111    async fn start(&self) -> Result<()>;
112
113    /// Called during a graceful shutdown.
114    ///
115    /// The host stops the services that started, in **reverse** start order
116    /// (the last dependency to start is the first to stop), with a timeout per
117    /// service so one stuck service cannot block the process forever. Like
118    /// `start()`, each `stop()` runs inside a fresh DI scope.
119    async fn stop(&self) -> Result<()> {
120        Ok(())
121    }
122}