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
//! 可在一次请求中聚合的通用诊断信息。

use std::{
    collections::BTreeMap,
    fmt::{self, Display, Write as _},
};

use serde::Serialize;
use serde_json::Value;

use crate::{
    observability::bounded_json::{BoundedJsonValue, to_bounded_json_value},
    web::response::ApiError,
};

pub(super) const MAX_NAME_BYTES: usize = 256;
pub(super) const MAX_ERROR_BYTES: usize = 8 * 1024;
pub(super) const MAX_DETAIL_FIELDS: usize = 32;
pub(super) const MAX_DETAIL_STRING_BYTES: usize = 4 * 1024;
pub(super) const MAX_DETAIL_JSON_BYTES: usize = 16 * 1024;
const MAX_DETAIL_COLLECTION_ITEMS: usize = 32;
const MAX_DETAIL_DEPTH: usize = 8;
pub(super) const MAX_STATEMENT_BYTES: usize = 16 * 1024;
const TRUNCATED_SUFFIX: &str = "…(已截断)";

/// 诊断来源类别。
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum DiagnosticKind {
    /// 数据库或 SQL 执行失败。
    Sql,
    /// 缓存或 Redis 操作失败。
    Cache,
    /// 外部服务调用失败。
    ExternalService,
    /// 应用内部处理失败。
    Internal,
}

/// 一条通用诊断记录。
///
/// 诊断只应记录失败信息。字段中不得放入令牌、密码或未脱敏的个人敏感数据。
#[derive(Clone, Debug, Serialize)]
#[non_exhaustive]
#[must_use = "诊断需要写入错误或请求日志上下文才会生效"]
pub struct Diagnostic {
    /// 诊断类别。
    pub kind: DiagnosticKind,
    /// 稳定的操作名称,便于检索和聚合。
    pub name: String,
    /// 原始错误信息,仅写入服务端日志。
    pub error: String,
    /// 与诊断有关的安全上下文。
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub details: BTreeMap<String, Value>,
}

impl Diagnostic {
    /// 创建诊断记录。
    pub fn new(kind: DiagnosticKind, name: impl Into<String>, error: impl Display) -> Self {
        Self {
            kind,
            name: truncate_owned(name.into(), MAX_NAME_BYTES),
            error: bounded_display(&error, MAX_ERROR_BYTES),
            details: BTreeMap::new(),
        }
    }

    /// 添加字符串形式的安全诊断字段。
    pub fn with_detail(mut self, key: impl Into<String>, value: impl Display) -> Self {
        let key = truncate_owned(key.into(), MAX_NAME_BYTES);
        if !self.details.contains_key(&key) && self.details.len() >= MAX_DETAIL_FIELDS {
            return self;
        }
        self.details.insert(
            key,
            Value::String(bounded_display(&value, MAX_DETAIL_STRING_BYTES)),
        );
        self
    }

    /// 添加保留原始 JSON 类型的安全诊断字段。
    ///
    /// # Errors
    ///
    /// `value` 无法序列化为 JSON 时返回错误;超过字节上限会安全省略。
    pub fn with_json_detail<T>(
        mut self,
        key: impl Into<String>,
        value: T,
    ) -> Result<Self, serde_json::Error>
    where
        T: Serialize,
    {
        let key = truncate_owned(key.into(), MAX_NAME_BYTES);
        if !self.details.contains_key(&key) && self.details.len() >= MAX_DETAIL_FIELDS {
            return Ok(self);
        }
        let value = match to_bounded_json_value(&value, MAX_DETAIL_JSON_BYTES)? {
            BoundedJsonValue::Value(mut value) => {
                bound_json_value(&mut value, 0);
                value
            }
            BoundedJsonValue::TooLarge => Value::String("内容过大,已省略".into()),
        };
        self.details.insert(key, value);
        Ok(self)
    }

    pub(crate) fn bounded_for_log(mut self) -> Self {
        self.name = truncate_owned(self.name, MAX_NAME_BYTES);
        self.error = truncate_owned(self.error, MAX_ERROR_BYTES);
        if self.details.len() > MAX_DETAIL_FIELDS {
            self.details = self.details.into_iter().take(MAX_DETAIL_FIELDS).collect();
        }
        for value in self.details.values_mut() {
            bound_json_value(value, 0);
        }
        self
    }
}

pub(super) fn bound_json_value(value: &mut Value, depth: usize) {
    if depth >= MAX_DETAIL_DEPTH {
        *value = Value::String("…(嵌套层级已截断)".to_owned());
        return;
    }

    match value {
        Value::String(value) => {
            *value = truncate_owned(std::mem::take(value), MAX_DETAIL_STRING_BYTES);
        }
        Value::Array(values) => {
            values.truncate(MAX_DETAIL_COLLECTION_ITEMS);
            for value in values {
                bound_json_value(value, depth + 1);
            }
        }
        Value::Object(values) => {
            if values.len() > MAX_DETAIL_COLLECTION_ITEMS {
                *values = std::mem::take(values)
                    .into_iter()
                    .take(MAX_DETAIL_COLLECTION_ITEMS)
                    .collect();
            }
            for value in values.values_mut() {
                bound_json_value(value, depth + 1);
            }
        }
        Value::Null | Value::Bool(_) | Value::Number(_) => {}
    }
}

pub(super) 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
}

pub(super) 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());
        let mut boundary = keep.min(writer.output.len());
        while boundary > 0 && !writer.output.is_char_boundary(boundary) {
            boundary -= 1;
        }
        writer.output.truncate(boundary);
        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)
    }
}

/// SQL 操作类别。
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum SqlOperation {
    /// 查询。
    Select,
    /// 新增。
    Insert,
    /// 修改。
    Update,
    /// 删除。
    Delete,
    /// 事务或无法进一步细分的数据库操作。
    Other,
}

/// SQL 失败诊断构造器。
///
/// `statement` 应使用带占位符的 SQL 模板,禁止记录拼接了用户输入的完整 SQL。
#[derive(Clone, Debug, Serialize)]
#[non_exhaustive]
#[must_use = "SQL 诊断需要写入错误或请求日志上下文才会生效"]
pub struct SqlDiagnostic {
    /// 稳定的查询名称。
    pub query_name: String,
    /// SQL 操作类别。
    pub operation: SqlOperation,
    /// 带占位符的 SQL 模板。
    pub statement: String,
    /// 数据库返回的原始错误。
    pub error: String,
    /// 已确认可安全记录的参数。
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub safe_parameters: BTreeMap<String, Value>,
    /// 数据库错误码。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_code: Option<String>,
    /// 约束或索引名称。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub constraint: Option<String>,
}

impl SqlDiagnostic {
    /// 创建 SQL 失败诊断。
    pub fn new(
        query_name: impl Into<String>,
        operation: SqlOperation,
        statement: impl Into<String>,
        error: impl Display,
    ) -> Self {
        Self {
            query_name: truncate_owned(query_name.into(), MAX_NAME_BYTES),
            operation,
            statement: truncate_owned(statement.into(), MAX_STATEMENT_BYTES),
            error: bounded_display(&error, MAX_ERROR_BYTES),
            safe_parameters: BTreeMap::new(),
            error_code: None,
            constraint: None,
        }
    }

    /// 添加一个已确认可安全记录的参数。
    pub fn with_safe_parameter(mut self, key: impl Into<String>, value: impl Display) -> Self {
        let key = truncate_owned(key.into(), MAX_NAME_BYTES);
        if !self.safe_parameters.contains_key(&key)
            && self.safe_parameters.len() >= MAX_DETAIL_FIELDS
        {
            return self;
        }
        self.safe_parameters.insert(
            key,
            Value::String(bounded_display(&value, MAX_DETAIL_STRING_BYTES)),
        );
        self
    }

    /// 添加一个保留原始 JSON 类型的安全参数。
    ///
    /// # Errors
    ///
    /// `value` 无法序列化为 JSON 时返回错误;超过字节上限会安全省略。
    pub fn with_safe_json_parameter<T>(
        mut self,
        key: impl Into<String>,
        value: T,
    ) -> Result<Self, serde_json::Error>
    where
        T: Serialize,
    {
        let key = truncate_owned(key.into(), MAX_NAME_BYTES);
        if !self.safe_parameters.contains_key(&key)
            && self.safe_parameters.len() >= MAX_DETAIL_FIELDS
        {
            return Ok(self);
        }
        let value = match to_bounded_json_value(&value, MAX_DETAIL_JSON_BYTES)? {
            BoundedJsonValue::Value(mut value) => {
                bound_json_value(&mut value, 0);
                value
            }
            BoundedJsonValue::TooLarge => Value::String("内容过大,已省略".into()),
        };
        self.safe_parameters.insert(key, value);
        Ok(self)
    }

    /// 设置数据库错误码。
    pub fn with_error_code(mut self, code: impl Into<String>) -> Self {
        self.error_code = Some(truncate_owned(code.into(), MAX_NAME_BYTES));
        self
    }

    /// 设置约束或索引名称。
    pub fn with_constraint(mut self, constraint: impl Into<String>) -> Self {
        self.constraint = Some(truncate_owned(constraint.into(), MAX_NAME_BYTES));
        self
    }
}

impl From<SqlDiagnostic> for Diagnostic {
    fn from(sql: SqlDiagnostic) -> Self {
        let mut details = BTreeMap::new();
        details.insert(
            "operation".into(),
            serde_json::to_value(sql.operation).expect("SQL 操作枚举始终可以序列化"),
        );
        details.insert("statement".into(), Value::String(sql.statement));
        if !sql.safe_parameters.is_empty() {
            details.insert(
                "safe_parameters".into(),
                Value::Object(sql.safe_parameters.into_iter().collect()),
            );
        }
        if let Some(error_code) = sql.error_code {
            details.insert("error_code".into(), Value::String(error_code));
        }
        if let Some(constraint) = sql.constraint {
            details.insert("constraint".into(), Value::String(constraint));
        }

        Self {
            kind: DiagnosticKind::Sql,
            name: sql.query_name,
            error: sql.error,
            details,
        }
    }
}

/// 把底层结果转换为统一错误并保留真实诊断的扩展方法。
pub trait ResultApiErrorExt<T, E> {
    /// 转换为统一错误,同时记录原始错误及来源链。
    ///
    /// # Errors
    ///
    /// 原始 `Result` 为 `Err` 时返回附带诊断信息的 `ApiError`。
    fn map_api_error(self, error: ApiError) -> Result<T, ApiError>
    where
        E: std::error::Error;

    /// 转换为数据库错误,同时记录 SQL 模板和原始错误。
    ///
    /// # Errors
    ///
    /// 原始 `Result` 为 `Err` 时返回附带 SQL 诊断的 `ApiError`。
    fn map_sql_error<F>(self, error: ApiError, diagnostic: F) -> Result<T, ApiError>
    where
        E: std::error::Error,
        F: FnOnce(&E) -> SqlDiagnostic;
}

impl<T, E> ResultApiErrorExt<T, E> for Result<T, E> {
    fn map_api_error(self, error: ApiError) -> Result<T, ApiError>
    where
        E: std::error::Error,
    {
        self.map_err(|source| error.with_source(&source))
    }

    fn map_sql_error<F>(self, error: ApiError, diagnostic: F) -> Result<T, ApiError>
    where
        E: std::error::Error,
        F: FnOnce(&E) -> SqlDiagnostic,
    {
        self.map_err(|source| {
            let diagnostic = diagnostic(&source);
            error.with_source(&source).with_sql_error(diagnostic)
        })
    }
}

#[cfg(test)]
mod tests {
    use std::{error::Error, fmt};

    use super::*;

    #[derive(Debug)]
    struct TestError;

    impl fmt::Display for TestError {
        fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            formatter.write_str("数据库拒绝执行")
        }
    }

    impl Error for TestError {}

    #[test]
    fn sql_result_extension_keeps_private_diagnostic() {
        let result: Result<(), TestError> = Err(TestError);
        let error = result
            .map_sql_error(
                ApiError::err_database("保存失败,请稍后重试"),
                |source| {
                    SqlDiagnostic::new(
                        "create_user",
                        SqlOperation::Insert,
                        "INSERT INTO users(name) VALUES (?)",
                        source,
                    )
                    .with_safe_parameter("user_id", 1001)
                },
            )
            .unwrap_err();

        assert_eq!(error.msg, "保存失败,请稍后重试");
        assert_eq!(error.internal_error(), Some("数据库拒绝执行"));
        assert_eq!(error.diagnostics().unwrap().len(), 1);
    }

    #[test]
    fn diagnostic_bounds_json_and_sql_fields_during_construction() {
        let diagnostic = Diagnostic::new(
            DiagnosticKind::Internal,
            "n".repeat(MAX_NAME_BYTES * 2),
            "错误",
        )
        .with_json_detail("payload", "x".repeat(MAX_DETAIL_JSON_BYTES * 2))
        .unwrap();
        assert!(diagnostic.name.len() <= MAX_NAME_BYTES);
        assert_eq!(diagnostic.details["payload"], "内容过大,已省略");

        let sql = SqlDiagnostic::new(
            "query",
            SqlOperation::Select,
            "S".repeat(MAX_STATEMENT_BYTES * 2),
            "错误",
        );
        assert!(sql.statement.len() <= MAX_STATEMENT_BYTES);
    }
}