Skip to main content

rust_webx_core/
mediator.rs

1//! Mediator traits: IMediator, IRequest, IEventRequest.
2
3pub mod default;
4pub mod dispatch;
5pub mod pipeline;
6pub use default::Mediator;
7pub use dispatch::dispatch;
8pub use pipeline::build_chain as build_pipeline_chain;
9
10use crate::error::Result;
11
12/// Marker trait for a request (command or query) carrying a structured response `TResponse`.
13///
14/// The HTTP adapter serializes `TResponse` as JSON, so it must implement
15/// [`serde::Serialize`] — unless it is [`crate::route::scan::ResponseData`],
16/// the raw-response envelope used for file downloads and other responses that
17/// control their own status, headers and body. That is why this trait itself
18/// only requires `Send`: the `Serialize` bound is enforced where the value is
19/// actually serialized.
20///
21/// - `TResponse: Serialize` → framework writes JSON and sets status 200
22/// - `TResponse = ()`        → framework writes no body and sets status 204
23/// - `TResponse = ResponseData` → the handler builds the whole response
24///
25/// ```ignore
26/// impl IRequest<UserModel> for GetUserRequest {}
27/// impl IRequest<()> for DeleteUserRequest {}
28/// impl IRequest<ResponseData> for DownloadFileRequest {}
29/// ```
30pub trait IRequest<TResponse>: Send + 'static
31where
32    TResponse: Send + 'static,
33{
34}
35
36/// Marker trait for an event (notification) that does not produce a response.
37///
38/// Use `IEventRequest` for fire-and-forget notifications.
39///
40/// ```ignore
41/// impl IEventRequest for UserCreatedEvent {}
42/// ```
43pub trait IEventRequest: Clone + Send + 'static {}
44
45/// The mediator dispatches requests to their handlers and publishes events
46/// to all registered handlers.
47///
48/// Analogous to MediatR's IMediator.
49#[async_trait::async_trait]
50pub trait IMediator: Send + Sync {
51    /// Send a request and return its structured response.
52    async fn send<T, R>(&self, req: T) -> Result<R>
53    where
54        T: IRequest<R> + Send + 'static,
55        R: Send + 'static;
56
57    /// Publish an event to all registered handlers.
58    async fn publish<T: IEventRequest>(&self, event: T) -> Result<()>;
59}