zenith-web 0.1.0

Zenith Web 应用框架:编译期 Trie 路由、类型化 Extractor、中间件 DAG、静态文件服务、统一错误处理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
//! App 构建器与完整请求链路
//!
//! 整合路由、中间件、错误处理,提供统一的请求处理入口。

use zenith_api::{CanonicalRequest, CanonicalResponse};

use crate::error::WebError;
use crate::extract::ExtractError;
use crate::middleware::{Middleware, MiddlewareChain};
use crate::router::{RouteEntry, Router, RouteMatch, RouteMethod};

/// 处理器函数类型
pub type HandlerFn =
    dyn Fn(&CanonicalRequest, &RouteMatch) -> Result<CanonicalResponse, WebError>
        + Send
        + Sync
        + 'static;

/// 处理器存储条目
pub struct HandlerEntry {
    id: usize,
    handler: Box<HandlerFn>,
}

impl std::fmt::Debug for HandlerEntry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HandlerEntry")
            .field("id", &self.id)
            .finish()
    }
}

/// Web 应用构建器
#[derive(Default)]
pub struct App {
    router: Router,
    handlers: Vec<HandlerEntry>,
    middleware_chain: MiddlewareChain,
    next_handler_id: usize,
}

impl App {
    /// 创建新的 Web 应用实例
    pub fn new() -> Self {
        Self {
            router: Router::new(),
            handlers: Vec::new(),
            middleware_chain: MiddlewareChain::new(),
            next_handler_id: 0,
        }
    }

    // -----------------------------------------------------------------------
    // 路由注册
    // -----------------------------------------------------------------------

    /// 注册 GET 路由
    pub fn get<F>(&mut self, path: &str, handler: F) -> &mut Self
    where
        F: Fn(&CanonicalRequest, &RouteMatch) -> Result<CanonicalResponse, WebError>
            + Send
            + Sync
            + 'static,
    {
        self.add_route(RouteMethod::Get, path, handler)
    }

    /// 注册 POST 路由
    pub fn post<F>(&mut self, path: &str, handler: F) -> &mut Self
    where
        F: Fn(&CanonicalRequest, &RouteMatch) -> Result<CanonicalResponse, WebError>
            + Send
            + Sync
            + 'static,
    {
        self.add_route(RouteMethod::Post, path, handler)
    }

    /// 注册 PUT 路由
    pub fn put<F>(&mut self, path: &str, handler: F) -> &mut Self
    where
        F: Fn(&CanonicalRequest, &RouteMatch) -> Result<CanonicalResponse, WebError>
            + Send
            + Sync
            + 'static,
    {
        self.add_route(RouteMethod::Put, path, handler)
    }

    /// 注册 DELETE 路由
    pub fn delete<F>(&mut self, path: &str, handler: F) -> &mut Self
    where
        F: Fn(&CanonicalRequest, &RouteMatch) -> Result<CanonicalResponse, WebError>
            + Send
            + Sync
            + 'static,
    {
        self.add_route(RouteMethod::Delete, path, handler)
    }

    /// 注册 PATCH 路由
    pub fn patch<F>(&mut self, path: &str, handler: F) -> &mut Self
    where
        F: Fn(&CanonicalRequest, &RouteMatch) -> Result<CanonicalResponse, WebError>
            + Send
            + Sync
            + 'static,
    {
        self.add_route(RouteMethod::Patch, path, handler)
    }

    /// 注册任意方法路由
    pub fn any<F>(&mut self, path: &str, handler: F) -> &mut Self
    where
        F: Fn(&CanonicalRequest, &RouteMatch) -> Result<CanonicalResponse, WebError>
            + Send
            + Sync
            + 'static,
    {
        self.add_route(RouteMethod::Any, path, handler)
    }

    fn add_route<F>(&mut self, method: RouteMethod, path: &str, handler: F) -> &mut Self
    where
        F: Fn(&CanonicalRequest, &RouteMatch) -> Result<CanonicalResponse, WebError>
            + Send
            + Sync
            + 'static,
    {
        let id = self.next_handler_id;
        self.next_handler_id += 1;

        self.handlers.push(HandlerEntry {
            id,
            handler: Box::new(handler),
        });

        self.router.add_route(method, path, id);
        self
    }

    // -----------------------------------------------------------------------
    // 中间件
    // -----------------------------------------------------------------------

    /// 添加中间件
    pub fn middleware<M: Middleware>(&mut self, middleware: M) -> &mut Self {
        self.middleware_chain.add(middleware);
        self
    }

    // -----------------------------------------------------------------------
    // 处理请求
    // -----------------------------------------------------------------------

    /// 处理规范化请求(全链路入口)
    ///
    /// 调度顺序(与中间件语义一致):
    /// 1. 中间件链 `before` 前置处理(含短路,例如 CORS OPTIONS 预检)
    /// 2. 路由匹配(在 `before` 未短路时执行)
    /// 3. 路由未匹配 → 404(仍会经过 `after` 后置处理)
    /// 4. 路由匹配 → 执行 handler
    /// 5. 中间件链 `after` 逆序后置处理
    ///
    /// 该顺序保证:
    /// - 全局中间件(CORS / Auth / RequestId / Logging)对所有请求生效,包括未匹配路由的请求
    /// - OPTIONS 预检由 CorsMiddleware 透明短路,无需调用方在 App 之外重复处理
    pub fn handle(&self, request: CanonicalRequest) -> CanonicalResponse {
        let method = request.method;

        // 中间件链统一编排:before → (路由匹配 → handler) → after
        // 路由匹配被移入 handler 闭包,确保 before 阶段可短路(如 OPTIONS 预检),
        // 且未匹配路由的 404 也会经过 after 后置处理(如 RequestId 注入)。
        self.middleware_chain.run(request, |req| {
            let path = req.path_bytes();
            let route_match = match self.router.match_route(method, path) {
                Some(m) => m,
                None => {
                    // 路径存在但方法不匹配 → 405 Method Not Allowed
                    // 路径完全不存在 → 404 Not Found
                    if self.router.path_exists(path) {
                        return WebError::MethodNotAllowed(format!(
                            "Method {} not allowed for {}",
                            method.as_str(),
                            String::from_utf8_lossy(path)
                        ))
                        .into_response();
                    }
                    return WebError::NotFound(format!(
                        "Route not found: {} {}",
                        method.as_str(),
                        String::from_utf8_lossy(path)
                    ))
                    .into_response();
                }
            };

            let handler = &self.handlers[route_match.handler_id];
            // catch_unwind provides panic → 500 protection in debug builds;
            // release builds use panic = "abort" where catch_unwind is ineffective
            // but the wrapper is still correct (panic aborts the process).
            // AssertUnwindSafe is needed because CanonicalRequest/RouteMatch
            // may not implement UnwindSafe; catch_panic wraps with it internally.
            crate::error::catch_panic(|| {
                match (handler.handler)(req, &route_match) {
                    Ok(response) => response,
                    Err(web_error) => web_error.into_response(),
                }
            })
        })
    }

    /// 获取路由数量
    pub fn route_count(&self) -> usize {
        self.router.route_count()
    }

    /// 获取所有路由条目
    pub fn routes(&self) -> &[RouteEntry] {
        self.router.routes()
    }

    /// 验证应用配置
    pub fn validate(&self) -> Result<(), crate::error::RouterError> {
        self.router.validate()
    }
}

impl std::fmt::Debug for App {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("App")
            .field("routes", &self.router.route_count())
            .field("handlers", &self.handlers.len())
            .field("middleware_count", &self.middleware_chain.len())
            .finish()
    }
}

// ---------------------------------------------------------------------------
// 辅助函数
// ---------------------------------------------------------------------------

/// 创建成功响应
pub fn success_response(body: impl Into<Vec<u8>>, content_type: &str) -> CanonicalResponse {
    let mut response = CanonicalResponse::new(200);
    let _ = response
        .add_header(b"content-type", content_type.as_bytes());
    response.set_body(body.into());
    response
}

/// 创建 JSON 响应
pub fn json_response<T: serde::Serialize>(value: &T) -> Result<CanonicalResponse, WebError> {
    let json = serde_json::to_string(value)
        .map_err(|e| WebError::InternalError(format!("JSON serialize error: {}", e)))?;
    Ok(success_response(json, "application/json"))
}

/// 从 ExtractError 转换为 WebError
impl From<ExtractError> for WebError {
    fn from(err: ExtractError) -> Self {
        match err {
            ExtractError::NotFound(name) => WebError::BadRequest(format!("Missing parameter: {}", name)),
            ExtractError::ParseError { name, expected } => {
                WebError::BadRequest(format!("Invalid '{}', expected {}", name, expected))
            }
            ExtractError::OutOfRange { name, value } => {
                WebError::BadRequest(format!("'{}' value '{}' out of range", name, value))
            }
            ExtractError::Custom(msg) => WebError::BadRequest(msg),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use zenith_api::Method;

    #[test]
    fn test_app_creation() {
        let app = App::new();
        assert_eq!(app.route_count(), 0);
    }

    #[test]
    fn test_get_route() {
        let mut app = App::new();
        app.get("/hello", |_req, _params| {
            Ok(success_response("Hello World", "text/plain"))
        });

        assert_eq!(app.route_count(), 1);

        let mut request = CanonicalRequest::empty();
        let _ = request.set_path("/hello");
        let response = app.handle(request);
        assert_eq!(response.status_code, 200);
        assert_eq!(response.body(), b"Hello World");
    }

    #[test]
    fn test_post_route() {
        let mut app = App::new();
        app.post("/data", |_req, _params| {
            Ok(success_response("Created", "text/plain"))
        });

        let mut request = CanonicalRequest::empty();
        request.method = Method::Post;
        let _ = request.set_path("/data");
        let response = app.handle(request);
        assert_eq!(response.status_code, 200);
    }

    #[test]
    fn test_param_route() {
        let mut app = App::new();
        app.get("/users/:id", |_req, params| {
            let id = params.get("id").unwrap_or_default();
            Ok(success_response(format!("User: {}", id), "text/plain"))
        });

        let mut request = CanonicalRequest::empty();
        let _ = request.set_path("/users/42");
        let response = app.handle(request);
        assert_eq!(response.status_code, 200);
    }

    #[test]
    fn test_not_found() {
        let mut app = App::new();
        app.get("/exists", |_req, _params| {
            Ok(success_response("OK", "text/plain"))
        });

        let mut request = CanonicalRequest::empty();
        let _ = request.set_path("/nonexistent");
        let response = app.handle(request);
        assert_eq!(response.status_code, 404);
    }

    #[test]
    fn test_method_not_allowed() {
        let mut app = App::new();
        app.get("/api", |_req, _params| {
            Ok(success_response("GET OK", "text/plain"))
        });

        let mut request = CanonicalRequest::empty();
        request.method = Method::Post;
        let _ = request.set_path("/api");
        let response = app.handle(request);
        assert_eq!(response.status_code, 405);
    }

    #[test]
    fn test_middleware_integration() {
        use crate::middleware::LoggingMiddleware;

        let mut app = App::new();
        app.middleware(LoggingMiddleware::new(false));
        app.get("/test", |_req, _params| {
            Ok(success_response("Test", "text/plain"))
        });

        let mut request = CanonicalRequest::empty();
        let _ = request.set_path("/test");
        let response = app.handle(request);
        assert_eq!(response.status_code, 200);
    }

    #[test]
    fn test_options_preflight_transparent_short_circuit() {
        // 回归测试:OPTIONS 预检必须由 CorsMiddleware 在 before 阶段透明短路,
        // 不依赖具名路由匹配。修复前 App::handle 先做路由匹配 → 未注册 OPTIONS 路由
        // 直接 404,绕过 CorsMiddleware;修复后中间件链先执行 before。
        use crate::middleware::{CorsMiddleware, RequestIdMiddleware};

        let mut app = App::new();
        app.middleware(CorsMiddleware::new().with_origin("*"));
        app.middleware(RequestIdMiddleware::new());
        app.get("/api/data", |_req, _params| {
            Ok(success_response("OK", "text/plain"))
        });

        let mut request = CanonicalRequest::empty();
        request.method = Method::Options;
        let _ = request.set_path("/api/data");

        let response = app.handle(request);
        // 必须是 204 预检响应,而非 404
        assert_eq!(response.status_code, 204);
        assert!(response.find_header("access-control-allow-origin").is_some());
        assert!(response.find_header("access-control-allow-methods").is_some());
        assert!(response.find_header("access-control-allow-headers").is_some());
        assert!(response.find_header("access-control-max-age").is_some());
        // after 阶段的 RequestId 也应正常注入(证明后置链路未被跳过)
        assert!(response.find_header("x-request-id").is_some());
    }

    #[test]
    fn test_options_preflight_unregistered_path() {
        // 即使 path 完全未注册任何路由,OPTIONS 预检也应由 CorsMiddleware 短路
        use crate::middleware::CorsMiddleware;

        let mut app = App::new();
        app.middleware(CorsMiddleware::new().with_origin("*"));
        app.get("/api/data", |_req, _params| {
            Ok(success_response("OK", "text/plain"))
        });

        let mut request = CanonicalRequest::empty();
        request.method = Method::Options;
        let _ = request.set_path("/totally/unregistered/path");

        let response = app.handle(request);
        assert_eq!(response.status_code, 204);
        assert!(response.find_header("access-control-allow-origin").is_some());
    }

    #[test]
    fn test_not_found_still_runs_after_middleware() {
        // 404 响应也应经过 after 后置处理(如 RequestId 注入)
        use crate::middleware::RequestIdMiddleware;

        let mut app = App::new();
        app.middleware(RequestIdMiddleware::new());
        app.get("/exists", |_req, _params| {
            Ok(success_response("OK", "text/plain"))
        });

        let mut request = CanonicalRequest::empty();
        let _ = request.set_path("/nonexistent");
        let response = app.handle(request);
        assert_eq!(response.status_code, 404);
        assert!(response.find_header("x-request-id").is_some());
    }

    #[test]
    fn test_error_handler() {
        let mut app = App::new();
        app.get("/error", |_req, _params| {
            Err(WebError::InternalError("Something went wrong".to_string()))
        });

        let mut request = CanonicalRequest::empty();
        let _ = request.set_path("/error");
        let response = app.handle(request);
        assert_eq!(response.status_code, 500);
        let body = response.body();
        let body_str = String::from_utf8_lossy(body);
        assert!(body_str.contains("Something went wrong"));
    }

    #[test]
    fn test_multiple_routes() {
        let mut app = App::new();
        app.get("/", |_req, _params| {
            Ok(success_response("Root", "text/plain"))
        });
        app.get("/api/health", |_req, _params| {
            Ok(success_response("OK", "text/plain"))
        });
        app.post("/api/data", |_req, _params| {
            Ok(success_response("Created", "text/plain"))
        });

        assert_eq!(app.route_count(), 3);
        assert!(app.validate().is_ok());
    }

    #[test]
    fn test_success_response() {
        let response = success_response(b"test data".to_vec(), "application/octet-stream");
        assert_eq!(response.status_code, 200);
        assert_eq!(response.body(), b"test data");
        assert_eq!(
            response.find_header("content-type").unwrap().value_str(),
            "application/octet-stream"
        );
    }

    #[test]
    fn test_extract_error_to_web_error() {
        let extract_err = crate::extract::ExtractError::NotFound("id".to_string());
        let web_err: WebError = extract_err.into();
        assert_eq!(web_err.status_code(), 400);
        assert!(web_err.message().contains("id"));
    }

    #[test]
    fn test_app_debug() {
        let mut app = App::new();
        app.get("/test", |_req, _params| {
            Ok(success_response("OK", "text/plain"))
        });
        let debug = format!("{:?}", app);
        assert!(debug.contains("App"));
    }
}