wedb_standalone 0.1.1

单机网络服务底座:RESP 协议帧、AOF 逻辑层与节点服务编排(对标 Garnet libs/server 单机半区)
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
use std::{
  sync::{
    Arc, LazyLock,
    atomic::{AtomicI64, Ordering},
  },
  time::Duration,
};

use super::{
  config_kind::ConfigKind,
  config_meta::{ConfigMeta, ConfigUpdateAction, ConfigUpdateOwner, EnumMeta},
  config_name_comparer::ConfigNameComparer,
  config_time_unit::ConfigTimeUnit,
  error::ConfigError,
  log_compaction_type::LogCompactionType,
  runtime_server_options::RuntimeServerOptions,
  server_config_type::ServerConfigType,
};

/// 全部 CONFIG 类型的槽位表(对标 libs/server/Config/RuntimeServerConfig.cs:RuntimeServerConfig)。
///
/// 以 `ServerConfigType` 为下标的运行时可调配置中心表:启动时从
/// `RuntimeServerOptions`(GarnetServerOptions 子集)播种,运行期经 CONFIG SET
/// 更新,由 StoreWrapper 持有以便服务器与集群层实时读取。
///
/// 底层为单个 `AtomicI64` 数组(无分配、连续、O(1) 下标;load/store 即 C#
/// `Volatile.Read/Write` 的原子语义)。每个槽位是原始 8 字节单元,具体解释由
/// 每个选项的 `ConfigMeta` 给出——异构类型(int、long、bool、enum、秒数超时)
/// 无损编码进槽位。
pub struct RuntimeServerConfig {
  /// 槽位值数组,下标即 `ServerConfigType` 判别值。
  values: [AtomicI64; Self::TABLE_SIZE],
  /// 启动选项副本:仅为只读参数的回落格式化保留(对齐 C# `serverOptions`);
  /// 运行时可调值播种后一律经类型化访问器读取,保证 CONFIG SET 全局可见。
  options: RuntimeServerOptions,
  /// 持有方,更新动作经其触达后台任务生命周期。None 时仅落槽位、无生命周期副作用
  ///(对齐 C# 单测独立构造时的 null owner)。
  owner: Option<Arc<dyn ConfigUpdateOwner>>,
}

/// 静态元数据表(下标 == `ServerConfigType` 判别值)。非 runtime 成员保持默认
///(IsRuntime == false),由 bespoke CONFIG 代码处理而非本表。
static META: LazyLock<Box<[ConfigMeta]>> = LazyLock::new(RuntimeServerConfig::build_meta);

/// 参数名(含别名)→ 类型的静态查找表。
static NAME_LOOKUP: LazyLock<Vec<(&'static [u8], ServerConfigType)>> =
  LazyLock::new(RuntimeServerConfig::build_name_lookup);

/// 本表处理的全部类型(可设置 + 只读),供 CONFIG GET *。
static RUNTIME_TYPES: LazyLock<Vec<ServerConfigType>> =
  LazyLock::new(RuntimeServerConfig::build_runtime_types);

impl RuntimeServerConfig {
  /// 索引全部已声明 `ServerConfigType` 所需的槽位数
  ///(libs/server/Config/RuntimeServerConfig.cs:ComputeTableSize)。
  ///
  /// 取最大判别值 + 1,无需哨兵成员,枚举空洞亦可安全下标。
  #[inline]
  pub const fn compute_table_size() -> usize {
    (ServerConfigType::AofNullDevice as u16 + 1) as usize
  }

  const TABLE_SIZE: usize = Self::compute_table_size();

  /// libs/server/Config/RuntimeServerConfig.cs:RuntimeServerConfig(构造)。
  ///
  /// 创建以启动选项播种的运行时配置。`owner` 为持有方,更新动作经其执行
  /// 任务生命周期变更;独立构造(无持有服务器)传 None。
  pub fn new(options: RuntimeServerOptions, owner: Option<Arc<dyn ConfigUpdateOwner>>) -> Self {
    let config = Self {
      values: [const { AtomicI64::new(0) }; Self::TABLE_SIZE],
      options,
      owner,
    };
    config.init(&config.options);
    config
  }

  /// 以默认启动选项构造(对齐 `new(GarnetServerOptions)` 的字段默认值)。
  pub fn with_defaults() -> Self {
    Self::new(RuntimeServerOptions::default(), None)
  }

  /// 本表处理的全部配置类型
  ///(libs/server/Config/RuntimeServerConfig.cs:RuntimeTypes)。
  #[inline]
  pub fn runtime_types() -> &'static [ServerConfigType] {
    &RUNTIME_TYPES
  }

  /// 播种全部运行时槽位(libs/server/Config/RuntimeServerConfig.cs:Init)。
  fn init(&self, o: &RuntimeServerOptions) {
    let seed = |t: ServerConfigType, v: i64| {
      self.values[t as usize].store(v, Ordering::Release);
    };
    seed(
      ServerConfigType::ClusterNodeTimeout,
      i64::from(o.cluster_timeout),
    );
    seed(
      ServerConfigType::ReplicaSyncDelay,
      i64::from(o.replica_sync_delay_ms),
    );
    seed(
      ServerConfigType::AofReplayMaxLagBytes,
      i64::from(o.aof_replay_max_lag_bytes),
    );
    seed(
      ServerConfigType::AofTailWitnessFreq,
      i64::from(o.aof_tail_witness_freq_ms),
    );
    seed(
      ServerConfigType::AofSyncMaxLagBytes,
      o.aof_sync_max_lag_bytes,
    );
    seed(
      ServerConfigType::ReplDisklessSyncDelay,
      i64::from(o.replica_diskless_sync_delay),
    );
    seed(
      ServerConfigType::ReplAttachTimeout,
      Self::seconds_from_time_span(o.replica_attach_timeout_secs),
    );
    seed(
      ServerConfigType::ClusterReplicationReestablishmentTimeout,
      i64::from(o.cluster_replication_reestablishment_timeout),
    );
    seed(
      ServerConfigType::CompactionMaxSegments,
      i64::from(o.compaction_max_segments),
    );
    seed(
      ServerConfigType::CompactionForceDelete,
      i64::from(o.compaction_force_delete),
    );
    seed(
      ServerConfigType::CompactionType,
      i64::from(o.compaction_type as u8),
    );
    seed(
      ServerConfigType::SlowlogLogSlowerThan,
      i64::from(o.slow_log_threshold),
    );
    seed(
      ServerConfigType::ObjectScanCountLimit,
      i64::from(o.object_scan_count_limit),
    );
    seed(
      ServerConfigType::SgGet,
      i64::from(o.enable_scatter_gather_get),
    );
    seed(
      ServerConfigType::AofSizeLimitEnforceFrequency,
      i64::from(o.aof_size_limit_enforce_frequency_secs),
    );
    seed(
      ServerConfigType::AofCommitFreq,
      i64::from(o.commit_frequency_ms),
    );
    seed(
      ServerConfigType::ExpiredObjectCollectionFreq,
      i64::from(o.expired_object_collection_frequency_secs),
    );
    seed(
      ServerConfigType::ExpiredKeyDeletionScanFreq,
      i64::from(o.expired_key_deletion_scan_frequency_secs),
    );
  }

  /// libs/server/Config/RuntimeServerConfig.cs:BuildMeta
  ///
  /// 为每个 `ServerConfigType` 建立元数据(下标 == 判别值)。
  fn build_meta() -> Box<[ConfigMeta]> {
    let mut m = vec![ConfigMeta::EMPTY; Self::TABLE_SIZE];

    // 运行时可调选项登记(对齐 C# 局部函数 Set)。
    let set = |m: &mut [ConfigMeta],
               t: ServerConfigType,
               name: &'static str,
               kind: ConfigKind,
               min: i64,
               max: i64,
               enum_type: Option<EnumMeta>,
               time_unit: ConfigTimeUnit,
               update_action: Option<ConfigUpdateAction>| {
      if (kind & ConfigKind::ENUM) != ConfigKind::NONE {
        debug_assert!(
          Self::ensure_supported_enum(enum_type).is_ok(),
          "运行时配置选项声明的枚举类别不受支持"
        );
      }
      debug_assert!(Self::ensure_valid_kind(name, kind, time_unit).is_ok());
      m[t as usize] = ConfigMeta {
        name,
        kind,
        min,
        max,
        enum_type,
        is_runtime: true,
        read_only: false,
        time_unit,
        read_only_formatter: None,
        update_action,
      };
    };

    // 只读参数:经本表暴露于 CONFIG GET(含 GET *),但 CONFIG SET 拒绝——
    // 常量或物理参数(需重启)。取值由逐选项 formatter 直接读启动选项
    //(只读回落)计算,不占用运行时槽位。
    // 注意:slave-read-only 刻意不在表内:它是会话级取值(READWRITE/READONLY),
    // 由持有会话的 CONFIG GET 处理器直接处理。
    // libs/server/Config/RuntimeServerConfig.cs:SetReadOnly
    let set_read_only = |m: &mut [ConfigMeta],
                         t: ServerConfigType,
                         name: &'static str,
                         kind: ConfigKind,
                         formatter: fn(&RuntimeServerOptions) -> String,
                         time_unit: ConfigTimeUnit| {
      debug_assert!(Self::ensure_valid_kind(name, kind, time_unit).is_ok());
      m[t as usize] = ConfigMeta {
        name,
        kind,
        min: 0,
        max: 0,
        enum_type: None,
        is_runtime: true,
        read_only: true,
        time_unit,
        read_only_formatter: Some(formatter),
        update_action: None,
      };
    };

    set_read_only(
      &mut m,
      ServerConfigType::Timeout,
      "timeout",
      ConfigKind::INT32 | ConfigKind::SECONDS | ConfigKind::TIME_SPAN,
      |_| "0".into(),
      ConfigTimeUnit::Seconds,
    );
    set_read_only(
      &mut m,
      ServerConfigType::Save,
      "save",
      ConfigKind::STRING,
      |_| String::new(),
      ConfigTimeUnit::None,
    );
    set_read_only(
      &mut m,
      ServerConfigType::AppendOnly,
      "appendonly",
      ConfigKind::BOOL,
      |o| {
        if o.enable_aof {
          "yes".into()
        } else {
          "no".into()
        }
      },
      ConfigTimeUnit::None,
    );
    set_read_only(
      &mut m,
      ServerConfigType::Databases,
      "databases",
      ConfigKind::INT32,
      |o| o.max_databases.to_string(),
      ConfigTimeUnit::None,
    );

    // 直接从启动选项解析的只读非数值参数(文件路径、套接字、物理开关)。
    // 无运行时槽位,纯为 CONFIG GET 暴露。
    set_read_only(
      &mut m,
      ServerConfigType::Dir,
      "dir",
      ConfigKind::STRING,
      |o| o.checkpoint_base_directory.clone(),
      ConfigTimeUnit::None,
    );
    set_read_only(
      &mut m,
      ServerConfigType::Logdir,
      "logdir",
      ConfigKind::STRING,
      |o| o.log_dir.clone().unwrap_or_default(),
      ConfigTimeUnit::None,
    );
    set_read_only(
      &mut m,
      ServerConfigType::UnixSocket,
      "unixsocket",
      ConfigKind::STRING,
      |o| o.unix_socket_path.clone().unwrap_or_default(),
      ConfigTimeUnit::None,
    );
    set_read_only(
      &mut m,
      ServerConfigType::ClusterEnabled,
      "cluster-enabled",
      ConfigKind::BOOL,
      |o| {
        if o.enable_cluster {
          "yes".into()
        } else {
          "no".into()
        }
      },
      ConfigTimeUnit::None,
    );

    // 直接从启动选项解析的只读 AOF 参数。描述物理 AOF 布局或仅启动期开关,
    // 变更需重启,故 CONFIG SET 拒绝;无运行时槽位,纯为 CONFIG GET 暴露。
    set_read_only(
      &mut m,
      ServerConfigType::AofMemory,
      "aof-memory",
      ConfigKind::STRING,
      |o| o.aof_memory_size.clone().unwrap_or_default(),
      ConfigTimeUnit::None,
    );
    set_read_only(
      &mut m,
      ServerConfigType::AofPageSize,
      "aof-page-size",
      ConfigKind::STRING,
      |o| o.aof_page_size.clone().unwrap_or_default(),
      ConfigTimeUnit::None,
    );
    set_read_only(
      &mut m,
      ServerConfigType::AofSegmentSize,
      "aof-segment-size",
      ConfigKind::STRING,
      |o| o.aof_segment_size.clone().unwrap_or_default(),
      ConfigTimeUnit::None,
    );
    set_read_only(
      &mut m,
      ServerConfigType::AofPhysicalSublogCount,
      "aof-physical-sublog-count",
      ConfigKind::INT32,
      |o| o.aof_physical_sublog_count.to_string(),
      ConfigTimeUnit::None,
    );
    set_read_only(
      &mut m,
      ServerConfigType::AofReplayTaskCount,
      "aof-replay-task-count",
      ConfigKind::INT32,
      |o| o.aof_replay_task_count.to_string(),
      ConfigTimeUnit::None,
    );
    set_read_only(
      &mut m,
      ServerConfigType::AofCommitWait,
      "aof-commit-wait",
      ConfigKind::BOOL,
      |o| {
        if o.wait_for_commit {
          "yes".into()
        } else {
          "no".into()
        }
      },
      ConfigTimeUnit::None,
    );
    set_read_only(
      &mut m,
      ServerConfigType::AofSizeLimit,
      "aof-size-limit",
      ConfigKind::STRING,
      |o| o.aof_size_limit.clone().unwrap_or_default(),
      ConfigTimeUnit::None,
    );
    set_read_only(
      &mut m,
      ServerConfigType::FastAofTruncate,
      "fast-aof-truncate",
      ConfigKind::BOOL,
      |o| {
        if o.fast_aof_truncate {
          "yes".into()
        } else {
          "no".into()
        }
      },
      ConfigTimeUnit::None,
    );
    set_read_only(
      &mut m,
      ServerConfigType::AofNullDevice,
      "aof-null-device",
      ConfigKind::BOOL,
      |o| {
        if o.use_aof_null_device {
          "yes".into()
        } else {
          "no".into()
        }
      },
      ConfigTimeUnit::None,
    );

    set(
      &mut m,
      ServerConfigType::ClusterNodeTimeout,
      "cluster-node-timeout",
      ConfigKind::INT32 | ConfigKind::SECONDS | ConfigKind::TIME_SPAN,
      0,
      i64::from(i32::MAX),
      None,
      ConfigTimeUnit::Seconds,
      None,
    );
    set(
      &mut m,
      ServerConfigType::ReplicaSyncDelay,
      "replica-sync-delay",
      ConfigKind::INT32 | ConfigKind::MILLISECONDS | ConfigKind::SECONDS | ConfigKind::TIME_SPAN,
      0,
      i64::from(i32::MAX),
      None,
      ConfigTimeUnit::Milliseconds,
      None,
    );
    set(
      &mut m,
      ServerConfigType::AofReplayMaxLagBytes,
      "aof-replay-max-lag-bytes",
      ConfigKind::INT32,
      -1,
      i64::from(i32::MAX),
      None,
      ConfigTimeUnit::None,
      None,
    );
    // 主侧复制背压预算(整日志字节数)。每个数据库常驻构造的 AofBackpressure
    // 读取裸字段,故 ApplyAofSyncMaxLagUpdate 将 CONFIG SET 直接推入活跃闸门
    // ——无重启、无生命周期任务。
    set(
      &mut m,
      ServerConfigType::AofSyncMaxLagBytes,
      "aof-sync-max-lag-bytes",
      ConfigKind::INT64,
      -1,
      i64::MAX,
      None,
      ConfigTimeUnit::None,
      Some(Self::apply_aof_sync_max_lag_update),
    );
    set(
      &mut m,
      ServerConfigType::AofTailWitnessFreq,
      "aof-tail-witness-freq",
      ConfigKind::INT32 | ConfigKind::MILLISECONDS | ConfigKind::SECONDS | ConfigKind::TIME_SPAN,
      0,
      i64::from(i32::MAX),
      None,
      ConfigTimeUnit::Milliseconds,
      None,
    );
    set(
      &mut m,
      ServerConfigType::ReplDisklessSyncDelay,
      "repl-diskless-sync-delay",
      ConfigKind::INT32 | ConfigKind::SECONDS | ConfigKind::TIME_SPAN,
      0,
      i64::from(i32::MAX),
      None,
      ConfigTimeUnit::Seconds,
      None,
    );
    set(
      &mut m,
      ServerConfigType::ReplAttachTimeout,
      "repl-attach-timeout",
      ConfigKind::INT32 | ConfigKind::SECONDS | ConfigKind::TIME_SPAN,
      0,
      i64::from(i32::MAX),
      None,
      ConfigTimeUnit::Seconds,
      None,
    );
    set(
      &mut m,
      ServerConfigType::ClusterReplicationReestablishmentTimeout,
      "cluster-replication-reestablishment-timeout",
      ConfigKind::INT32 | ConfigKind::SECONDS | ConfigKind::TIME_SPAN,
      0,
      i64::from(i32::MAX),
      None,
      ConfigTimeUnit::Seconds,
      None,
    );
    set(
      &mut m,
      ServerConfigType::CompactionMaxSegments,
      "compaction-max-segments",
      ConfigKind::INT32,
      0,
      i64::from(i32::MAX),
      None,
      ConfigTimeUnit::None,
      None,
    );
    set(
      &mut m,
      ServerConfigType::CompactionForceDelete,
      "compaction-force-delete",
      ConfigKind::BOOL,
      0,
      1,
      None,
      ConfigTimeUnit::None,
      None,
    );
    set(
      &mut m,
      ServerConfigType::CompactionType,
      "compaction-type",
      ConfigKind::ENUM,
      0,
      0,
      Some(EnumMeta::LogCompactionType),
      ConfigTimeUnit::None,
      None,
    );
    set(
      &mut m,
      ServerConfigType::SlowlogLogSlowerThan,
      "slowlog-log-slower-than",
      ConfigKind::INT32 | ConfigKind::MICROSECONDS | ConfigKind::TIME_SPAN,
      0,
      i64::from(i32::MAX),
      None,
      ConfigTimeUnit::Microseconds,
      None,
    );
    set(
      &mut m,
      ServerConfigType::ObjectScanCountLimit,
      "object-scan-count-limit",
      ConfigKind::INT32,
      0,
      i64::from(i32::MAX),
      None,
      ConfigTimeUnit::None,
      None,
    );
    set(
      &mut m,
      ServerConfigType::SgGet,
      "sg-get",
      ConfigKind::BOOL,
      0,
      1,
      None,
      ConfigTimeUnit::None,
      None,
    );

    // AOF 大小上限执行频率(秒):后台 checkpoint 执行任务每轮重读,
    // 故 CONFIG SET 对运行中任务即时生效。
    set(
      &mut m,
      ServerConfigType::AofSizeLimitEnforceFrequency,
      "aof-size-limit-enforce-frequency",
      ConfigKind::INT32,
      0,
      i64::from(i32::MAX),
      None,
      ConfigTimeUnit::None,
      None,
    );

    // 变更需经 UpdateAction 重启 / 停止所属任务的后台任务频率:任务在启动时
    // 捕获自身间隔,运行期变更需 kill+restart 而非重读。
    //
    // aof-commit-freq(ms):-1 = 手动提交(无周期任务),> 0 = 周期提交间隔。
    // 取值 0(逐操作自动提交)在启动时固化进 AOF 日志,无法在活跃日志上切换;
    // ApplyCommitFrequencyUpdate 拒绝改为 0,也拒绝在启动即为 0 时的任何变更。
    set(
      &mut m,
      ServerConfigType::AofCommitFreq,
      "aof-commit-freq",
      ConfigKind::INT32,
      -1,
      i64::from(i32::MAX),
      None,
      ConfigTimeUnit::None,
      Some(Self::apply_commit_frequency_update),
    );
    // expired-object-collection-freq(秒):<= 0 = 禁用(无任务),> 0 = 收集间隔。
    set(
      &mut m,
      ServerConfigType::ExpiredObjectCollectionFreq,
      "expired-object-collection-freq",
      ConfigKind::INT32,
      0,
      i64::from(i32::MAX),
      None,
      ConfigTimeUnit::None,
      Some(Self::apply_expired_object_collection_update),
    );
    // expired-key-deletion-scan-freq(秒):<= 0 = 禁用(无任务,允许按需 EXPDELSCAN),
    // > 0 = 后台扫描间隔。
    set(
      &mut m,
      ServerConfigType::ExpiredKeyDeletionScanFreq,
      "expired-key-deletion-scan-freq",
      ConfigKind::INT32,
      -1,
      i64::from(i32::MAX),
      None,
      ConfigTimeUnit::None,
      Some(Self::apply_expired_key_deletion_update),
    );

    m.into()
  }

  /// libs/server/Config/RuntimeServerConfig.cs:BuildNameLookup
  ///
  /// 参数名(含别名)→ 类型的查找表。规模仅数十项,查找走线性扫描 +
  /// ASCII 大小写不敏感比较,零哈希、零分配。
  fn build_name_lookup() -> Vec<(&'static [u8], ServerConfigType)> {
    let mut d = Vec::with_capacity(Self::TABLE_SIZE + 1);
    for (i, meta) in META.iter().enumerate() {
      if meta.is_runtime {
        d.push((meta.name.as_bytes(), ServerConfigType::ALL_MEMBERS[i]));
      }
    }

    // cluster-node-timeout 的 Redis / CLI 兼容别名。
    d.push((b"cluster-timeout", ServerConfigType::ClusterNodeTimeout));
    d
  }

  /// libs/server/Config/RuntimeServerConfig.cs:BuildRuntimeTypes
  ///
  /// 本表处理的全部类型(settable + read-only),供 CONFIG GET *。
  fn build_runtime_types() -> Vec<ServerConfigType> {
    META
      .iter()
      .enumerate()
      .filter(|(_, meta)| meta.is_runtime)
      .map(|(i, _)| ServerConfigType::ALL_MEMBERS[i])
      .collect()
  }

  /// libs/server/Config/RuntimeServerConfig.cs:GetInt
  ///
  /// 以原生单位的 32 位整数读取当前值。
  #[inline]
  pub fn get_int(&self, type_: ServerConfigType) -> i32 {
    Self::assert_kind(type_, ConfigKind::INT32);
    self.values[type_ as usize].load(Ordering::Acquire) as i32
  }

  /// libs/server/Config/RuntimeServerConfig.cs:GetLong
  ///
  /// 以原生单位的 64 位整数读取当前值。
  #[inline]
  pub fn get_long(&self, type_: ServerConfigType) -> i64 {
    Self::assert_kind(type_, ConfigKind::INT64);
    self.values[type_ as usize].load(Ordering::Acquire)
  }

  /// libs/server/Config/RuntimeServerConfig.cs:GetBool
  ///
  /// 以布尔读取当前值。
  #[inline]
  pub fn get_bool(&self, type_: ServerConfigType) -> bool {
    Self::assert_kind(type_, ConfigKind::BOOL);
    self.values[type_ as usize].load(Ordering::Acquire) != 0
  }

  /// libs/server/Config/RuntimeServerConfig.cs:GetMicroseconds
  ///
  /// 以微秒读取当前值。
  #[inline]
  pub fn get_microseconds(&self, type_: ServerConfigType) -> i64 {
    self.convert_duration(
      type_,
      ConfigKind::MICROSECONDS,
      ConfigTimeUnit::Microseconds,
    )
  }

  /// libs/server/Config/RuntimeServerConfig.cs:GetMilliseconds
  ///
  /// 以毫秒读取当前值。
  #[inline]
  pub fn get_milliseconds(&self, type_: ServerConfigType) -> i64 {
    self.convert_duration(
      type_,
      ConfigKind::MILLISECONDS,
      ConfigTimeUnit::Milliseconds,
    )
  }

  /// libs/server/Config/RuntimeServerConfig.cs:GetSeconds
  ///
  /// 以秒读取当前值。
  #[inline]
  pub fn get_seconds(&self, type_: ServerConfigType) -> i64 {
    self.convert_duration(type_, ConfigKind::SECONDS, ConfigTimeUnit::Seconds)
  }

  /// libs/server/Config/RuntimeServerConfig.cs:GetTimeSpan
  ///
  /// 以时长读取当前值。非正存储值按“无限超时”解释并返回 `None`
  ///(对齐 `Timeout.InfiniteTimeSpan`,遵循全仓“非正即无限”的超时约定)。
  /// 以 0 表示“无延迟”(如 replica-sync-delay)而非“无限”的选项,
  /// 必须经 `get_milliseconds` / `get_seconds` 读取,不得走本方法。
  #[inline]
  pub fn get_time_span(&self, type_: ServerConfigType) -> Option<Duration> {
    Self::assert_kind(type_, ConfigKind::TIME_SPAN);

    let meta = &META[type_ as usize];
    let raw = self.values[type_ as usize].load(Ordering::Acquire);
    if raw <= 0 {
      return None;
    }

    Some(match meta.time_unit {
      ConfigTimeUnit::Microseconds => Duration::from_micros(raw as u64),
      ConfigTimeUnit::Milliseconds => Duration::from_millis(raw as u64),
      _ => Duration::from_secs(raw as u64),
    })
  }

  /// libs/server/Config/RuntimeServerConfig.cs:GetEnum
  ///
  /// 以声明的枚举成员读取当前值。表内唯一枚举选项为 compaction-type
  ///(LogCompactionType),故以具体类型承接 C# 的泛型 `GetEnum<TEnum>`。
  ///
  /// 槽位值越界或非已声明成员时返回 `Err`。实践中不可达:全部写入经
  /// `try_set`(拒绝未声明值);与 C# 的仅调试断言不同,此检查保留于
  /// release,损坏槽位表现为错误而非越界枚举流入服务器。
  #[inline]
  pub fn get_enum(&self, type_: ServerConfigType) -> Result<LogCompactionType, ConfigError> {
    Self::assert_kind(type_, ConfigKind::ENUM);

    // 槽位保存的是加宽到 64 位的底层值。
    let raw = self.values[type_ as usize].load(Ordering::Acquire);

    // 校验边界与成员声明,并安全收窄。
    LogCompactionType::from_raw(raw).ok_or(ConfigError::EnumOutOfRange { raw })
  }

  /// libs/server/Config/RuntimeServerConfig.cs:TrySet
  ///
  /// 校验 `value`,合法则更新 `type_` 的槽位;拒绝时返回 `Err`("ERR " 前缀
  /// 的拒绝原因),槽位保持不变。
  pub fn try_set(&self, type_: ServerConfigType, value: &str) -> Result<(), ConfigError> {
    let meta = &META[type_ as usize];
    if meta.read_only {
      return Err(ConfigError::ReadOnly {
        name: meta.name.into(),
      });
    }

    let parsed: i64 = match meta.kind & ConfigKind::STORAGE_MASK {
      ConfigKind::INT32 => {
        let Ok(i32_value) = value.parse::<i32>() else {
          return Err(ConfigError::InvalidInteger {
            name: meta.name.into(),
          });
        };
        let v = i64::from(i32_value);
        if v < meta.min || v > meta.max {
          return Err(ConfigError::OutOfRange {
            name: meta.name.into(),
            min: meta.min,
            max: meta.max,
          });
        }
        v
      }
      ConfigKind::INT64 => {
        let Ok(v) = value.parse::<i64>() else {
          return Err(ConfigError::InvalidInteger {
            name: meta.name.into(),
          });
        };
        if v < meta.min || v > meta.max {
          return Err(ConfigError::OutOfRange {
            name: meta.name.into(),
            min: meta.min,
            max: meta.max,
          });
        }
        v
      }
      ConfigKind::BOOL => {
        if value.eq_ignore_ascii_case("yes") || value.eq_ignore_ascii_case("true") || value == "1" {
          1
        } else if value.eq_ignore_ascii_case("no")
          || value.eq_ignore_ascii_case("false")
          || value == "0"
        {
          0
        } else {
          return Err(ConfigError::InvalidBool {
            name: meta.name.into(),
          });
        }
      }
      ConfigKind::ENUM => {
        let Some(v) = meta.enum_type.and_then(|e| e.try_parse_to_long(value)) else {
          return Err(ConfigError::InvalidEnum {
            name: meta.name.into(),
            value: value.into(),
          });
        };
        v
      }
      _ => {
        return Err(ConfigError::NotRuntimeAdjustable {
          name: meta.name.into(),
        });
      }
    };

    // 先发布新值,使更新动作重启的任务能观察到它,再执行动作;
    // 动作拒绝则回滚槽位,保持选项不变。
    let old_value = self.values[type_ as usize].load(Ordering::Acquire);
    self.values[type_ as usize].store(parsed, Ordering::Release);

    if let Some(Err(error)) = meta
      .update_action
      .map(|action| action(self, old_value, parsed))
    {
      self.values[type_ as usize].store(old_value, Ordering::Release);
      return Err(error);
    }

    Ok(())
  }

  /// libs/server/Config/RuntimeServerConfig.cs:ApplyCommitFrequencyUpdate
  ///
  /// 在周期 AOF 提交任务上落实 aof-commit-freq 变更。取值 0(逐操作自动提交)
  /// 在构造时固化进 AOF 日志,无法在活跃日志上切换,故改 0——或启动即为 0 时
  /// 的任何变更——均被拒绝。安全的 {-1, >0} 转换经 owner 重启(或停止)提交
  /// 任务以采纳新间隔。
  fn apply_commit_frequency_update(
    &self,
    _old_value: i64,
    new_value: i64,
  ) -> Result<(), ConfigError> {
    if new_value == 0 {
      return Err(ConfigError::CommitFreqZero);
    }
    if self.options.commit_frequency_ms == 0 {
      return Err(ConfigError::CommitFreqAutoCommitStart);
    }
    if let Some(owner) = &self.owner {
      owner.reconcile_commit_task();
    }
    Ok(())
  }

  /// libs/server/Config/RuntimeServerConfig.cs:ApplyAofSyncMaxLagUpdate
  ///
  /// 将新的整日志预算推入每个数据库常驻构造的主侧 AofBackpressure。闸门读取
  /// 裸字段,故重调预算——或从禁用状态启用——无需重启即生效,不涉生命周期任务。
  fn apply_aof_sync_max_lag_update(
    &self,
    _old_value: i64,
    new_value: i64,
  ) -> Result<(), ConfigError> {
    if let Some(owner) = &self.owner {
      owner.apply_aof_sync_max_lag_bytes(new_value);
    }
    Ok(())
  }

  /// libs/server/Config/RuntimeServerConfig.cs:ApplyExpiredObjectCollectionUpdate
  ///
  /// 重启 / 停止收集任务以采纳新间隔(禁用时停止),
  /// 落实 expired-object-collection-freq 变更。
  fn apply_expired_object_collection_update(
    &self,
    _old_value: i64,
    _new_value: i64,
  ) -> Result<(), ConfigError> {
    if let Some(owner) = &self.owner {
      owner.reconcile_object_collect_task();
    }
    Ok(())
  }

  /// libs/server/Config/RuntimeServerConfig.cs:ApplyExpiredKeyDeletionUpdate
  ///
  /// 重启 / 停止扫描任务以采纳新间隔(禁用时停止并恢复按需 EXPDELSCAN),
  /// 落实 expired-key-deletion-scan-freq 变更。
  fn apply_expired_key_deletion_update(
    &self,
    _old_value: i64,
    _new_value: i64,
  ) -> Result<(), ConfigError> {
    if let Some(owner) = &self.owner {
      owner.reconcile_expired_key_deletion_task();
    }
    Ok(())
  }

  /// libs/server/Config/RuntimeServerConfig.cs:Name
  ///
  /// `type_` 的规范线上参数名。
  #[inline]
  pub fn name(type_: ServerConfigType) -> &'static str {
    META[type_ as usize].name
  }

  /// libs/server/Config/RuntimeServerConfig.cs:TryGetType
  ///
  /// 将参数名(含别名、ASCII 大小写不敏感)解析为本表处理的配置类型。
  #[inline]
  pub fn try_get_type(name: &[u8]) -> Option<ServerConfigType> {
    NAME_LOOKUP
      .iter()
      .find(|(key, _)| ConfigNameComparer::equals(name, key))
      .map(|(_, t)| *t)
  }

  /// CLI/CONFIG 面以秒表达这些超时,<= 0 视为无限超时(存 0)。
  ///
  /// C# 入参为 `TimeSpan`(含 InfiniteTimeSpan 哨兵);Rust 侧选项以秒整数
  /// 承接(见 `RuntimeServerOptions.replica_attach_timeout_secs`),
  /// 负值即 C# 的负 TimeSpan / 无限。
  ///
  ///(libs/server/Config/RuntimeServerConfig.cs:SecondsFromTimeSpan)
  #[inline]
  fn seconds_from_time_span(ts_secs: i64) -> i64 {
    if ts_secs <= 0 { 0 } else { ts_secs }
  }

  /// libs/server/Config/RuntimeServerConfig.cs:AssertKind
  ///
  /// 仅调试:请求的读取视图必须在选项声明内。
  #[inline]
  fn assert_kind(type_: ServerConfigType, requested_kind: ConfigKind) {
    debug_assert!(
      (META[type_ as usize].kind & requested_kind) != ConfigKind::NONE,
      "配置 {type_:?} 声明为 {:?},不能按 {requested_kind:?} 读取",
      META[type_ as usize].kind
    );
  }

  /// libs/server/Config/RuntimeServerConfig.cs:ConvertDuration
  ///
  /// 读取时长类槽位并从存储单位换算到请求单位。向粗单位换算截断;
  /// 需要全精度时用 `get_time_span`。
  #[inline]
  fn convert_duration(
    &self,
    type_: ServerConfigType,
    requested_kind: ConfigKind,
    requested_unit: ConfigTimeUnit,
  ) -> i64 {
    Self::assert_kind(type_, requested_kind);

    let meta = &META[type_ as usize];
    let raw = self.values[type_ as usize].load(Ordering::Acquire);
    if meta.time_unit == requested_unit {
      return raw;
    }

    let stored_micros = match meta.time_unit {
      ConfigTimeUnit::Microseconds => raw,
      ConfigTimeUnit::Milliseconds => raw * 1000,
      _ => raw * 1_000_000,
    };

    match requested_unit {
      ConfigTimeUnit::Microseconds => stored_micros,
      ConfigTimeUnit::Milliseconds => stored_micros / 1000,
      _ => stored_micros / 1_000_000,
    }
  }

  /// libs/server/Config/RuntimeServerConfig.cs:EnsureValidKind
  ///
  /// 元数据静态校验:恰好一个 storage 类别;duration 视图与时间单位互相绑定。
  /// 建表处以 debug_assert 调用(全部条目静态可见,正确性由编译期 +
  /// 单元测试共同保证),错误语义与 C# 的 InvalidOperationException 对齐。
  fn ensure_valid_kind(
    name: &'static str,
    kind: ConfigKind,
    time_unit: ConfigTimeUnit,
  ) -> Result<(), &'static str> {
    let storage_kind = kind & ConfigKind::STORAGE_MASK;
    let single = storage_kind.bits() != 0 && (storage_kind.bits() & (storage_kind.bits() - 1)) == 0;
    if !single {
      return Err("必须声明恰好一个 storage 类别");
    }

    if (kind & ConfigKind::DURATION_MASK) != ConfigKind::NONE && time_unit == ConfigTimeUnit::None {
      let _ = name;
      return Err("声明了 duration 视图但未声明时间单位");
    }

    if (kind & ConfigKind::DURATION_MASK) == ConfigKind::NONE && time_unit != ConfigTimeUnit::None {
      let _ = name;
      return Err("声明了时间单位但没有 duration 视图");
    }

    Ok(())
  }

  /// libs/server/Config/RuntimeServerConfig.cs:EnsureSupportedEnum
  ///
  /// 元数据静态校验:ENUM 选项必须声明受支持的枚举类别。C# 侧校验底层
  /// 整型可无损加宽进 64 位槽位;Rust 侧枚举一律整型判别值,仅需保证
  /// 元数据存在。
  fn ensure_supported_enum(enum_type: Option<EnumMeta>) -> Result<(), &'static str> {
    if enum_type.is_none() {
      return Err("运行时配置选项未声明枚举类别");
    }
    Ok(())
  }

  /// libs/server/Config/RuntimeServerConfig.cs:RespFormat
  ///
  /// 以 RESP 字符串表示读取当前值。
  pub fn resp_format(&self, type_: ServerConfigType) -> String {
    let meta = &META[type_ as usize];
    if meta.read_only {
      // 只读回落:取值直接来自启动选项。
      return meta
        .read_only_formatter
        .map_or_else(String::new, |f| f(&self.options));
    }

    let raw = self.values[type_ as usize].load(Ordering::Acquire);
    match meta.kind & ConfigKind::STORAGE_MASK {
      ConfigKind::INT32 => (raw as i32).to_string(),
      ConfigKind::INT64 => raw.to_string(),
      ConfigKind::BOOL => if raw != 0 { "yes" } else { "no" }.into(),
      ConfigKind::ENUM => meta
        .enum_type
        .and_then(|e| e.name_of(raw))
        .map_or_else(|| raw.to_string(), str::to_owned),
      _ => raw.to_string(),
    }
  }
}

#[cfg(test)]
mod tests {
  use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};

  use super::*;
  use crate::config::error::ConfigError;

  /// 记录更新动作触达情况的 owner 桩。
  struct TestOwner {
    commit: AtomicUsize,
    collect: AtomicUsize,
    expiry: AtomicUsize,
    lag: AtomicI64,
  }

  impl TestOwner {
    fn new() -> Arc<Self> {
      Arc::new(Self {
        commit: AtomicUsize::new(0),
        collect: AtomicUsize::new(0),
        expiry: AtomicUsize::new(0),
        lag: AtomicI64::new(0),
      })
    }
  }

  impl ConfigUpdateOwner for TestOwner {
    fn reconcile_commit_task(&self) {
      self.commit.fetch_add(1, AtomicOrdering::Relaxed);
    }
    fn reconcile_object_collect_task(&self) {
      self.collect.fetch_add(1, AtomicOrdering::Relaxed);
    }
    fn reconcile_expired_key_deletion_task(&self) {
      self.expiry.fetch_add(1, AtomicOrdering::Relaxed);
    }
    fn apply_aof_sync_max_lag_bytes(&self, max_lag_bytes: i64) {
      self.lag.store(max_lag_bytes, AtomicOrdering::Relaxed);
    }
  }

  #[test]
  fn table_size() {
    assert_eq!(RuntimeServerConfig::compute_table_size(), 38);
    assert_eq!(META.len(), 38);
  }

  #[test]
  fn meta_static_validity() {
    // 每个登记条目均通过静态校验(对齐 C# 建表期的 EnsureValidKind/EnsureSupportedEnum)。
    for (i, meta) in META.iter().enumerate() {
      if !meta.is_runtime {
        assert_eq!(meta.name, "");
        continue;
      }
      assert!(
        RuntimeServerConfig::ensure_valid_kind(meta.name, meta.kind, meta.time_unit).is_ok(),
        "槽位 {i} 元数据非法"
      );
      if (meta.kind & ConfigKind::ENUM) != ConfigKind::NONE {
        assert!(RuntimeServerConfig::ensure_supported_enum(meta.enum_type).is_ok());
      }
    }
  }

  #[test]
  fn name_lookup_contains_alias_and_case_insensitive() {
    assert_eq!(
      RuntimeServerConfig::try_get_type(b"cluster-node-timeout"),
      Some(ServerConfigType::ClusterNodeTimeout)
    );
    assert_eq!(
      RuntimeServerConfig::try_get_type(b"CLUSTER-TIMEOUT"),
      Some(ServerConfigType::ClusterNodeTimeout)
    );
    assert_eq!(
      RuntimeServerConfig::try_get_type(b"slowlog-log-slower-than"),
      Some(ServerConfigType::SlowlogLogSlowerThan)
    );
    assert_eq!(RuntimeServerConfig::try_get_type(b"nonexistent"), None);
    assert_eq!(RuntimeServerConfig::name(ServerConfigType::SgGet), "sg-get");
  }

  #[test]
  fn runtime_types_cover_settable_and_readonly() {
    let types = RuntimeServerConfig::runtime_types();
    assert!(!types.contains(&ServerConfigType::None));
    assert!(!types.contains(&ServerConfigType::SlaveReadOnly));
    assert!(types.contains(&ServerConfigType::ClusterNodeTimeout));
    assert!(types.contains(&ServerConfigType::Dir));
    assert!(types.contains(&ServerConfigType::AofNullDevice));
  }

  #[test]
  fn init_seeds_slots_from_options() {
    let config = RuntimeServerConfig::with_defaults();
    assert_eq!(config.get_int(ServerConfigType::ClusterNodeTimeout), 60);
    assert_eq!(config.get_int(ServerConfigType::ReplicaSyncDelay), 5);
    assert_eq!(config.get_long(ServerConfigType::AofSyncMaxLagBytes), -1);
    assert_eq!(config.get_int(ServerConfigType::AofReplayMaxLagBytes), -1);
    assert!(!config.get_bool(ServerConfigType::CompactionForceDelete));
    assert!(config.get_bool(ServerConfigType::SgGet));
    assert_eq!(
      config.get_enum(ServerConfigType::CompactionType),
      Ok(LogCompactionType::None)
    );
    // ReplicaAttachTimeout 60s -> 60(秒);负值/无限归 0。
    assert_eq!(config.get_int(ServerConfigType::ReplAttachTimeout), 60);
    assert_eq!(
      config.get_int(ServerConfigType::ExpiredKeyDeletionScanFreq),
      -1
    );
  }

  #[test]
  fn duration_unit_conversions() {
    let config = RuntimeServerConfig::with_defaults();
    // slowlog-log-slower-than 存微秒(声明 MICROSECONDS 视图)。
    assert_eq!(
      config.get_microseconds(ServerConfigType::SlowlogLogSlowerThan),
      0
    );
    // replica-sync-delay 存毫秒(声明 MILLISECONDS/SECONDS 视图,无 MICROSECONDS)。
    assert_eq!(
      config.get_milliseconds(ServerConfigType::ReplicaSyncDelay),
      5
    );
    assert_eq!(config.get_seconds(ServerConfigType::ReplicaSyncDelay), 0);
    assert_eq!(config.get_seconds(ServerConfigType::ClusterNodeTimeout), 60);
    // aof-tail-witness-freq 存毫秒。
    assert_eq!(
      config.get_milliseconds(ServerConfigType::AofTailWitnessFreq),
      100
    );
  }

  #[test]
  fn time_span_non_positive_means_infinite() {
    let config = RuntimeServerConfig::with_defaults();
    assert_eq!(
      config.get_time_span(ServerConfigType::ClusterNodeTimeout),
      Some(Duration::from_secs(60))
    );
    // 0 = 无限超时(下界 0,负值被 CONFIG SET 拒绝)。
    assert_eq!(
      config.try_set(ServerConfigType::ClusterNodeTimeout, "0"),
      Ok(())
    );
    assert_eq!(
      config.get_time_span(ServerConfigType::ClusterNodeTimeout),
      None
    );
  }

  #[test]
  fn try_set_int_range_and_errors() {
    let config = RuntimeServerConfig::with_defaults();
    assert_eq!(
      config.try_set(ServerConfigType::ObjectScanCountLimit, "2000"),
      Ok(())
    );
    assert_eq!(config.get_int(ServerConfigType::ObjectScanCountLimit), 2000);

    assert_eq!(
      config.try_set(ServerConfigType::ObjectScanCountLimit, "abc"),
      Err(ConfigError::InvalidInteger {
        name: "object-scan-count-limit".into()
      })
    );
    assert_eq!(
      config.try_set(ServerConfigType::ObjectScanCountLimit, "-1"),
      Err(ConfigError::OutOfRange {
        name: "object-scan-count-limit".into(),
        min: 0,
        max: i64::from(i32::MAX)
      })
    );
    // 拒绝后槽位不变。
    assert_eq!(config.get_int(ServerConfigType::ObjectScanCountLimit), 2000);

    // Int32 负下界(-1 合法)。
    assert_eq!(
      config.try_set(ServerConfigType::AofReplayMaxLagBytes, "-1"),
      Ok(())
    );
    assert_eq!(
      config.try_set(ServerConfigType::AofReplayMaxLagBytes, "-2"),
      Err(ConfigError::OutOfRange {
        name: "aof-replay-max-lag-bytes".into(),
        min: -1,
        max: i64::from(i32::MAX)
      })
    );
  }

  #[test]
  fn try_set_bool_forms() {
    let config = RuntimeServerConfig::with_defaults();
    for yes in ["yes", "YES", "true", "1"] {
      assert_eq!(config.try_set(ServerConfigType::SgGet, yes), Ok(()));
      assert!(config.get_bool(ServerConfigType::SgGet));
    }
    for no in ["no", "False", "0"] {
      assert_eq!(config.try_set(ServerConfigType::SgGet, no), Ok(()));
      assert!(!config.get_bool(ServerConfigType::SgGet));
    }
    assert!(matches!(
      config.try_set(ServerConfigType::SgGet, "maybe"),
      Err(ConfigError::InvalidBool { .. })
    ));
  }

  #[test]
  fn try_set_enum_by_name_and_number() {
    let config = RuntimeServerConfig::with_defaults();
    assert_eq!(
      config.try_set(ServerConfigType::CompactionType, "lookup"),
      Ok(())
    );
    assert_eq!(
      config.get_enum(ServerConfigType::CompactionType),
      Ok(LogCompactionType::Lookup)
    );
    assert_eq!(
      config.try_set(ServerConfigType::CompactionType, "3"),
      Ok(())
    );
    assert_eq!(
      config.get_enum(ServerConfigType::CompactionType),
      Ok(LogCompactionType::Scan)
    );
    // 数值越界/未声明成员与未知名字均拒绝。
    assert!(matches!(
      config.try_set(ServerConfigType::CompactionType, "9"),
      Err(ConfigError::InvalidEnum { .. })
    ));
    assert!(matches!(
      config.try_set(ServerConfigType::CompactionType, "bogus"),
      Err(ConfigError::InvalidEnum { .. })
    ));
  }

  #[test]
  fn read_only_rejects_set_and_falls_through_options() {
    let config = RuntimeServerConfig::with_defaults();
    assert_eq!(
      config.try_set(ServerConfigType::AppendOnly, "yes"),
      Err(ConfigError::ReadOnly {
        name: "appendonly".into()
      })
    );
    assert_eq!(config.resp_format(ServerConfigType::AppendOnly), "no");
    assert_eq!(config.resp_format(ServerConfigType::Timeout), "0");
    assert_eq!(config.resp_format(ServerConfigType::Save), "");
    assert_eq!(config.resp_format(ServerConfigType::Databases), "16");
    assert_eq!(config.resp_format(ServerConfigType::ClusterEnabled), "no");
    assert_eq!(config.resp_format(ServerConfigType::AofMemory), "128m");
    assert_eq!(
      config.resp_format(ServerConfigType::AofPhysicalSublogCount),
      "1"
    );
    assert_eq!(config.resp_format(ServerConfigType::UnixSocket), "");
  }

  #[test]
  fn update_actions_invoke_owner_and_rollback_on_reject() {
    let owner = TestOwner::new();
    // 启动即周期提交(-1 手动基线),aof-commit-freq 才可运行期变更。
    let options = RuntimeServerOptions {
      commit_frequency_ms: -1,
      ..RuntimeServerOptions::default()
    };
    let config = RuntimeServerConfig::new(options, Some(owner.clone()));

    // aof-commit-freq:-1 -> 5000,触发 commit 任务 reconcile。
    assert_eq!(
      config.try_set(ServerConfigType::AofCommitFreq, "5000"),
      Ok(())
    );
    assert_eq!(config.get_int(ServerConfigType::AofCommitFreq), 5000);
    assert_eq!(owner.commit.load(AtomicOrdering::Relaxed), 1);

    // 改 0 被拒绝且回滚。
    assert_eq!(
      config.try_set(ServerConfigType::AofCommitFreq, "0"),
      Err(ConfigError::CommitFreqZero)
    );
    assert_eq!(config.get_int(ServerConfigType::AofCommitFreq), 5000);
    assert_eq!(owner.commit.load(AtomicOrdering::Relaxed), 1);

    // aof-sync-max-lag-bytes 直推 owner 闸门。
    assert_eq!(
      config.try_set(ServerConfigType::AofSyncMaxLagBytes, "123456"),
      Ok(())
    );
    assert_eq!(owner.lag.load(AtomicOrdering::Relaxed), 123456);

    // 收集 / 扫描任务 reconcile。
    assert_eq!(
      config.try_set(ServerConfigType::ExpiredObjectCollectionFreq, "30"),
      Ok(())
    );
    assert_eq!(owner.collect.load(AtomicOrdering::Relaxed), 1);
    assert_eq!(
      config.try_set(ServerConfigType::ExpiredKeyDeletionScanFreq, "15"),
      Ok(())
    );
    assert_eq!(owner.expiry.load(AtomicOrdering::Relaxed), 1);

    // 无 owner 时更新动作仍成功(仅无生命周期副作用)。
    let bare_options = RuntimeServerOptions {
      commit_frequency_ms: -1,
      ..RuntimeServerOptions::default()
    };
    let bare = RuntimeServerConfig::new(bare_options, None);
    assert_eq!(bare.try_set(ServerConfigType::AofCommitFreq, "100"), Ok(()));
  }

  #[test]
  fn commit_freq_rejected_when_started_auto_commit() {
    let options = RuntimeServerOptions {
      commit_frequency_ms: 0,
      ..RuntimeServerOptions::default()
    };
    let config = RuntimeServerConfig::new(options, None);
    assert_eq!(
      config.try_set(ServerConfigType::AofCommitFreq, "100"),
      Err(ConfigError::CommitFreqAutoCommitStart)
    );
  }

  #[test]
  fn resp_format_of_runtime_slots() {
    let config = RuntimeServerConfig::with_defaults();
    assert_eq!(
      config.resp_format(ServerConfigType::ClusterNodeTimeout),
      "60"
    );
    assert_eq!(config.resp_format(ServerConfigType::SgGet), "yes");
    assert_eq!(config.resp_format(ServerConfigType::CompactionType), "None");
    assert_eq!(
      config.try_set(ServerConfigType::CompactionType, "Shift"),
      Ok(())
    );
    assert_eq!(
      config.resp_format(ServerConfigType::CompactionType),
      "Shift"
    );
    assert_eq!(
      config.resp_format(ServerConfigType::AofSyncMaxLagBytes),
      "-1"
    );
  }

  #[test]
  fn seconds_from_time_span_non_positive_is_zero() {
    assert_eq!(RuntimeServerConfig::seconds_from_time_span(60), 60);
    assert_eq!(RuntimeServerConfig::seconds_from_time_span(0), 0);
    assert_eq!(RuntimeServerConfig::seconds_from_time_span(-1), 0);
  }

  #[test]
  fn name_comparer_semantics() {
    use crate::config::config_name_comparer::ConfigNameComparer;
    assert!(ConfigNameComparer::equals(b"AppendOnly", b"appendonly"));
    assert!(!ConfigNameComparer::equals(b"appendonly", b"appendonlyx"));
    assert_eq!(ConfigNameComparer::to_upper_ascii(b'a'), b'A');
    assert_eq!(ConfigNameComparer::to_upper_ascii(b'0'), b'0');
  }
}