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
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
//! 请求生命周期内共享的结构化上下文。

use std::{
    borrow::Cow,
    collections::BTreeMap,
    fmt::{self, Display, Write as _},
    future::Future,
    io,
    sync::{Arc, Mutex},
};

use serde::{Serialize, Serializer, ser::SerializeMap};
use serde_json::Value;
use thiserror::Error;

use super::{
    Diagnostic, SqlDiagnostic, SqlExecution,
    bounded_json::{BoundedJsonValue, to_bounded_json_value},
};

const TRUNCATE_SUFFIX: &str = "…";
const DEFAULT_MAX_KEY_BYTES: usize = 256;
const DEFAULT_MAX_IDENTIFIER_BYTES: usize = 4 * 1024;
const DEFAULT_MAX_VALUE_BYTES: usize = 16 * 1024;

tokio::task_local! {
    static CURRENT_REQUEST_LOG: RequestLogContext;
}

/// 请求操作类别。
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum OperationKind {
    /// 只读取数据的操作。
    Query,
    /// 会改变状态或产生外部副作用的操作。
    Command,
}

/// 一次请求对应的业务操作。
#[derive(Clone, Debug, Serialize)]
#[non_exhaustive]
#[must_use = "操作信息需要写入请求日志上下文才会生效"]
pub struct RequestOperation {
    /// 稳定的操作名称。
    pub name: Cow<'static, str>,
    /// 操作类别。
    pub kind: OperationKind,
    /// 面向排障人员的操作说明。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<Cow<'static, str>>,
    /// 通用资源类型,例如 `user` 或 `order`。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resource: Option<Cow<'static, str>>,
}

impl RequestOperation {
    /// 创建查询操作。
    pub fn query(name: impl Into<String>) -> Self {
        Self::new(name, OperationKind::Query)
    }

    /// 创建命令操作。
    pub fn command(name: impl Into<String>) -> Self {
        Self::new(name, OperationKind::Command)
    }

    /// 创建指定类别的操作。
    pub fn new(name: impl Into<String>, kind: OperationKind) -> Self {
        Self {
            name: Cow::Owned(truncate_owned(name.into(), DEFAULT_MAX_KEY_BYTES)),
            kind,
            description: None,
            resource: None,
        }
    }

    /// 使用静态字符串创建查询操作,不产生字符串堆分配。
    pub const fn query_static(name: &'static str) -> Self {
        Self::new_static(name, OperationKind::Query)
    }

    /// 使用静态字符串创建命令操作,不产生字符串堆分配。
    pub const fn command_static(name: &'static str) -> Self {
        Self::new_static(name, OperationKind::Command)
    }

    const fn new_static(name: &'static str, kind: OperationKind) -> Self {
        Self {
            name: Cow::Borrowed(name),
            kind,
            description: None,
            resource: None,
        }
    }

    /// 设置操作说明。
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(Cow::Owned(truncate_owned(
            description.into(),
            DEFAULT_MAX_VALUE_BYTES,
        )));
        self
    }

    /// 设置静态操作说明,不产生字符串堆分配。
    pub fn with_description_static(mut self, description: &'static str) -> Self {
        self.description = Some(Cow::Borrowed(description));
        self
    }

    /// 设置资源类型。
    pub fn with_resource(mut self, resource: impl Into<String>) -> Self {
        self.resource = Some(Cow::Owned(truncate_owned(
            resource.into(),
            DEFAULT_MAX_KEY_BYTES,
        )));
        self
    }

    /// 设置静态资源类型,不产生字符串堆分配。
    pub fn with_resource_static(mut self, resource: &'static str) -> Self {
        self.resource = Some(Cow::Borrowed(resource));
        self
    }
}

/// 发起请求的通用主体。
#[derive(Clone, Debug, Serialize)]
#[non_exhaustive]
#[must_use = "主体信息需要写入请求日志上下文才会生效"]
pub struct RequestSubject {
    /// 由应用确认可信的主体唯一标识。
    pub id: String,
    /// 主体类型,例如 `user`、`admin` 或 `service`。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kind: Option<String>,
    /// 已确认可安全记录的扩展属性。
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub attributes: BTreeMap<String, Value>,
}

impl RequestSubject {
    /// 创建请求主体。
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: truncate_owned(id.into(), DEFAULT_MAX_IDENTIFIER_BYTES),
            kind: None,
            attributes: BTreeMap::new(),
        }
    }

    /// 设置主体类型。
    pub fn with_kind(mut self, kind: impl Into<String>) -> Self {
        self.kind = Some(truncate_owned(kind.into(), DEFAULT_MAX_KEY_BYTES));
        self
    }

    /// 添加字符串形式的安全属性。
    pub fn with_attribute(mut self, key: impl Into<String>, value: impl Display) -> Self {
        self.attributes.insert(
            truncate_owned(key.into(), DEFAULT_MAX_KEY_BYTES),
            Value::String(bounded_display(&value, DEFAULT_MAX_VALUE_BYTES)),
        );
        self
    }
}

/// 本次操作影响的资源目标。
#[derive(Clone, Debug, Serialize)]
#[non_exhaustive]
#[must_use = "资源目标需要写入请求日志上下文才会生效"]
pub struct ResourceTarget {
    /// 资源类型。
    pub kind: String,
    /// 资源唯一标识;批量操作时可以为空。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// 已确认可安全记录的目标属性。
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub attributes: BTreeMap<String, Value>,
}

impl ResourceTarget {
    /// 创建资源目标。
    pub fn new(kind: impl Into<String>) -> Self {
        Self {
            kind: truncate_owned(kind.into(), DEFAULT_MAX_KEY_BYTES),
            id: None,
            attributes: BTreeMap::new(),
        }
    }

    /// 设置资源唯一标识。
    pub fn with_id(mut self, id: impl Into<String>) -> Self {
        self.id = Some(truncate_owned(id.into(), DEFAULT_MAX_IDENTIFIER_BYTES));
        self
    }

    /// 添加字符串形式的安全目标属性。
    pub fn with_attribute(mut self, key: impl Into<String>, value: impl Display) -> Self {
        self.attributes.insert(
            truncate_owned(key.into(), DEFAULT_MAX_KEY_BYTES),
            Value::String(bounded_display(&value, DEFAULT_MAX_VALUE_BYTES)),
        );
        self
    }
}

/// 一项字段变化。
#[derive(Clone, Debug, Serialize)]
#[non_exhaustive]
pub struct FieldChange {
    /// 字段名。
    pub field: String,
    /// 修改前的安全值。
    pub before: Value,
    /// 修改后的安全值。
    pub after: Value,
}

/// 单次请求日志可收集的最大数量和字段大小。
///
/// 边界在写入请求上下文时立即生效,避免未命中最终日志策略的请求
/// 长时间持有过大的审计数据。
#[derive(Clone, Debug)]
#[must_use = "需要将限制传给 RequestLoggingConfig 才会生效"]
#[allow(clippy::struct_field_names)]
pub struct RequestLoggingLimits {
    pub(crate) max_fields: usize,
    pub(crate) max_targets: usize,
    pub(crate) max_changes: usize,
    pub(crate) max_diagnostics: usize,
    pub(crate) max_sql_executions: usize,
    pub(crate) max_value_bytes: usize,
    pub(crate) max_collection_items: usize,
    pub(crate) max_nesting_depth: usize,
    pub(crate) max_header_value_bytes: usize,
    pub(crate) max_uri_bytes: usize,
}

/// 请求日志容量限制的配置错误。
#[derive(Clone, Debug, Eq, Error, PartialEq)]
pub enum RequestLoggingLimitsError {
    /// 数值必须大于零。
    #[error("{name}必须大于 0")]
    NonPositive { name: &'static str },
    /// 数值不能小于安全下限。
    #[error("{name}不能小于 {minimum}")]
    TooSmall { name: &'static str, minimum: usize },
}

impl Default for RequestLoggingLimits {
    fn default() -> Self {
        Self {
            max_fields: 32,
            max_targets: 32,
            max_changes: 32,
            max_diagnostics: 16,
            max_sql_executions: 16,
            max_value_bytes: DEFAULT_MAX_VALUE_BYTES,
            max_collection_items: 64,
            max_nesting_depth: 8,
            max_header_value_bytes: 2 * 1024,
            max_uri_bytes: 4 * 1024,
        }
    }
}

impl RequestLoggingLimits {
    /// 创建默认限制。
    pub fn new() -> Self {
        Self::default()
    }

    /// 设置自定义字段数量上限。
    pub fn max_fields(mut self, value: usize) -> Self {
        assert_positive(value, "请求日志字段数量上限");
        self.max_fields = value;
        self
    }

    /// 尝试设置自定义字段数量上限,不会因配置错误触发 panic。
    ///
    /// # Errors
    ///
    /// `value` 为零时返回配置错误。
    pub fn try_max_fields(mut self, value: usize) -> Result<Self, RequestLoggingLimitsError> {
        ensure_positive(value, "请求日志字段数量上限")?;
        self.max_fields = value;
        Ok(self)
    }

    /// 设置目标资源数量上限。
    pub fn max_targets(mut self, value: usize) -> Self {
        assert_positive(value, "请求日志目标数量上限");
        self.max_targets = value;
        self
    }

    /// 尝试设置目标资源数量上限,不会因配置错误触发 panic。
    ///
    /// # Errors
    ///
    /// `value` 为零时返回配置错误。
    pub fn try_max_targets(mut self, value: usize) -> Result<Self, RequestLoggingLimitsError> {
        ensure_positive(value, "请求日志目标数量上限")?;
        self.max_targets = value;
        Ok(self)
    }

    /// 设置已提交和尝试变化各自的数量上限。
    pub fn max_changes(mut self, value: usize) -> Self {
        assert_positive(value, "请求日志变化数量上限");
        self.max_changes = value;
        self
    }

    /// 尝试设置字段变化数量上限,不会因配置错误触发 panic。
    ///
    /// # Errors
    ///
    /// `value` 为零时返回配置错误。
    pub fn try_max_changes(mut self, value: usize) -> Result<Self, RequestLoggingLimitsError> {
        ensure_positive(value, "请求日志变化数量上限")?;
        self.max_changes = value;
        Ok(self)
    }

    /// 设置失败诊断数量上限。
    pub fn max_diagnostics(mut self, value: usize) -> Self {
        assert_positive(value, "请求日志诊断数量上限");
        self.max_diagnostics = value;
        self
    }

    /// 尝试设置失败诊断数量上限,不会因配置错误触发 panic。
    ///
    /// # Errors
    ///
    /// `value` 为零时返回配置错误。
    pub fn try_max_diagnostics(mut self, value: usize) -> Result<Self, RequestLoggingLimitsError> {
        ensure_positive(value, "请求日志诊断数量上限")?;
        self.max_diagnostics = value;
        Ok(self)
    }

    /// 设置单次请求保留的 SQL 执行记录数量上限。
    pub fn max_sql_executions(mut self, value: usize) -> Self {
        assert_positive(value, "请求日志 SQL 执行记录数量上限");
        self.max_sql_executions = value;
        self
    }

    /// 尝试设置 SQL 执行记录数量上限,不会因配置错误触发 panic。
    ///
    /// # Errors
    ///
    /// `value` 为零时返回配置错误。
    pub fn try_max_sql_executions(
        mut self,
        value: usize,
    ) -> Result<Self, RequestLoggingLimitsError> {
        ensure_positive(value, "请求日志 SQL 执行记录数量上限")?;
        self.max_sql_executions = value;
        Ok(self)
    }

    /// 设置单个 JSON 值序列化后的字节上限。
    pub fn max_value_bytes(mut self, value: usize) -> Self {
        assert_minimum(value, 64, "请求日志单值字节上限");
        self.max_value_bytes = value;
        self
    }

    /// 尝试设置单个 JSON 值的字节上限,不会因配置错误触发 panic。
    ///
    /// # Errors
    ///
    /// `value` 小于 64 时返回配置错误。
    pub fn try_max_value_bytes(mut self, value: usize) -> Result<Self, RequestLoggingLimitsError> {
        ensure_minimum(value, 64, "请求日志单值字节上限")?;
        self.max_value_bytes = value;
        Ok(self)
    }

    /// 设置 JSON 数组或对象保留的元素上限。
    pub fn max_collection_items(mut self, value: usize) -> Self {
        assert_positive(value, "请求日志 JSON 集合元素上限");
        self.max_collection_items = value;
        self
    }

    /// 尝试设置 JSON 集合元素上限,不会因配置错误触发 panic。
    ///
    /// # Errors
    ///
    /// `value` 为零时返回配置错误。
    pub fn try_max_collection_items(
        mut self,
        value: usize,
    ) -> Result<Self, RequestLoggingLimitsError> {
        ensure_positive(value, "请求日志 JSON 集合元素上限")?;
        self.max_collection_items = value;
        Ok(self)
    }

    /// 设置 JSON 值可保留的最大嵌套深度。
    pub fn max_nesting_depth(mut self, value: usize) -> Self {
        assert_positive(value, "请求日志 JSON 嵌套深度上限");
        self.max_nesting_depth = value;
        self
    }

    /// 尝试设置 JSON 嵌套深度上限,不会因配置错误触发 panic。
    ///
    /// # Errors
    ///
    /// `value` 为零时返回配置错误。
    pub fn try_max_nesting_depth(
        mut self,
        value: usize,
    ) -> Result<Self, RequestLoggingLimitsError> {
        ensure_positive(value, "请求日志 JSON 嵌套深度上限")?;
        self.max_nesting_depth = value;
        Ok(self)
    }

    /// 设置单个请求头日志值的字节上限。
    pub fn max_header_value_bytes(mut self, value: usize) -> Self {
        assert_minimum(value, 4, "请求头日志值字节上限");
        self.max_header_value_bytes = value;
        self
    }

    /// 尝试设置请求头日志值字节上限,不会因配置错误触发 panic。
    ///
    /// # Errors
    ///
    /// `value` 小于 4 时返回配置错误。
    pub fn try_max_header_value_bytes(
        mut self,
        value: usize,
    ) -> Result<Self, RequestLoggingLimitsError> {
        ensure_minimum(value, 4, "请求头日志值字节上限")?;
        self.max_header_value_bytes = value;
        Ok(self)
    }

    /// 设置记录 URI 时的字节上限。
    pub fn max_uri_bytes(mut self, value: usize) -> Self {
        assert_minimum(value, 4, "请求 URI 日志字节上限");
        self.max_uri_bytes = value;
        self
    }

    /// 尝试设置 URI 日志字节上限,不会因配置错误触发 panic。
    ///
    /// # Errors
    ///
    /// `value` 小于 4 时返回配置错误。
    pub fn try_max_uri_bytes(mut self, value: usize) -> Result<Self, RequestLoggingLimitsError> {
        ensure_minimum(value, 4, "请求 URI 日志字节上限")?;
        self.max_uri_bytes = value;
        Ok(self)
    }
}

fn assert_positive(value: usize, name: &str) {
    assert!(value > 0, "{name}必须大于 0");
}

fn assert_minimum(value: usize, minimum: usize, name: &str) {
    assert!(value >= minimum, "{name}不能小于 {minimum}");
}

const fn ensure_positive(
    value: usize,
    name: &'static str,
) -> Result<(), RequestLoggingLimitsError> {
    if value == 0 {
        Err(RequestLoggingLimitsError::NonPositive { name })
    } else {
        Ok(())
    }
}

const fn ensure_minimum(
    value: usize,
    minimum: usize,
    name: &'static str,
) -> Result<(), RequestLoggingLimitsError> {
    if value < minimum {
        Err(RequestLoggingLimitsError::TooSmall { name, minimum })
    } else {
        Ok(())
    }
}

/// 请求日志因容量保护而丢弃或缩减的内容统计。
#[derive(Clone, Debug, Default, Serialize)]
pub struct RequestLogTruncation {
    #[serde(skip_serializing_if = "is_zero")]
    pub dropped_fields: usize,
    #[serde(skip_serializing_if = "is_zero")]
    pub dropped_targets: usize,
    #[serde(skip_serializing_if = "is_zero")]
    pub dropped_changes: usize,
    #[serde(skip_serializing_if = "is_zero")]
    pub dropped_attempted_changes: usize,
    #[serde(skip_serializing_if = "is_zero")]
    pub dropped_diagnostics: usize,
    #[serde(skip_serializing_if = "is_zero")]
    pub dropped_sql_executions: usize,
    #[serde(skip_serializing_if = "is_zero")]
    pub truncated_values: usize,
}

impl RequestLogTruncation {
    const fn is_empty(&self) -> bool {
        self.dropped_fields == 0
            && self.dropped_targets == 0
            && self.dropped_changes == 0
            && self.dropped_attempted_changes == 0
            && self.dropped_diagnostics == 0
            && self.dropped_sql_executions == 0
            && self.truncated_values == 0
    }
}

#[allow(clippy::trivially_copy_pass_by_ref)]
const fn is_zero(value: &usize) -> bool {
    *value == 0
}

impl FieldChange {
    /// 使用字符串形式的值创建字段变化。
    pub fn new(field: impl Into<String>, before: impl Display, after: impl Display) -> Self {
        Self {
            field: truncate_owned(field.into(), DEFAULT_MAX_KEY_BYTES),
            before: Value::String(bounded_display(&before, DEFAULT_MAX_VALUE_BYTES)),
            after: Value::String(bounded_display(&after, DEFAULT_MAX_VALUE_BYTES)),
        }
    }

    /// 使用保留原始 JSON 类型的值创建字段变化。
    ///
    /// # Errors
    ///
    /// `before` 或 `after` 无法序列化为 JSON 时返回错误。
    pub fn from_json<T, U>(
        field: impl Into<String>,
        before: T,
        after: U,
    ) -> Result<Self, serde_json::Error>
    where
        T: Serialize,
        U: Serialize,
    {
        let before = standalone_json_value(&before)?;
        let after = standalone_json_value(&after)?;
        Ok(Self {
            field: truncate_owned(field.into(), DEFAULT_MAX_KEY_BYTES),
            before,
            after,
        })
    }

    /// 使用可直接转换为 JSON 值的类型创建字段变化,不会发生序列化失败。
    pub fn from_values(
        field: impl Into<String>,
        before: impl Into<Value>,
        after: impl Into<Value>,
    ) -> Self {
        Self {
            field: truncate_owned(field.into(), DEFAULT_MAX_KEY_BYTES),
            before: standalone_bounded_value(before.into()),
            after: standalone_bounded_value(after.into()),
        }
    }
}

/// 请求日志上下文的结构化快照。
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct RequestLogSnapshot {
    /// 应用自行添加的安全字段。
    pub fields: BTreeMap<String, Value>,
    /// 当前业务操作。
    pub operation: Option<RequestOperation>,
    /// 请求主体。
    pub subject: Option<RequestSubject>,
    /// 操作目标。
    pub targets: Vec<ResourceTarget>,
    /// 已确认提交的字段变化。
    pub changes: Vec<FieldChange>,
    /// 尝试执行但尚未确认提交的字段变化。
    pub attempted_changes: Vec<FieldChange>,
    /// 请求期间收集的失败诊断。
    pub diagnostics: Vec<Diagnostic>,
    /// 请求期间收集的 SQL 执行记录。
    pub sql_executions: Vec<SqlExecution>,
    /// 因容量保护而丢弃或缩减的内容统计。
    pub truncation: RequestLogTruncation,
}

impl RequestLogSnapshot {
    /// 返回操作类别。
    #[must_use]
    pub fn operation_kind(&self) -> Option<OperationKind> {
        self.operation.as_ref().map(|operation| operation.kind)
    }
}

impl Serialize for RequestLogSnapshot {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let structured_count = usize::from(self.operation.is_some())
            + usize::from(self.subject.is_some())
            + usize::from(!self.targets.is_empty())
            + usize::from(!self.changes.is_empty())
            + usize::from(!self.attempted_changes.is_empty())
            + usize::from(!self.diagnostics.is_empty())
            + usize::from(!self.sql_executions.is_empty())
            + usize::from(!self.truncation.is_empty());
        let mut map = serializer.serialize_map(Some(self.fields.len() + structured_count))?;

        for (key, value) in &self.fields {
            let reserved = matches!(
                key.as_str(),
                "operation"
                    | "subject"
                    | "targets"
                    | "changes"
                    | "attempted_changes"
                    | "diagnostics"
                    | "sql_executions"
                    | "truncation"
            );
            if !reserved
                || (key == "operation" && self.operation.is_none())
                || (key == "subject" && self.subject.is_none())
                || (key == "targets" && self.targets.is_empty())
                || (key == "changes" && self.changes.is_empty())
                || (key == "attempted_changes" && self.attempted_changes.is_empty())
                || (key == "diagnostics" && self.diagnostics.is_empty())
                || (key == "sql_executions" && self.sql_executions.is_empty())
                || (key == "truncation" && self.truncation.is_empty())
            {
                map.serialize_entry(key, value)?;
            }
        }
        if let Some(operation) = &self.operation {
            map.serialize_entry("operation", operation)?;
        }
        if let Some(subject) = &self.subject {
            map.serialize_entry("subject", subject)?;
        }
        if !self.targets.is_empty() {
            map.serialize_entry("targets", &self.targets)?;
        }
        if !self.changes.is_empty() {
            map.serialize_entry("changes", &self.changes)?;
        }
        if !self.attempted_changes.is_empty() {
            map.serialize_entry("attempted_changes", &self.attempted_changes)?;
        }
        if !self.diagnostics.is_empty() {
            map.serialize_entry("diagnostics", &self.diagnostics)?;
        }
        if !self.sql_executions.is_empty() {
            map.serialize_entry("sql_executions", &self.sql_executions)?;
        }
        if !self.truncation.is_empty() {
            map.serialize_entry("truncation", &self.truncation)?;
        }
        map.end()
    }
}

/// 一次请求内共享的日志上下文。
///
/// 克隆只会克隆共享句柄。中间件、handler、service 和 repository 可以共同向其中追加信息,
/// 请求结束时由最外层中间件统一输出。
#[derive(Clone, Default)]
#[must_use = "应将请求日志上下文写入请求扩展或继续传递"]
pub struct RequestLogContext {
    state: Arc<Mutex<RequestLogState>>,
}

#[derive(Default)]
struct RequestLogState {
    snapshot: RequestLogSnapshot,
    limits: RequestLoggingLimits,
    #[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
    next_sql_execution_id: u64,
}

#[derive(Clone, Copy)]
pub(super) struct RequestLogDecision {
    pub operation_kind: Option<OperationKind>,
    pub has_failures: bool,
    pub is_empty: bool,
}

impl RequestLogContext {
    /// 创建空上下文。
    pub fn new() -> Self {
        Self::default()
    }

    pub(crate) fn with_limits(limits: RequestLoggingLimits) -> Self {
        Self {
            state: Arc::new(Mutex::new(RequestLogState {
                snapshot: RequestLogSnapshot::default(),
                limits,
                #[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
                next_sql_execution_id: 0,
            })),
        }
    }

    /// 获取当前异步请求的上下文。
    ///
    /// 该方法只在 `with_request_logging` 所包裹的异步调用链中返回值。
    pub fn try_current() -> Option<Self> {
        CURRENT_REQUEST_LOG.try_with(Clone::clone).ok()
    }

    /// 返回当前异步调用链是否存在请求日志上下文。
    pub(crate) fn is_current() -> bool {
        CURRENT_REQUEST_LOG.try_with(|_| ()).is_ok()
    }

    /// 在当前异步请求上下文存在时执行操作。
    ///
    /// 适合 service 或 repository 追加诊断;未安装完整请求日志时直接返回 `None`。
    pub fn with_current<T>(action: impl FnOnce(&Self) -> T) -> Option<T> {
        CURRENT_REQUEST_LOG.try_with(|context| action(context)).ok()
    }

    /// 在新异步任务中继承当前请求日志上下文。
    ///
    /// 普通 `tokio::spawn` 不会继承 task-local;通过该方法创建的任务可以继续使用
    /// [`RequestLogContext::try_current`] 和审计快捷接口。
    pub fn spawn_current<F>(future: F) -> tokio::task::JoinHandle<F::Output>
    where
        F: Future + Send + 'static,
        F::Output: Send + 'static,
    {
        let context = Self::try_current();
        tokio::spawn(async move {
            if let Some(context) = context {
                scope_request_log(context, future).await
            } else {
                future.await
            }
        })
    }

    /// 插入或覆盖字符串字段。
    pub fn insert(&self, key: impl Into<String>, value: impl Display) {
        let Some((key, max_bytes)) = self.prepare_field_key(key.into()) else {
            return;
        };
        // Display 可能执行任意业务代码,必须在释放上下文锁后格式化。
        let value = bounded_display(&value, max_bytes);
        self.insert_prepared_value(key, Value::String(value), false);
    }

    fn prepare_field_key(&self, mut key: String) -> Option<(String, usize)> {
        self.with_state(|state| {
            bound_string(
                &mut key,
                key_limit(&state.limits),
                &mut state.snapshot.truncation,
            );
            if state.snapshot.fields.contains_key(&key)
                || state.snapshot.fields.len() < state.limits.max_fields
            {
                Some((key, state.limits.max_value_bytes))
            } else {
                state.snapshot.truncation.dropped_fields += 1;
                None
            }
        })
    }

    fn insert_prepared_value(&self, key: String, value: Value, was_truncated: bool) {
        self.with_state(|state| {
            // 两次加锁之间可能有并发写入,因此提交前再次执行容量检查。
            if !state.snapshot.fields.contains_key(&key)
                && state.snapshot.fields.len() >= state.limits.max_fields
            {
                state.snapshot.truncation.dropped_fields += 1;
                return;
            }
            if was_truncated {
                state.snapshot.truncation.truncated_values += 1;
            }
            let value = bounded_value(value, &state.limits, &mut state.snapshot.truncation);
            state.snapshot.fields.insert(key, value);
        });
    }

    /// 插入或覆盖保留原始 JSON 类型的字段。
    ///
    /// # Errors
    ///
    /// `value` 无法序列化为 JSON 时返回错误;超过容量限制会记录省略值而不是错误。
    pub fn insert_json<T>(&self, key: impl Into<String>, value: T) -> Result<(), serde_json::Error>
    where
        T: Serialize,
    {
        let Some((key, max_bytes)) = self.prepare_field_key(key.into()) else {
            // 上下文已满时不再执行可能昂贵的 JSON 序列化。
            return Ok(());
        };
        match to_bounded_json_value(&value, max_bytes)? {
            BoundedJsonValue::Value(value) => self.insert_prepared_value(key, value, false),
            BoundedJsonValue::TooLarge => {
                self.insert_prepared_value(key, Value::String("内容过大,已省略".into()), true);
            }
        }
        Ok(())
    }

    /// 删除字段,并把旧值转换为字符串返回。
    #[must_use]
    pub fn remove(&self, key: &str) -> Option<String> {
        self.with_state(|state| state.snapshot.fields.remove(key).map(value_to_string))
    }

    /// 获取兼容旧接口的字符串字段快照。
    #[must_use]
    pub fn snapshot(&self) -> BTreeMap<String, String> {
        self.with_state(|state| {
            state
                .snapshot
                .fields
                .iter()
                .map(|(key, value)| (key.clone(), value_to_string(value.clone())))
                .collect()
        })
    }

    /// 获取完整结构化快照。
    #[must_use]
    pub fn structured_snapshot(&self) -> RequestLogSnapshot {
        self.with_state(|state| state.snapshot.clone())
    }

    /// 返回当前操作类别,不复制其余上下文。
    #[must_use]
    pub fn operation_kind(&self) -> Option<OperationKind> {
        self.with_state(|state| state.snapshot.operation_kind())
    }

    /// 返回当前请求是否已经收集失败诊断,不复制诊断内容。
    #[must_use]
    pub fn has_diagnostics(&self) -> bool {
        self.with_state(|state| !state.snapshot.diagnostics.is_empty())
    }

    pub(super) fn decision(&self) -> RequestLogDecision {
        self.with_state(|state| RequestLogDecision {
            operation_kind: state.snapshot.operation_kind(),
            has_failures: !state.snapshot.diagnostics.is_empty()
                || state
                    .snapshot
                    .sql_executions
                    .iter()
                    .any(SqlExecution::is_failure),
            is_empty: snapshot_is_empty(&state.snapshot),
        })
    }

    /// 设置本次请求的操作语义。
    pub fn set_operation(&self, mut operation: RequestOperation) {
        self.with_state(|state| {
            bound_cow(
                &mut operation.name,
                key_limit(&state.limits),
                &mut state.snapshot.truncation,
            );
            if let Some(description) = &mut operation.description {
                bound_cow(
                    description,
                    state.limits.max_value_bytes,
                    &mut state.snapshot.truncation,
                );
            }
            if let Some(resource) = &mut operation.resource {
                bound_cow(
                    resource,
                    key_limit(&state.limits),
                    &mut state.snapshot.truncation,
                );
            }
            state.snapshot.operation = Some(operation);
        });
    }

    /// 设置发起请求的主体。
    pub fn set_subject(&self, mut subject: RequestSubject) {
        self.with_state(|state| {
            bound_string(
                &mut subject.id,
                identifier_limit(&state.limits),
                &mut state.snapshot.truncation,
            );
            if let Some(kind) = &mut subject.kind {
                bound_string(
                    kind,
                    key_limit(&state.limits),
                    &mut state.snapshot.truncation,
                );
            }
            bound_map(
                &mut subject.attributes,
                &state.limits,
                &mut state.snapshot.truncation,
            );
            state.snapshot.subject = Some(subject);
        });
    }

    /// 增加一个操作目标。
    pub fn add_target(&self, mut target: ResourceTarget) {
        self.with_state(|state| {
            if state.snapshot.targets.len() >= state.limits.max_targets {
                state.snapshot.truncation.dropped_targets += 1;
                return;
            }
            bound_string(
                &mut target.kind,
                key_limit(&state.limits),
                &mut state.snapshot.truncation,
            );
            if let Some(id) = &mut target.id {
                bound_string(
                    id,
                    identifier_limit(&state.limits),
                    &mut state.snapshot.truncation,
                );
            }
            bound_map(
                &mut target.attributes,
                &state.limits,
                &mut state.snapshot.truncation,
            );
            state.snapshot.targets.push(target);
        });
    }

    /// 增加一项已提交的字段变化。
    ///
    /// 应在数据库事务提交成功后调用,避免把未生效的尝试记录成最终结果。
    pub fn add_change(&self, change: FieldChange) {
        self.with_state(|state| {
            if state.snapshot.changes.len() >= state.limits.max_changes {
                state.snapshot.truncation.dropped_changes += 1;
                return;
            }
            let change = bounded_change(change, &state.limits, &mut state.snapshot.truncation);
            state.snapshot.changes.push(change);
        });
    }

    /// 增加一项尝试执行但尚未确认提交的字段变化。
    ///
    /// 失败日志需要展示用户试图修改的内容时使用;事务提交后应改用 `add_change` 记录最终变化。
    pub fn add_attempted_change(&self, change: FieldChange) {
        self.with_state(|state| {
            if state.snapshot.attempted_changes.len() >= state.limits.max_changes {
                state.snapshot.truncation.dropped_attempted_changes += 1;
                return;
            }
            let change = bounded_change(change, &state.limits, &mut state.snapshot.truncation);
            state.snapshot.attempted_changes.push(change);
        });
    }

    /// 增加一条失败诊断。
    pub fn record_diagnostic(&self, diagnostic: impl Into<Diagnostic>) {
        let diagnostic = diagnostic.into();
        self.with_state(|state| {
            if state.snapshot.diagnostics.len() >= state.limits.max_diagnostics {
                state.snapshot.truncation.dropped_diagnostics += 1;
                return;
            }
            let mut diagnostic = diagnostic;
            bound_string(
                &mut diagnostic.name,
                key_limit(&state.limits),
                &mut state.snapshot.truncation,
            );
            bound_string(
                &mut diagnostic.error,
                state.limits.max_value_bytes,
                &mut state.snapshot.truncation,
            );
            bound_map(
                &mut diagnostic.details,
                &state.limits,
                &mut state.snapshot.truncation,
            );
            state.snapshot.diagnostics.push(diagnostic);
        });
    }

    /// 增加一条 SQL 失败诊断。
    pub fn record_sql_error(&self, diagnostic: SqlDiagnostic) {
        self.record_diagnostic(diagnostic);
    }

    /// 增加一条 SQL 执行记录,并返回当前请求中的执行编号。
    ///
    /// 超过配置上限时不保留记录,返回 `None`。
    #[must_use]
    #[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
    pub(crate) fn record_sql_execution(&self, mut execution: SqlExecution) -> Option<u64> {
        self.with_state(|state| {
            if state.snapshot.sql_executions.len() >= state.limits.max_sql_executions {
                state.snapshot.truncation.dropped_sql_executions += 1;
                return None;
            }
            state.next_sql_execution_id = state.next_sql_execution_id.saturating_add(1);
            execution.execution_id = state.next_sql_execution_id;
            bound_sql_execution(
                &mut execution,
                &state.limits,
                &mut state.snapshot.truncation,
            );
            let execution_id = execution.execution_id;
            state.snapshot.sql_executions.push(execution);
            Some(execution_id)
        })
    }

    fn with_state<T>(&self, action: impl FnOnce(&mut RequestLogState) -> T) -> T {
        let mut state = self
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        action(&mut state)
    }
}

impl Serialize for RequestLogContext {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let state = self
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        state.snapshot.serialize(serializer)
    }
}

fn snapshot_is_empty(snapshot: &RequestLogSnapshot) -> bool {
    snapshot.fields.is_empty()
        && snapshot.operation.is_none()
        && snapshot.subject.is_none()
        && snapshot.targets.is_empty()
        && snapshot.changes.is_empty()
        && snapshot.attempted_changes.is_empty()
        && snapshot.diagnostics.is_empty()
        && snapshot.sql_executions.is_empty()
        && snapshot.truncation.is_empty()
}

#[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
fn bound_sql_execution(
    execution: &mut SqlExecution,
    limits: &RequestLoggingLimits,
    truncation: &mut RequestLogTruncation,
) {
    bound_string(&mut execution.query_name, key_limit(limits), truncation);
    bound_string(&mut execution.statement, limits.max_value_bytes, truncation);
    bound_map(&mut execution.safe_parameters, limits, truncation);
    if let Some(error) = &mut execution.error {
        bound_string(&mut error.class, key_limit(limits), truncation);
        bound_string(&mut error.message, limits.max_value_bytes, truncation);
        if let Some(code) = &mut error.code {
            bound_string(code, key_limit(limits), truncation);
        }
        if let Some(constraint) = &mut error.constraint {
            bound_string(constraint, key_limit(limits), truncation);
        }
    }
}

fn bounded_change(
    mut change: FieldChange,
    limits: &RequestLoggingLimits,
    truncation: &mut RequestLogTruncation,
) -> FieldChange {
    bound_string(&mut change.field, key_limit(limits), truncation);
    change.before = bounded_value(change.before, limits, truncation);
    change.after = bounded_value(change.after, limits, truncation);
    change
}

fn bound_map(
    values: &mut BTreeMap<String, Value>,
    limits: &RequestLoggingLimits,
    truncation: &mut RequestLogTruncation,
) {
    let original_len = values.len();
    let mut bounded = BTreeMap::new();
    for (mut key, value) in std::mem::take(values)
        .into_iter()
        .take(limits.max_collection_items)
    {
        bound_string(&mut key, key_limit(limits), truncation);
        bounded.insert(key, bounded_value(value, limits, truncation));
    }
    if original_len > bounded.len() {
        truncation.truncated_values += 1;
    }
    *values = bounded;
}

const fn key_limit(limits: &RequestLoggingLimits) -> usize {
    if limits.max_value_bytes < DEFAULT_MAX_KEY_BYTES {
        limits.max_value_bytes
    } else {
        DEFAULT_MAX_KEY_BYTES
    }
}

const fn identifier_limit(limits: &RequestLoggingLimits) -> usize {
    if limits.max_value_bytes < DEFAULT_MAX_IDENTIFIER_BYTES {
        limits.max_value_bytes
    } else {
        DEFAULT_MAX_IDENTIFIER_BYTES
    }
}

fn bound_cow(
    value: &mut Cow<'static, str>,
    max_bytes: usize,
    truncation: &mut RequestLogTruncation,
) {
    if value.len() <= max_bytes {
        return;
    }
    let mut owned = value.to_string();
    if truncate_utf8(&mut owned, max_bytes) {
        truncation.truncated_values += 1;
    }
    *value = Cow::Owned(owned);
}

fn bound_string(value: &mut String, max_bytes: usize, truncation: &mut RequestLogTruncation) {
    if truncate_utf8(value, max_bytes) {
        truncation.truncated_values += 1;
    }
}

fn bounded_value(
    mut value: Value,
    limits: &RequestLoggingLimits,
    truncation: &mut RequestLogTruncation,
) -> Value {
    truncate_value_structure(&mut value, limits, truncation, 0);
    if json_fits_limit(&value, limits.max_value_bytes) {
        value
    } else {
        truncation.truncated_values += 1;
        Value::String("内容过大,已省略".into())
    }
}

fn standalone_json_value<T>(value: &T) -> Result<Value, serde_json::Error>
where
    T: Serialize + ?Sized,
{
    Ok(
        match to_bounded_json_value(value, DEFAULT_MAX_VALUE_BYTES)? {
            BoundedJsonValue::Value(value) => standalone_bounded_value(value),
            BoundedJsonValue::TooLarge => Value::String("内容过大,已省略".into()),
        },
    )
}

fn standalone_bounded_value(value: Value) -> Value {
    let limits = RequestLoggingLimits::default();
    let mut truncation = RequestLogTruncation::default();
    bounded_value(value, &limits, &mut truncation)
}

fn json_fits_limit(value: &Value, max_bytes: usize) -> bool {
    serde_json::to_writer(
        SizeLimitedWriter {
            written: 0,
            max_bytes,
        },
        value,
    )
    .is_ok()
}

struct SizeLimitedWriter {
    written: usize,
    max_bytes: usize,
}

impl io::Write for SizeLimitedWriter {
    fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
        let Some(total) = self.written.checked_add(buffer.len()) else {
            return Err(io::Error::other("JSON 字节数溢出"));
        };
        if total > self.max_bytes {
            return Err(io::Error::other("JSON 超过日志字段限制"));
        }
        self.written = total;
        Ok(buffer.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

fn truncate_value_structure(
    value: &mut Value,
    limits: &RequestLoggingLimits,
    truncation: &mut RequestLogTruncation,
    depth: usize,
) {
    if depth >= limits.max_nesting_depth && matches!(value, Value::Array(_) | Value::Object(_)) {
        *value = Value::String("嵌套过深,已省略".into());
        truncation.truncated_values += 1;
        return;
    }

    match value {
        Value::String(text) => {
            if truncate_utf8(text, limits.max_value_bytes) {
                truncation.truncated_values += 1;
            }
        }
        Value::Array(values) => {
            if values.len() > limits.max_collection_items {
                values.truncate(limits.max_collection_items);
                truncation.truncated_values += 1;
            }
            for value in values {
                truncate_value_structure(value, limits, truncation, depth + 1);
            }
        }
        Value::Object(values) => {
            if values.len() > limits.max_collection_items {
                let retained = std::mem::take(values)
                    .into_iter()
                    .take(limits.max_collection_items)
                    .collect();
                *values = retained;
                truncation.truncated_values += 1;
            }
            for value in values.values_mut() {
                truncate_value_structure(value, limits, truncation, depth + 1);
            }
        }
        Value::Null | Value::Bool(_) | Value::Number(_) => {}
    }
}

pub(super) fn truncate_utf8(value: &mut String, max_bytes: usize) -> bool {
    if value.len() <= max_bytes {
        return false;
    }
    let target = max_bytes.saturating_sub(TRUNCATE_SUFFIX.len());
    let mut end = target.min(value.len());
    while !value.is_char_boundary(end) {
        end -= 1;
    }
    value.truncate(end);
    if max_bytes >= TRUNCATE_SUFFIX.len() {
        value.push_str(TRUNCATE_SUFFIX);
    }
    true
}

fn truncate_owned(mut value: String, max_bytes: usize) -> String {
    truncate_utf8(&mut value, max_bytes);
    value
}

pub(crate) async fn scope_request_log<F>(context: RequestLogContext, future: F) -> F::Output
where
    F: Future,
{
    CURRENT_REQUEST_LOG.scope(context, future).await
}

fn value_to_string(value: Value) -> String {
    match value {
        Value::String(value) => value,
        value => value.to_string(),
    }
}

fn bounded_display<T>(value: &T, max_bytes: usize) -> String
where
    T: Display + ?Sized,
{
    let mut writer = LimitedDisplayWriter {
        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(TRUNCATE_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 >= TRUNCATE_SUFFIX.len() {
            writer.output.push_str(TRUNCATE_SUFFIX);
        }
    }
    writer.output
}

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

impl fmt::Write for LimitedDisplayWriter {
    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)
    }
}

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

    #[test]
    fn structured_context_preserves_native_json_values() {
        let context = RequestLogContext::new();
        context.insert_json("count", 2_u64).unwrap();
        context.set_operation(RequestOperation::command("create_user"));
        context.set_subject(RequestSubject::new("guid-1").with_kind("user"));
        context.add_change(FieldChange::from_json("enabled", false, true).unwrap());

        let value = serde_json::to_value(context.structured_snapshot()).unwrap();
        assert_eq!(value["count"], 2);
        assert_eq!(value["operation"]["kind"], "command");
        assert_eq!(value["subject"]["id"], "guid-1");
        assert_eq!(value["changes"][0]["before"], false);
    }

    #[test]
    fn fallible_limit_builders_reject_invalid_configuration() {
        assert!(RequestLoggingLimits::new().try_max_fields(0).is_err());
        assert!(
            RequestLoggingLimits::new()
                .try_max_sql_executions(0)
                .is_err()
        );
        assert!(RequestLoggingLimits::new().try_max_value_bytes(63).is_err());
        assert!(RequestLoggingLimits::new().try_max_uri_bytes(3).is_err());
        assert!(RequestLoggingLimits::new().try_max_fields(1).is_ok());
    }

    #[tokio::test]
    async fn current_context_is_available_only_inside_scope() {
        assert!(RequestLogContext::try_current().is_none());
        assert!(!RequestLogContext::is_current());
        let context = RequestLogContext::new();
        scope_request_log(context.clone(), async {
            assert!(RequestLogContext::is_current());
            RequestLogContext::try_current()
                .unwrap()
                .insert("stage", "service");
        })
        .await;
        assert_eq!(context.snapshot().get("stage").unwrap(), "service");
        assert!(RequestLogContext::try_current().is_none());
        assert!(!RequestLogContext::is_current());
    }

    #[test]
    fn configured_limits_bound_context_and_report_truncation() {
        let context = RequestLogContext::with_limits(
            RequestLoggingLimits::new()
                .max_fields(2)
                .max_value_bytes(64)
                .max_collection_items(2),
        );
        context.insert("first", "x".repeat(100));
        context.insert("second", "保留");
        context.insert("third", "丢弃");
        context
            .insert_json("second", serde_json::json!([1, 2, 3, 4]))
            .unwrap();

        let snapshot = context.structured_snapshot();
        assert_eq!(snapshot.fields.len(), 2);
        assert_eq!(snapshot.fields["second"], serde_json::json!([1, 2]));
        assert_eq!(snapshot.truncation.dropped_fields, 1);
        assert!(snapshot.truncation.truncated_values >= 2);
    }

    #[test]
    fn field_names_keep_an_independent_hard_limit() {
        let context = RequestLogContext::with_limits(
            RequestLoggingLimits::new().max_value_bytes(DEFAULT_MAX_VALUE_BYTES * 2),
        );
        context.insert("k".repeat(DEFAULT_MAX_KEY_BYTES * 2), "值");

        let snapshot = context.structured_snapshot();
        assert_eq!(snapshot.fields.len(), 1);
        assert!(snapshot.fields.keys().next().unwrap().len() <= DEFAULT_MAX_KEY_BYTES);
        assert_eq!(snapshot.truncation.truncated_values, 1);
    }

    #[test]
    fn oversized_json_is_omitted_without_building_an_unbounded_value() {
        let context =
            RequestLogContext::with_limits(RequestLoggingLimits::new().max_value_bytes(64));
        context.insert_json("payload", "x".repeat(1024)).unwrap();

        let snapshot = context.structured_snapshot();
        assert_eq!(snapshot.fields["payload"], "内容过大,已省略");
        assert_eq!(snapshot.truncation.truncated_values, 1);
    }

    #[test]
    fn standalone_audit_values_apply_safe_default_bounds() {
        let change =
            FieldChange::from_json("field", "x".repeat(DEFAULT_MAX_VALUE_BYTES * 2), true).unwrap();
        assert_eq!(change.before, "内容过大,已省略");

        let subject = RequestSubject::new("id")
            .with_attribute("source", "x".repeat(DEFAULT_MAX_VALUE_BYTES * 2));
        assert!(
            subject.attributes["source"]
                .as_str()
                .is_some_and(|value| value.len() <= DEFAULT_MAX_VALUE_BYTES)
        );
    }

    #[tokio::test]
    async fn spawn_current_propagates_task_local_context() {
        let context = RequestLogContext::new();
        scope_request_log(context.clone(), async {
            RequestLogContext::spawn_current(async {
                RequestLogContext::with_current(|current| current.insert("task", "完成"));
            })
            .await
            .unwrap();
        })
        .await;

        assert_eq!(context.snapshot()["task"], "完成");
    }
}