loveyu-kit 0.2.0

面向 Axum 项目的可组合 API 工具库
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
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
//! 统一 API 成功响应、错误响应及结果别名。

use std::{
    borrow::Cow,
    collections::BTreeMap,
    error::Error,
    fmt::{self, Display, Formatter, Write as _},
};

use axum::{
    Json,
    http::StatusCode,
    response::{IntoResponse, Response},
};
use serde::Serialize;

#[cfg(feature = "logging")]
use crate::observability::{Diagnostic, SqlDiagnostic};

const MAX_INTERNAL_ERROR_BYTES: usize = 16 * 1024;
#[cfg(feature = "logging")]
const MAX_SOURCE_ERROR_BYTES: usize = 4 * 1024;
#[cfg(feature = "logging")]
const MAX_SOURCE_DEPTH: usize = 16;
const MAX_CONTEXT_FIELDS: usize = 32;
const MAX_CONTEXT_KEY_BYTES: usize = 256;
const MAX_CONTEXT_VALUE_BYTES: usize = 4 * 1024;
#[cfg(feature = "logging")]
const MAX_DIAGNOSTICS: usize = 16;
const TRUNCATED_SUFFIX: &str = "…(已截断)";

#[derive(Debug, Default)]
struct InternalError {
    error: Option<String>,
    #[cfg(feature = "logging")]
    source_chain: Vec<String>,
    context: BTreeMap<String, String>,
    #[cfg(feature = "logging")]
    diagnostics: Vec<Diagnostic>,
}

/// 仅供请求日志中间件读取的错误元数据,不会发送给客户端。
#[cfg(feature = "logging")]
#[derive(Clone, Debug, Serialize)]
pub(crate) struct ErrorLogMetadata {
    pub(crate) code: u32,
    #[serde(rename = "message")]
    pub(crate) client_message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) internal_error: Option<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub(crate) source_chain: Vec<String>,
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub(crate) context: BTreeMap<String, String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub(crate) diagnostics: Vec<Diagnostic>,
}

#[cfg(feature = "logging")]
impl ErrorLogMetadata {
    pub(crate) const fn has_internal_diagnostics(&self) -> bool {
        self.internal_error.is_some()
            || !self.source_chain.is_empty()
            || !self.diagnostics.is_empty()
    }
}

/// 统一成功响应。
#[derive(Clone, Debug, Serialize)]
#[must_use = "应将统一成功响应返回给调用方"]
pub struct ApiResponse<T> {
    /// 业务状态码。
    pub code: u32,
    /// 返回数据。
    pub data: T,
    /// 面向客户端的提示信息。
    pub msg: Cow<'static, str>,
}

impl<T> ApiResponse<T> {
    /// 使用默认成功业务码和提示信息创建响应。
    pub const fn new(data: T) -> Self {
        Self {
            code: 200,
            data,
            msg: Cow::Borrowed("操作成功"),
        }
    }

    /// 使用默认成功业务码和自定义提示信息创建响应。
    pub fn with_message(data: T, msg: impl Into<Cow<'static, str>>) -> Self {
        Self {
            code: 200,
            data,
            msg: msg.into(),
        }
    }

    /// 使用自定义业务码和提示信息创建响应。
    pub fn with_code(data: T, code: u32, msg: impl Into<Cow<'static, str>>) -> Self {
        Self {
            code,
            data,
            msg: msg.into(),
        }
    }

    /// `with_message` 的兼容别名。
    pub fn new_and_msg(data: T, msg: impl Into<Cow<'static, str>>) -> Self {
        Self::with_message(data, msg)
    }

    /// 取出响应数据。
    pub fn into_data(self) -> T {
        self.data
    }

    /// 在不改变业务码和提示信息的前提下转换响应数据。
    pub fn map<U>(self, mapper: impl FnOnce(T) -> U) -> ApiResponse<U> {
        ApiResponse {
            code: self.code,
            data: mapper(self.data),
            msg: self.msg,
        }
    }
}

impl<T> IntoResponse for ApiResponse<T>
where
    T: Serialize,
{
    fn into_response(self) -> Response {
        (StatusCode::OK, Json(self)).into_response()
    }
}

/// 统一错误响应。
#[derive(Debug, Serialize)]
#[must_use = "应将统一错误响应返回给调用方或继续传播"]
pub struct ApiError {
    /// 业务错误码。
    pub code: u32,
    /// 面向客户端的错误信息。
    pub msg: String,
    #[serde(skip)]
    http_status: StatusCode,
    #[serde(skip)]
    internal: Option<Box<InternalError>>,
}

impl ApiError {
    /// 使用自定义业务码创建错误;默认保持 `200 OK` 以兼容业务码响应模式。
    pub fn new(code: u32, msg: impl Into<String>) -> Self {
        Self {
            code,
            msg: msg.into(),
            http_status: StatusCode::OK,
            internal: None,
        }
    }

    /// 创建外部服务请求错误,业务码为 `100000`。
    pub fn err_request_external_service(msg: impl Into<String>) -> Self {
        Self::new(100_000, msg)
    }

    /// 创建请求错误,业务码为 `400000`。
    pub fn err_bad_request(msg: impl Into<String>) -> Self {
        Self::new(400_000, msg)
    }

    /// 创建请求参数错误,业务码为 `400001`。
    pub fn err_invalid_param(msg: impl Into<String>) -> Self {
        Self::new(400_001, msg)
    }

    /// 创建客户端登录凭证无效错误,业务码为 `400002`。
    pub fn err_token_client_invalid(msg: impl Into<String>) -> Self {
        Self::new(400_002, msg)
    }

    /// 创建服务端登录凭证生成失败错误,业务码为 `400003`。
    pub fn err_token_server_invalid(msg: impl Into<String>) -> Self {
        Self::new(400_003, msg)
    }

    /// 创建未授权错误,业务码为 `401000`。
    pub fn err_unauthorized(msg: impl Into<String>) -> Self {
        Self::new(401_000, msg)
    }

    /// 创建权限不足错误,业务码为 `403000`。
    pub fn err_forbidden_auth(msg: impl Into<String>) -> Self {
        Self::new(403_000, msg)
    }

    /// 创建用户不存在或已禁用错误,业务码为 `403001`。
    pub fn err_user_disabled(msg: impl Into<String>) -> Self {
        Self::new(403_001, msg)
    }

    /// 创建数据不存在错误,业务码为 `404000`。
    pub fn err_not_found(msg: impl Into<String>) -> Self {
        Self::new(404_000, msg)
    }

    /// 创建数据已存在错误,业务码为 `409000`。
    pub fn err_data_exists(msg: impl Into<String>) -> Self {
        Self::new(409_000, msg)
    }

    /// 创建唯一索引冲突错误,业务码为 `409001`。
    pub fn err_unique_index_conflict(msg: impl Into<String>) -> Self {
        Self::new(409_001, msg)
    }

    /// 创建数据版本冲突错误,业务码为 `409002`。
    pub fn err_version_conflict(msg: impl Into<String>) -> Self {
        Self::new(409_002, msg)
    }

    /// 创建外键约束冲突错误,业务码为 `409003`。
    pub fn err_foreign_key_conflict(msg: impl Into<String>) -> Self {
        Self::new(409_003, msg)
    }

    /// 创建数据约束冲突错误,业务码为 `409004`。
    pub fn err_constraint_conflict(msg: impl Into<String>) -> Self {
        Self::new(409_004, msg)
    }

    /// 创建服务繁忙错误,业务码为 `500000`。
    pub fn err_server_busy(msg: impl Into<String>) -> Self {
        Self::new(500_000, msg)
    }

    /// 创建数据库错误,业务码为 `500001`。
    pub fn err_database(msg: impl Into<String>) -> Self {
        Self::new(500_001, msg)
    }

    /// 创建 Redis 错误,业务码为 `500002`。
    pub fn err_redis(msg: impl Into<String>) -> Self {
        Self::new(500_002, msg)
    }

    /// 创建数据加密或处理错误,业务码为 `600000`。
    pub fn err_encrypt(msg: impl Into<String>) -> Self {
        Self::new(600_000, msg)
    }

    /// 创建其他错误,业务码为 `999999`。
    pub fn err_other(msg: impl Into<String>) -> Self {
        Self::new(999_999, msg)
    }

    /// 写入仅供服务端诊断的真实错误信息,不会序列化到客户端响应。
    pub fn with_error(mut self, error: impl Display) -> Self {
        self.internal
            .get_or_insert_with(|| Box::new(InternalError::default()))
            .error = Some(bounded_display(&error, MAX_INTERNAL_ERROR_BYTES));
        self
    }

    /// 写入实现了 `Error` 的真实错误及其来源链,仅供服务端诊断。
    pub fn with_source<E>(mut self, error: &E) -> Self
    where
        E: Error + ?Sized,
    {
        let internal = self
            .internal
            .get_or_insert_with(|| Box::new(InternalError::default()));
        internal.error = Some(bounded_display(error, MAX_INTERNAL_ERROR_BYTES));
        #[cfg(feature = "logging")]
        {
            internal.source_chain.clear();
            let mut source = error.source();
            while let Some(current) = source
                && internal.source_chain.len() < MAX_SOURCE_DEPTH
            {
                internal
                    .source_chain
                    .push(bounded_display(current, MAX_SOURCE_ERROR_BYTES));
                source = current.source();
            }
            if source.is_some() {
                internal.source_chain.push("…(来源链已截断)".to_owned());
            }
        }
        self
    }

    /// 增加一条仅供服务端排障的结构化诊断。
    #[cfg(feature = "logging")]
    pub fn with_diagnostic(mut self, diagnostic: impl Into<Diagnostic>) -> Self {
        let diagnostics = &mut self
            .internal
            .get_or_insert_with(|| Box::new(InternalError::default()))
            .diagnostics;
        if diagnostics.len() < MAX_DIAGNOSTICS {
            diagnostics.push(diagnostic.into().bounded_for_log());
        }
        self
    }

    /// 增加一条 SQL 失败诊断。
    #[cfg(feature = "logging")]
    pub fn with_sql_error(self, diagnostic: SqlDiagnostic) -> Self {
        self.with_diagnostic(diagnostic)
    }

    /// 设置实际 HTTP 状态码;默认保持 `200 OK` 以兼容业务码响应模式。
    pub const fn with_http_status(mut self, status: StatusCode) -> Self {
        self.http_status = status;
        self
    }

    /// 添加仅供服务端诊断的上下文字段;可以连续调用以记录多个字段。
    pub fn with_context(mut self, key: impl Into<String>, value: impl Display) -> Self {
        let key = truncate_owned(key.into(), MAX_CONTEXT_KEY_BYTES);
        let internal = self
            .internal
            .get_or_insert_with(|| Box::new(InternalError::default()));
        if internal.context.contains_key(&key) || internal.context.len() < MAX_CONTEXT_FIELDS {
            internal
                .context
                .insert(key, bounded_display(&value, MAX_CONTEXT_VALUE_BYTES));
        }
        self
    }

    /// 返回当前 HTTP 状态码。
    #[must_use]
    pub const fn http_status(&self) -> StatusCode {
        self.http_status
    }

    /// 返回仅供服务端诊断使用的底层错误信息。
    #[must_use]
    pub fn internal_error(&self) -> Option<&str> {
        self.internal
            .as_ref()
            .and_then(|internal| internal.error.as_deref())
    }

    /// 返回仅供服务端诊断使用的错误上下文。
    #[must_use]
    pub fn internal_context(&self) -> Option<&BTreeMap<String, String>> {
        self.internal.as_ref().map(|internal| &internal.context)
    }

    /// 返回仅供服务端诊断使用的结构化诊断。
    #[cfg(feature = "logging")]
    #[must_use]
    pub fn diagnostics(&self) -> Option<&[Diagnostic]> {
        self.internal
            .as_ref()
            .map(|internal| internal.diagnostics.as_slice())
    }
}

fn truncate_owned(mut value: String, max_bytes: usize) -> String {
    if value.len() <= max_bytes {
        return value;
    }

    let mut boundary = max_bytes.saturating_sub(TRUNCATED_SUFFIX.len());
    while boundary > 0 && !value.is_char_boundary(boundary) {
        boundary -= 1;
    }
    value.truncate(boundary);
    value.push_str(TRUNCATED_SUFFIX);
    value
}

fn bounded_display<T>(value: &T, max_bytes: usize) -> String
where
    T: Display + ?Sized,
{
    let mut writer = LimitedStringWriter {
        output: String::with_capacity(max_bytes.min(256)),
        max_bytes,
        truncated: false,
    };
    let _ = write!(&mut writer, "{value}");
    if writer.truncated {
        let keep = max_bytes.saturating_sub(TRUNCATED_SUFFIX.len());
        truncate_to_boundary(&mut writer.output, keep);
        if max_bytes >= TRUNCATED_SUFFIX.len() {
            writer.output.push_str(TRUNCATED_SUFFIX);
        }
    }
    writer.output
}

struct LimitedStringWriter {
    output: String,
    max_bytes: usize,
    truncated: bool,
}

impl fmt::Write for LimitedStringWriter {
    fn write_str(&mut self, value: &str) -> fmt::Result {
        let remaining = self.max_bytes.saturating_sub(self.output.len());
        if value.len() <= remaining {
            self.output.push_str(value);
            return Ok(());
        }
        let mut boundary = remaining;
        while boundary > 0 && !value.is_char_boundary(boundary) {
            boundary -= 1;
        }
        self.output.push_str(&value[..boundary]);
        self.truncated = true;
        Err(fmt::Error)
    }
}

fn truncate_to_boundary(value: &mut String, max_bytes: usize) {
    let mut boundary = max_bytes.min(value.len());
    while boundary > 0 && !value.is_char_boundary(boundary) {
        boundary -= 1;
    }
    value.truncate(boundary);
}

impl Display for ApiError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        write!(formatter, "{}(业务码:{})", self.msg, self.code)
    }
}

impl Error for ApiError {}

#[cfg(feature = "connection")]
impl From<crate::connection::ConnectionUnavailable> for ApiError {
    fn from(error: crate::connection::ConnectionUnavailable) -> Self {
        let connector = error.connector().to_owned();
        Self::err_server_busy("依赖服务暂时不可用,请稍后重试")
            .with_source(&error)
            .with_context("connector", connector)
    }
}

#[cfg(feature = "connection")]
impl<E> From<crate::connection::ManagedConnectionError<E>> for ApiError
where
    E: Error + 'static,
{
    fn from(error: crate::connection::ManagedConnectionError<E>) -> Self {
        Self::err_server_busy("依赖服务健康检查失败,请稍后重试").with_source(&error)
    }
}

#[cfg(any(
    feature = "connection-mysql",
    feature = "connection-postgres",
    feature = "connection-redis",
    feature = "connection-kafka",
    feature = "connection-etcd",
    feature = "connection-mqtt",
    feature = "connection-elasticsearch"
))]
impl From<crate::connection::ConnectionError> for ApiError {
    fn from(error: crate::connection::ConnectionError) -> Self {
        // 数据库和 Redis 保留已有专用业务码,其余连接器统一归类为依赖服务错误。
        #[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
        if matches!(
            &error,
            crate::connection::ConnectionError::InvalidPoolOptions(_)
                | crate::connection::ConnectionError::Sqlx(_)
        ) {
            return Self::err_database("数据库操作失败,请稍后重试").with_source(&error);
        }

        #[cfg(feature = "connection-redis")]
        if matches!(
            &error,
            crate::connection::ConnectionError::Redis(_)
                | crate::connection::ConnectionError::UnexpectedRedisPing(_)
        ) {
            return Self::err_redis("Redis 操作失败,请稍后重试").with_source(&error);
        }

        Self::err_server_busy("依赖服务操作失败,请稍后重试").with_source(&error)
    }
}

#[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
/// SQLx 错误的稳定分类,用于映射统一 API 错误。
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum SqlErrorClass {
    /// 查询要求返回数据,但没有找到任何行。
    NotFound,
    /// 唯一索引或主键冲突。
    UniqueViolation,
    /// 外键约束冲突。
    ForeignKeyViolation,
    /// 非空约束冲突。
    NotNullViolation,
    /// 检查约束冲突。
    CheckViolation,
    /// 连接池等待超时或已关闭。
    PoolUnavailable,
    /// 连接、TLS 或数据库协议异常。
    Connection,
    /// 列或数值编解码异常。
    Decode,
    /// 其他数据库异常。
    Database,
}

#[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
impl SqlErrorClass {
    /// 返回适合结构化日志和指标的稳定标识。
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::NotFound => "not_found",
            Self::UniqueViolation => "unique_violation",
            Self::ForeignKeyViolation => "foreign_key_violation",
            Self::NotNullViolation => "not_null_violation",
            Self::CheckViolation => "check_violation",
            Self::PoolUnavailable => "pool_unavailable",
            Self::Connection => "connection",
            Self::Decode => "decode",
            Self::Database => "database",
        }
    }

    /// 分类 SQLx 错误,不解析不稳定的人类可读错误文本。
    #[must_use]
    pub fn classify(error: &sqlx::Error) -> Self {
        use sqlx::error::ErrorKind;

        match error {
            sqlx::Error::RowNotFound => Self::NotFound,
            sqlx::Error::Database(error) => match error.kind() {
                ErrorKind::UniqueViolation => Self::UniqueViolation,
                ErrorKind::ForeignKeyViolation => Self::ForeignKeyViolation,
                ErrorKind::NotNullViolation => Self::NotNullViolation,
                ErrorKind::CheckViolation | ErrorKind::ExclusionViolation => Self::CheckViolation,
                _ => Self::Database,
            },
            sqlx::Error::PoolTimedOut | sqlx::Error::PoolClosed => Self::PoolUnavailable,
            sqlx::Error::Io(_)
            | sqlx::Error::Tls(_)
            | sqlx::Error::Protocol(_)
            | sqlx::Error::WorkerCrashed
            | sqlx::Error::BeginFailed => Self::Connection,
            sqlx::Error::ColumnIndexOutOfBounds { .. }
            | sqlx::Error::ColumnNotFound(_)
            | sqlx::Error::ColumnDecode { .. }
            | sqlx::Error::Encode(_)
            | sqlx::Error::Decode(_) => Self::Decode,
            _ => Self::Database,
        }
    }
}

#[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
pub(crate) fn default_sqlx_api_error(error: &sqlx::Error) -> ApiError {
    match SqlErrorClass::classify(error) {
        SqlErrorClass::NotFound => ApiError::err_not_found("数据不存在"),
        SqlErrorClass::UniqueViolation => ApiError::err_unique_index_conflict("数据已存在"),
        SqlErrorClass::PoolUnavailable => ApiError::err_server_busy("数据库连接繁忙,请稍后重试"),
        SqlErrorClass::ForeignKeyViolation
        | SqlErrorClass::NotNullViolation
        | SqlErrorClass::CheckViolation
        | SqlErrorClass::Connection
        | SqlErrorClass::Decode
        | SqlErrorClass::Database => ApiError::err_database("数据库操作失败,请稍后重试"),
    }
}

#[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
impl From<sqlx::Error> for ApiError {
    fn from(error: sqlx::Error) -> Self {
        default_sqlx_api_error(&error).with_source(&error)
    }
}

#[cfg(feature = "connection-redis")]
impl From<redis::RedisError> for ApiError {
    fn from(error: redis::RedisError) -> Self {
        Self::err_redis("Redis 操作失败,请稍后重试").with_source(&error)
    }
}

#[cfg(feature = "connection-kafka")]
impl From<rdkafka::error::KafkaError> for ApiError {
    fn from(error: rdkafka::error::KafkaError) -> Self {
        Self::err_server_busy("Kafka 操作失败,请稍后重试")
            .with_source(&error)
            .with_context("connector", "kafka")
    }
}

#[cfg(feature = "connection-kafka")]
impl From<(rdkafka::error::KafkaError, rdkafka::message::OwnedMessage)> for ApiError {
    fn from(
        (error, _message): (rdkafka::error::KafkaError, rdkafka::message::OwnedMessage),
    ) -> Self {
        // 失败消息可能包含业务载荷,只记录 Kafka 错误,避免把消息内容写入诊断日志。
        Self::from(error)
    }
}

#[cfg(feature = "connection-etcd")]
impl From<etcd_client::Error> for ApiError {
    fn from(error: etcd_client::Error) -> Self {
        Self::err_server_busy("etcd 操作失败,请稍后重试")
            .with_source(&error)
            .with_context("connector", "etcd")
    }
}

#[cfg(feature = "connection-mqtt")]
impl From<rumqttc::ClientError> for ApiError {
    fn from(error: rumqttc::ClientError) -> Self {
        Self::err_server_busy("MQTT 操作失败,请稍后重试")
            .with_source(&error)
            .with_context("connector", "mqtt")
    }
}

#[cfg(feature = "connection-mqtt")]
impl From<rumqttc::ConnectionError> for ApiError {
    fn from(error: rumqttc::ConnectionError) -> Self {
        Self::err_server_busy("MQTT 连接失败,请稍后重试")
            .with_source(&error)
            .with_context("connector", "mqtt")
    }
}

#[cfg(feature = "connection-mqtt")]
impl From<rumqttc::OptionError> for ApiError {
    fn from(error: rumqttc::OptionError) -> Self {
        Self::err_server_busy("MQTT 配置无效,请检查服务配置")
            .with_source(&error)
            .with_context("connector", "mqtt")
    }
}

#[cfg(feature = "connection-elasticsearch")]
impl From<elasticsearch::Error> for ApiError {
    fn from(error: elasticsearch::Error) -> Self {
        Self::err_server_busy("Elasticsearch 操作失败,请稍后重试")
            .with_source(&error)
            .with_context("connector", "elasticsearch")
    }
}

impl IntoResponse for ApiError {
    fn into_response(self) -> Response {
        #[cfg(feature = "logging")]
        {
            // 先完成客户端响应序列化,再把服务端字段移入日志元数据,避免克隆错误详情。
            let status = self.http_status;
            let mut response = (status, Json(&self)).into_response();
            let Self {
                code,
                msg,
                internal,
                ..
            } = self;
            let InternalError {
                error,
                source_chain,
                context,
                diagnostics,
            } = internal.map(|internal| *internal).unwrap_or_default();
            let metadata = ErrorLogMetadata {
                code,
                client_message: msg,
                internal_error: error,
                source_chain,
                context,
                diagnostics,
            };
            response.extensions_mut().insert(metadata);
            response
        }

        #[cfg(not(feature = "logging"))]
        {
            (self.http_status, Json(self)).into_response()
        }
    }
}

/// 统一 API 结果类型。
pub type ApiResult<T> = Result<ApiResponse<T>, ApiError>;
/// `ApiResponse` 的兼容别名。
pub type AppOk<T> = ApiResponse<T>;
/// `ApiError` 的兼容别名。
pub type AppError = ApiError;
/// `ApiResult` 的兼容别名。
pub type AppResult<T> = ApiResult<T>;

#[cfg(test)]
mod tests {
    use std::borrow::Cow;

    use axum::response::IntoResponse;
    use http_body_util::BodyExt;

    use super::*;

    #[cfg(feature = "connection")]
    #[test]
    fn unavailable_connection_converts_to_safe_api_error() {
        let source = crate::connection::ConnectionUnavailable::new("primary-mysql");
        let error = ApiError::from(source);

        assert_eq!(error.code, 500_000);
        assert_eq!(error.msg, "依赖服务暂时不可用,请稍后重试");
        assert_eq!(
            error.internal_error(),
            Some("连接 `primary-mysql` 未启用,无法执行操作")
        );
        assert_eq!(
            error.internal_context().unwrap().get("connector"),
            Some(&"primary-mysql".to_owned())
        );
    }

    #[cfg(feature = "connection")]
    #[test]
    fn managed_connection_error_converts_to_safe_api_error() {
        let source = crate::connection::ManagedConnectionError::<std::io::Error>::Unavailable(
            crate::connection::ConnectionUnavailable::new("custom"),
        );
        let error = ApiError::from(source);

        assert_eq!(error.code, 500_000);
        assert_eq!(error.msg, "依赖服务健康检查失败,请稍后重试");
        assert_eq!(
            error.internal_error(),
            Some("连接 `custom` 未启用,无法执行操作")
        );
    }

    #[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
    #[test]
    fn sqlx_row_not_found_converts_to_not_found_api_error() {
        let error = ApiError::from(sqlx::Error::RowNotFound);

        assert_eq!(error.code, 404_000);
        assert_eq!(error.msg, "数据不存在");
        assert!(
            error
                .internal_error()
                .is_some_and(|message| message.contains("no rows returned"))
        );
    }

    #[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
    #[derive(Debug)]
    struct UniqueDatabaseError;

    #[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
    impl Display for UniqueDatabaseError {
        fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
            formatter.write_str("唯一索引冲突")
        }
    }

    #[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
    impl Error for UniqueDatabaseError {}

    #[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
    impl sqlx::error::DatabaseError for UniqueDatabaseError {
        fn message(&self) -> &str {
            "唯一索引冲突"
        }

        fn code(&self) -> Option<Cow<'_, str>> {
            Some(Cow::Borrowed("23505"))
        }

        fn constraint(&self) -> Option<&str> {
            Some("uk_users_email")
        }

        fn as_error(&self) -> &(dyn Error + Send + Sync + 'static) {
            self
        }

        fn as_error_mut(&mut self) -> &mut (dyn Error + Send + Sync + 'static) {
            self
        }

        fn into_error(self: Box<Self>) -> Box<dyn Error + Send + Sync + 'static> {
            self
        }

        fn kind(&self) -> sqlx::error::ErrorKind {
            sqlx::error::ErrorKind::UniqueViolation
        }
    }

    #[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
    #[test]
    fn sqlx_unique_violation_converts_to_conflict_api_error() {
        let source = sqlx::Error::Database(Box::new(UniqueDatabaseError));
        assert_eq!(
            SqlErrorClass::classify(&source),
            SqlErrorClass::UniqueViolation
        );

        let error = ApiError::from(source);
        assert_eq!(error.code, 409_001);
        assert_eq!(error.msg, "数据已存在");
        assert!(
            error
                .internal_error()
                .is_some_and(|message| message.contains("唯一索引冲突"))
        );
    }

    #[cfg(feature = "connection-redis")]
    #[test]
    fn redis_error_converts_to_safe_redis_api_error() {
        let source = redis::RedisError::from((redis::ErrorKind::Client, "Redis 测试错误"));
        let error = ApiError::from(source);

        assert_eq!(error.code, 500_002);
        assert_eq!(error.msg, "Redis 操作失败,请稍后重试");
        assert!(
            error
                .internal_error()
                .is_some_and(|message| message.contains("Redis 测试错误"))
        );
    }

    #[cfg(any(
        feature = "connection-mysql",
        feature = "connection-postgres",
        feature = "connection-redis",
        feature = "connection-kafka",
        feature = "connection-etcd",
        feature = "connection-mqtt",
        feature = "connection-elasticsearch"
    ))]
    #[test]
    fn all_builtin_connection_errors_support_question_mark_propagation() {
        fn assert_into_api_error<E: Into<ApiError>>() {}

        assert_into_api_error::<crate::connection::ConnectionError>();
        #[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
        assert_into_api_error::<sqlx::Error>();
        #[cfg(feature = "connection-redis")]
        assert_into_api_error::<redis::RedisError>();
        #[cfg(feature = "connection-kafka")]
        {
            assert_into_api_error::<rdkafka::error::KafkaError>();
            assert_into_api_error::<(rdkafka::error::KafkaError, rdkafka::message::OwnedMessage)>();
        }
        #[cfg(feature = "connection-etcd")]
        assert_into_api_error::<etcd_client::Error>();
        #[cfg(feature = "connection-mqtt")]
        {
            assert_into_api_error::<rumqttc::ClientError>();
            assert_into_api_error::<rumqttc::ConnectionError>();
            assert_into_api_error::<rumqttc::OptionError>();
        }
        #[cfg(feature = "connection-elasticsearch")]
        assert_into_api_error::<elasticsearch::Error>();
    }

    #[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
    #[test]
    fn shared_connection_error_preserves_database_classification() {
        let error = ApiError::from(crate::connection::ConnectionError::Sqlx(
            sqlx::Error::RowNotFound,
        ));

        assert_eq!(error.code, 500_001);
        assert_eq!(error.msg, "数据库操作失败,请稍后重试");
        assert!(
            error
                .internal_error()
                .is_some_and(|message| message.contains("数据库连接失败"))
        );
    }

    #[tokio::test]
    async fn success_response_uses_expected_json_shape() {
        let response = ApiResponse::new("数据").into_response();
        let body = response.into_body().collect().await.unwrap().to_bytes();
        let value: serde_json::Value = serde_json::from_slice(&body).unwrap();

        assert_eq!(value["code"], 200);
        assert_eq!(value["data"], "数据");
        assert_eq!(value["msg"], "操作成功");
    }

    #[test]
    fn default_success_message_does_not_allocate() {
        let response = ApiResponse::new(1);

        assert!(matches!(response.msg, Cow::Borrowed("操作成功")));
        assert_eq!(response.map(|value| value + 1).into_data(), 2);
    }

    #[test]
    fn success_constructors_preserve_code_data_and_message() {
        let with_message = ApiResponse::with_message(1, "创建完成");
        assert_eq!(with_message.code, 200);
        assert_eq!(with_message.data, 1);
        assert_eq!(with_message.msg, "创建完成");

        let with_code = ApiResponse::with_code(2, 201, "已创建");
        assert_eq!(with_code.code, 201);
        assert_eq!(with_code.data, 2);
        assert_eq!(with_code.msg, "已创建");

        let alias = ApiResponse::new_and_msg(3, "兼容接口");
        assert_eq!(alias.code, 200);
        assert_eq!(alias.data, 3);
        assert_eq!(alias.msg, "兼容接口");
    }

    #[tokio::test]
    async fn internal_error_hides_details_from_client() {
        let response = ApiError::err_database("查询失败")
            .with_error("数据库连接被拒绝")
            .with_context("user_id", 1001)
            .into_response();
        let body = response.into_body().collect().await.unwrap().to_bytes();
        let value: serde_json::Value = serde_json::from_slice(&body).unwrap();

        assert_eq!(value["msg"], "查询失败");
        assert!(value.get("internal").is_none());
        assert!(!String::from_utf8_lossy(&body).contains("数据库连接被拒绝"));
    }

    #[test]
    fn constructors_use_expected_business_codes() {
        assert_eq!(ApiError::new(400_099, "自定义错误").code, 400_099);
        assert_eq!(ApiError::err_request_external_service("错误").code, 100_000);
        assert_eq!(ApiError::err_bad_request("错误").code, 400_000);
        assert_eq!(ApiError::err_invalid_param("错误").code, 400_001);
        assert_eq!(ApiError::err_token_client_invalid("错误").code, 400_002);
        assert_eq!(ApiError::err_token_server_invalid("错误").code, 400_003);
        assert_eq!(ApiError::err_unauthorized("错误").code, 401_000);
        assert_eq!(ApiError::err_forbidden_auth("错误").code, 403_000);
        assert_eq!(ApiError::err_user_disabled("错误").code, 403_001);
        assert_eq!(ApiError::err_not_found("错误").code, 404_000);
        assert_eq!(ApiError::err_data_exists("错误").code, 409_000);
        assert_eq!(ApiError::err_unique_index_conflict("错误").code, 409_001);
        assert_eq!(ApiError::err_version_conflict("错误").code, 409_002);
        assert_eq!(ApiError::err_foreign_key_conflict("错误").code, 409_003);
        assert_eq!(ApiError::err_constraint_conflict("错误").code, 409_004);
        assert_eq!(ApiError::err_server_busy("错误").code, 500_000);
        assert_eq!(ApiError::err_database("错误").code, 500_001);
        assert_eq!(ApiError::err_redis("错误").code, 500_002);
        assert_eq!(ApiError::err_encrypt("错误").code, 600_000);
        assert_eq!(ApiError::err_other("错误").code, 999_999);
    }

    #[derive(Debug)]
    struct CyclicError;

    impl Display for CyclicError {
        fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
            formatter.write_str("循环错误")
        }
    }

    impl Error for CyclicError {
        fn source(&self) -> Option<&(dyn Error + 'static)> {
            Some(self)
        }
    }

    #[cfg(feature = "logging")]
    #[test]
    fn internal_metadata_is_bounded() {
        let mut error = ApiError::err_other("失败")
            .with_error("错误".repeat(MAX_INTERNAL_ERROR_BYTES))
            .with_source(&CyclicError);
        for index in 0..(MAX_CONTEXT_FIELDS + 10) {
            error = error.with_context(format!("field-{index}"), "值");
        }
        for index in 0..(MAX_DIAGNOSTICS + 10) {
            error = error.with_diagnostic(Diagnostic::new(
                crate::observability::DiagnosticKind::Internal,
                format!("diagnostic-{index}"),
                "错误",
            ));
        }

        let internal = error.internal.as_ref().unwrap();
        assert!(internal.error.as_ref().unwrap().len() <= MAX_INTERNAL_ERROR_BYTES);
        assert_eq!(internal.source_chain.len(), MAX_SOURCE_DEPTH + 1);
        assert_eq!(internal.context.len(), MAX_CONTEXT_FIELDS);
        assert_eq!(internal.diagnostics.len(), MAX_DIAGNOSTICS);
    }

    #[test]
    fn api_error_keeps_large_diagnostics_behind_a_pointer() {
        assert!(std::mem::size_of::<ApiError>() <= 64);
    }

    #[test]
    fn internal_error_and_context_support_chaining() {
        let error = ApiError::err_bad_request("这是 msg 信息")
            .with_error("真实错误")
            .with_context("key", "value")
            .with_context("request_id", 1001);

        assert_eq!(error.msg, "这是 msg 信息");
        assert_eq!(error.internal_error(), Some("真实错误"));
        let context = error.internal_context().unwrap();
        assert_eq!(context.get("key").map(String::as_str), Some("value"));
        assert_eq!(context.get("request_id").map(String::as_str), Some("1001"));
    }

    #[test]
    fn context_can_be_added_before_error_and_duplicate_keys_are_replaced() {
        let error = ApiError::err_database("查询失败")
            .with_context("operation", "旧值")
            .with_context("operation", "查询用户")
            .with_error("连接超时");

        assert_eq!(error.internal_error(), Some("连接超时"));
        assert_eq!(
            error
                .internal_context()
                .and_then(|context| context.get("operation"))
                .map(String::as_str),
            Some("查询用户")
        );
    }

    #[cfg(feature = "logging")]
    #[test]
    fn response_extension_receives_owned_internal_metadata() {
        let response = ApiError::err_database("查询失败")
            .with_error("连接超时")
            .with_context("operation", "查询用户")
            .into_response();
        let metadata = response.extensions().get::<ErrorLogMetadata>().unwrap();

        assert_eq!(metadata.code, 500_001);
        assert_eq!(metadata.client_message, "查询失败");
        assert_eq!(metadata.internal_error.as_deref(), Some("连接超时"));
        assert_eq!(
            metadata.context.get("operation").map(String::as_str),
            Some("查询用户")
        );
    }
}