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 (after sorting by [`order`](IHostedService::order))
104    /// and the host waits for all of them
105    /// before accepting requests. There is **no ambient DI context**: a hosted
106    /// service that needs scoped dependencies (DbContext, transactions, ...)
107    /// takes rust-dix's built-in `#[inject] services: Arc<dyn ScopeFactory>`
108    /// field and opens its own scope
109    /// (`let scope = services.create_scope();`), disposed with the scope.
110    /// If one `start()` fails, the services that already started are stopped
111    /// again in reverse order before the host reports the error.
112    async fn start(&self) -> Result<()>;
113
114    /// Called during a graceful shutdown.
115    ///
116    /// The host stops the services that started, in **reverse** start order
117    /// (the last dependency to start is the first to stop), with a timeout per
118    /// service so one stuck service cannot block the process forever. Like
119    /// `start()`, each `stop()` runs inside a fresh DI scope.
120    ///
121    /// Shutdown stops hosted services **before** in-flight connections are
122    /// drained, so a worker never keeps running against services that are about
123    /// to be torn down.
124    async fn stop(&self) -> Result<()> {
125        Ok(())
126    }
127
128    /// Start/stop priority. Lower starts first and stops last.
129    ///
130    /// Defaults to `0`; services with equal order keep their **registration
131    /// order** (the sort is stable). Use it when a dependency must be ready
132    /// before another: a migration/seed service at `-100`, cache warmup at `0`,
133    /// queue consumers at `100`.
134    ///
135    /// Register with order through `add_hosted_service_ordered` /
136    /// `add_hosted_service_with_ordered`; the default keeps the historical
137    /// registration-order behavior.
138    fn order(&self) -> i32 {
139        0
140    }
141}