Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

IRequest 与 IRequestHandler

核心契约

rust-webx 用两个 trait 定义一个完整端点:

#![allow(unused)]
fn main() {
// 声明:这是一个请求,响应类型为 T
pub trait IRequest<TResponse>: Send + 'static
where
    TResponse: Send + 'static,
{}

// 实现:如何处理这个请求
#[async_trait]
pub trait IRequestHandler<T, R>: Send + Sync
where
    T: IRequest<R> + Send + 'static,
    R: Send + 'static,
{
    async fn handle(&mut self, req: T) -> ActionResult<R>;
}
}

编译期校验

路由宏(#[get]/#[post]/…)只接受 impl IRequest<Response> for Type:

  • 写在其它 trait impl 或 inherent impl 上会在编译期报错(不会再静默把响应类型当成 ()、 等到启动期才发现孤儿路由);
  • IRequest 必须带且只带一个响应类型参数;
  • #[handler] 只接受 impl IRequestHandler<Req, Rsp> 或 impl IEventHandler<Event>;事件 impl 与请求 impl 使用同一套构造规则: #[handler](Default)或 #[handler(inject)](#[derive(Inject)]), 自动生成路由 + 构造注册(EventHandlerRegistration),不需要显式 dyn IEventHandler DI 注册。其它 trait 直接编译失败。

端点属性与 handler 的 impl 仍由两个宏分别处理;需要查看生成代码时用 cargo expand。

返回类型:ActionResult<T>

handle 返回 ActionResult<T> —— 框架级类型,对标 ASP.NET Core 的 ActionResult<T>: Ok(value) 是成功的响应数据(框架序列化为 JSON),Err(webx::Error) 由框架映射为 problem+json 并用对应状态码写出。它与通用错误别名 Result<T> 是同一个类型 (ActionResult<T> = Result<T, Error>),区别只在命名面向“端点动作“:Handler、管道行为、 Next::run 用 ActionResult<T>,基础设施代码(host、中间件、缓存)继续用 Result<T>。

类型绑定规则(铁律)

IRequest<T> 的泛型参数 T 必须等于 IRequestHandler<T, R> 的 R。

#![allow(unused)]
fn main() {
// ✅ 正确
#[get("/users/{id}")]
impl IRequest<UserDto> for GetUserRequest {}

impl IRequestHandler<GetUserRequest, UserDto> for GetUserHandler { ... }

// ❌ 错误:响应类型不一致
impl IRequest<String> for GetUserRequest {}
impl IRequestHandler<GetUserRequest, UserDto> for GetUserHandler { ... }
}

违反此规则会导致编译失败或运行时类型不匹配。

IRequest 的职责

IRequest<T> 是一个标记 trait(marker trait),本身无方法。它的价值在于:

  1. 承载响应类型信息 — 框架据此决定序列化什么、返回什么状态码
  2. 关联路由元数据 — 通过 #[get] 等宏在 impl 块上附加
  3. 作为类型参数 — IMediator::send() 的泛型约束

响应类型语义

下表是 ActionResult<T> 中 T 的取值语义。

响应类型HTTP 行为
String, UserDto, Vec<T> 等(Serialize)200 + JSON body
()204 No Content,空 body
PagedResult<T>200 + {success, status, message, items, total}(扁平页信封,无请求回声字段)
OperationResult<T>200 + {success, status, message, result}
OperationResult200 + {success, status, message}
ResponseHandler 返回 IActionResult(文件、自定义状态码/头/body)

PagedResult<T> 与 OperationResult 是框架随附的两个业务 DTO 信封(类型定义在 rust-core,由 webx/webx_core 重导出):列表用前者,更新/删除/状态流转等操作结果用后者, 业务模块不必再各自定义 {success, status, message}。

#![allow(unused)]
fn main() {
#[put("/users/{id}")]
impl IRequest<OperationResult<UserDto>> for UpdateUserRequest {}

impl IRequestHandler<UpdateUserRequest, OperationResult<UserDto>> for UpdateUserHandler {
    async fn handle(&mut self, req: UpdateUserRequest) -> ActionResult<OperationResult<UserDto>> {
        let user = self.update(req).await?;
        Ok(OperationResult::success("user updated").with_result(user))
    }
}
}

OperationResult 的 status 是业务状态码(错误码、流程状态,含义由业务定义), 不是 HTTP 状态码;HTTP 状态仍由框架决定——正常返回 200 + 信封 JSON, Err(webx::Error) 仍写 problem+json(见错误处理)。构造器: success(message) / failed(status, message),以及 with_status / with_message / with_result;不带泛型的 OperationResult 没有 result 成员。结果常在业务执行过程中才确定,因此创建后可以继续调整: with_status / with_message / with_result(把无数据信封升级为带 result 的形态), 或直接给公开字段赋值。

掌控响应:IActionResult

Response 就是 ASP.NET Core 的 IActionResult:把响应类型写成 Response,Handler 返回一个 action result,由结果自己写状态码、响应头与响应体(框架不序列化它):

#![allow(unused)]
fn main() {
#[get("/reports/{id}/download")]
impl IRequest<Response> for DownloadReportRequest {}

impl IRequestHandler<DownloadReportRequest, Response> for DownloadReportHandler {
    async fn handle(&mut self, req: DownloadReportRequest) -> ActionResult<Response> {
        let path = self.reports.path_for(&req.id)?;
        Ok(Box::new(FileResult::path(path).download_name("report.csv")))
    }
}
}
结果ASP.NET Core 对应用途
JsonResult<T>JsonResultJSON body(普通 DTO 由框架自动用它)
ContentResultContentResult文本/HTML/字节,.content_type(...)、.download_name(...)
FileResultPhysicalFile(...) / File(...)磁盘/流/可 seek 流,自带 Range、ETag、304
NoContentResultNoContentResult204 无 body
StatusCodeResultStatusCodeResult只有状态码

FileResult 的三种来源:FileResult::path(p)、FileResult::stream(reader)、 FileResult::seekable_stream(reader, len);需要完全自定义时用 FileResult::with_body(FileBody)。 文件响应的 HTTP 细节见文件上传与下载。

响应类型必须按字面写:宏在展开期按类型名判定「自控响应」(末段为 Response,或类型名含 IActionResult)。请写 IRequest<Response> 或 IRequest<Box<dyn IActionResult>>;type Resp = Response; 这类别名、或把业务 DTO 命名为 Response,会被当作普通 JSON 响应并在编译期报错。

IRequestHandler 的职责

Handler 是唯一执行业务逻辑的地方:

#![allow(unused)]
fn main() {
#[async_trait]
impl IRequestHandler<CreateUserRequest, UserDto> for CreateUserHandler {
    async fn handle(&mut self, req: CreateUserRequest) -> ActionResult<UserDto> {
        // 1. 校验(或用 PipelineBehavior)
        // 2. 调用领域服务
        // 3. 返回结果或 Error
        let user = self.service.create(&req.name, &req.email).await?;
        Ok(user)
    }
}
}

分发方式:inventory + HandlerCache

HTTP 请求分发使用 编译时 inventory 收集,不通过 DI 查找 dyn IRequestHandler:

宏提交内容
#[handler] / #[handler(inject)]HandlerRegistration — 每请求工厂与调用桥接

Host::build() 将这些记录收集为 HandlerCache,按请求类型(TypeId / 类型名)查找后在每请求作用域内构造处理器。手动把处理器注册为 dyn IRequestHandler<T, R> 仅用于非 HTTP 的显式 DI 场景,不会参与 HTTP 路由分发。详见 Handler 注册策略。

与 IMediator 的协作

在 Handler 或 Service 中跨模块发送请求,见 IMediator 请求调度。

设计优势

优势说明
一个文件一个端点Request + Handler 可放在同一文件
编译期类型检查响应类型不匹配 = 编译错误
可测试直接实例化 Handler 调用 handle()
OpenAPI 友好类型信息可自动提取

小结

IRequest<T> 声明「要什么」,IRequestHandler<T,R> 实现「怎么做」。掌握这对 trait 是使用框架的全部钥匙。

下一节:路由宏详解