garrison 0.7.2

Garrison - 面向 Rust 生态的一站式身份认证鉴权框架
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
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
//! Copyright (c) 2026 Kirky.X. All rights reserved.
//! See LICENSE for full license text.

//! DAO 模块,定义持久化数据访问抽象层。
//!
//! 对应 `SaTokenDao`,
//! 通过 oxcache / dbnexus 提供多后端(缓存 / 关系型数据库)支持。

use crate::error::{GarrisonError, GarrisonResult};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::time::Duration;

/// DAO 抽象层 trait,定义 Token 与会话的持久化操作。
///
/// 对应 `SaTokenDao`,提供 get / set / update / delete / expire 五元操作
/// + set_permanent / get_timeout / keys / rename 四个扩展方法。
///
/// - `set` 必须指定 TTL(Token/Session 不应永久驻留,与 既有语义一致)
/// - `update` 更新值时保留原有 TTL(不重置过期时间)
/// - `expire` 重置键的过期时间
/// - `set_permanent` 存储永久键(无 TTL,默认实现委托 `set(key, value, 0)`)
/// - `get_timeout` 查询剩余 TTL(默认返回 `NotImplemented`,需后端重写)
/// - `keys` 按 glob pattern 扫描 key(默认返回 `NotImplemented`;`MockDao` 已实现;`GarrisonDaoOxcache` 因 oxcache 0.3.3 限制待 oxcache 提供原生 iter API)
/// - `rename` 重命名 key(默认 get→set→delete 三步,非原子)
#[async_trait]
pub trait GarrisonDao: Send + Sync {
    /// 获取指定键的值。
    ///
    /// # 参数
    /// - `key`: 存储键。
    ///
    /// # 返回
    /// - `Some(value)`: 键存在且未过期。
    /// - `None`: 键不存在或已过期。
    async fn get(&self, key: &str) -> GarrisonResult<Option<String>>;

    /// 设置键值对,附带 TTL。
    ///
    /// # 参数
    /// - `key`: 存储键。
    /// - `value`: 存储值。
    /// - `ttl_seconds`: 过期秒数(0 表示永久驻留;可被 `expire` 重置)。
    async fn set(&self, key: &str, value: &str, ttl_seconds: u64) -> GarrisonResult<()>;

    /// 更新键的值,保留原有 TTL(不重置过期时间)。
    ///
    /// # 参数
    /// - `key`: 存储键(必须已存在)。
    /// - `value`: 新值。
    ///
    /// # 错误
    /// - 若键不存在,返回 `GarrisonError::Dao`。
    async fn update(&self, key: &str, value: &str) -> GarrisonResult<()>;

    /// 设置(或重置)键的过期时间。
    ///
    /// # 参数
    /// - `key`: 存储键。
    /// - `seconds`: 过期秒数(0 表示永久驻留)。
    ///
    /// # 错误
    /// - 若键不存在,返回 `GarrisonError::Dao`。
    async fn expire(&self, key: &str, seconds: u64) -> GarrisonResult<()>;

    /// 删除指定键。
    ///
    /// # 参数
    /// - `key`: 存储键。
    async fn delete(&self, key: &str) -> GarrisonResult<()>;

    /// 存储永久键(无 TTL)。
    ///
    ///
    /// # 参数
    /// - `key`: 存储键。
    /// - `value`: 存储值。
    ///
    /// # 默认实现
    /// 委托 `self.set(key, value, 0)`。
    /// 后端可重写以使用原生"无 TTL"API(如 oxcache `set_with_ttl_sync(None)`)。
    async fn set_permanent(&self, key: &str, value: &str) -> GarrisonResult<()> {
        self.set(key, value, 0).await
    }

    /// 查询键的剩余 TTL。
    ///
    ///
    /// # 参数
    /// - `key`: 存储键。
    ///
    /// # 返回
    /// - `Ok(Some(remaining))`: 键存在且设置了 TTL,返回剩余存活时间。
    /// - `Ok(None)`: 键不存在,或键存在但未设置 TTL(永久驻留)。
    ///
    /// # 默认实现
    /// 返回 `GarrisonError::NotImplemented`(需后端原生 TTL 查询 API 支持)。
    /// `GarrisonDaoOxcache` 与 `MockDao` 已重写。
    async fn get_timeout(&self, _key: &str) -> GarrisonResult<Option<Duration>> {
        Err(GarrisonError::NotImplemented(format!(
            "get_timeout 未实现:{} 后端不支持 TTL 查询",
            std::any::type_name::<Self>()
        )))
    }

    /// 原子地获取键值与剩余 TTL(性能优化接口)。
    ///
    /// 单次 DAO 调用同时返回 value 与 TTL,避免 `get` + `get_timeout` 两次调用。
    /// 用于 `renew_to_equivalent` 等热路径,减少 DAO 往返次数。
    ///
    /// # 参数
    /// - `key`: 存储键。
    ///
    /// # 返回
    /// - `Ok(Some((value, ttl)))`: 键存在。`ttl` 为 `Some(d)` 表示设置了 TTL,`None` 表示永久驻留。
    /// - `Ok(None)`: 键不存在或已过期。
    ///
    /// # 默认实现
    /// 委托 `self.get(key)` + `self.get_timeout(key)` 两次调用(向后兼容)。
    /// 后端若支持原子获取 value + TTL(如 Redis pipeline / 内存 HashMap 单次 lookup),
    /// 应重写此方法以减少 DAO 往返。
    async fn get_with_ttl(&self, key: &str) -> GarrisonResult<Option<(String, Option<Duration>)>> {
        let value = self.get(key).await?;
        if value.is_none() {
            return Ok(None);
        }
        let ttl = self.get_timeout(key).await?;
        Ok(Some((value.unwrap(), ttl)))
    }

    /// 按 glob pattern 扫描 key。
    ///
    ///
    /// # 参数
    /// - `pattern`: glob 模式,支持 `*`(任意字符序列)与 `?`(单字符)。
    ///
    /// # 返回
    /// - `Ok(Vec<String>)`: 匹配的 key 列表(无序),无匹配返回空 Vec。
    ///
    /// # 性能警告
    /// - 大规模 key 场景下性能差(需全量扫描 + 过滤)
    ///
    /// # 已知限制(A-010 评估结论)
    ///
    /// `GarrisonDaoOxcache` 当前不重写此方法(走默认 `NotImplemented`),原因:
    /// - oxcache 0.3.3 的 `CacheReader`/`CacheBackend` trait 未暴露 iter/keys/scan API(2026-07-08 验证)
    /// - `Cache.backend` 字段为 `pub(crate)`,外部无法访问底层 `DashMap`
    /// - `CacheReader` trait 仅有 `get`/`exists`/`ttl`/`len`/`is_empty`/`capacity`/`stats`/`get_many`,无 iter/keys 方法
    /// - 维护独立 key 索引(如 `DashMap<String, ()>`)会增加内存开销 + 一致性复杂度(set/delete 需同步索引)
    /// - oxcache 上游路线图有 iter API 计划(0.3.3 仍未实现,crates.io 最新无更高版本)
    ///
    /// **决策**:defer 到 oxcache 提供原生 iter API。业务方临时方案:自行维护 key 集合(参考 `ApiKeyHandler::list_by_namespace` 的 `MockDao` 测试)。
    ///
    /// **业务影响**:`ApiKeyHandler::list_by_namespace` 在使用 `GarrisonDaoOxcache` 时返回 `NotImplemented`(生产可用性受限)。
    ///
    /// # 默认实现
    /// 返回 `GarrisonError::NotImplemented`。
    async fn keys(&self, _pattern: &str) -> GarrisonResult<Vec<String>> {
        Err(GarrisonError::NotImplemented(format!(
            "keys 未实现:{} 后端不支持 key scan(待 oxcache 提供原生 iter API)",
            std::any::type_name::<Self>()
        )))
    }

    /// 重命名 key。
    ///
    ///
    /// # 参数
    /// - `old_key`: 原 key(必须已存在)。
    /// - `new_key`: 新 key。
    ///
    /// # 错误
    /// - `GarrisonError::InvalidParam`: `old_key` 不存在。
    ///
    /// # 非原子性警告
    /// 默认实现为 `get → set_permanent → delete` 三步操作,存在竞态窗口:
    /// 1. 读取 old_key 后、写入 new_key 前,old_key 可能被其他线程修改或删除
    /// 2. 写入 new_key 后、删除 old_key 前,old_key 与 new_key 同时存在
    /// 后端若支持原子 rename(如 Redis RENAME),应重写此方法。
    ///
    /// # TTL 保留
    /// 默认实现**不保留**原键 TTL(用 `set_permanent` 写入新键)。
    /// 后端若需保留 TTL,应重写此方法(如 `GarrisonDaoOxcache` 用 `ttl_sync` + `set_with_ttl_sync`)。
    async fn rename(&self, old_key: &str, new_key: &str) -> GarrisonResult<()> {
        let value = self
            .get(old_key)
            .await?
            .ok_or_else(|| GarrisonError::InvalidParam(format!("dao-key-missing::{}", old_key)))?;
        self.set_permanent(new_key, &value).await?;
        self.delete(old_key).await
    }

    /// 原子地获取并删除键。
    ///
    /// 保证 get 与 delete 在同一临界区内执行,消除 TOCTOU 竞态。
    /// 用于 SSO ticket 一次性消费等场景。
    ///
    /// # 参数
    /// - `key`: 存储键。
    ///
    /// # 返回
    /// - `Ok(Some(value))`: 键存在,已原子读取并删除。
    /// - `Ok(None)`: 键不存在或已过期。
    ///
    /// # 默认实现(非原子)
    /// 默认实现为 `get → delete` 两步操作,**存在 TOCTOU 竞态**:
    /// 并发调用同一 key 时可能多个调用都返回 `Some`。
    /// 后端若支持原子操作(如 Redis Lua / oxcache 内存后端原子操作),应重写此方法。
    ///
    /// # 已重写的实现
    /// - `MockDao`:`parking_lot::Mutex` 保护,进程内原子
    /// - `GarrisonDaoOxcache`:`parking_lot::Mutex` 保护,进程内原子
    /// - `AloneCache`:委托内部 dao
    ///
    /// # 生产实现警告
    ///
    /// **生产部署必须重写此方法**,使用后端原子的 CAS / GETDEL / Lua 脚本:
    /// - `GarrisonDaoOxcache`:已重写,用 `parking_lot::Mutex` 保护(进程内原子)
    /// - `MockDao`:已重写,用 `parking_lot::Mutex` 保护(进程内原子)
    /// - Redis 后端:应重写为 `GETDEL` 原子命令或 Lua 脚本
    /// - dbnexus 后端:应重写为 SQL `DELETE ... RETURNING` 语句
    ///
    /// 使用默认实现(如 `MinimalDao`)在生产环境会导致 TOCTOU 竞态:
    /// 并发调用同一 key 时多个调用都可能返回 `Some`。
    async fn get_and_delete(&self, key: &str) -> GarrisonResult<Option<String>> {
        let value = self.get(key).await?;
        if value.is_some() {
            self.delete(key).await?;
        }
        Ok(value)
    }

    /// 原子递增计数器(带 TTL)。
    ///
    /// 将 key 的值递增 1。若 key 不存在则初始化为 1 并设置 TTL;
    /// 若 key 已存在则仅递增值,**不重置 TTL**(保留原窗口过期时间)。
    /// 用于 SMS 限速计数器等场景。
    ///
    /// # 参数
    /// - `key`: 计数器键。
    /// - `ttl_seconds`: TTL 秒数(仅 key 首次创建时设置)。
    ///
    /// # 返回
    /// - `Ok(new_value)`: 递增后的新值。
    ///
    /// # 默认实现(非原子)
    /// 默认实现为 get → parse → update/set 三步操作,存在竞态风险。
    /// 后端若支持原子 incr(如 Redis INCR + EXPIRE),应重写此方法。
    /// `MockDao` 已重写为进程内原子(Mutex 保护)。
    async fn incr(&self, key: &str, ttl_seconds: u64) -> GarrisonResult<u64> {
        let current = self.get(key).await?;
        match current {
            Some(v) => {
                // Rule 12:parse 失败必须显式报错,禁止静默返回 0 导致计数器重置
                let cur_val: u64 = v.parse().map_err(|_| {
                    GarrisonError::Dao(format!("dao-incr-parse-u64::{}::{}", key, v))
                })?;
                let new_val = cur_val + 1;
                self.update(key, &new_val.to_string()).await?;
                Ok(new_val)
            },
            None => {
                self.set(key, "1", ttl_seconds).await?;
                Ok(1)
            },
        }
    }

    /// 原子递减计数器(与 [`incr`](Self::incr) 对称)。
    ///
    /// 将 key 的值递减 1。语义:
    /// - key 不存在或已过期:返回 0(不报错,不创建 key)
    /// - 当前值为 0:返回 0(不递减为负)
    /// - 当前值 > 0:递减 1;递减后值为 0 时删除 key(与 `SmsRateLimiter::decrement_counter` 语义一致);
    ///   递减后值 > 0 时保留原 TTL(不重置窗口)
    ///
    /// 用于 SMS 限速计数器回滚(`SmsRateLimiter::decrement_counter`)等场景,
    /// 消除 `get → parse → update/delete` 三步组合的 TOCTOU 竞态。
    ///
    /// # 参数
    /// - `key`: 计数器键。
    ///
    /// # 返回
    /// - `Ok(new_value)`: 递减后的新值(key 不存在/已过期/值为 0 时返回 0)。
    ///
    /// # 默认实现(返回 NotImplemented)
    /// 默认实现返回 `GarrisonError::NotImplemented`(M2 修复,与
    /// `compare_and_update_if_greater` 对齐,消除 TOCTOU 竞态):
    /// 原默认实现为 `get → parse → update/delete` 三步操作,存在 TOCTOU 竞态,
    /// 并发调用同一 key 时多个调用可能基于同一过时 get 值计算新值并覆盖写入,
    /// 导致"跨越式递减"(实际递减量大于 1)。`SmsRateLimiter::decrement_counter`
    /// 的 flaky test(`concurrent_send_does_not_exceed_limit`)即由此引发。
    /// 此方法用于 SMS 限速等安全敏感场景,必须由后端用原子 decr 实现。
    ///
    /// # 已重写的实现
    /// - `MockDao`:`parking_lot::Mutex` 保护,进程内原子
    /// - `GarrisonDaoOxcache`:`atomic_lock` 保护,进程内原子
    /// - `AloneCache`:委托内部 dao(M1 修复,与 `compare_and_update_if_greater` 对称)
    ///
    /// # 生产实现警告
    ///
    /// **生产部署必须重写此方法**,使用后端原子的 DECR / Lua 脚本:
    /// - `GarrisonDaoOxcache`:已重写,用 `atomic_lock` 保护(进程内原子)
    /// - `MockDao`:已重写,用 `parking_lot::Mutex` 保护(进程内原子)
    /// - `AloneCache`:已重写,委托内部 dao(M1 修复)
    /// - Redis 后端:应重写为 `DECR` 原子命令(值为 0 时额外 `DEL`)
    /// - dbnexus 后端:应重写为 SQL `UPDATE ... WHERE ... RETURNING` 语句
    ///
    /// 使用默认实现(如 `MinimalDao`)会返回 `NotImplemented` 错误,
    /// 强制调用方显式选择支持原子 decr 的后端,避免静默引入 TOCTOU 竞态。
    async fn decr(&self, _key: &str) -> GarrisonResult<u64> {
        Err(GarrisonError::NotImplemented(format!(
            "decr 未实现:{} 后端不支持原子 decr(SMS 限速计数器回滚必须重写)",
            std::any::type_name::<Self>()
        )))
    }

    /// 原子地比较并更新(仅当新值大于当前值时)。
    ///
    /// 读取当前值(解析为 u64),若 `new_value > current_value` 则更新为 `new_value` 并返回 true;
    /// 否则不修改,返回 false。键不存在时 current_value 视为 0。
    ///
    /// 用于 HTTP Digest nc 单调性校验(RFC 7616 §3.4.6),消除 get→compare→set TOCTOU 竞态。
    ///
    /// # 参数
    /// - `key`: 存储键。
    /// - `new_value`: 待比较并写入的新值。
    /// - `ttl_seconds`: TTL 秒数(仅 key 首次创建时设置,已存在时不重置 TTL)。
    ///
    /// # 返回
    /// - `Ok(true)`: new_value > current_value,已更新。
    /// - `Ok(false)`: new_value <= current_value,未更新。
    ///
    /// # 默认实现(返回 NotImplemented)
    /// 默认实现返回 `GarrisonError::NotImplemented`(M2 修复,消除 TOCTOU 竞态):
    /// 原默认实现为 get → parse → compare → set 四步操作,存在 TOCTOU 竞态,
    /// 在并发场景下多个调用可能同时读到旧值并各自执行 set,破坏 nc 单调性。
    /// 此方法用于 HTTP Digest nc 单调性校验等安全敏感场景,必须由后端用原子 CAS 实现。
    ///
    /// # 已重写的实现
    /// - `MockDao`:`parking_lot::Mutex` 保护,进程内原子
    /// - `GarrisonDaoOxcache`:`atomic_lock` + oxcache set_with_ttl_sync 保护,进程内原子
    /// - `AloneCache`:委托内部 dao
    ///
    /// # 生产实现警告
    ///
    /// **生产部署必须重写此方法**,使用后端原子的 CAS / Lua 脚本:
    /// - `GarrisonDaoOxcache`:已重写,用 `atomic_lock` 保护(进程内原子)
    /// - `MockDao`:已重写,用 `parking_lot::Mutex` 保护(进程内原子)
    /// - Redis 后端:应重写为 Lua 脚本(GET + COMPARE + SET 原子执行)
    /// - dbnexus 后端:应重写为 SQL `UPDATE ... WHERE ... RETURNING` 语句
    ///
    /// 使用默认实现(如 `MinimalDao`)会返回 `NotImplemented` 错误,
    /// fail-closed 语义:宁可拒绝所有请求也不接受非原子 CAS。
    async fn compare_and_update_if_greater(
        &self,
        _key: &str,
        _new_value: u64,
        _ttl_seconds: u64,
    ) -> GarrisonResult<bool> {
        Err(GarrisonError::NotImplemented(format!(
            "compare_and_update_if_greater 未实现:{} 后端不支持原子 CAS(HTTP Digest nc 单调性校验必须重写)",
            std::any::type_name::<Self>()
        )))
    }

    /// 查询社交账号绑定关系。
    ///
    /// 按 `(tenant_id, provider, provider_user_id)` 三元组查询 `social_bindings` 表,
    /// 返回关联的 `login_id`。
    ///
    /// # 参数
    /// - `tenant_id`: 租户 ID(0=默认租户)。
    /// - `provider`: 社交平台标识(`"wechat"` / `"alipay"` / `"wechat_mini_app"`)。
    /// - `provider_user_id`: 第三方平台用户唯一 ID(微信 openid / 支付宝 user_id)。
    ///
    /// # 返回
    /// - `Ok(Some(login_id))`: 绑定关系存在,返回关联的 login_id。
    /// - `Ok(None)`: 绑定关系不存在(首次登录)。
    ///
    /// # 默认实现
    /// 返回 `GarrisonError::NotImplemented`(GarrisonDao 是 KV 缓存抽象,不支持 SQL SELECT)。
    /// `SocialBindingService` 实际用 `DbPool` 查 SQL,不调用此方法。
    /// 此方法仅为满足 spec trait 契约,供未来纯 KV 后端实现重写。
    async fn find_social_binding(
        &self,
        _tenant_id: i64,
        _provider: &str,
        _provider_user_id: &str,
    ) -> GarrisonResult<Option<i64>> {
        Err(GarrisonError::NotImplemented(format!(
            "find_social_binding 未实现:{} 后端不支持 SQL 查询(SocialBindingService 用 DbPool)",
            std::any::type_name::<Self>()
        )))
    }

    /// 插入社交账号绑定关系。
    ///
    /// 将 `(tenant_id, login_id, provider, provider_user_id, union_id)` 写入 `social_bindings` 表。
    ///
    /// # 参数
    /// - `tenant_id`: 租户 ID(0=默认租户)。
    /// - `login_id`: Garrison 内部用户 ID(INTEGER,由 `SocialBindingService::find_or_create` 生成)。
    /// - `provider`: 社交平台标识(`"wechat"` / `"alipay"` / `"wechat_mini_app"`)。
    /// - `provider_user_id`: 第三方平台用户唯一 ID。
    /// - `union_id`: 跨应用统一 ID(微信 unionid,可空)。
    /// - `created_at`: 创建时间戳(Unix 秒)。
    ///
    /// # 默认实现
    /// 返回 `GarrisonError::NotImplemented`(GarrisonDao 是 KV 缓存抽象,不支持 SQL INSERT)。
    /// `SocialBindingService` 实际用 `DbPool` 执行 INSERT,不调用此方法。
    /// 此方法仅为满足 spec trait 契约,供未来纯 KV 后端实现重写。
    async fn insert_social_binding(
        &self,
        _tenant_id: i64,
        _login_id: i64,
        _provider: &str,
        _provider_user_id: &str,
        _union_id: Option<&str>,
        _created_at: i64,
    ) -> GarrisonResult<()> {
        Err(GarrisonError::NotImplemented(format!(
            "insert_social_binding 未实现:{} 后端不支持 SQL 插入(SocialBindingService 用 DbPool)",
            std::any::type_name::<Self>()
        )))
    }

    /// 执行 Redis Lua 脚本(原子操作)。
    ///
    /// 用于实现原子 check-and-increment 等复合操作,消除多步操作间的竞态窗口。
    /// 典型场景:限速计数器(INCR + EXPIRE 原子化)、一次性 token 消费(GET + DEL 原子化)。
    ///
    /// # 参数
    /// - `script`: Lua 脚本字符串(Redis EVAL 语法)。
    /// - `keys`: KEYS 数组(脚本中通过 `KEYS[1]`、`KEYS[2]`... 访问)。
    /// - `args`: ARGV 数组(脚本中通过 `ARGV[1]`、`ARGV[2]`... 访问)。
    ///
    /// # 返回
    /// - `Ok(Vec<String>)`: 脚本返回值(每个元素对应一个返回值)。
    ///
    /// # 默认实现
    /// 返回 `GarrisonError::NotImplemented`(仅 Redis 后端支持 Lua 脚本)。
    /// `MockDao` 重写为内存模拟(识别 INCR + EXPIRE 模式,委托 `incr` 实现)。
    /// `GarrisonDaoOxcache` 使用默认实现(oxcache 未暴露 Redis Lua API)。
    ///
    /// # 降级策略
    /// 调用方应在 `eval_lua` 返回 `NotImplemented` 时降级到非原子路径
    /// (如 `incr` + 阈值判断,进程内原子但跨进程非原子)。
    async fn eval_lua(
        &self,
        _script: &str,
        _keys: Vec<String>,
        _args: Vec<String>,
    ) -> GarrisonResult<Vec<String>> {
        Err(GarrisonError::NotImplemented(format!(
            "eval_lua 未实现:{} 后端不支持 Lua 脚本(仅 Redis 后端支持)",
            std::any::type_name::<Self>()
        )))
    }
}

// ============================================================================
// Redis 部署模式配置
// ============================================================================

/// Redis 部署模式枚举,覆盖生产环境常见拓扑。
///
/// 参阅 Redis 集群部署文档:单节点 / Sentinel / Cluster / Master-Slave。
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "mode", rename_all = "lowercase")]
pub enum RedisDeploymentMode {
    /// 单节点模式:单个 Redis 实例。
    Single {
        /// Redis 连接 URL(如 `redis://127.6379`)。
        url: String,
    },
    /// 哨兵模式:通过 Sentinel 集群自动故障转移。
    Sentinel {
        /// Sentinel 集群主节点名称(如 `mymaster`)。
        master_name: String,
        /// Sentinel 节点 URL 列表。
        urls: Vec<String>,
    },
    /// 集群模式:Redis Cluster 分片存储。
    Cluster {
        /// Cluster 节点 URL 列表(至少 3 个 master 节点)。
        urls: Vec<String>,
    },
    /// 主从模式:1 个 master + N 个 slave,读分离需客户端支持。
    MasterSlave {
        /// Master 节点 URL。
        master_url: String,
        /// Slave 节点 URL 列表。
        slave_urls: Vec<String>,
    },
}

/// Redis 配置聚合结构,包含部署模式、连接池参数与认证信息。
///
/// # 默认值
///
/// - `mode`: `Single { url: "redis://127.6379" }`
/// - `password`: `None`
/// - `db`: `0`
/// - `connection_timeout_secs`: `5`
/// - `pool_size`: `10`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct RedisConfig {
    /// Redis 部署模式。
    pub mode: RedisDeploymentMode,
    /// 认证密码(`None` 表示无密码)。
    pub password: Option<String>,
    /// Redis 数据库编号(0-15)。
    pub db: u8,
    /// 连接超时秒数。
    pub connection_timeout_secs: u64,
    /// 连接池大小。
    pub pool_size: u32,
}

// ============================================================================
// `RedisDeploymentMode` 与 `RedisConfig` 的 trait 实现分离至 `defaults` 子模块
// (规则 25:mod.rs 只放 trait/struct/enum 定义,impl 块拆到独立文件)
// ============================================================================
pub mod defaults;

// ============================================================================
// oxcache 实现(feature = "cache-memory" 或 "cache-redis")
// ============================================================================

#[cfg(any(feature = "cache-memory", feature = "cache-redis"))]
mod oxcache_impl {
    use super::GarrisonDao;
    #[cfg(feature = "cache-redis")]
    use super::RedisConfig;
    #[cfg(feature = "tenant-isolation")]
    use crate::constants::DaoKeyPrefix;
    use crate::error::{GarrisonError, GarrisonResult};
    use async_trait::async_trait;
    use oxcache::Cache;
    use std::time::Duration;

    /// 根据租户上下文返回实际存储 key。
    ///
    /// - `tenant-isolation` feature 启用且 `TENANT.try_get()` 返回 `Ok(ctx)`:
    ///   返回 `format!("{}{}:{}", DaoKeyPrefix::Tenant, ctx.tenant_id, key)`
    /// - feature 关闭或 `TENANT` 上下文不存在(`try_get` 返回 `Err`):返回 `key.to_string()`(不变)
    ///
    /// # 设计
    ///
    /// - `TENANT.try_get()` 返回 `Err` 而非 `None`(tokio task_local 语义),用 `Ok` 模式匹配
    /// - 不 panic:无上下文时 key 保持原样,保证向后兼容
    /// - 同步函数:`try_get` 是同步的,无需 async
    fn prefixed_key(key: &str) -> String {
        #[cfg(feature = "tenant-isolation")]
        {
            if let Ok(ctx) = crate::context::tenant::TENANT.try_get() {
                return format!("{}{}:{}", DaoKeyPrefix::Tenant, ctx.tenant_id, key);
            }
        }
        // feature 关闭或无 TENANT 上下文时 key 保持原样
        #[allow(unused_variables)]
        let _ = key;
        key.to_string()
    }

    /// 通配符匹配(支持 `*` 匹配任意字符序列)。
    ///
    /// 用于 `keys()` 方法过滤匹配 pattern 的 key。
    /// pattern 如 `"anomalous:login:*"` 匹配 `"anomalous:login:1001:1234567890"`。
    #[cfg(feature = "anomalous-detector-dual")]
    fn matches_pattern(key: &str, pattern: &str) -> bool {
        if pattern == "*" {
            return true;
        }
        if let Some(prefix) = pattern.strip_suffix('*') {
            return key.starts_with(prefix);
        }
        key == pattern
    }

    /// 去除 DAO 前缀,返回原始 key(`prefixed_key` 的逆操作)。
    ///
    /// `prefixed_key` 在 `tenant-isolation` 启用且有 TENANT 上下文时
    /// 返回 `format!("tenant:{id}:{key}")`,否则原样返回。
    /// 本函数逆向该操作:去除 `"tenant:{id}:"` 前缀,或原样返回。
    #[cfg(feature = "anomalous-detector-dual")]
    fn strip_prefix(prefixed: &str) -> String {
        #[cfg(feature = "tenant-isolation")]
        {
            // 格式 "tenant:{id}:{key}",找到第二个 ':' 之后的内容
            if let Some(rest) = prefixed.strip_prefix("tenant:") {
                if let Some(pos) = rest.find(':') {
                    return rest[pos + 1..].to_string();
                }
            }
        }
        // 无前缀(tenant-isolation 关闭或无 TENANT 上下文)时原样返回
        prefixed.to_string()
    }

    /// oxcache 0.3 默认实现,包装 `oxcache::Cache<String, String>`。
    ///
    /// - L1(内存)+ L2(redis)由 oxcache 0.3 自动管理(oxcache 0.3 支持 per-entry TTL)。
    /// - Garrison 自身不实现任何缓存逻辑,全部委托给 oxcache。
    /// - 启用 `sync_mode(true)` 后使用 `_sync` API,
    ///   要求调用方在 multi_thread tokio runtime 中执行。
    ///
    /// # TTL 保留
    /// - `update` 通过 `cache.ttl_sync()` 读取剩余 TTL,用 `set_with_ttl_sync` 保留原 TTL(不重置过期时间)
    /// - `expire` 通过 `cache.expire_sync()` 原子更新 TTL(不触碰 value)
    /// - 依赖本地 oxcache 仓库(crates.io 0.3.0 未暴露 `Cache<K,V>::ttl_sync()`,本地仓库已暴露)
    ///
    /// # 性能约束(A-009 评估结论)
    ///
    /// `_sync` API 仅适用于 oxcache in-memory 后端:
    /// - 读操作(`get_sync`/`exists_sync`/`ttl_sync`):无锁读,<100ns
    /// - 写操作(`set_with_ttl_sync`/`delete_sync`/`expire_sync`):短临界区,<1μs
    /// - 对比 `tokio::task::spawn_blocking` 开销:~10-50μs(线程池调度)
    ///
    /// 结论:对 in-memory backend,`_sync` 调用比 `spawn_blocking` 更快,保留现有实现。
    ///
    /// **后续跟进**:若未来引入 Redis/分布式 backend,需改用 async API(`_sync` 在网络 I/O 场景下会阻塞 tokio worker 线程)。
    pub struct GarrisonDaoOxcache {
        cache: Cache<String, String>,
        /// 原子操作锁,仅用于 `get_and_delete` 的进程内原子性保护。
        /// 其他操作(get/set/delete 等)不持有此锁,不影响并发性能。
        atomic_lock: parking_lot::Mutex<()>,
        /// Redis 部署模式配置(仅在 `cache-redis` feature 启用时存在)。
        ///
        /// 通过 [`with_redis_config`] builder 方法设置。未设置时为 `None`,
        /// oxcache 使用默认 Redis 配置。
        #[cfg(feature = "cache-redis")]
        redis_config: Option<RedisConfig>,
        /// key 索引,用于实现 `keys()` 方法(oxcache 0.3.3 无原生 keys/iter API)。
        /// 仅在 `anomalous-detector-dual` feature 启用时维护,避免影响其他场景的内存开销。
        /// TTL 过期的 key 会在 `keys()` 调用时惰性清理。
        #[cfg(feature = "anomalous-detector-dual")]
        key_index: parking_lot::RwLock<std::collections::HashSet<String>>,
    }

    impl GarrisonDaoOxcache {
        /// 创建默认的 oxcache DAO 实例。
        ///
        /// 启用 `sync_mode(true)` 以支持 `_sync` API。
        ///
        /// # 返回
        /// 已初始化的 `GarrisonDaoOxcache` 实例(内部 `oxcache::Cache` 已就绪,sync_mode 启用)。
        ///
        /// # 错误
        /// - `GarrisonError::Dao`:oxcache 初始化失败(消息含 "oxcache 初始化失败")。
        pub async fn new() -> GarrisonResult<Self> {
            let cache = Cache::builder()
                .sync_mode(true)
                .build()
                .await
                .map_err(|e| GarrisonError::Dao(format!("dao-oxcache-init::{}", e)))?;
            Ok(Self {
                cache,
                atomic_lock: parking_lot::Mutex::new(()),
                #[cfg(feature = "cache-redis")]
                redis_config: None,
                #[cfg(feature = "anomalous-detector-dual")]
                key_index: parking_lot::RwLock::new(std::collections::HashSet::new()),
            })
        }

        /// 设置 Redis 部署模式配置。
        ///
        /// 仅在 `cache-redis` feature 启用时可用。消费 self 并返回新实例(builder 模式)。
        /// 调用后 oxcache 的 Redis L2 后端使用指定部署模式。
        /// 未调用时保持现有行为(oxcache 默认 Redis 配置)。
        ///
        /// # 参数
        /// - `config`: Redis 配置(包含部署模式、连接池参数、认证信息)。
        ///
        /// # 返回
        /// 消费 self 并返回新实例。
        #[cfg(feature = "cache-redis")]
        pub fn with_redis_config(mut self, config: RedisConfig) -> Self {
            tracing::info!(
                mode = %config.mode,
                db = config.db,
                pool_size = config.pool_size,
                "设置 Redis 部署模式配置"
            );
            self.redis_config = Some(config);
            self
        }

        /// 返回当前 Redis 配置(仅在 `cache-redis` feature 启用时可用)。
        ///
        /// 用于测试与诊断:确认 `with_redis_config` 是否已调用。
        #[cfg(feature = "cache-redis")]
        pub fn redis_config(&self) -> Option<&RedisConfig> {
            self.redis_config.as_ref()
        }
    }

    #[async_trait]
    impl GarrisonDao for GarrisonDaoOxcache {
        async fn get(&self, key: &str) -> GarrisonResult<Option<String>> {
            let actual_key = prefixed_key(key);
            self.cache
                .get_sync(&actual_key)
                .map_err(|e| GarrisonError::Dao(format!("dao-oxcache-get-sync::{}", e)))
        }

        async fn set(&self, key: &str, value: &str, ttl_seconds: u64) -> GarrisonResult<()> {
            let actual_key = prefixed_key(key);
            let ttl = if ttl_seconds == 0 {
                None
            } else {
                Some(Duration::from_secs(ttl_seconds))
            };
            self.cache
                .set_with_ttl_sync(&actual_key, &value.to_string(), ttl)
                .map_err(|e| GarrisonError::Dao(format!("dao-oxcache-set-with-ttl-sync::{}", e)))?;
            #[cfg(feature = "anomalous-detector-dual")]
            self.key_index.write().insert(actual_key);
            Ok(())
        }

        async fn update(&self, key: &str, value: &str) -> GarrisonResult<()> {
            // 通过 cache.ttl_sync() 读取剩余 TTL,用 set_with_ttl_sync 保留原 TTL(不重置过期时间)。
            // ttl_sync() 返回 None 表示永久驻留(set_with_ttl_sync 接受 None 表示无 TTL)。
            // 但 None 也可能表示键不存在,需要先检查键存在性。
            let actual_key = prefixed_key(key);
            if !self
                .cache
                .exists_sync(&actual_key)
                .map_err(|e| GarrisonError::Dao(format!("dao-oxcache-exists-sync::{}", e)))?
            {
                return Err(GarrisonError::Dao(format!("dao-key-missing::{}", key)));
            }
            let remaining_ttl = self
                .cache
                .ttl_sync(&actual_key)
                .map_err(|e| GarrisonError::Dao(format!("dao-oxcache-ttl-sync::{}", e)))?;
            self.cache
                .set_with_ttl_sync(&actual_key, &value.to_string(), remaining_ttl)
                .map_err(|e| {
                    GarrisonError::Dao(format!("dao-oxcache-update-set-with-ttl-sync::{}", e))
                })
        }

        async fn expire(&self, key: &str, seconds: u64) -> GarrisonResult<()> {
            // oxcache 0.3 的 Cache<K,V> 暴露了 expire_sync(key, ttl) 方法(原子更新 TTL,不触碰 value)。
            // expire_sync 返回 bool:true=更新成功,false=键不存在。
            // 注意:seconds=0 表示永久驻留,需要用 get_sync + set_with_ttl_sync(None) 实现
            // (cache.expire_sync(key, Duration::from_secs(0)) 会让键立即过期,不符合 spec 的 0=永久语义)。
            let actual_key = prefixed_key(key);
            if seconds == 0 {
                let value = self
                    .cache
                    .get_sync(&actual_key)
                    .map_err(|e| GarrisonError::Dao(format!("dao-oxcache-get-sync::{}", e)))?
                    .ok_or_else(|| GarrisonError::Dao(format!("dao-key-missing::{}", key)))?;
                self.cache
                    .set_with_ttl_sync(&actual_key, &value, None)
                    .map_err(|e| {
                        GarrisonError::Dao(format!("dao-oxcache-expire-set-with-ttl-sync::{}", e))
                    })
            } else {
                let updated = self
                    .cache
                    .expire_sync(&actual_key, Duration::from_secs(seconds))
                    .map_err(|e| GarrisonError::Dao(format!("dao-oxcache-expire-sync::{}", e)))?;
                if !updated {
                    return Err(GarrisonError::Dao(format!("dao-key-missing::{}", key)));
                }
                Ok(())
            }
        }

        async fn delete(&self, key: &str) -> GarrisonResult<()> {
            let actual_key = prefixed_key(key);
            self.cache
                .delete_sync(&actual_key)
                .map_err(|e| GarrisonError::Dao(format!("dao-oxcache-delete-sync::{}", e)))?;
            #[cfg(feature = "anomalous-detector-dual")]
            self.key_index.write().remove(&actual_key);
            Ok(())
        }

        /// set_permanent 用 set_with_ttl_sync(None) 写入永久键。
        ///
        /// 重写默认实现以使用 oxcache 原生"无 TTL"API(避免 ttl=0 歧义)。
        async fn set_permanent(&self, key: &str, value: &str) -> GarrisonResult<()> {
            let actual_key = prefixed_key(key);
            self.cache
                .set_with_ttl_sync(&actual_key, &value.to_string(), None)
                .map_err(|e| GarrisonError::Dao(format!("dao-oxcache-set-with-ttl-sync::{}", e)))?;
            #[cfg(feature = "anomalous-detector-dual")]
            self.key_index.write().insert(actual_key);
            Ok(())
        }

        /// get_timeout 用 ttl_sync 查询剩余 TTL。
        ///
        /// oxcache 0.3 的 `ttl_sync(key)` 返回 `Option<Duration>`:
        /// - `Some(remaining)`: 键存在且设置了 TTL
        /// - `None`: 键不存在,或键存在但未设置 TTL(永久驻留)
        async fn get_timeout(&self, key: &str) -> GarrisonResult<Option<Duration>> {
            let actual_key = prefixed_key(key);
            self.cache
                .ttl_sync(&actual_key)
                .map_err(|e| GarrisonError::Dao(format!("dao-oxcache-ttl-sync::{}", e)))
        }

        /// rename 用 get → ttl_sync → set_with_ttl_sync → delete 四步。
        ///
        /// 重写默认实现以保留原键 TTL(用 `ttl_sync` 读取剩余 TTL,用 `set_with_ttl_sync` 写入)。
        /// 仍是**非原子**操作(oxcache 0.3.3 无原子 rename API,待 oxcache 提供原子 rename API)。
        async fn rename(&self, old_key: &str, new_key: &str) -> GarrisonResult<()> {
            let actual_old = prefixed_key(old_key);
            let actual_new = prefixed_key(new_key);
            let value = self
                .cache
                .get_sync(&actual_old)
                .map_err(|e| GarrisonError::Dao(format!("dao-oxcache-get-sync::{}", e)))?
                .ok_or_else(|| {
                    GarrisonError::InvalidParam(format!("dao-key-missing::{}", old_key))
                })?;
            let remaining_ttl = self
                .cache
                .ttl_sync(&actual_old)
                .map_err(|e| GarrisonError::Dao(format!("dao-oxcache-ttl-sync::{}", e)))?;
            self.cache
                .set_with_ttl_sync(&actual_new, &value, remaining_ttl)
                .map_err(|e| GarrisonError::Dao(format!("dao-oxcache-set-with-ttl-sync::{}", e)))?;
            self.cache
                .delete_sync(&actual_old)
                .map_err(|e| GarrisonError::Dao(format!("dao-oxcache-delete-sync::{}", e)))
        }

        /// get_and_delete 用 `parking_lot::Mutex` 保护 get+delete。
        ///
        /// 进程内原子:同一进程内并发调用同一 key 仅一个返回 `Some`。
        /// 跨进程限制:多进程共享 Redis L2 时,仍存在 TOCTOU 竞态
        /// (需 Redis Lua 脚本 `redis.call('GET',K[1]);redis.call('DEL',K[1])` 修复,待引入 Redis L2 后端)。
        async fn get_and_delete(&self, key: &str) -> GarrisonResult<Option<String>> {
            let _guard = self.atomic_lock.lock();
            let actual_key = prefixed_key(key);
            let value = self
                .cache
                .get_sync(&actual_key)
                .map_err(|e| GarrisonError::Dao(format!("dao-oxcache-get-sync::{}", e)))?;
            if value.is_some() {
                self.cache
                    .delete_sync(&actual_key)
                    .map_err(|e| GarrisonError::Dao(format!("dao-oxcache-delete-sync::{}", e)))?;
            }
            Ok(value)
        }

        /// incr 用 `parking_lot::Mutex` 保护原子性(进程内原子)。
        ///
        /// 在单个 lock() 作用域内完成 get → set_with_ttl_sync,保证进程内原子。
        /// key 已存在时通过 `ttl_sync` 读取剩余 TTL 并保留(不重置过期时间)。
        async fn incr(&self, key: &str, ttl_seconds: u64) -> GarrisonResult<u64> {
            let _guard = self.atomic_lock.lock();
            let actual_key = prefixed_key(key);
            match self
                .cache
                .get_sync(&actual_key)
                .map_err(|e| GarrisonError::Dao(format!("dao-oxcache-get-sync::{}", e)))?
            {
                Some(v) => {
                    // Rule 12:parse 失败必须显式报错,禁止静默返回 0 导致计数器重置
                    let cur_val: u64 = v.parse().map_err(|_| {
                        GarrisonError::Dao(format!(
                            "incr: 现存值非 u64,key={}, value={}",
                            actual_key, v
                        ))
                    })?;
                    let new_val = cur_val + 1;
                    let remaining_ttl = self
                        .cache
                        .ttl_sync(&actual_key)
                        .map_err(|e| GarrisonError::Dao(format!("dao-oxcache-ttl-sync::{}", e)))?;
                    self.cache
                        .set_with_ttl_sync(&actual_key, &new_val.to_string(), remaining_ttl)
                        .map_err(|e| {
                            GarrisonError::Dao(format!("dao-oxcache-set-with-ttl-sync::{}", e))
                        })?;
                    Ok(new_val)
                },
                None => {
                    let ttl = if ttl_seconds == 0 {
                        None
                    } else {
                        Some(Duration::from_secs(ttl_seconds))
                    };
                    self.cache
                        .set_with_ttl_sync(&actual_key, &"1".to_string(), ttl)
                        .map_err(|e| {
                            GarrisonError::Dao(format!("dao-oxcache-set-with-ttl-sync::{}", e))
                        })?;
                    Ok(1)
                },
            }
        }

        /// decr 用 `atomic_lock` 保护原子性(进程内原子,与 `incr` 对称)。
        ///
        /// 在单个 lock() 作用域内完成 get → parse → set_with_ttl_sync/delete_sync,
        /// 消除 `SmsRateLimiter::decrement_counter` 的 TOCTOU 竞态。
        /// 语义(与 trait 默认实现 + `MockDao::decr` 一致):
        /// - key 不存在或已过期:返回 0(不创建 key)
        /// - cur_val == 0:返回 0(不递减为负,不删除 key)
        /// - cur_val > 0:递减 1;new_val == 0 时 `delete_sync` 删除 key;
        ///   new_val > 0 时用 `ttl_sync` 读取剩余 TTL 并 `set_with_ttl_sync` 保留(不重置窗口)
        ///
        /// 修复 `concurrent_send_does_not_exceed_limit` flaky test(fix-refresh-race-and-test-contracts):
        /// 原 `SmsRateLimiter::decrement_counter` 用 `dao.get → parse → dao.update/delete`
        /// 三步组合,跨越 await 间隙允许其他 task 的 `incr` 插入,导致 update 基于过时 get 值
        /// 覆盖 incr 结果,产生"跨越式递减"(实际递减量大于 1)。
        async fn decr(&self, key: &str) -> GarrisonResult<u64> {
            let _guard = self.atomic_lock.lock();
            let actual_key = prefixed_key(key);
            let v = match self
                .cache
                .get_sync(&actual_key)
                .map_err(|e| GarrisonError::Dao(format!("dao-oxcache-get-sync::{}", e)))?
            {
                Some(v) => v,
                None => return Ok(0),
            };
            // Rule 12:parse 失败必须显式报错(与 incr 一致,禁止静默返回 0)
            let cur_val: u64 = v.parse().map_err(|_| {
                GarrisonError::Dao(format!(
                    "decr: 现存值非 u64,key={}, value={}",
                    actual_key, v
                ))
            })?;
            if cur_val == 0 {
                return Ok(0);
            }
            let new_val = cur_val - 1;
            if new_val == 0 {
                // 递减到 0:删除 key(与 trait 默认实现 + MockDao::decr 一致)
                self.cache
                    .delete_sync(&actual_key)
                    .map_err(|e| GarrisonError::Dao(format!("dao-oxcache-delete-sync::{}", e)))?;
            } else {
                // 保留原 TTL(不重置窗口):用 ttl_sync 读取剩余 TTL
                let remaining_ttl = self
                    .cache
                    .ttl_sync(&actual_key)
                    .map_err(|e| GarrisonError::Dao(format!("dao-oxcache-ttl-sync::{}", e)))?;
                self.cache
                    .set_with_ttl_sync(&actual_key, &new_val.to_string(), remaining_ttl)
                    .map_err(|e| {
                        GarrisonError::Dao(format!("dao-oxcache-set-with-ttl-sync::{}", e))
                    })?;
            }
            Ok(new_val)
        }

        /// compare_and_update_if_greater 用 `atomic_lock` 保护原子性(进程内原子)。
        ///
        /// 在单个 lock() 作用域内完成 get → parse → compare → set_with_ttl_sync。
        /// - key 不存在或已过期:current_val = 0,new_value > 0 时初始化并设置 TTL
        /// - key 已存在且 new_value > current_val:用 `ttl_sync` 读取剩余 TTL 保留(不重置)
        /// - key 已存在但 new_value <= current_val:不修改,返回 false
        ///
        /// 用于 HTTP Digest nc 单调性校验(RFC 7616 §3.4.6),消除 TOCTOU 竞态。
        async fn compare_and_update_if_greater(
            &self,
            key: &str,
            new_value: u64,
            ttl_seconds: u64,
        ) -> GarrisonResult<bool> {
            let _guard = self.atomic_lock.lock();
            let actual_key = prefixed_key(key);
            // M1 修复:parse 失败必须显式报错(与 incr 方法一致,Rule 12 错误显性化),
            // 禁止 unwrap_or(0) 静默返回 0 导致 nc 计数器被错误重置
            let current_val: u64 = match self
                .cache
                .get_sync(&actual_key)
                .map_err(|e| GarrisonError::Dao(format!("dao-oxcache-get-sync::{}", e)))?
            {
                Some(v) => v.parse::<u64>().map_err(|_| {
                    GarrisonError::Dao(format!(
                        "dao-compare-and-update-parse-u64::{}::{}",
                        actual_key, v
                    ))
                })?,
                None => 0,
            };
            if new_value > current_val {
                // 保留原 TTL:若键已存在,读取剩余 TTL;新键用传入的 ttl_seconds
                let ttl = if ttl_seconds == 0 {
                    None
                } else {
                    let remaining = self
                        .cache
                        .ttl_sync(&actual_key)
                        .map_err(|e| GarrisonError::Dao(format!("dao-oxcache-ttl-sync::{}", e)))?;
                    Some(remaining.unwrap_or_else(|| Duration::from_secs(ttl_seconds)))
                };
                self.cache
                    .set_with_ttl_sync(&actual_key, &new_value.to_string(), ttl)
                    .map_err(|e| {
                        GarrisonError::Dao(format!("dao-oxcache-set-with-ttl-sync::{}", e))
                    })?;
                #[cfg(feature = "anomalous-detector-dual")]
                self.key_index.write().insert(actual_key);
                Ok(true)
            } else {
                Ok(false)
            }
        }

        /// keys 用 key_index 实现(oxcache 0.3.3 无原生 keys/iter API)。
        ///
        /// 遍历 key_index,过滤匹配 pattern 的 key,同时惰性清理已过期的 key。
        /// pattern 支持 `*` 通配符(与 MockDao::keys 一致)。
        #[cfg(feature = "anomalous-detector-dual")]
        async fn keys(&self, pattern: &str) -> GarrisonResult<Vec<String>> {
            let actual_pattern = prefixed_key(pattern);
            let mut result = Vec::new();
            let mut expired_keys = Vec::new();

            {
                let index = self.key_index.read();
                for key in index.iter() {
                    if matches_pattern(key, &actual_pattern) {
                        // 检查 key 是否仍然存在(TTL 可能已过期)
                        if self.cache.exists_sync(key).unwrap_or(false) {
                            // 去除 prefix 返回原始 key
                            let raw_key = strip_prefix(key);
                            result.push(raw_key);
                        } else {
                            expired_keys.push(key.clone());
                        }
                    }
                }
            }

            // 惰性清理过期 key
            if !expired_keys.is_empty() {
                let mut index = self.key_index.write();
                for key in &expired_keys {
                    index.remove(key);
                }
                tracing::debug!("keys() 清理了 {} 个过期 key", expired_keys.len());
            }

            Ok(result)
        }
    }
}

#[cfg(any(feature = "cache-memory", feature = "cache-redis"))]
pub use oxcache_impl::GarrisonDaoOxcache;

// ============================================================================
// dbnexus 实现(feature = "db-sqlite" 或 "db-postgres")
// ============================================================================
//
// `init_dbnexus` 和 `GarrisonMigration` 是 backend-agnostic 的——它们仅封装
// `DbPool::new(url)` 和 `DbPool::run_migrations(dir)`,不关心底层是 SQLite 还是
// PostgreSQL。后端由 dbnexus 的 feature flag(sqlite/postgres)控制。
//
// 注意:`GarrisonMigration::new()` 默认使用 `migrations/sqlite/` 路径,
// PostgreSQL 用户应使用 `with_base_dir` 指定 `migrations/postgres/` 路径。

#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
mod dbnexus_impl;

#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
pub use dbnexus_impl::{init_dbnexus, GarrisonMigration};

// ============================================================================
// Repository 层
// ============================================================================
// 9 个核心表的 Repository trait + Row struct,与 dbnexus 解耦。
// SQLite 实现见 `repository::sqlite` 子模块(启用 `db-sqlite` feature,
// T019 Green 阶段创建后由 repository/mod.rs 内部声明)。
pub mod repository;

// ============================================================================
// AloneCache 装饰器(feature = "alone-cache")
// ============================================================================

#[cfg(feature = "alone-cache")]
pub mod alone_cache;

// ============================================================================
// 缓存预热子模块
// ============================================================================

pub mod warmup;

// `MockDao` 在生产代码中也作为进程内原子 DAO 使用
// (如 `PasswordRateLimiter` / `GarrisonFirewallCheckHookDefault` 的内存模式),
// 不再限制为 `cfg(test)`。
mod mock;

pub use mock::MockDao;

#[cfg(all(test, feature = "protocol-apikey"))]
pub(crate) use mock::glob_match;

#[cfg(test)]
/// DAO trait 契约测试与跨模块共享的 mock 实现(仅 `cfg(test)` 下编译)。
pub mod tests {
    use super::*;
    // 兼容层:重导出 mock 模块的 MockDao 与 glob_match,保持旧路径
    // `crate::dao::tests::MockDao` / `crate::dao::tests::glob_match` 可用
    #[cfg(feature = "protocol-apikey")]
    pub(crate) use super::glob_match;
    pub use super::MockDao;
    use crate::error::GarrisonError;
    use parking_lot::Mutex;
    use std::collections::HashMap;
    use std::sync::Arc;
    use std::time::Duration;

    // ------------------------------------------------------------------------
    // GarrisonDaoOxcache keys() 测试(CRIT-001 修复验证)
    // 仅在 anomalous-detector-dual + cache-memory/cache-redis 启用时编译
    // ------------------------------------------------------------------------
    #[cfg(all(
        feature = "anomalous-detector-dual",
        any(feature = "cache-memory", feature = "cache-redis")
    ))]
    mod oxcache_keys_tests {
        use super::*;

        /// 无 key 时 keys() 返回空 Vec。
        #[tokio::test(flavor = "multi_thread")]
        async fn test_oxcache_keys_empty() {
            let dao = GarrisonDaoOxcache::new().await.unwrap();
            let keys = dao.keys("anomalous:login:*").await.unwrap();
            assert!(keys.is_empty(), "无 key 时 keys() 应返回空 Vec");
        }

        /// set 3 个 key,keys("anomalous:login:*") 返回 2 个匹配的 key。
        #[tokio::test(flavor = "multi_thread")]
        async fn test_oxcache_keys_pattern_match() {
            let dao = GarrisonDaoOxcache::new().await.unwrap();
            dao.set("anomalous:login:1:1", "v1", 3600).await.unwrap();
            dao.set("anomalous:login:2:2", "v2", 3600).await.unwrap();
            dao.set("other:key", "v3", 3600).await.unwrap();

            let mut keys = dao.keys("anomalous:login:*").await.unwrap();
            keys.sort();
            assert_eq!(
                keys,
                vec![
                    "anomalous:login:1:1".to_string(),
                    "anomalous:login:2:2".to_string()
                ],
                "keys() 应返回 2 个匹配 anomalous:login:* 的 key"
            );
        }

        /// TTL 过期后 keys() 返回空且 key_index 已惰性清理。
        #[tokio::test(flavor = "multi_thread")]
        async fn test_oxcache_keys_clears_expired() {
            let dao = GarrisonDaoOxcache::new().await.unwrap();
            dao.set("anomalous:login:1:1", "v1", 1).await.unwrap();
            // 等待 TTL 过期(1s + 1s 余量)
            tokio::time::sleep(Duration::from_secs(2)).await;
            let keys = dao.keys("anomalous:login:*").await.unwrap();
            assert!(
                keys.is_empty(),
                "TTL 过期后 keys() 应返回空 Vec(惰性清理)"
            );
            // 再次调用 keys() 验证 key_index 已清理(不会 panic 或残留)
            let keys2 = dao.keys("anomalous:login:*").await.unwrap();
            assert!(keys2.is_empty(), "清理后再次 keys() 仍应返回空");
        }

        /// delete 后 keys() 返回空。
        #[tokio::test(flavor = "multi_thread")]
        async fn test_oxcache_keys_after_delete() {
            let dao = GarrisonDaoOxcache::new().await.unwrap();
            dao.set("anomalous:login:1:1", "v1", 3600).await.unwrap();
            let keys = dao.keys("anomalous:login:*").await.unwrap();
            assert_eq!(keys.len(), 1, "set 后应有 1 个 key");
            dao.delete("anomalous:login:1:1").await.unwrap();
            let keys = dao.keys("anomalous:login:*").await.unwrap();
            assert!(keys.is_empty(), "delete 后 keys() 应返回空 Vec");
        }
    }

    // ------------------------------------------------------------------------
    // 契约测试:验证 GarrisonDao trait 行为契约(使用 MockDao)
    // 对应 dao-oxcache-basic spec 的 4 个 scenario
    // ------------------------------------------------------------------------

    /// Scenario: set 与 get 配对。
    /// WHEN 调用 set("key1", "value1", 3600) 后 get("key1")
    /// THEN 返回 Some("value1")
    #[tokio::test]
    async fn mock_set_get_pair() {
        let dao = MockDao::new();
        dao.set("key1", "value1", 3600).await.unwrap();
        let got = dao.get("key1").await.unwrap();
        assert_eq!(got, Some("value1".to_string()));
    }

    /// Scenario: 过期自动删除。
    /// WHEN set("key1", "value1", 1) 并等待 2 秒
    /// THEN get("key1") 返回 None
    #[tokio::test]
    async fn mock_expire_auto_delete() {
        let dao = MockDao::new();
        dao.set("key1", "value1", 1).await.unwrap();
        tokio::time::sleep(Duration::from_secs(2)).await;
        let got = dao.get("key1").await.unwrap();
        assert!(got.is_none(), "过期后 get 应返回 None");
    }

    /// Scenario: delete 删除键。
    /// WHEN set("key1", "value1", 3600) 后 delete("key1")
    /// THEN get("key1") 返回 None
    #[tokio::test]
    async fn mock_delete_removes_key() {
        let dao = MockDao::new();
        dao.set("key1", "value1", 3600).await.unwrap();
        dao.delete("key1").await.unwrap();
        let got = dao.get("key1").await.unwrap();
        assert!(got.is_none(), "delete 后 get 应返回 None");
    }

    /// Scenario: update 更新值(保留 TTL)。
    /// WHEN set("key1", "value1", 3600) 后 update("key1", "value2")
    /// THEN get("key1") 返回 Some("value2")
    /// AND  TTL 保持 3600(不重置)
    #[tokio::test]
    async fn mock_update_preserves_ttl() {
        let dao = MockDao::new();
        // 用短 TTL 验证 update 不重置 TTL
        dao.set("key1", "value1", 2).await.unwrap();
        // 立即 update(在 TTL 内)
        dao.update("key1", "value2").await.unwrap();
        // 验证值已更新
        let got = dao.get("key1").await.unwrap();
        assert_eq!(got, Some("value2".to_string()));
        // 等待原 TTL 过期(2 秒 + 1 秒余量)
        tokio::time::sleep(Duration::from_secs(3)).await;
        // update 保留了原 TTL,应已过期
        let got = dao.get("key1").await.unwrap();
        assert!(
            got.is_none(),
            "update 不应重置 TTL,原 TTL 过期后应返回 None"
        );
    }

    /// 验证 update 不存在的键返回错误(Fail Loud 原则)。
    #[tokio::test]
    async fn mock_update_missing_key_errors() {
        let dao = MockDao::new();
        let result = dao.update("missing", "value").await;
        assert!(
            matches!(result, Err(GarrisonError::Dao(_))),
            "update 不存在的键应返回 Dao 错误"
        );
    }

    /// 验证 expire 重置过期时间。
    #[tokio::test]
    async fn mock_expire_resets_ttl() {
        let dao = MockDao::new();
        dao.set("key1", "value1", 1).await.unwrap();
        // 在过期前重置 TTL
        dao.expire("key1", 3600).await.unwrap();
        tokio::time::sleep(Duration::from_secs(2)).await;
        // 原 TTL 已过,但 expire 重置后应仍存在
        let got = dao.get("key1").await.unwrap();
        assert_eq!(got, Some("value1".to_string()));
    }

    /// 验证 expire 不存在的键返回错误。
    #[tokio::test]
    async fn mock_expire_missing_key_errors() {
        let dao = MockDao::new();
        let result = dao.expire("missing", 3600).await;
        assert!(
            matches!(result, Err(GarrisonError::Dao(_))),
            "expire 不存在的键应返回 Dao 错误"
        );
    }

    /// 验证 set(ttl=0) 表示永久驻留。
    #[tokio::test]
    async fn mock_set_zero_ttl_means_permanent() {
        let dao = MockDao::new();
        dao.set("perm", "value", 0).await.unwrap();
        // 即使等待也不会过期(mock 用 Instant,sleep 仅作示意)
        tokio::time::sleep(Duration::from_millis(10)).await;
        let got = dao.get("perm").await.unwrap();
        assert_eq!(got, Some("value".to_string()));
    }

    /// 验证 get 不存在的键返回 None(不报错)。
    #[tokio::test]
    async fn mock_get_missing_returns_none() {
        let dao = MockDao::new();
        let got = dao.get("never_set").await.unwrap();
        assert!(got.is_none());
    }

    /// 验证 MockDao::default() 等价于 new()。
    ///
    /// 覆盖 MockDao 的 Default trait 实现。
    #[tokio::test]
    async fn mock_dao_default_equals_new() {
        let dao = MockDao::default();
        dao.set("default_key", "default_value", 60).await.unwrap();
        let got = dao.get("default_key").await.unwrap();
        assert_eq!(got, Some("default_value".to_string()));
    }

    /// 验证 expire(key, 0) 将键设为永久驻留。
    ///
    /// 覆盖 MockDao::expire 的 `seconds == 0` 分支(expire_at = None)。
    #[tokio::test]
    async fn mock_expire_zero_seconds_means_permanent() {
        let dao = MockDao::new();
        dao.set("k", "v", 1).await.unwrap();
        // expire(0) 改为永久驻留
        dao.expire("k", 0).await.unwrap();
        // 等待原 TTL 过期
        tokio::time::sleep(Duration::from_secs(2)).await;
        let got = dao.get("k").await.unwrap();
        assert_eq!(got, Some("v".to_string()), "expire(0) 应改为永久驻留");
    }

    // ------------------------------------------------------------------------
    // 4 方法扩展测试(v0.4.2 spec dao-garrison-dao)
    // ------------------------------------------------------------------------

    /// R-001: set_permanent 设置后 get 返回值。
    #[tokio::test]
    async fn mock_set_permanent_persists_value() {
        let dao = MockDao::new();
        dao.set_permanent("perm_key", "perm_value").await.unwrap();
        let got = dao.get("perm_key").await.unwrap();
        assert_eq!(got, Some("perm_value".to_string()));
    }

    /// R-001: set_permanent 永久键短时间等待不过期。
    #[tokio::test]
    async fn mock_set_permanent_does_not_expire_quickly() {
        let dao = MockDao::new();
        dao.set_permanent("perm_key", "perm_value").await.unwrap();
        tokio::time::sleep(Duration::from_millis(50)).await;
        let got = dao.get("perm_key").await.unwrap();
        assert_eq!(got, Some("perm_value".to_string()), "永久键不应过期");
    }

    /// R-002: get_timeout 永久键返回 None。
    #[tokio::test]
    async fn mock_get_timeout_returns_none_for_permanent_key() {
        let dao = MockDao::new();
        dao.set_permanent("perm", "v").await.unwrap();
        let timeout = dao.get_timeout("perm").await.unwrap();
        assert!(timeout.is_none(), "永久键应返回 None");
    }

    /// R-002: get_timeout TTL 键返回 Some(remaining),剩余 ≤ 原 TTL。
    #[tokio::test]
    async fn mock_get_timeout_returns_some_for_ttl_key() {
        let dao = MockDao::new();
        dao.set("ttl_key", "v", 3600).await.unwrap();
        let timeout = dao.get_timeout("ttl_key").await.unwrap();
        assert!(timeout.is_some(), "TTL 键应返回 Some");
        let remaining = timeout.unwrap();
        assert!(
            remaining <= Duration::from_secs(3600),
            "剩余时间应 ≤ 原 TTL"
        );
    }

    /// R-002: get_timeout 不存在的键返回 None。
    #[tokio::test]
    async fn mock_get_timeout_returns_none_for_missing_key() {
        let dao = MockDao::new();
        let timeout = dao.get_timeout("missing").await.unwrap();
        assert!(timeout.is_none(), "不存在的键应返回 None");
    }

    /// R-003: keys("garrison:apikey:*") 返回命名空间下所有 key。
    #[tokio::test]
    async fn mock_keys_returns_namespace_matches() {
        let dao = MockDao::new();
        dao.set("garrison:apikey:abc123", "v1", 3600).await.unwrap();
        dao.set("garrison:apikey:def456", "v2", 3600).await.unwrap();
        dao.set("garrison:session:xyz", "v3", 3600).await.unwrap();
        let keys = dao.keys("garrison:apikey:*").await.unwrap();
        assert_eq!(keys.len(), 2, "应匹配 2 个 apikey");
        assert!(keys.contains(&"garrison:apikey:abc123".to_string()));
        assert!(keys.contains(&"garrison:apikey:def456".to_string()));
    }

    /// R-003: keys("*") 返回所有 key。
    #[tokio::test]
    async fn mock_keys_star_returns_all() {
        let dao = MockDao::new();
        dao.set("k1", "v1", 3600).await.unwrap();
        dao.set("k2", "v2", 3600).await.unwrap();
        let keys = dao.keys("*").await.unwrap();
        assert!(keys.len() >= 2, "应至少返回 2 个 key");
    }

    /// R-003: keys 无匹配返回空 Vec。
    #[tokio::test]
    async fn mock_keys_no_match_returns_empty() {
        let dao = MockDao::new();
        dao.set("k1", "v1", 3600).await.unwrap();
        let keys = dao.keys("nonexistent:*").await.unwrap();
        assert!(keys.is_empty(), "无匹配应返回空 Vec");
    }

    /// R-003: keys 支持 ? 单字符通配符。
    #[tokio::test]
    async fn mock_keys_supports_question_mark() {
        let dao = MockDao::new();
        dao.set("key1", "v1", 3600).await.unwrap();
        dao.set("key2", "v2", 3600).await.unwrap();
        dao.set("key10", "v3", 3600).await.unwrap();
        let keys = dao.keys("key?").await.unwrap();
        assert_eq!(
            keys.len(),
            2,
            "? 应匹配单个字符,key1/key2 匹配,key10 不匹配"
        );
    }

    /// R-004: rename 重命名后 old 不存在,new 存在。
    #[tokio::test]
    async fn mock_rename_moves_key() {
        let dao = MockDao::new();
        dao.set("old_key", "value", 3600).await.unwrap();
        dao.rename("old_key", "new_key").await.unwrap();
        let old = dao.get("old_key").await.unwrap();
        let new = dao.get("new_key").await.unwrap();
        assert!(old.is_none(), "rename 后 old_key 应不存在");
        assert_eq!(new, Some("value".to_string()), "rename 后 new_key 应有值");
    }

    /// R-004: rename 不存在的 old_key 返回 InvalidParam。
    #[tokio::test]
    async fn mock_rename_missing_key_returns_invalid_param() {
        let dao = MockDao::new();
        let result = dao.rename("missing", "new").await;
        assert!(
            matches!(result, Err(GarrisonError::InvalidParam(_))),
            "rename 不存在的键应返回 InvalidParam,实际: {:?}",
            result
        );
    }

    // ------------------------------------------------------------------------
    // oxcache 集成测试(feature = "cache-memory" 或 "cache-redis")
    // ------------------------------------------------------------------------

    #[cfg(any(feature = "cache-memory", feature = "cache-redis"))]
    mod oxcache_tests {
        use super::*;

        /// Scenario: set 与 get 配对。
        #[tokio::test(flavor = "multi_thread")]
        async fn oxcache_set_get_pair() {
            let dao = GarrisonDaoOxcache::new().await.unwrap();
            dao.set("oc_key1", "value1", 3600).await.unwrap();
            let got = dao.get("oc_key1").await.unwrap();
            assert_eq!(got, Some("value1".to_string()));
        }

        /// Scenario: 过期自动删除。
        #[tokio::test(flavor = "multi_thread")]
        async fn oxcache_expire_auto_delete() {
            let dao = GarrisonDaoOxcache::new().await.unwrap();
            dao.set("oc_key2", "value1", 1).await.unwrap();
            tokio::time::sleep(Duration::from_secs(2)).await;
            let got = dao.get("oc_key2").await.unwrap();
            assert!(got.is_none(), "过期后 get 应返回 None");
        }

        /// Scenario: delete 删除键。
        #[tokio::test(flavor = "multi_thread")]
        async fn oxcache_delete_removes_key() {
            let dao = GarrisonDaoOxcache::new().await.unwrap();
            dao.set("oc_key3", "value1", 3600).await.unwrap();
            dao.delete("oc_key3").await.unwrap();
            let got = dao.get("oc_key3").await.unwrap();
            assert!(got.is_none(), "delete 后 get 应返回 None");
        }

        /// 验证 oxcache update 更新值(仅验证值,TTL 保留见 ignore 测试)。
        #[tokio::test(flavor = "multi_thread")]
        async fn oxcache_update_changes_value() {
            let dao = GarrisonDaoOxcache::new().await.unwrap();
            dao.set("oc_key4", "value1", 3600).await.unwrap();
            dao.update("oc_key4", "value2").await.unwrap();
            let got = dao.get("oc_key4").await.unwrap();
            assert_eq!(got, Some("value2".to_string()));
        }

        /// 验证 update 不存在的键返回错误。
        #[tokio::test(flavor = "multi_thread")]
        async fn oxcache_update_missing_key_errors() {
            let dao = GarrisonDaoOxcache::new().await.unwrap();
            let result = dao.update("oc_missing", "value").await;
            assert!(
                matches!(result, Err(GarrisonError::Dao(_))),
                "update 不存在的键应返回 Dao 错误"
            );
        }

        /// 验证 expire 重置过期时间。
        #[tokio::test(flavor = "multi_thread")]
        async fn oxcache_expire_resets_ttl() {
            let dao = GarrisonDaoOxcache::new().await.unwrap();
            dao.set("oc_key5", "value1", 1).await.unwrap();
            dao.expire("oc_key5", 3600).await.unwrap();
            tokio::time::sleep(Duration::from_secs(2)).await;
            let got = dao.get("oc_key5").await.unwrap();
            assert_eq!(got, Some("value1".to_string()));
        }

        /// 验证 GarrisonDaoOxcache::new() 直接构造(init_oxcache_dao 包装已移除)。
        #[tokio::test(flavor = "multi_thread")]
        async fn oxcache_new_direct_construction() {
            let dao = GarrisonDaoOxcache::new().await.unwrap();
            dao.set("oc_init", "init_value", 60).await.unwrap();
            let got = dao.get("oc_init").await.unwrap();
            assert_eq!(got, Some("init_value".to_string()));
        }

        /// Scenario: update 更新值(保留 TTL)。
        ///
        /// oxcache 0.3 的 Cache<K,V> 暴露了 ttl() 方法,update 用 ttl() + set_with_ttl 保留原 TTL。
        ///
        /// 参见:dao-oxcache-basic spec Requirement "GarrisonDao 抽象 trait" Scenario "update 更新值(保留 TTL)"
        #[tokio::test(flavor = "multi_thread")]
        async fn oxcache_update_preserves_ttl() {
            let dao = GarrisonDaoOxcache::new().await.unwrap();
            dao.set("oc_ttl", "value1", 2).await.unwrap();
            dao.update("oc_ttl", "value2").await.unwrap();
            // update 保留了原 TTL(2 秒),sleep 后应过期
            tokio::time::sleep(Duration::from_secs(3)).await;
            let got = dao.get("oc_ttl").await.unwrap();
            assert!(
                got.is_none(),
                "update 不应重置 TTL,原 TTL 过期后应返回 None"
            );
        }

        /// 验证 expire(key, 0) 将键设为永久驻留(不删除)。
        ///
        /// 覆盖 GarrisonDaoOxcache::expire 的 `seconds == 0` 分支:
        /// 通过 get + set_with_ttl(None) 实现 0=永久语义。
        #[tokio::test(flavor = "multi_thread")]
        async fn oxcache_expire_zero_seconds_makes_permanent() {
            let dao = GarrisonDaoOxcache::new().await.unwrap();
            // 设置短 TTL,键会在 1 秒后过期
            dao.set("oc_perm", "value1", 1).await.unwrap();
            // expire(0) 将键改为永久驻留
            dao.expire("oc_perm", 0).await.unwrap();
            // 等待原 TTL 过期
            tokio::time::sleep(Duration::from_secs(2)).await;
            // 键应仍存在(已改为永久驻留)
            let got = dao.get("oc_perm").await.unwrap();
            assert_eq!(
                got,
                Some("value1".to_string()),
                "expire(0) 应将键改为永久驻留,不应过期"
            );
        }

        /// 验证 expire(0) 对不存在的键返回 Dao 错误。
        ///
        /// 覆盖 GarrisonDaoOxcache::expire 的 `seconds == 0` 分支中
        /// `ok_or_else(|| GarrisonError::Dao(...))` 错误路径。
        #[tokio::test(flavor = "multi_thread")]
        async fn oxcache_expire_zero_seconds_missing_key_errors() {
            let dao = GarrisonDaoOxcache::new().await.unwrap();
            let result = dao.expire("oc_missing_perm", 0).await;
            assert!(
                matches!(result, Err(GarrisonError::Dao(_))),
                "expire(0) 不存在的键应返回 Dao 错误"
            );
        }

        /// 验证 expire 对不存在的键返回 Dao 错误(seconds > 0 分支)。
        ///
        /// 覆盖 GarrisonDaoOxcache::expire 的 `else` 分支中
        /// `if !updated { return Err(...) }` 错误路径。
        #[tokio::test(flavor = "multi_thread")]
        async fn oxcache_expire_missing_key_errors() {
            let dao = GarrisonDaoOxcache::new().await.unwrap();
            let result = dao.expire("oc_missing_expire", 3600).await;
            assert!(
                matches!(result, Err(GarrisonError::Dao(ref msg)) if msg.contains("dao-key-missing")),
                "expire 不存在的键应返回含 'dao-key-missing' 的 Dao 错误,实际: {:?}",
                result
            );
        }

        /// 验证 set(ttl=0) 写入永久驻留的键。
        ///
        /// 覆盖 GarrisonDaoOxcache::set 的 `ttl_seconds == 0` 分支(ttl=None):
        /// 键应永久驻留,不会因短时间等待而过期。
        #[tokio::test(flavor = "multi_thread")]
        async fn oxcache_set_with_zero_ttl() {
            let dao = GarrisonDaoOxcache::new().await.unwrap();
            // set(ttl=0) 表示永久驻留
            dao.set("oc_zero_ttl", "permanent_value", 0).await.unwrap();
            // 等待 2 秒,验证键未过期
            tokio::time::sleep(Duration::from_secs(2)).await;
            let got = dao.get("oc_zero_ttl").await.unwrap();
            assert_eq!(
                got,
                Some("permanent_value".to_string()),
                "set(ttl=0) 应写入永久驻留的键,2 秒后仍应存在"
            );
        }

        // --------------------------------------------------------------------
        // v0.4.2 4 方法扩展测试
        // --------------------------------------------------------------------

        /// R-001: set_permanent 写入永久键,短时间等待不过期。
        ///
        /// 覆盖 GarrisonDaoOxcache::set_permanent 重写实现(用 set_with_ttl_sync(None))。
        #[tokio::test(flavor = "multi_thread")]
        async fn oxcache_set_permanent_persists_without_ttl() {
            let dao = GarrisonDaoOxcache::new().await.unwrap();
            dao.set_permanent("oc_perm", "perm_value").await.unwrap();
            tokio::time::sleep(Duration::from_secs(2)).await;
            let got = dao.get("oc_perm").await.unwrap();
            assert_eq!(
                got,
                Some("perm_value".to_string()),
                "set_permanent 应写入永久键,2 秒后仍应存在"
            );
        }

        /// R-002: get_timeout 永久键返回 None。
        ///
        /// 覆盖 GarrisonDaoOxcache::get_timeout 重写实现(用 ttl_sync)。
        #[tokio::test(flavor = "multi_thread")]
        async fn oxcache_get_timeout_returns_none_for_permanent_key() {
            let dao = GarrisonDaoOxcache::new().await.unwrap();
            dao.set_permanent("oc_perm_ttl", "v").await.unwrap();
            let timeout = dao.get_timeout("oc_perm_ttl").await.unwrap();
            assert!(timeout.is_none(), "永久键应返回 None");
        }

        /// R-002: get_timeout TTL 键返回 Some(remaining),剩余 ≤ 原 TTL。
        #[tokio::test(flavor = "multi_thread")]
        async fn oxcache_get_timeout_returns_some_for_ttl_key() {
            let dao = GarrisonDaoOxcache::new().await.unwrap();
            dao.set("oc_ttl_key", "v", 3600).await.unwrap();
            let timeout = dao.get_timeout("oc_ttl_key").await.unwrap();
            assert!(timeout.is_some(), "TTL 键应返回 Some");
            let remaining = timeout.unwrap();
            assert!(
                remaining <= Duration::from_secs(3600),
                "剩余时间应 ≤ 原 TTL"
            );
        }

        /// R-002: get_timeout 不存在的键返回 None。
        #[tokio::test(flavor = "multi_thread")]
        async fn oxcache_get_timeout_returns_none_for_missing_key() {
            let dao = GarrisonDaoOxcache::new().await.unwrap();
            let timeout = dao.get_timeout("oc_missing_ttl").await.unwrap();
            assert!(timeout.is_none(), "不存在的键应返回 None");
        }

        /// R-003: keys 行为取决于 feature gate。
        ///
        /// - 启用 `anomalous-detector-dual`:keys() 通过 key_index 返回匹配的 key 列表
        /// - 未启用 `anomalous-detector-dual`:keys() 返回 NotImplemented(oxcache 不支持原生 key scan)
        #[tokio::test(flavor = "multi_thread")]
        async fn oxcache_keys_behavior() {
            let dao = GarrisonDaoOxcache::new().await.unwrap();
            dao.set("oc_key1", "v1", 3600).await.unwrap();
            let result = dao.keys("oc_*").await;
            #[cfg(feature = "anomalous-detector-dual")]
            {
                let keys = result.expect("anomalous-detector-dual 启用时 keys() 应返回 key 列表");
                assert!(
                    keys.iter().any(|k| k.contains("oc_key1")),
                    "keys 应包含 oc_key1, 实际: {:?}",
                    keys
                );
            }
            #[cfg(not(feature = "anomalous-detector-dual"))]
            {
                assert!(
                    matches!(result, Err(GarrisonError::NotImplemented(_))),
                    "未启用 anomalous-detector-dual 时 keys() 应返回 NotImplemented, 实际: {:?}",
                    result
                );
            }
        }

        /// R-004: rename 重命名后 old 不存在,new 存在。
        ///
        /// 覆盖 GarrisonDaoOxcache::rename 重写实现(用 get → ttl_sync → set_with_ttl_sync → delete)。
        #[tokio::test(flavor = "multi_thread")]
        async fn oxcache_rename_moves_key() {
            let dao = GarrisonDaoOxcache::new().await.unwrap();
            dao.set("oc_old", "value", 3600).await.unwrap();
            dao.rename("oc_old", "oc_new").await.unwrap();
            let old = dao.get("oc_old").await.unwrap();
            let new = dao.get("oc_new").await.unwrap();
            assert!(old.is_none(), "rename 后 oc_old 应不存在");
            assert_eq!(new, Some("value".to_string()), "rename 后 oc_new 应有值");
        }

        /// R-004: rename 不存在的 old_key 返回 InvalidParam。
        #[tokio::test(flavor = "multi_thread")]
        async fn oxcache_rename_missing_key_returns_invalid_param() {
            let dao = GarrisonDaoOxcache::new().await.unwrap();
            let result = dao.rename("oc_missing_old", "oc_new").await;
            assert!(
                matches!(result, Err(GarrisonError::InvalidParam(_))),
                "rename 不存在的键应返回 InvalidParam,实际: {:?}",
                result
            );
        }

        /// R-004: rename 保留原键 TTL(重写实现的核心价值)。
        ///
        /// 验证 GarrisonDaoOxcache::rename 用 ttl_sync + set_with_ttl_sync 保留 TTL,
        /// 而非默认实现的 set_permanent(丢失 TTL)。
        #[tokio::test(flavor = "multi_thread")]
        async fn oxcache_rename_preserves_ttl() {
            let dao = GarrisonDaoOxcache::new().await.unwrap();
            // 设置短 TTL(2 秒)
            dao.set("oc_short_ttl", "value", 2).await.unwrap();
            // rename 到新 key
            dao.rename("oc_short_ttl", "oc_renamed").await.unwrap();
            // 验证新 key 存在
            let got = dao.get("oc_renamed").await.unwrap();
            assert_eq!(got, Some("value".to_string()));
            // 等待原 TTL 过期(2 秒 + 1 秒余量)
            tokio::time::sleep(Duration::from_secs(3)).await;
            // rename 保留了原 TTL,应已过期
            let got = dao.get("oc_renamed").await.unwrap();
            assert!(
                got.is_none(),
                "rename 应保留原 TTL,原 TTL 过期后应返回 None"
            );
        }

        /// R-001: oxcache get_and_delete 返回值并删除 key。
        #[tokio::test(flavor = "multi_thread")]
        async fn oxcache_get_and_delete_returns_value_and_removes_key() {
            let dao = GarrisonDaoOxcache::new().await.unwrap();
            dao.set("oc_atomic", "value", 3600).await.unwrap();
            let got = dao.get_and_delete("oc_atomic").await.unwrap();
            assert_eq!(got, Some("value".to_string()));
            let after = dao.get("oc_atomic").await.unwrap();
            assert!(after.is_none(), "get_and_delete 后 key 应不存在");
        }

        /// R-001: oxcache get_and_delete 不存在的 key 返回 None。
        #[tokio::test(flavor = "multi_thread")]
        async fn oxcache_get_and_delete_missing_returns_none() {
            let dao = GarrisonDaoOxcache::new().await.unwrap();
            let got = dao.get_and_delete("oc_missing").await.unwrap();
            assert!(got.is_none());
        }

        /// R-001: oxcache get_and_delete 并发原子性验证。
        #[tokio::test(flavor = "multi_thread")]
        async fn oxcache_get_and_delete_concurrent_only_one_succeeds() {
            let dao = Arc::new(GarrisonDaoOxcache::new().await.unwrap());
            dao.set("oc_concurrent", "value", 3600).await.unwrap();

            let mut handles = Vec::new();
            for _ in 0..10 {
                let d = dao.clone();
                handles.push(tokio::spawn(async move {
                    d.get_and_delete("oc_concurrent").await
                }));
            }

            let mut success = 0;
            let mut none_count = 0;
            for handle in handles {
                let result = handle.await.unwrap();
                match result {
                    Ok(Some(_)) => success += 1,
                    Ok(None) => none_count += 1,
                    Err(e) => panic!("get_and_delete 不应返回错误: {:?}", e),
                }
            }

            assert_eq!(success, 1, "并发调用仅一个返回 Some");
            assert_eq!(none_count, 9, "其他 9 个返回 None");
        }

        // --------------------------------------------------------------------
        // 多租户 key 前缀测试
        // --------------------------------------------------------------------

        /// R-tenant-isolation-003: tenant-isolation feature 启用且 TENANT 上下文存在时,
        /// GarrisonDao 的 set/get 实际操作的 key 为 `tenant:{tid}:original_key`。
        ///
        /// 通过公共 API 验证(不直接探测内部存储 key,避免 get 自身再次 prepend 前缀):
        /// 1. tenant 42 在 TENANT.scope 内 set("shared_key", "tenant_42_value")
        /// 2. 同一 TENANT.scope 内 get("shared_key") 应返回 Some(证明 set/get 用同一前缀)
        /// 3. tenant 1 在另一 TENANT.scope 内 get("shared_key") 应返回 None(证明跨租户隔离)
        /// 4. tenant 1 在另一 TENANT.scope 内 set("shared_key", "tenant_1_value") 应不影响 tenant 42 的值
        #[cfg(feature = "tenant-isolation")]
        #[tokio::test(flavor = "multi_thread")]
        async fn dao_key_prefixed_with_tenant_when_isolation_enabled() {
            use crate::context::tenant::{TenantContext, TenantSource, TENANT};

            let dao = GarrisonDaoOxcache::new().await.unwrap();

            // tenant 42 写入
            let ctx_42 = TenantContext {
                tenant_id: 42,
                resolved_from: TenantSource::Header,
            };
            TENANT
                .scope(ctx_42.clone(), async {
                    dao.set("shared_key", "tenant_42_value", 3600)
                        .await
                        .unwrap();
                    // 同租户 get 应命中(证明 set 与 get 用相同前缀 `tenant:42:`)
                    let got = dao.get("shared_key").await.unwrap();
                    assert_eq!(
                        got,
                        Some("tenant_42_value".to_string()),
                        "同租户 get 应命中 set 写入的值(前缀一致)"
                    );
                })
                .await;

            // tenant 1 跨租户访问应隔离
            let ctx_1 = TenantContext {
                tenant_id: 1,
                resolved_from: TenantSource::Header,
            };
            TENANT
                .scope(ctx_1, async {
                    // 跨租户 get 应返回 None(key 前缀不同:`tenant:1:` vs `tenant:42:`)
                    let got = dao.get("shared_key").await.unwrap();
                    assert!(
                        got.is_none(),
                        "跨租户 get 应返回 None(隔离失败),实际: {:?}",
                        got
                    );

                    // tenant 1 写入同名 key 不应影响 tenant 42
                    dao.set("shared_key", "tenant_1_value", 3600).await.unwrap();
                    let got_self = dao.get("shared_key").await.unwrap();
                    assert_eq!(
                        got_self,
                        Some("tenant_1_value".to_string()),
                        "tenant 1 应读到自己的值"
                    );
                })
                .await;

            // 回到 tenant 42 验证值未被 tenant 1 覆盖
            TENANT
                .scope(ctx_42.clone(), async {
                    let got = dao.get("shared_key").await.unwrap();
                    assert_eq!(
                        got,
                        Some("tenant_42_value".to_string()),
                        "tenant 42 的值不应被 tenant 1 覆盖(隔离失败)"
                    );
                })
                .await;
        }

        /// R-tenant-isolation-003: TENANT 上下文不存在时 key 不变(不 panic)。
        ///
        /// 验证:不在 TENANT.scope 内调用 set/get,key 应保持原样(无前缀)。
        #[cfg(feature = "tenant-isolation")]
        #[tokio::test(flavor = "multi_thread")]
        async fn dao_key_unchanged_when_tenant_context_absent() {
            let dao = GarrisonDaoOxcache::new().await.unwrap();

            // 不在 TENANT.scope 内,TENANT.try_get() 返回 Err,key 应保持原样
            dao.set("no_ctx_key", "value", 3600).await.unwrap();
            let got = dao.get("no_ctx_key").await.unwrap();
            assert_eq!(
                got,
                Some("value".to_string()),
                "TENANT 上下文不存在时 key 应保持原样(无前缀)"
            );

            // 带前缀的 key 应返回 None(因 set 时未加前缀)
            let prefixed = dao.get("tenant:0:no_ctx_key").await.unwrap();
            assert!(
                prefixed.is_none(),
                "TENANT 上下文不存在时不应有带前缀的 key"
            );
        }

        /// R-tenant-isolation-003: delete 也应使用带前缀的 key。
        ///
        /// 验证:在 TENANT.scope 内 set 后,用 delete 删除原始 key 应能成功删除
        ///(delete 内部加前缀 `tenant:42:`,与 set 写入的 key 匹配)。
        /// 通过公共 API 验证:delete 后同租户 get 应返回 None。
        #[cfg(feature = "tenant-isolation")]
        #[tokio::test(flavor = "multi_thread")]
        async fn dao_delete_uses_prefixed_key_in_tenant_context() {
            use crate::context::tenant::{TenantContext, TenantSource, TENANT};

            let dao = GarrisonDaoOxcache::new().await.unwrap();
            let ctx = TenantContext {
                tenant_id: 42,
                resolved_from: TenantSource::Header,
            };

            TENANT
                .scope(ctx, async {
                    dao.set("del_key", "value", 3600).await.unwrap();
                    // 先确认值已写入
                    assert_eq!(
                        dao.get("del_key").await.unwrap(),
                        Some("value".to_string()),
                        "set 后同租户 get 应命中"
                    );

                    // delete 用原始 key,内部应加前缀匹配到 `tenant:42:del_key`
                    dao.delete("del_key").await.unwrap();

                    // 同租户 get 应返回 None(证明 delete 命中了带前缀的 key)
                    let after = dao.get("del_key").await.unwrap();
                    assert!(
                        after.is_none(),
                        "delete 后同租户 get 应返回 None(delete 也加了前缀)"
                    );
                })
                .await;
        }
    }

    // ------------------------------------------------------------------------
    // get_and_delete 原子方法测试(v0.4.2 spec protocol-sso-toctou R-001)
    // ------------------------------------------------------------------------

    /// R-001: get_and_delete 返回值并删除 key。
    #[tokio::test]
    async fn mock_get_and_delete_returns_value_and_removes_key() {
        let dao = MockDao::new();
        dao.set("atomic_key", "value", 3600).await.unwrap();
        let got = dao.get_and_delete("atomic_key").await.unwrap();
        assert_eq!(got, Some("value".to_string()));
        // key 应已被删除
        let after = dao.get("atomic_key").await.unwrap();
        assert!(after.is_none(), "get_and_delete 后 key 应不存在");
    }

    /// R-001: get_and_delete 不存在的 key 返回 None。
    #[tokio::test]
    async fn mock_get_and_delete_missing_returns_none() {
        let dao = MockDao::new();
        let got = dao.get_and_delete("missing").await.unwrap();
        assert!(got.is_none(), "不存在的 key 应返回 None");
    }

    /// R-001: get_and_delete 并发调用同一 key 仅一个返回 Some(原子性验证)。
    ///
    /// 使用 10 个并发任务同时调用 get_and_delete,仅一个应返回 Some。
    /// 这是 TOCTOU 修复的核心验证测试。
    #[tokio::test(flavor = "multi_thread")]
    async fn mock_get_and_delete_concurrent_only_one_succeeds() {
        let dao = Arc::new(MockDao::new());
        dao.set("concurrent_key", "value", 3600).await.unwrap();

        let mut handles = Vec::new();
        for _ in 0..10 {
            let d = dao.clone();
            handles.push(tokio::spawn(async move {
                d.get_and_delete("concurrent_key").await
            }));
        }

        let mut success = 0;
        let mut none_count = 0;
        for handle in handles {
            let result = handle.await.unwrap();
            match result {
                Ok(Some(_)) => success += 1,
                Ok(None) => none_count += 1,
                Err(e) => panic!("get_and_delete 不应返回错误: {:?}", e),
            }
        }

        assert_eq!(success, 1, "并发调用仅一个返回 Some");
        assert_eq!(none_count, 9, "其他 9 个返回 None");
    }

    // ========================================================================
    // decr 并发原子性测试(fix-refresh-race-and-test-contracts / T011-T012)
    // ========================================================================

    /// 验证 MockDao::decr 并发原子性:10 个 task 并发 decr 同一 key(初始值 5),
    /// 恰好 5 次 decr 实际生效(5→4→3→2→1→0)+ 5 次返回 0(key 已删除)。
    ///
    /// 返回值分类:
    /// - 4 个返回非 0(4,3,2,1):归入 effective
    /// - 1 个返回 0(1→0,new_val==0 删除 key):归入 zero_count(返回值无法区分"递减到 0"与"key 不存在")
    /// - 5 个返回 0(key 已删除):归入 zero_count
    ///
    /// 修复前:`SmsRateLimiter::decrement_counter` 用 `dao.get → parse → dao.update/delete`
    /// 三步组合,跨越 await 间隙允许其他 task 的 `incr` 插入,导致 update 基于过时 get 值
    /// 覆盖 incr 结果,产生"跨越式递减"(实际递减量大于 1)。
    ///
    /// 修复后:MockDao::decr 在单次 `parking_lot::Mutex` lock 作用域内完成 get→parse→update/delete,
    /// 消除 TOCTOU 竞态。10 个并发 task decr 同一 key(初始值 5),恰好 5 次 decr 生效(4 个返回非 0 + 1 个返回 0)+ 5 次返回 0。
    #[tokio::test(flavor = "multi_thread")]
    async fn mock_decr_concurrent_only_5_effective() {
        let dao = Arc::new(MockDao::new());
        dao.set("counter", "5", 3600).await.unwrap();

        let mut handles = Vec::new();
        for _ in 0..10 {
            let d = dao.clone();
            handles.push(tokio::spawn(async move { d.decr("counter").await }));
        }

        let mut effective = 0;
        let mut zero_count = 0;
        for handle in handles {
            let result = handle.await.unwrap();
            match result {
                Ok(0) => zero_count += 1,
                Ok(_) => effective += 1,
                Err(e) => panic!("decr 不应返回错误: {:?}", e),
            }
        }

        // 5 次 decr 生效:4 次返回非 0(4,3,2,1)+ 1 次返回 0(1→0 删除 key)
        assert_eq!(
            effective, 4,
            "4 次 decr 返回非 0(5→4→3→2→1),实际 {} 个",
            effective
        );
        // 6 次返回 0:1 次(1→0)+ 5 次(key 已删除)
        assert_eq!(
            zero_count, 6,
            "6 次 decr 返回 0(1 次 1→0 + 5 次 key 不存在),实际 {} 个",
            zero_count
        );

        // 计数器最终应为 0(已被删除)
        let final_val = dao.get("counter").await.unwrap();
        assert!(
            final_val.is_none(),
            "decr 到 0 后 key 应被删除,实际存在: {:?}",
            final_val
        );
    }

    /// 验证 MockDao::decr 单线程基本语义(覆盖率补充)。
    ///
    /// 语义(与 trait 默认实现 + incr 对称):
    /// - key 不存在或已过期:返回 0(不创建 key)
    /// - cur_val == 0:返回 0(不递减为负,不删除 key)
    /// - cur_val > 0:递减 1;new_val == 0 时删除 key;new_val > 0 时保留原 TTL
    #[tokio::test]
    async fn mock_decr_basic_semantics() {
        let dao = MockDao::new();

        // key 不存在 → 返回 0(不创建 key)
        assert_eq!(dao.decr("missing").await.unwrap(), 0);
        assert!(
            dao.get("missing").await.unwrap().is_none(),
            "decr 不存在的 key 不应创建 key"
        );

        // 设置初始值 3,递减 3 → 2 → 1 → 0
        dao.set("counter", "3", 3600).await.unwrap();
        assert_eq!(dao.decr("counter").await.unwrap(), 2);
        assert_eq!(dao.decr("counter").await.unwrap(), 1);
        assert_eq!(dao.decr("counter").await.unwrap(), 0);

        // 从 1 decr 到 0 时(new_val == 0)应删除 key(与默认实现一致)
        assert!(
            dao.get("counter").await.unwrap().is_none(),
            "从 1 decr 到 0 应删除 key(new_val == 0 分支)"
        );

        // key 已删除后 decr 返回 0(key 不存在分支)
        assert_eq!(dao.decr("counter").await.unwrap(), 0);

        // 单独验证 cur_val == 0 分支:直接 set "0"(绕过 decr 的删除逻辑)
        dao.set("zero_counter", "0", 3600).await.unwrap();
        assert_eq!(
            dao.decr("zero_counter").await.unwrap(),
            0,
            "cur_val == 0 时返回 0(不递减为负)"
        );
        assert_eq!(
            dao.get("zero_counter").await.unwrap(),
            Some("0".to_string()),
            "cur_val == 0 时 decr 不删除 key(提前返回,不进入 new_val == 0 分支)"
        );
    }

    /// 验证 MockDao::decr 非数字值返回 Dao 错误(Rule 12:禁止静默吞掉 parse 失败)。
    #[tokio::test]
    async fn mock_decr_non_numeric_value_returns_error() {
        let dao = MockDao::new();
        dao.set("bad_counter", "not_a_number", 3600).await.unwrap();
        let result = dao.decr("bad_counter").await;
        assert!(result.is_err(), "非数字值应返回 Dao 错误");
        match result.err().unwrap() {
            GarrisonError::Dao(msg) => {
                assert!(
                    msg.contains("dao-decr-parse-u64"),
                    "错误消息应含 dao-decr-parse-u64,实际: {}",
                    msg
                );
            },
            other => panic!("期望 GarrisonError::Dao,实际: {:?}", other),
        }
    }

    // ========================================================================
    // 覆盖率补充:GarrisonDao trait 默认方法测试
    // ========================================================================

    /// 最小化 DAO 实现,只实现 5 个必需方法,不重写任何默认方法。
    ///
    /// 用于验证 trait 默认实现的行为:
    /// - `set_permanent` 默认委托 `set(key, value, 0)`
    /// - `get_timeout` 默认返回 `NotImplemented`
    /// - `keys` 默认返回 `NotImplemented`
    /// - `rename` 默认 `get → set_permanent → delete`
    pub struct MinimalDao {
        store: Mutex<HashMap<String, String>>,
    }

    impl Default for MinimalDao {
        fn default() -> Self {
            Self::new()
        }
    }

    impl MinimalDao {
        /// 创建空的 MinimalDao 实例。
        pub fn new() -> Self {
            Self {
                store: Mutex::new(HashMap::new()),
            }
        }
    }

    #[async_trait]
    impl GarrisonDao for MinimalDao {
        async fn get(&self, key: &str) -> GarrisonResult<Option<String>> {
            Ok(self.store.lock().get(key).cloned())
        }

        async fn set(&self, key: &str, value: &str, _ttl_seconds: u64) -> GarrisonResult<()> {
            self.store.lock().insert(key.to_string(), value.to_string());
            Ok(())
        }

        async fn update(&self, key: &str, value: &str) -> GarrisonResult<()> {
            match self.store.lock().get_mut(key) {
                Some(existing) => {
                    *existing = value.to_string();
                    Ok(())
                },
                None => Err(GarrisonError::Dao(format!("dao-key-missing::{}", key))),
            }
        }

        async fn expire(&self, _key: &str, _seconds: u64) -> GarrisonResult<()> {
            Ok(()) // MinimalDao 不支持 TTL,no-op
        }

        async fn delete(&self, key: &str) -> GarrisonResult<()> {
            self.store.lock().remove(key);
            Ok(())
        }
    }

    /// R-001: `set_permanent` 默认实现委托 `set(key, value, 0)`。
    #[tokio::test]
    async fn default_set_permanent_delegates_to_set_with_ttl_zero() {
        let dao = MinimalDao::new();
        // 调用默认实现的 set_permanent
        dao.set_permanent("perm_key", "perm_value").await.unwrap();
        // 验证值已写入(通过 get 读取)
        let val = dao.get("perm_key").await.unwrap();
        assert_eq!(val.as_deref(), Some("perm_value"));
    }

    /// R-002: `get_timeout` 默认实现返回 `NotImplemented`。
    #[tokio::test]
    async fn default_get_timeout_returns_not_implemented() {
        let dao = MinimalDao::new();
        dao.set("key", "value", 3600).await.unwrap();
        let result = dao.get_timeout("key").await;
        assert!(matches!(result, Err(GarrisonError::NotImplemented(_))));
    }

    /// R-003: `keys` 默认实现返回 `NotImplemented`。
    #[tokio::test]
    async fn default_keys_returns_not_implemented() {
        let dao = MinimalDao::new();
        dao.set("key1", "v1", 0).await.unwrap();
        let result = dao.keys("*").await;
        assert!(matches!(result, Err(GarrisonError::NotImplemented(_))));
    }

    /// R-004: `rename` 默认实现执行 `get → set_permanent → delete` 三步操作。
    #[tokio::test]
    async fn default_rename_get_set_permanent_delete() {
        let dao = MinimalDao::new();
        dao.set("old_key", "old_value", 0).await.unwrap();
        // 调用默认实现的 rename
        dao.rename("old_key", "new_key").await.unwrap();
        // 验证 old_key 已被删除
        assert!(dao.get("old_key").await.unwrap().is_none());
        // 验证 new_key 已写入
        assert_eq!(
            dao.get("new_key").await.unwrap().as_deref(),
            Some("old_value")
        );
    }

    /// R-004: `rename` 对不存在的 key 返回 `InvalidParam`。
    #[tokio::test]
    async fn default_rename_missing_key_returns_invalid_param() {
        let dao = MinimalDao::new();
        let result = dao.rename("nonexistent", "new_key").await;
        assert!(matches!(result, Err(GarrisonError::InvalidParam(_))));
    }

    // ========================================================================
    // 覆盖率补充:社交账号绑定关系默认实现
    // ========================================================================

    /// `find_social_binding` 默认实现返回 `NotImplemented`(GarrisonDao 是 KV 缓存抽象,不支持 SQL)。
    ///
    /// 覆盖 trait 默认实现(行 208-218)。
    #[tokio::test]
    async fn default_find_social_binding_returns_not_implemented() {
        let dao = MinimalDao::new();
        let result = dao.find_social_binding(0, "wechat", "wx_openid").await;
        assert!(
            matches!(result, Err(GarrisonError::NotImplemented(ref msg)) if msg.contains("find_social_binding")),
            "find_social_binding 默认实现应返回 NotImplemented,实际: {:?}",
            result
        );
    }

    /// `insert_social_binding` 默认实现返回 `NotImplemented`。
    ///
    /// 覆盖 trait 默认实现(行 236-249)。
    #[tokio::test]
    async fn default_insert_social_binding_returns_not_implemented() {
        let dao = MinimalDao::new();
        let result = dao
            .insert_social_binding(0, 1001, "wechat", "wx_openid", None, 1700000000)
            .await;
        assert!(
            matches!(result, Err(GarrisonError::NotImplemented(ref msg)) if msg.contains("insert_social_binding")),
            "insert_social_binding 默认实现应返回 NotImplemented,实际: {:?}",
            result
        );
    }

    /// `compare_and_update_if_greater` 默认实现返回 `NotImplemented`(M2 修复)。
    ///
    /// 默认实现原为 get → parse → compare → set 四步操作,存在 TOCTOU 竞态。
    /// M2 修复:改为返回 `NotImplemented`(fail-closed),强制后端重写以使用原子 CAS。
    /// 此测试验证 MinimalDao(不重写任何默认方法)调用时返回 NotImplemented。
    #[tokio::test]
    async fn default_compare_and_update_if_greater_returns_not_implemented() {
        let dao = MinimalDao::new();
        let result = dao.compare_and_update_if_greater("key", 1, 60).await;
        assert!(
            matches!(result, Err(GarrisonError::NotImplemented(ref msg)) if msg.contains("compare_and_update_if_greater")),
            "compare_and_update_if_greater 默认实现应返回 NotImplemented,实际: {:?}",
            result
        );
    }

    /// `decr` 默认实现返回 `NotImplemented`(M2 修复)。
    ///
    /// 默认实现原为 get → parse → update/delete 三步组合,存在 TOCTOU 竞态:
    /// 并发调用同一 key 时多个调用可能基于同一过时 get 值计算新值并覆盖写入,
    /// 导致"跨越式递减"(实际递减量大于 1)。`SmsRateLimiter::decrement_counter`
    /// 的 flaky test(`concurrent_send_does_not_exceed_limit`)即由此引发。
    /// M2 修复:改为返回 `NotImplemented`(fail-closed),与
    /// `compare_and_update_if_greater` 对齐,强制后端重写以使用原子 decr。
    ///
    /// 此测试验证 MinimalDao(不重写任何默认方法)调用 decr 时返回 NotImplemented。
    #[tokio::test]
    async fn default_decr_returns_not_implemented() {
        let dao = MinimalDao::new();
        // 即使 key 存在(get 会返回 Some),decr 默认实现也直接返回 NotImplemented,
        // 不进入 get → parse → update/delete 路径,避免静默引入 TOCTOU 竞态
        dao.set("counter", "5", 60).await.unwrap();
        let result = dao.decr("counter").await;
        assert!(
            matches!(result, Err(GarrisonError::NotImplemented(ref msg)) if msg.contains("decr") && msg.contains("原子 decr")),
            "decr 默认实现应返回 NotImplemented(含 '原子 decr' 提示),实际: {:?}",
            result
        );
        // 验证 key 未被修改(默认实现完全 short-circuit,不执行任何 DAO 操作)
        let after = dao.get("counter").await.unwrap();
        assert_eq!(
            after.as_deref(),
            Some("5"),
            "decr 默认实现 short-circuit 后 key 不应被修改"
        );
    }

    /// `get_and_delete` 默认实现(非原子 get → delete)在键存在时返回值并删除。
    ///
    /// 覆盖 trait 默认实现(行 182-188)。
    #[tokio::test]
    async fn default_get_and_delete_returns_value_and_removes_key() {
        let dao = MinimalDao::new();
        dao.set("k1", "v1", 60).await.unwrap();
        let val = dao.get_and_delete("k1").await.unwrap();
        assert_eq!(val, Some("v1".to_string()));
        assert!(dao.get("k1").await.unwrap().is_none());
    }

    /// `get_and_delete` 默认实现对不存在的键返回 None 且不报错。
    #[tokio::test]
    async fn default_get_and_delete_missing_key_returns_none() {
        let dao = MinimalDao::new();
        let val = dao.get_and_delete("nope").await.unwrap();
        assert!(val.is_none());
    }

    // ========================================================================
    // Redis 部署模式配置测试
    // ========================================================================

    /// R-002: RedisConfig::default() 返回 Single 模式,url 为 "redis://127.6379"。
    #[test]
    fn redis_config_default_returns_single_mode() {
        let config = RedisConfig::default();
        assert_eq!(
            config.mode,
            RedisDeploymentMode::Single {
                url: "redis://127.0.0.1:6379".to_string()
            }
        );
        assert_eq!(config.password, None);
        assert_eq!(config.db, 0);
        assert_eq!(config.connection_timeout_secs, 5);
        assert_eq!(config.pool_size, 10);
    }

    /// R-002: RedisConfig serde 序列化/反序列化 round-trip。
    #[test]
    fn redis_config_serde_roundtrip() {
        let config = RedisConfig {
            mode: RedisDeploymentMode::Cluster {
                urls: vec![
                    "redis://10.0.0.1:6379".to_string(),
                    "redis://10.0.0.2:6379".to_string(),
                    "redis://10.0.0.3:6379".to_string(),
                ],
            },
            password: Some("secret".to_string()),
            db: 1,
            connection_timeout_secs: 10,
            pool_size: 20,
        };
        let json = serde_json::to_string(&config).unwrap();
        let deserialized: RedisConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(config.mode, deserialized.mode);
        assert_eq!(config.password, deserialized.password);
        assert_eq!(config.db, deserialized.db);
        assert_eq!(
            config.connection_timeout_secs,
            deserialized.connection_timeout_secs
        );
        assert_eq!(config.pool_size, deserialized.pool_size);
    }

    /// R-002: RedisConfig serde 用 `#[serde(default)]` 支持部分覆盖。
    #[test]
    fn redis_config_serde_partial_override() {
        // 仅提供 mode,其余字段应使用 default
        let json = r#"{"mode":{"mode":"cluster","urls":["redis://10.0.0.1:6379"]}}"#;
        let config: RedisConfig = serde_json::from_str(json).unwrap();
        match config.mode {
            RedisDeploymentMode::Cluster { urls } => {
                assert_eq!(urls, vec!["redis://10.0.0.1:6379".to_string()]);
            },
            _ => panic!("期望 Cluster 模式"),
        }
        // 其余字段应为 default 值
        assert_eq!(config.password, None);
        assert_eq!(config.db, 0);
        assert_eq!(config.connection_timeout_secs, 5);
        assert_eq!(config.pool_size, 10);
    }

    /// R-001: RedisDeploymentMode 各变体 Display 输出可读。
    #[test]
    fn redis_deployment_mode_display() {
        let single = RedisDeploymentMode::Single {
            url: "redis://127.0.0.1:6379".to_string(),
        };
        assert!(format!("{}", single).contains("single"));
        assert!(format!("{}", single).contains("redis://127.0.0.1:6379"));

        let sentinel = RedisDeploymentMode::Sentinel {
            master_name: "mymaster".to_string(),
            urls: vec!["redis://s1:26379".to_string()],
        };
        let s = format!("{}", sentinel);
        assert!(s.contains("sentinel"));
        assert!(s.contains("mymaster"));

        let cluster = RedisDeploymentMode::Cluster {
            urls: vec!["redis://c1:6379".to_string(), "redis://c2:6379".to_string()],
        };
        let c = format!("{}", cluster);
        assert!(c.contains("cluster"));
        assert!(c.contains("2 nodes"));

        let ms = RedisDeploymentMode::MasterSlave {
            master_url: "redis://master:6379".to_string(),
            slave_urls: vec!["redis://slave1:6379".to_string()],
        };
        let m = format!("{}", ms);
        assert!(m.contains("master-slave"));
        assert!(m.contains("master:6379"));
        assert!(m.contains("1 slaves"));
    }

    /// R-001: RedisDeploymentMode PartialEq 比较。
    #[test]
    fn redis_deployment_mode_eq() {
        let a = RedisDeploymentMode::Single {
            url: "redis://127.0.0.1:6379".to_string(),
        };
        let b = RedisDeploymentMode::Single {
            url: "redis://127.0.0.1:6379".to_string(),
        };
        let c = RedisDeploymentMode::Single {
            url: "redis://10.0.0.1:6379".to_string(),
        };
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    /// R-003: with_redis_config builder 方法在 cache-redis feature 下存在并存储配置。
    #[cfg(feature = "cache-redis")]
    #[tokio::test(flavor = "multi_thread")]
    async fn with_redis_config_stores_config() {
        let dao = GarrisonDaoOxcache::new().await.unwrap();
        assert!(
            dao.redis_config().is_none(),
            "新建实例的 redis_config 应为 None"
        );
        let config = RedisConfig {
            mode: RedisDeploymentMode::Sentinel {
                master_name: "mymaster".to_string(),
                urls: vec![
                    "redis://s1:26379".to_string(),
                    "redis://s2:26379".to_string(),
                    "redis://s3:26379".to_string(),
                ],
            },
            password: Some("pass123".to_string()),
            db: 2,
            connection_timeout_secs: 15,
            pool_size: 50,
        };
        let dao = dao.with_redis_config(config);
        let stored = dao.redis_config().expect("with_redis_config 后应有配置");
        assert!(matches!(
            &stored.mode,
            RedisDeploymentMode::Sentinel { master_name, urls }
            if master_name == "mymaster" && urls.len() == 3
        ));
        assert_eq!(stored.password, Some("pass123".to_string()));
        assert_eq!(stored.db, 2);
        assert_eq!(stored.connection_timeout_secs, 15);
        assert_eq!(stored.pool_size, 50);
    }

    /// R-003: 未调用 with_redis_config 时 redis_config 为 None。
    #[cfg(feature = "cache-redis")]
    #[tokio::test(flavor = "multi_thread")]
    async fn without_redis_config_returns_none() {
        let dao = GarrisonDaoOxcache::new().await.unwrap();
        assert!(
            dao.redis_config().is_none(),
            "未调用 with_redis_config 时 redis_config 应为 None"
        );
    }

    // ========================================================================
    // 覆盖率补充:GarrisonDao trait 默认方法(incr / eval_lua)
    // ========================================================================

    /// `incr` 默认实现初始化新键为 1。
    ///
    /// 覆盖 trait 默认实现中 `None` 分支(键不存在时 set 初始值 1)。
    #[tokio::test]
    async fn default_incr_initializes_new_key() {
        let dao = MinimalDao::new();
        let result = dao.incr("counter", 3600).await.unwrap();
        assert_eq!(result, 1, "新键应初始化为 1");
        // 验证值已写入
        let val = dao.get("counter").await.unwrap();
        assert_eq!(val.as_deref(), Some("1"));
    }

    /// `incr` 默认实现递增已存在键的值。
    ///
    /// 覆盖 trait 默认实现中 `Some` 分支(键存在时 parse + update)。
    #[tokio::test]
    async fn default_incr_increments_existing_key() {
        let dao = MinimalDao::new();
        dao.set("counter", "5", 3600).await.unwrap();
        let result = dao.incr("counter", 3600).await.unwrap();
        assert_eq!(result, 6, "已存在键 5 应递增为 6");
        // 再次递增
        let result = dao.incr("counter", 3600).await.unwrap();
        assert_eq!(result, 7, "已存在键 6 应递增为 7");
    }

    /// `incr` 默认实现对非数字值回退为 0 后递增。
    ///
    /// 覆盖 Rule 12:非数字值必须显式报错,禁止静默回退为 0 导致计数器重置。
    #[tokio::test]
    async fn default_incr_rejects_non_numeric_value() {
        let dao = MinimalDao::new();
        dao.set("bad_counter", "not_a_number", 3600).await.unwrap();
        let result = dao.incr("bad_counter", 3600).await;
        assert!(
            result.is_err(),
            "非数字值必须显式报错,禁止静默回退为 0 导致计数器重置(Rule 12)"
        );
    }

    /// `eval_lua` 默认实现返回 `NotImplemented`。
    ///
    /// 覆盖 trait 默认实现(仅 Redis 后端支持 Lua 脚本)。
    #[tokio::test]
    async fn default_eval_lua_returns_not_implemented() {
        let dao = MinimalDao::new();
        let result = dao
            .eval_lua("return 1", vec!["k".to_string()], vec!["a".to_string()])
            .await;
        assert!(
            matches!(result, Err(GarrisonError::NotImplemented(ref msg)) if msg.contains("eval_lua")),
            "eval_lua 默认实现应返回 NotImplemented,实际: {:?}",
            result
        );
    }

    /// MinimalDao::default() 等价于 new()。
    ///
    /// 覆盖 MinimalDao 的 Default trait 实现。
    #[tokio::test]
    async fn minimal_dao_default_equals_new() {
        let dao = MinimalDao::default();
        dao.set("k", "v", 60).await.unwrap();
        let got = dao.get("k").await.unwrap();
        assert_eq!(got.as_deref(), Some("v"));
    }
}