yang-base 0.6.0

个人使用构建后端服务器
Documentation
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
//! Action 响应结构
//!
//! 提供统一的 API 响应格式,包含状态码、消息和数据。

use crate::error::BaseError;
use schemars::JsonSchema;
use serde::Serialize;
use std::path::PathBuf;

/// [`ResponseBody::Raw`] 唯一允许的响应内容类型。
///
/// 该逃生口存在的理由是「外部系统的响应契约与框架 JSON 包络不兼容」,不是通用响应通道;
/// [`ResponseBody::raw`] 构造器与派发边界 [`wrap_dispatch_output`] 都按本白名单校验,
/// 防止该变体被用来返回 `text/html`,从而绕过前端 JSON 契约的保护。
///
/// 注意该保证只覆盖 [`ResponseBody::Raw`]:下游直接构造的
/// [`ResponseAttachment::Raw`](如在用的 receivables-system `text/csv` 模板下载)与
/// 按扩展名可能返回 `text/html`/`image/svg+xml` 的 [`ResponseBody::Preview`] 是另外的
/// 非 JSON 通道,不在本白名单范围内。
const RAW_ALLOWED_CONTENT_TYPE: &str = "application/json";

/// 校验 Raw 响应内容类型。
///
/// 构造器与派发边界共用,确保「直接构造变体」不能绕过 [`ResponseBody::raw`] 的白名单。
fn validate_raw_content_type(content_type: &str) -> Result<(), BaseError> {
    if content_type != RAW_ALLOWED_CONTENT_TYPE {
        return Err(BaseError::ConfigError(format!(
            "Raw 响应 content-type 只允许 {RAW_ALLOWED_CONTENT_TYPE},收到 {content_type}"
        )));
    }
    Ok(())
}

/// API 响应
///
/// 统一的 API 响应格式,用于所有 Action 的返回值
///
/// # 字段
///
/// - `code`: 状态码(0 表示成功,非零表示失败)
/// - `message`: 响应消息
/// - `data`: 响应数据(可选)
///
/// 标注 `#[non_exhaustive]`:未来新增字段不构成破坏性变更。
/// 请使用 [`ApiResponse::success`] / [`ApiResponse::fail`] / [`ApiResponse::from_error`] 等构造。
///
/// # 示例
///
/// ```rust,ignore
/// use yang_base::action::ApiResponse;
/// use serde_json::json;
///
/// // 创建成功响应
/// let response = ApiResponse::success(
///     json!({ "id": 123, "name": "Alice" }),
///     "操作成功"
/// );
/// assert_eq!(response.code, 0);
///
/// // 创建失败响应
/// let response = ApiResponse::fail(400001, "参数错误");
/// assert_eq!(response.code, 400001);
/// assert!(response.data.is_none());
/// ```
#[derive(Debug, Clone, Serialize, JsonSchema)]
#[non_exhaustive]
pub struct ApiResponse {
    /// 状态码
    ///
    /// - 0: 成功
    /// - 非零: 失败(具体错误码由业务定义)
    pub code: i32,

    /// 响应消息
    ///
    /// 描述操作结果的文本信息
    pub message: String,

    /// 响应数据
    ///
    /// 成功时包含业务数据,失败时通常为 None
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<serde_json::Value>,

    /// 非 JSON 附件(文件下载/预览/重定向),由传输层消费。
    ///
    /// 仅当 Action 以 [`ResponseBody`] 为输出时由派发边界填充;
    /// `serde(skip)` 保证普通 Action 的 JSON 线格式不受影响。
    #[serde(skip)]
    #[schemars(skip)]
    pub attachment: Option<ResponseAttachment>,

    /// 由 Action 显式声明、传输层消费的 HTTP 状态码覆盖。
    #[serde(skip)]
    #[schemars(skip)]
    http_status: Option<u16>,

    /// 由 Action 显式声明、传输层消费的响应头。
    #[serde(skip)]
    #[schemars(skip)]
    headers: Vec<(String, String)>,
}

impl ApiResponse {
    /// 创建成功响应
    ///
    /// 状态码为 0,包含业务数据。序列化失败时返回 `BaseError::JsonSerializeFailed`。
    ///
    /// # 参数
    ///
    /// - `data`: 响应数据(任何可序列化的类型)
    /// - `message`: 成功消息
    ///
    /// # 返回
    ///
    /// - `Ok(ApiResponse)`: 序列化成功时返回响应实例
    /// - `Err(BaseError::JsonSerializeFailed)`: 序列化失败时返回错误
    ///
    /// # Errors
    ///
    /// - `BaseError::JsonSerializeFailed`: 当 `data` 无法被序列化为 JSON 时
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::action::ApiResponse;
    /// use serde_json::json;
    ///
    /// // 返回单个对象
    /// let response = ApiResponse::success(
    ///     json!({ "id": 1, "name": "Alice" }),
    ///     "获取成功"
    /// )?;
    ///
    /// // 返回影响行数
    /// let response = ApiResponse::success(
    ///     json!({ "affected": 1 }),
    ///     "更新成功"
    /// )?;
    /// ```
    pub fn success<T: Serialize>(data: T, message: impl Into<String>) -> Result<Self, BaseError> {
        // 序列化数据,失败时返回结构化错误而非静默吞错
        let json_value = serde_json::to_value(data)
            .map_err(|e| BaseError::JsonSerializeFailed(e.to_string()))?;
        Ok(Self {
            code: 0,
            message: message.into(),
            data: Some(json_value),
            attachment: None,
            http_status: None,
            headers: Vec::new(),
        })
    }

    /// 创建成功响应(接受已序列化的 JSON 值)
    ///
    /// 当数据已经是 `serde_json::Value` 类型时,使用此方法可避免额外的序列化开销,
    /// 且不会失败,因此直接返回 `Self` 而非 `Result`。
    ///
    /// # 参数
    ///
    /// - `data`: 已序列化的 JSON 值
    /// - `message`: 成功消息
    ///
    /// # 返回
    ///
    /// - ApiResponse 实例
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::action::ApiResponse;
    /// use serde_json::json;
    ///
    /// // 直接使用 serde_json::Value
    /// let data = json!({ "id": 1, "name": "Alice" });
    /// let response = ApiResponse::success_value(data, "获取成功");
    /// assert_eq!(response.code, 0);
    /// ```
    pub fn success_value(data: serde_json::Value, message: impl Into<String>) -> Self {
        Self {
            code: 0,
            message: message.into(),
            data: Some(data),
            attachment: None,
            http_status: None,
            headers: Vec::new(),
        }
    }

    /// 创建失败响应
    ///
    /// 状态码为非零错误码,不包含数据
    ///
    /// # 参数
    ///
    /// - `code`: 错误码(非零整数)
    /// - `message`: 错误消息
    ///
    /// # 返回
    ///
    /// - ApiResponse 实例
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::action::ApiResponse;
    ///
    /// // 参数错误
    /// let response = ApiResponse::fail(400001, "参数缺失: username");
    ///
    /// // 权限错误
    /// let response = ApiResponse::fail(403001, "权限不足");
    ///
    /// // 业务错误
    /// let response = ApiResponse::fail(500001, "用户名已存在");
    /// ```
    pub fn fail(code: i32, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
            data: None,
            attachment: None,
            http_status: None,
            headers: Vec::new(),
        }
    }

    /// 创建携带诊断数据的失败响应。
    ///
    /// 与 [`ApiResponse::fail`](`data` 恒为空)相对,保留 `data` 载荷,
    /// 供就绪探针等需要自描述失败原因的端点使用。
    pub fn fail_value(code: i32, data: serde_json::Value, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
            data: Some(data),
            attachment: None,
            http_status: None,
            headers: Vec::new(),
        }
    }

    /// 创建携带附件的成功响应
    ///
    /// 由派发边界在识别到 Action 返回 [`ResponseBody`] 时调用。`data` 为 None,
    /// 附件信息仅对传输层可见(`serde(skip)`),JSON 线格式保持不变。
    ///
    /// # 参数
    ///
    /// - `attachment`: 传输层消费的附件描述
    /// - `message`: 成功消息
    ///
    /// # 返回
    ///
    /// - ApiResponse 实例
    pub fn attachment(attachment: ResponseAttachment, message: impl Into<String>) -> Self {
        Self {
            code: 0,
            message: message.into(),
            data: None,
            attachment: Some(attachment),
            http_status: None,
            headers: Vec::new(),
        }
    }

    /// 覆盖 Action 静态声明的成功 HTTP 状态码。
    pub fn with_http_status(mut self, status: u16) -> Result<Self, BaseError> {
        if !(100..=599).contains(&status) {
            return Err(BaseError::ConfigError(format!(
                "响应 HTTP 状态码无效: {status}"
            )));
        }
        self.http_status = Some(status);
        Ok(self)
    }

    /// 追加一个经过最小 RFC 语法校验的响应头。
    ///
    /// 使用列表而不是 Map,以保留多个 `Set-Cookie` 等同名响应头。
    pub fn with_header(
        mut self,
        name: impl Into<String>,
        value: impl Into<String>,
    ) -> Result<Self, BaseError> {
        let name = name.into();
        let value = value.into();
        let valid_name = !name.is_empty()
            && name.bytes().all(|byte| {
                byte.is_ascii_alphanumeric()
                    || matches!(
                        byte,
                        b'!' | b'#'
                            | b'$'
                            | b'%'
                            | b'&'
                            | b'\''
                            | b'*'
                            | b'+'
                            | b'-'
                            | b'.'
                            | b'^'
                            | b'_'
                            | b'`'
                            | b'|'
                            | b'~'
                    )
            });
        let valid_value = value
            .bytes()
            .all(|byte| byte == b'\t' || (byte >= 0x20 && byte != 0x7f));
        if !valid_name || !valid_value {
            return Err(BaseError::ConfigError(
                "响应头名称或值包含非法字符".to_string(),
            ));
        }
        self.headers.push((name, value));
        Ok(self)
    }

    #[cfg(any(feature = "transport-axum", test))]
    pub(crate) const fn http_status(&self) -> Option<u16> {
        self.http_status
    }

    /// 返回 Action 显式追加、由传输层消费的响应头。
    ///
    /// 响应头不参与 [`ApiResponse`] 的 JSON 序列化;此只读视图主要用于
    /// 传输适配器、集成测试以及需要检查 Cookie/缓存契约的应用层边界。
    pub fn response_headers(&self) -> &[(String, String)] {
        &self.headers
    }

    /// 从 BaseError 创建失败响应
    ///
    /// 自动提取错误码和错误消息。接受引用以避免消费 `BaseError` 所有权,
    /// 调用方可在构建响应的同时保留 error 用于日志记录等后续用途。
    ///
    /// # 参数
    ///
    /// - `error`: BaseError 引用
    ///
    /// # 返回
    ///
    /// - ApiResponse 实例
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::action::ApiResponse;
    /// use yang_base::error::BaseError;
    ///
    /// let error = BaseError::FieldRequired("username".to_string());
    /// let response = ApiResponse::from_error(&error);
    ///
    /// assert_ne!(response.code, 0);
    /// assert!(response.message.contains("username"));
    /// assert!(response.data.is_none());
    /// ```
    pub fn from_error(error: &BaseError) -> Self {
        Self::fail(error.code(), error.to_string())
    }
}

impl Default for ApiResponse {
    /// 创建默认响应
    ///
    /// 默认为成功响应,消息为 "OK",无数据
    fn default() -> Self {
        Self {
            code: 0,
            message: "OK".to_string(),
            data: None,
            attachment: None,
            http_status: None,
            headers: Vec::new(),
        }
    }
}

/// Action 的特殊业务响应体:文件下载、文件预览、重定向、原始响应体。
///
/// Action 将本类型作为 `type Output` 返回时,派发边界
/// ([`DynAction::dispatch`](crate::action::DynAction))会识别并把它转为
/// [`ApiResponse::attachment`],普通输出的 JSON 线格式不受影响。
///
/// 标注 `#[non_exhaustive]`:未来新增变体不再构成破坏性变更,下游穷尽 `match`
/// 请保留通配臂。
///
/// # 示例
///
/// ```rust,ignore
/// use yang_base::action::ResponseBody;
///
/// async fn index(&self, ctx: ActionContext, input: Self::Input) -> Result<Self::Output, BaseError> {
///     // 文件下载
///     Ok(ResponseBody::download("/data/report.pdf", "report.pdf"))
///     // 文件预览
///     // Ok(ResponseBody::preview("/data/a.png"))
///     // 重定向
///     // Ok(ResponseBody::redirect("https://example.com/next"))
///     // 原始 JSON 响应体(不套 ApiResponse 包络)
///     // ResponseBody::raw(r#"{"code":0,"msg":"ok"}"#, "application/json")
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
#[serde(tag = "type", rename_all = "snake_case")]
#[non_exhaustive]
pub enum ResponseBody {
    /// 文件下载:传输层以 `Content-Disposition: attachment` 返回文件字节。
    Download {
        /// 服务器本地文件路径。
        path: PathBuf,
        /// 下载文件名(写入 Content-Disposition 的 filename 参数)。
        filename: String,
    },
    /// 文件预览:传输层以 `Content-Disposition: inline` 返回文件字节。
    Preview {
        /// 服务器本地文件路径。
        path: PathBuf,
    },
    /// 重定向:传输层返回 302 状态码与 `Location` 头。
    Redirect {
        /// 目标地址。
        url: String,
    },
    /// 原始响应体:传输层直接以 `content_type` 返回 `body`,**不套 [`ApiResponse`] 包络**。
    ///
    /// 供外部系统要求固定响应形状(顶层键名、层级与框架包络不一致)时使用。
    /// `content_type` 只允许 `application/json`;`body` 必须是该类型下的完整响应文本。
    ///
    /// 请优先用 [`ResponseBody::raw`] 构造,它会校验 `content_type`;派发边界
    /// `wrap_dispatch_output` 会对直接构造的本变体再执行同一白名单校验。
    Raw {
        /// 完整响应体文本(UTF-8)。
        body: String,
        /// 响应 `Content-Type`;当前只允许 `application/json`。
        content_type: String,
    },
}

impl ResponseBody {
    /// 构造文件下载响应。
    pub fn download(path: impl Into<PathBuf>, filename: impl Into<String>) -> Self {
        Self::Download {
            path: path.into(),
            filename: filename.into(),
        }
    }

    /// 构造文件预览响应。
    pub fn preview(path: impl Into<PathBuf>) -> Self {
        Self::Preview { path: path.into() }
    }

    /// 构造重定向响应。
    pub fn redirect(url: impl Into<String>) -> Self {
        Self::Redirect { url: url.into() }
    }

    /// 构造原始响应体,传输层将原样返回 `body` 而不套 [`ApiResponse`] 包络。
    ///
    /// 这是给「外部系统契约与框架包络不兼容」用的逃生口,不是通用响应通道——
    /// `content_type` 被限死为 `application/json`,防止它被用来返回 `text/html`。
    /// 该白名单与派发边界 `wrap_dispatch_output` 的运行期再校验完全一致;
    /// 直接构造 [`ResponseBody::Raw`] 的非法 `content_type` 会在派发时被拒绝。
    ///
    /// # 错误
    ///
    /// `content_type` 不是 `application/json` 时返回 [`BaseError::ConfigError`]。
    ///
    /// # 示例
    ///
    /// ```rust
    /// use yang_base::action::ResponseBody;
    ///
    /// let body = ResponseBody::raw(r#"{"code":0}"#, "application/json")?;
    /// assert!(matches!(body, ResponseBody::Raw { .. }));
    ///
    /// // 非 JSON 类型被拒绝
    /// assert!(ResponseBody::raw("<html></html>", "text/html").is_err());
    /// # Ok::<(), yang_base::BaseError>(())
    /// ```
    pub fn raw(
        body: impl Into<String>,
        content_type: impl Into<String>,
    ) -> Result<Self, BaseError> {
        let content_type = content_type.into();
        validate_raw_content_type(&content_type)?;
        Ok(Self::Raw {
            body: body.into(),
            content_type,
        })
    }
}

/// 一次响应携带的非 JSON 附件描述,由传输层消费,不参与 JSON 序列化。
///
/// 与 [`ResponseBody`] 结构一一对应;拆开是为了让 Action 输出类型满足
/// `Serialize + JsonSchema` 契约,而响应上的附件字段不受该契约约束。
///
/// 标注 `#[non_exhaustive]`:未来新增变体不再构成破坏性变更。
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ResponseAttachment {
    /// 文件下载(`Content-Disposition: attachment`)。
    Download {
        /// 服务器本地文件路径。
        path: PathBuf,
        /// 下载文件名。
        filename: String,
    },
    /// 文件预览(`Content-Disposition: inline`)。
    Preview {
        /// 服务器本地文件路径。
        path: PathBuf,
    },
    /// 重定向(302 + `Location`)。
    Redirect {
        /// 目标地址。
        url: String,
    },
    /// 原始响应体:`Content-Type` 由变体自带,**不套 [`ApiResponse`] 包络**。
    Raw {
        /// 完整响应体文本。
        body: String,
        /// 响应 `Content-Type`。
        content_type: String,
    },
}

impl From<ResponseBody> for ResponseAttachment {
    fn from(body: ResponseBody) -> Self {
        match body {
            ResponseBody::Download { path, filename } => Self::Download { path, filename },
            ResponseBody::Preview { path } => Self::Preview { path },
            ResponseBody::Redirect { url } => Self::Redirect { url },
            ResponseBody::Raw { body, content_type } => Self::Raw { body, content_type },
        }
    }
}

/// 派发边界的统一输出去向:[`ResponseBody`] 转为附件响应,其余照旧序列化进 `data`。
///
/// 通过 `&dyn Any` downcast 识别 `ResponseBody`,不引入新的 trait bound,
/// 因此现有 Action 的输出契约与 `Result<ApiResponse, BaseError>` 派发签名保持不变。
pub(crate) fn wrap_dispatch_output<T>(output: T, message: &str) -> Result<ApiResponse, BaseError>
where
    T: Serialize + 'static,
{
    let erased = &output as &dyn std::any::Any;
    if let Some(response) = erased.downcast_ref::<ApiResponse>() {
        return Ok(response.clone());
    }
    if let Some(body) = erased.downcast_ref::<ResponseBody>() {
        // 运行期再校验:`ResponseBody::Raw` 是对外可构造的变体,枚举上的
        // `#[non_exhaustive]` 只限制下游穷尽 match,不能阻止直接构造变体绕过
        // `raw()` 的白名单。此处复用同一校验函数,合法 `application/json` 零变化。
        if let ResponseBody::Raw { content_type, .. } = body {
            validate_raw_content_type(content_type)?;
        }
        return Ok(ApiResponse::attachment(body.clone().into(), message));
    }
    ApiResponse::success(output, message)
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_success_response() {
        // success 现在返回 Result,需要用 ? 或 unwrap
        let response =
            ApiResponse::success(json!({ "id": 123, "name": "Alice" }), "操作成功").unwrap();

        assert_eq!(response.code, 0);
        assert_eq!(response.message, "操作成功");
        assert!(response.data.is_some());

        let data = response.data.unwrap();
        assert_eq!(data["id"], 123);
        assert_eq!(data["name"], "Alice");
    }

    #[test]
    fn test_success_response_with_null() {
        // 使用 success_value 传入已有的 JSON 值(不会失败)
        let response = ApiResponse::success_value(serde_json::Value::Null, "操作成功");

        assert_eq!(response.code, 0);
        assert_eq!(response.message, "操作成功");
        assert!(response.data.is_some());
        assert_eq!(response.data.unwrap(), serde_json::Value::Null);
    }

    #[test]
    fn test_success_value_response() {
        // 测试 success_value 便捷构造器
        let data = json!({ "count": 42 });
        let response = ApiResponse::success_value(data, "查询成功");

        assert_eq!(response.code, 0);
        assert_eq!(response.message, "查询成功");
        assert!(response.data.is_some());
        assert_eq!(response.data.unwrap()["count"], 42);
    }

    #[test]
    fn test_success_serialize_error_propagation() {
        // 构造一个序列化时主动返回错误的类型
        struct AlwaysFailSerialize;

        impl serde::Serialize for AlwaysFailSerialize {
            fn serialize<S: serde::Serializer>(&self, _serializer: S) -> Result<S::Ok, S::Error> {
                use serde::ser::Error;
                Err(S::Error::custom("测试序列化失败"))
            }
        }

        let result = ApiResponse::success(AlwaysFailSerialize, "测试");
        // 序列化失败应该返回 JsonSerializeFailed 错误
        assert!(result.is_err(), "序列化失败应该返回错误");
        if let Err(BaseError::JsonSerializeFailed(_)) = result {
            // 正确:返回了 JsonSerializeFailed
        } else {
            panic!("期望 JsonSerializeFailed 错误");
        }
    }

    #[test]
    fn test_fail_response() {
        let response = ApiResponse::fail(400001, "参数错误");

        assert_eq!(response.code, 400001);
        assert_eq!(response.message, "参数错误");
        assert!(response.data.is_none());
    }

    #[test]
    fn test_from_error() {
        let error = BaseError::FieldRequired("username".to_string());
        let response = ApiResponse::from_error(&error);

        assert_ne!(response.code, 0);
        assert!(response.message.contains("username"));
        assert!(response.data.is_none());
        // error 仍可用(未被消费)
        assert_eq!(error.code(), 600006);
    }

    #[test]
    fn test_default_response() {
        let response = ApiResponse::default();

        assert_eq!(response.code, 0);
        assert_eq!(response.message, "OK");
        assert!(response.data.is_none());
    }

    #[test]
    fn transport_metadata_is_validated_and_never_serialized() {
        let response = ApiResponse::default()
            .with_http_status(304)
            .expect("304 应是合法 HTTP 状态码")
            .with_header("set-cookie", "session=one; HttpOnly")
            .expect("Set-Cookie 应是合法响应头")
            .with_header("set-cookie", "session=two; HttpOnly")
            .expect("重复 Set-Cookie 必须保留");
        assert_eq!(response.http_status(), Some(304));
        assert_eq!(response.response_headers().len(), 2);
        let wire = serde_json::to_value(&response).expect("响应应可序列化");
        assert!(wire.get("http_status").is_none());
        assert!(wire.get("headers").is_none());
        assert!(ApiResponse::default().with_http_status(99).is_err());
        assert!(ApiResponse::default()
            .with_header("bad header", "value")
            .is_err());
        assert!(ApiResponse::default()
            .with_header("x-test", "line\r\nbreak")
            .is_err());
    }

    #[test]
    fn test_serialize_response() {
        // success 现在返回 Result
        let response = ApiResponse::success(json!({ "count": 10 }), "查询成功").unwrap();

        let json = serde_json::to_string(&response).unwrap();
        assert!(json.contains("\"code\":0"));
        assert!(json.contains("\"message\":\"查询成功\""));
        assert!(json.contains("\"data\""));
    }

    #[test]
    fn test_serialize_fail_response() {
        let response = ApiResponse::fail(500001, "服务器错误");

        let json = serde_json::to_string(&response).unwrap();
        assert!(json.contains("\"code\":500001"));
        assert!(json.contains("\"message\":\"服务器错误\""));
        // data 字段应该被跳过
        assert!(!json.contains("\"data\""));
    }

    #[test]
    fn test_response_body_constructors() {
        // download 携带路径与下载文件名
        let download = ResponseBody::download("/tmp/report.pdf", "report.pdf");
        assert_eq!(
            download,
            ResponseBody::Download {
                path: std::path::PathBuf::from("/tmp/report.pdf"),
                filename: "report.pdf".to_string(),
            }
        );
        // preview 仅携带路径
        assert_eq!(
            ResponseBody::preview("/tmp/a.png"),
            ResponseBody::Preview {
                path: std::path::PathBuf::from("/tmp/a.png"),
            }
        );
        // redirect 仅携带目标地址
        assert_eq!(
            ResponseBody::redirect("https://example.com/next"),
            ResponseBody::Redirect {
                url: "https://example.com/next".to_string(),
            }
        );
    }

    #[test]
    fn test_response_body_into_attachment() {
        // ResponseBody 到传输层附件描述的一一映射
        let attachment: ResponseAttachment = ResponseBody::download("/tmp/a.bin", "a.bin").into();
        assert_eq!(
            attachment,
            ResponseAttachment::Download {
                path: std::path::PathBuf::from("/tmp/a.bin"),
                filename: "a.bin".to_string(),
            }
        );
        let attachment: ResponseAttachment = ResponseBody::preview("/tmp/b.png").into();
        assert_eq!(
            attachment,
            ResponseAttachment::Preview {
                path: std::path::PathBuf::from("/tmp/b.png"),
            }
        );
        let attachment: ResponseAttachment = ResponseBody::redirect("/home").into();
        assert_eq!(
            attachment,
            ResponseAttachment::Redirect {
                url: "/home".to_string(),
            }
        );
    }

    #[test]
    fn test_response_body_implements_action_output_contract() {
        // 作为 Action::Output 必须满足 Serialize + JsonSchema + 'static
        fn assert_output_contract<T: Serialize + schemars::JsonSchema + 'static>() {}
        assert_output_contract::<ResponseBody>();

        let body = ResponseBody::redirect("/next");
        let json = serde_json::to_string(&body).unwrap();
        assert!(json.contains("/next"), "ResponseBody 应可序列化: {json}");
        // schema 生成不应 panic(output_schema 由构建期消费)
        let _schema = schemars::schema_for!(ResponseBody);
    }

    #[test]
    fn test_attachment_response_json_wire_format_unchanged() {
        // 附件响应序列化后不得出现 attachment 字段,保持 JSON 线格式不变
        let response = ApiResponse::attachment(
            ResponseAttachment::Redirect {
                url: "/next".to_string(),
            },
            "成功",
        );
        assert_eq!(response.code, 0);
        assert!(response.data.is_none());
        let json = serde_json::to_string(&response).unwrap();
        assert!(
            !json.contains("attachment"),
            "线格式不得包含附件信息: {json}"
        );
        assert!(json.contains("\"code\":0"));
    }

    #[test]
    fn test_plain_response_has_no_attachment() {
        // 普通成功/失败响应不带附件
        let ok = ApiResponse::success(json!({"a": 1}), "ok").unwrap();
        assert!(ok.attachment.is_none());
        let fail = ApiResponse::fail(1, "bad");
        assert!(fail.attachment.is_none());
        let default = ApiResponse::default();
        assert!(default.attachment.is_none());
    }

    #[test]
    fn test_wrap_dispatch_output_recognizes_response_body() {
        // ResponseBody 输出转为附件响应,不进 data
        let response = wrap_dispatch_output(ResponseBody::redirect("/next"), "成功").unwrap();
        assert_eq!(response.code, 0);
        assert!(response.data.is_none());
        assert_eq!(
            response.attachment,
            Some(ResponseAttachment::Redirect {
                url: "/next".to_string(),
            })
        );
    }

    #[test]
    fn test_wrap_dispatch_output_passes_through_plain_output() {
        // 普通输出照旧序列化进 data,attachment 为 None
        #[derive(Serialize)]
        struct Plain {
            value: i32,
        }
        let response = wrap_dispatch_output(Plain { value: 7 }, "成功").unwrap();
        assert_eq!(response.code, 0);
        assert_eq!(response.data.unwrap()["value"], 7);
        assert!(response.attachment.is_none());
    }

    #[test]
    fn raw_response_body_rejects_non_json_content_type() {
        // Raw 只允许 application/json:这个逃生口不得被用来返回 text/html
        let failed = ResponseBody::raw("<html></html>", "text/html")
            .expect_err("非 application/json 必须被拒绝");
        assert!(
            failed.to_string().contains("application/json"),
            "错误信息应说明允许的 content-type,实际: {failed}"
        );
    }

    #[test]
    fn directly_constructed_raw_is_revalidated_at_dispatch_boundary() {
        // RED(修复前):枚举上的 #[non_exhaustive] 不阻止下游直接构造 Raw,
        // text/html 会原样进入传输层,绕过 raw() 的 content-type 白名单。
        let body = ResponseBody::Raw {
            body: "<html><script>alert(1)</script></html>".to_string(),
            content_type: "text/html".to_string(),
        };

        let err =
            wrap_dispatch_output(body, "成功").expect_err("派发边界必须拒绝直接构造的非 JSON Raw");
        assert!(
            matches!(&err, BaseError::ConfigError(_)),
            "应与 raw() 使用同一错误类型,实际: {err:?}"
        );
        assert!(
            err.to_string().contains("application/json"),
            "错误信息应说明允许的 content-type,实际: {err}"
        );
    }

    #[test]
    fn directly_constructed_json_raw_still_maps_to_attachment() {
        // 合法直接构造(application/json)零变化:仍映射为 Raw 附件且不进入 data
        let body = ResponseBody::Raw {
            body: r#"{"code":0,"msg":"ok"}"#.to_string(),
            content_type: "application/json".to_string(),
        };

        let response = wrap_dispatch_output(body, "成功").expect("合法 Raw 应通过派发边界");
        assert_eq!(response.code, 0);
        assert!(response.data.is_none(), "Raw 不得进入 data");
        assert_eq!(
            response.attachment,
            Some(ResponseAttachment::Raw {
                body: r#"{"code":0,"msg":"ok"}"#.to_string(),
                content_type: "application/json".to_string(),
            })
        );
    }

    #[test]
    fn dispatch_validation_uses_same_exact_match_as_constructor() {
        // 与 raw() 完全一致:精确匹配 application/json;带参数的同类值同样被拒绝。
        assert!(ResponseBody::raw("{}", "application/json; charset=utf-8").is_err());

        let body = ResponseBody::Raw {
            body: "{}".to_string(),
            content_type: "application/json; charset=utf-8".to_string(),
        };
        assert!(
            wrap_dispatch_output(body, "成功").is_err(),
            "派发边界的白名单必须与 raw() 的精确匹配语义一致"
        );
    }

    #[test]
    fn attachment_raw_content_type_is_not_tightened() {
        // 契约边界:校验只覆盖 ResponseBody::Raw,不得扩大到 ResponseAttachment::Raw /
        // ApiResponse::attachment——receivables-system 的 text/csv 模板下载依赖此通道。
        let response = ApiResponse::attachment(
            ResponseAttachment::Raw {
                body: "a,b\r\n1,2".to_string(),
                content_type: "text/csv; charset=utf-8".to_string(),
            },
            "成功",
        );
        assert_eq!(
            response.attachment,
            Some(ResponseAttachment::Raw {
                body: "a,b\r\n1,2".to_string(),
                content_type: "text/csv; charset=utf-8".to_string(),
            })
        );

        // 已携带非 JSON 附件的 ApiResponse 走 wrap_dispatch_output 的第一分支原样透传。
        let passed = wrap_dispatch_output(response, "成功").expect("ApiResponse 应原样透传");
        assert_eq!(
            passed.attachment,
            Some(ResponseAttachment::Raw {
                body: "a,b\r\n1,2".to_string(),
                content_type: "text/csv; charset=utf-8".to_string(),
            })
        );
    }

    #[test]
    fn raw_response_body_maps_to_raw_attachment_without_envelope() {
        // Raw 输出映射为 Raw 附件,且不进入 data
        let body = ResponseBody::raw(r#"{"code":0,"msg":"ok"}"#, "application/json")
            .expect("application/json 应被接受");
        let response = wrap_dispatch_output(body, "成功").expect("收口应成功");
        assert_eq!(response.code, 0);
        assert!(response.data.is_none(), "Raw 不得进入 data");
        assert_eq!(
            response.attachment,
            Some(ResponseAttachment::Raw {
                body: r#"{"code":0,"msg":"ok"}"#.to_string(),
                content_type: "application/json".to_string(),
            })
        );
    }

    #[test]
    fn raw_response_body_survives_json_wire_format() {
        // Raw 变体不得让 ApiResponse 的 JSON 线格式出现 attachment 字段
        let body = ResponseBody::raw("{}", "application/json").expect("应被接受");
        let response = wrap_dispatch_output(body, "成功").expect("收口应成功");
        let json = serde_json::to_string(&response).expect("应可序列化");
        assert!(
            !json.contains("attachment"),
            "线格式不得含 attachment: {json}"
        );
    }
}