hyperi-rustlib 2.7.1

Opinionated, drop-in Rust toolkit for production services at scale. The patterns from blog posts as actual code: 8-layer config cascade, structured logging with PII masking, Prometheus + OpenTelemetry, Kafka/gRPC transports, tiered disk-spillover, adaptive worker pools, graceful shutdown.
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
// Project:   hyperi-rustlib
// File:      tests/integration/directory_config.rs
// Purpose:   Integration tests for DirectoryConfigStore
// Language:  Rust
//
// License:   FSL-1.1-ALv2
// Copyright: (c) 2026 HYPERI PTY LIMITED

use std::path::PathBuf;
use std::time::Duration;

use hyperi_rustlib::directory_config::{
    ChangeOperation, DirectoryConfigError, DirectoryConfigStore, DirectoryConfigStoreConfig,
    WriteMode,
};

#[cfg(feature = "directory-config-git")]
use git2::Repository;

/// Helper to create a config pointing at a temp directory.
fn test_config(dir: &std::path::Path) -> DirectoryConfigStoreConfig {
    DirectoryConfigStoreConfig {
        directory: dir.to_path_buf(),
        refresh_interval: Duration::from_millis(100),
        git_enabled: false,
        git_push: false,
        ..Default::default()
    }
}

/// Write a YAML file into the given directory.
/// Supports subdirectory table names (e.g. `loaders/dfe-loader`).
fn write_yaml(dir: &std::path::Path, name: &str, content: &str) {
    let path = dir.join(format!("{name}.yaml"));
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).unwrap();
    }
    std::fs::write(path, content).unwrap();
}

// --- Construction and initialisation ---

#[tokio::test]
async fn test_new_with_empty_directory() {
    let tmp = tempfile::tempdir().unwrap();
    let store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();
    assert!(store.list_tables().await.is_empty());
    assert_eq!(store.write_mode(), WriteMode::DirectWrite);
}

#[tokio::test]
async fn test_new_with_nonexistent_directory() {
    let config = DirectoryConfigStoreConfig {
        directory: PathBuf::from("/nonexistent/path"),
        ..Default::default()
    };
    let result = DirectoryConfigStore::new(config).await;
    assert!(result.is_err());
    assert!(matches!(
        result.unwrap_err(),
        DirectoryConfigError::DirectoryNotFound(_)
    ));
}

#[tokio::test]
async fn test_new_loads_yaml_files() {
    let tmp = tempfile::tempdir().unwrap();
    write_yaml(tmp.path(), "service-a", "host: localhost\nport: 8080\n");
    write_yaml(tmp.path(), "service-b", "name: test\n");

    let store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();
    let tables = store.list_tables().await;
    assert_eq!(tables, vec!["service-a", "service-b"]);
}

#[tokio::test]
async fn test_non_yaml_files_ignored() {
    let tmp = tempfile::tempdir().unwrap();
    write_yaml(tmp.path(), "valid", "key: value\n");
    std::fs::write(tmp.path().join("readme.txt"), "not yaml").unwrap();
    std::fs::write(tmp.path().join("data.json"), "{}").unwrap();

    let store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();
    let tables = store.list_tables().await;
    assert_eq!(tables, vec!["valid"]);
}

// --- Read API ---

#[tokio::test]
async fn test_get_returns_full_table() {
    let tmp = tempfile::tempdir().unwrap();
    write_yaml(
        tmp.path(),
        "app",
        "database:\n  host: db.local\n  port: 5432\n",
    );

    let store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();
    let value = store.get("app").await.unwrap();
    assert!(value.is_mapping());
}

#[tokio::test]
async fn test_get_table_not_found() {
    let tmp = tempfile::tempdir().unwrap();
    let store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();
    let result = store.get("missing").await;
    assert!(matches!(
        result.unwrap_err(),
        DirectoryConfigError::TableNotFound(_)
    ));
}

#[tokio::test]
async fn test_get_key_top_level() {
    let tmp = tempfile::tempdir().unwrap();
    write_yaml(tmp.path(), "app", "name: myapp\nversion: 2\n");

    let store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();
    let value = store.get_key("app", "name").await.unwrap();
    assert_eq!(value, serde_yaml_ng::Value::String("myapp".to_string()));
}

#[tokio::test]
async fn test_get_key_nested() {
    let tmp = tempfile::tempdir().unwrap();
    write_yaml(
        tmp.path(),
        "app",
        "database:\n  host: db.local\n  port: 5432\n",
    );

    let store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();
    let value = store.get_key("app", "database.host").await.unwrap();
    assert_eq!(value, serde_yaml_ng::Value::String("db.local".to_string()));
}

#[tokio::test]
async fn test_get_key_not_found() {
    let tmp = tempfile::tempdir().unwrap();
    write_yaml(tmp.path(), "app", "name: myapp\n");

    let store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();
    let result = store.get_key("app", "missing.key").await;
    assert!(matches!(
        result.unwrap_err(),
        DirectoryConfigError::KeyNotFound { .. }
    ));
}

#[tokio::test]
async fn test_get_as_typed() {
    let tmp = tempfile::tempdir().unwrap();
    write_yaml(tmp.path(), "db", "host: localhost\nport: 5432\nssl: true\n");

    #[derive(serde::Deserialize, Debug, PartialEq)]
    struct DbConfig {
        host: String,
        port: u16,
        ssl: bool,
    }

    let store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();
    let config: DbConfig = store.get_as("db").await.unwrap();
    assert_eq!(
        config,
        DbConfig {
            host: "localhost".to_string(),
            port: 5432,
            ssl: true,
        }
    );
}

// --- Write API ---

#[tokio::test]
async fn test_set_creates_new_table() {
    let tmp = tempfile::tempdir().unwrap();
    let store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();

    let result = store
        .set(
            "new-service",
            "host",
            serde_yaml_ng::Value::String("localhost".to_string()),
            None,
        )
        .await
        .unwrap();

    assert_eq!(result.table, "new-service");
    assert_eq!(result.operation, ChangeOperation::Updated);

    // Verify in cache
    let value = store.get_key("new-service", "host").await.unwrap();
    assert_eq!(value, serde_yaml_ng::Value::String("localhost".to_string()));

    // Verify on disk
    let on_disk = std::fs::read_to_string(tmp.path().join("new-service.yaml")).unwrap();
    assert!(on_disk.contains("localhost"));
}

#[tokio::test]
async fn test_set_updates_existing_key() {
    let tmp = tempfile::tempdir().unwrap();
    write_yaml(tmp.path(), "app", "host: old-host\nport: 8080\n");

    let store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();

    store
        .set(
            "app",
            "host",
            serde_yaml_ng::Value::String("new-host".to_string()),
            None,
        )
        .await
        .unwrap();

    let value = store.get_key("app", "host").await.unwrap();
    assert_eq!(value, serde_yaml_ng::Value::String("new-host".to_string()));

    // Port should be unchanged
    let port = store.get_key("app", "port").await.unwrap();
    assert_eq!(port, serde_yaml_ng::Value::Number(8080.into()));
}

#[tokio::test]
async fn test_set_nested_key() {
    let tmp = tempfile::tempdir().unwrap();
    write_yaml(tmp.path(), "app", "database:\n  host: old\n");

    let store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();

    store
        .set(
            "app",
            "database.host",
            serde_yaml_ng::Value::String("new-host".to_string()),
            None,
        )
        .await
        .unwrap();

    let value = store.get_key("app", "database.host").await.unwrap();
    assert_eq!(value, serde_yaml_ng::Value::String("new-host".to_string()));
}

#[tokio::test]
async fn test_delete_key() {
    let tmp = tempfile::tempdir().unwrap();
    write_yaml(
        tmp.path(),
        "app",
        "host: localhost\nport: 8080\ndebug: true\n",
    );

    let store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();

    let result = store.delete_key("app", "debug", None).await.unwrap();
    assert_eq!(result.operation, ChangeOperation::Deleted);

    // Key should be gone
    let err = store.get_key("app", "debug").await.unwrap_err();
    assert!(matches!(err, DirectoryConfigError::KeyNotFound { .. }));

    // Other keys remain
    let host = store.get_key("app", "host").await.unwrap();
    assert_eq!(host, serde_yaml_ng::Value::String("localhost".to_string()));
}

#[tokio::test]
async fn test_delete_key_not_found() {
    let tmp = tempfile::tempdir().unwrap();
    write_yaml(tmp.path(), "app", "host: localhost\n");

    let store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();
    let result = store.delete_key("app", "missing", None).await;
    assert!(matches!(
        result.unwrap_err(),
        DirectoryConfigError::KeyNotFound { .. }
    ));
}

#[tokio::test]
async fn test_delete_table_not_found() {
    let tmp = tempfile::tempdir().unwrap();
    let store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();
    let result = store.delete_key("missing", "key", None).await;
    assert!(matches!(
        result.unwrap_err(),
        DirectoryConfigError::TableNotFound(_)
    ));
}

// --- Write mode ---

#[tokio::test]
async fn test_read_only_rejects_writes() {
    // Create a temp directory with YAML, then make it read-only
    let tmp = tempfile::tempdir().unwrap();
    write_yaml(tmp.path(), "existing", "key: value\n");

    // Remove write permission
    let mut perms = std::fs::metadata(tmp.path()).unwrap().permissions();
    #[allow(clippy::permissions_set_readonly_false)]
    {
        perms.set_readonly(true);
    }
    std::fs::set_permissions(tmp.path(), perms.clone()).unwrap();

    let config = DirectoryConfigStoreConfig {
        directory: tmp.path().to_path_buf(),
        git_enabled: false,
        ..Default::default()
    };

    let store = DirectoryConfigStore::new(config).await.unwrap();
    assert_eq!(store.write_mode(), WriteMode::ReadOnly);

    let result = store
        .set(
            "test",
            "key",
            serde_yaml_ng::Value::String("val".to_string()),
            None,
        )
        .await;
    assert!(matches!(
        result.unwrap_err(),
        DirectoryConfigError::ReadOnly
    ));

    // Restore permissions so tempdir cleanup works
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(tmp.path(), std::fs::Permissions::from_mode(0o755)).unwrap();
    }
}

// --- Lifecycle ---

#[tokio::test]
async fn test_start_stop() {
    let tmp = tempfile::tempdir().unwrap();
    let mut store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();

    store.start().await.unwrap();
    store.stop().await.unwrap();
}

#[tokio::test]
async fn test_double_start_error() {
    let tmp = tempfile::tempdir().unwrap();
    let mut store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();

    store.start().await.unwrap();
    let result = store.start().await;
    assert!(matches!(
        result.unwrap_err(),
        DirectoryConfigError::AlreadyRunning
    ));

    store.stop().await.unwrap();
}

#[tokio::test]
async fn test_stop_without_start_error() {
    let tmp = tempfile::tempdir().unwrap();
    let mut store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();
    let result = store.stop().await;
    assert!(matches!(
        result.unwrap_err(),
        DirectoryConfigError::NotStarted
    ));
}

// --- Background refresh ---

#[tokio::test]
async fn test_background_refresh_picks_up_changes() {
    let tmp = tempfile::tempdir().unwrap();
    write_yaml(tmp.path(), "app", "version: 1\n");

    let mut store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();
    store.start().await.unwrap();

    // Modify the file on disk
    write_yaml(tmp.path(), "app", "version: 2\n");

    // Wait for refresh to pick it up (interval is 100ms)
    tokio::time::sleep(Duration::from_millis(350)).await;

    let value = store.get_key("app", "version").await.unwrap();
    assert_eq!(value, serde_yaml_ng::Value::Number(2.into()));

    store.stop().await.unwrap();
}

#[tokio::test]
async fn test_background_refresh_detects_new_table() {
    let tmp = tempfile::tempdir().unwrap();

    let mut store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();
    assert!(store.list_tables().await.is_empty());

    store.start().await.unwrap();

    // Add a new file on disk
    write_yaml(tmp.path(), "new-service", "enabled: true\n");

    tokio::time::sleep(Duration::from_millis(350)).await;

    let tables = store.list_tables().await;
    assert!(tables.contains(&"new-service".to_string()));

    store.stop().await.unwrap();
}

#[tokio::test]
async fn test_background_refresh_detects_removed_table() {
    let tmp = tempfile::tempdir().unwrap();
    write_yaml(tmp.path(), "temporary", "data: test\n");

    let mut store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();
    assert_eq!(store.list_tables().await, vec!["temporary"]);

    store.start().await.unwrap();

    // Remove the file
    std::fs::remove_file(tmp.path().join("temporary.yaml")).unwrap();

    tokio::time::sleep(Duration::from_millis(350)).await;

    assert!(store.list_tables().await.is_empty());

    store.stop().await.unwrap();
}

// --- Change events ---

#[tokio::test]
async fn test_on_change_receives_write_events() {
    let tmp = tempfile::tempdir().unwrap();
    let store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();

    let mut rx = store.on_change();

    store
        .set(
            "app",
            "key",
            serde_yaml_ng::Value::String("value".to_string()),
            None,
        )
        .await
        .unwrap();

    let event = rx.try_recv().unwrap();
    assert_eq!(event.table, "app");
    assert_eq!(event.operation, ChangeOperation::Updated);
}

#[tokio::test]
async fn test_on_change_receives_delete_events() {
    let tmp = tempfile::tempdir().unwrap();
    write_yaml(tmp.path(), "app", "host: localhost\nport: 8080\n");

    let store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();
    let mut rx = store.on_change();

    store.delete_key("app", "host", None).await.unwrap();

    let event = rx.try_recv().unwrap();
    assert_eq!(event.table, "app");
    assert_eq!(event.operation, ChangeOperation::Deleted);
}

// --- Corrupt YAML ---

#[tokio::test]
async fn test_corrupt_yaml_keeps_last_good() {
    let tmp = tempfile::tempdir().unwrap();
    write_yaml(tmp.path(), "app", "host: localhost\n");

    let mut store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();
    let original = store.get_key("app", "host").await.unwrap();
    assert_eq!(
        original,
        serde_yaml_ng::Value::String("localhost".to_string())
    );

    store.start().await.unwrap();

    // Corrupt the file on disk
    std::fs::write(tmp.path().join("app.yaml"), "{{{{invalid yaml!!!!").unwrap();

    tokio::time::sleep(Duration::from_millis(350)).await;

    // Should still have the last good value
    let value = store.get_key("app", "host").await.unwrap();
    assert_eq!(value, serde_yaml_ng::Value::String("localhost".to_string()));

    store.stop().await.unwrap();
}

// --- .yml extension ---

#[tokio::test]
async fn test_yml_extension_supported() {
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("service.yml");
    std::fs::write(path, "name: test-service\n").unwrap();

    let store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();
    let tables = store.list_tables().await;
    assert_eq!(tables, vec!["service"]);

    let value = store.get_key("service", "name").await.unwrap();
    assert_eq!(
        value,
        serde_yaml_ng::Value::String("test-service".to_string())
    );
}

// --- Subdirectory support ---

#[tokio::test]
async fn test_subdirectory_tables_loaded() {
    let tmp = tempfile::tempdir().unwrap();
    write_yaml(tmp.path(), "root-config", "name: root\n");
    write_yaml(tmp.path(), "loaders/dfe-loader", "host: dfe\n");
    write_yaml(tmp.path(), "loaders/csv-loader", "host: csv\n");
    write_yaml(tmp.path(), "sinks/kafka/primary", "brokers: b1\n");

    let store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();
    let tables = store.list_tables().await;

    assert_eq!(
        tables,
        vec![
            "loaders/csv-loader",
            "loaders/dfe-loader",
            "root-config",
            "sinks/kafka/primary",
        ]
    );
}

#[tokio::test]
async fn test_subdirectory_get() {
    let tmp = tempfile::tempdir().unwrap();
    write_yaml(
        tmp.path(),
        "loaders/dfe-loader",
        "host: dfe-host\nport: 9090\n",
    );

    let store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();

    let value = store.get_key("loaders/dfe-loader", "host").await.unwrap();
    assert_eq!(value, serde_yaml_ng::Value::String("dfe-host".to_string()));
}

#[tokio::test]
async fn test_subdirectory_get_normalises_slashes() {
    let tmp = tempfile::tempdir().unwrap();
    write_yaml(tmp.path(), "loaders/dfe-loader", "host: dfe-host\n");

    let store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();

    // Leading/trailing slashes should be stripped
    let value = store.get_key("/loaders/dfe-loader/", "host").await.unwrap();
    assert_eq!(value, serde_yaml_ng::Value::String("dfe-host".to_string()));
}

#[tokio::test]
async fn test_subdirectory_set_creates_dirs() {
    let tmp = tempfile::tempdir().unwrap();
    let store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();

    // Write to a subdirectory table that doesn't exist yet
    store
        .set(
            "new-group/my-service",
            "enabled",
            serde_yaml_ng::Value::Bool(true),
            None,
        )
        .await
        .unwrap();

    // Verify in cache
    let value = store
        .get_key("new-group/my-service", "enabled")
        .await
        .unwrap();
    assert_eq!(value, serde_yaml_ng::Value::Bool(true));

    // Verify on disk
    let on_disk = tmp.path().join("new-group/my-service.yaml");
    assert!(on_disk.exists());
}

#[tokio::test]
async fn test_subdirectory_set_deep_nesting() {
    let tmp = tempfile::tempdir().unwrap();
    let store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();

    store
        .set(
            "a/b/c/deep",
            "key",
            serde_yaml_ng::Value::String("deep-value".to_string()),
            None,
        )
        .await
        .unwrap();

    let value = store.get_key("a/b/c/deep", "key").await.unwrap();
    assert_eq!(
        value,
        serde_yaml_ng::Value::String("deep-value".to_string())
    );
}

#[tokio::test]
async fn test_subdirectory_delete_key() {
    let tmp = tempfile::tempdir().unwrap();
    write_yaml(tmp.path(), "loaders/dfe-loader", "host: dfe\nport: 9090\n");

    let store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();

    store
        .delete_key("loaders/dfe-loader", "port", None)
        .await
        .unwrap();

    // Key should be gone
    let result = store.get_key("loaders/dfe-loader", "port").await;
    assert!(matches!(
        result.unwrap_err(),
        DirectoryConfigError::KeyNotFound { .. }
    ));

    // Other key remains
    let host = store.get_key("loaders/dfe-loader", "host").await.unwrap();
    assert_eq!(host, serde_yaml_ng::Value::String("dfe".to_string()));
}

#[tokio::test]
async fn test_subdirectory_yml_extension() {
    let tmp = tempfile::tempdir().unwrap();
    let subdir = tmp.path().join("configs");
    std::fs::create_dir_all(&subdir).unwrap();
    std::fs::write(subdir.join("service.yml"), "name: yml-service\n").unwrap();

    let store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();

    let tables = store.list_tables().await;
    assert_eq!(tables, vec!["configs/service"]);

    let value = store.get_key("configs/service", "name").await.unwrap();
    assert_eq!(
        value,
        serde_yaml_ng::Value::String("yml-service".to_string())
    );
}

#[tokio::test]
async fn test_subdirectory_hidden_dirs_skipped() {
    let tmp = tempfile::tempdir().unwrap();
    write_yaml(tmp.path(), "visible", "ok: true\n");

    // Create hidden directory with YAML file (should be skipped)
    let hidden = tmp.path().join(".git");
    std::fs::create_dir_all(&hidden).unwrap();
    std::fs::write(hidden.join("config.yaml"), "internal: true\n").unwrap();

    let store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();
    let tables = store.list_tables().await;
    assert_eq!(tables, vec!["visible"]);
}

#[tokio::test]
async fn test_invalid_table_name_rejected() {
    let tmp = tempfile::tempdir().unwrap();
    let store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();

    // Path traversal
    let result = store.get("../etc/passwd").await;
    assert!(matches!(
        result.unwrap_err(),
        DirectoryConfigError::InvalidTableName(_)
    ));

    // Backslash
    let result = store.get("foo\\bar").await;
    assert!(matches!(
        result.unwrap_err(),
        DirectoryConfigError::InvalidTableName(_)
    ));

    // Empty
    let result = store.get("").await;
    assert!(matches!(
        result.unwrap_err(),
        DirectoryConfigError::InvalidTableName(_)
    ));
}

#[tokio::test]
async fn test_subdirectory_background_refresh() {
    let tmp = tempfile::tempdir().unwrap();
    write_yaml(tmp.path(), "loaders/dfe", "version: 1\n");

    let mut store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();
    store.start().await.unwrap();

    // Modify file on disk
    write_yaml(tmp.path(), "loaders/dfe", "version: 2\n");

    tokio::time::sleep(Duration::from_millis(350)).await;

    let value = store.get_key("loaders/dfe", "version").await.unwrap();
    assert_eq!(value, serde_yaml_ng::Value::Number(2.into()));

    store.stop().await.unwrap();
}

#[tokio::test]
async fn test_subdirectory_background_refresh_new_subdir() {
    let tmp = tempfile::tempdir().unwrap();

    let mut store = DirectoryConfigStore::new(test_config(tmp.path()))
        .await
        .unwrap();
    assert!(store.list_tables().await.is_empty());

    store.start().await.unwrap();

    // Add a new subdirectory and file
    write_yaml(tmp.path(), "sinks/kafka", "brokers: b1\n");

    tokio::time::sleep(Duration::from_millis(350)).await;

    let tables = store.list_tables().await;
    assert!(tables.contains(&"sinks/kafka".to_string()));

    store.stop().await.unwrap();
}

// --- Git integration tests ---

#[cfg(feature = "directory-config-git")]
mod git_tests {
    use super::*;

    /// Helper: initialise a git repo in a temp dir with an initial commit.
    fn init_git_repo(dir: &std::path::Path) -> Repository {
        let repo = Repository::init(dir).unwrap();

        // Configure user for commits
        let mut config = repo.config().unwrap();
        config.set_str("user.name", "Test User").unwrap();
        config.set_str("user.email", "test@example.com").unwrap();
        drop(config);

        // Create initial commit (empty tree) so HEAD exists
        {
            let sig = git2::Signature::now("Test User", "test@example.com").unwrap();
            let tree_oid = repo.index().unwrap().write_tree().unwrap();
            let tree = repo.find_tree(tree_oid).unwrap();
            repo.commit(Some("HEAD"), &sig, &sig, "initial commit", &tree, &[])
                .unwrap();
        }

        repo
    }

    /// Helper: config for a git-enabled store.
    fn git_config(dir: &std::path::Path) -> DirectoryConfigStoreConfig {
        DirectoryConfigStoreConfig {
            directory: dir.to_path_buf(),
            refresh_interval: Duration::from_millis(100),
            git_enabled: true,
            git_push: false,
            ..Default::default()
        }
    }

    #[tokio::test]
    async fn test_git_write_mode_detected() {
        let tmp = tempfile::tempdir().unwrap();
        init_git_repo(tmp.path());

        let store = DirectoryConfigStore::new(git_config(tmp.path()))
            .await
            .unwrap();
        assert_eq!(store.write_mode(), WriteMode::GitCommit);
        assert!(store.is_git());
    }

    #[tokio::test]
    async fn test_git_current_branch() {
        let tmp = tempfile::tempdir().unwrap();
        init_git_repo(tmp.path());

        let store = DirectoryConfigStore::new(git_config(tmp.path()))
            .await
            .unwrap();
        let branch = store.current_branch();
        // Default branch for git init is typically "main" or "master"
        assert!(branch.is_some());
    }

    #[tokio::test]
    async fn test_git_list_branches() {
        let tmp = tempfile::tempdir().unwrap();
        init_git_repo(tmp.path());

        let store = DirectoryConfigStore::new(git_config(tmp.path()))
            .await
            .unwrap();
        let branches = store.list_branches().unwrap();
        assert!(!branches.is_empty());
    }

    #[tokio::test]
    async fn test_git_write_creates_commit() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(tmp.path());

        let store = DirectoryConfigStore::new(git_config(tmp.path()))
            .await
            .unwrap();

        // Count commits before
        let head_before = repo.head().unwrap().peel_to_commit().unwrap();
        let count_before = {
            let mut revwalk = repo.revwalk().unwrap();
            revwalk.push(head_before.id()).unwrap();
            revwalk.count()
        };

        // Write a key
        store
            .set(
                "app",
                "host",
                serde_yaml_ng::Value::String("localhost".to_string()),
                Some("test: add app config"),
            )
            .await
            .unwrap();

        // Count commits after — should have one more
        let head_after = repo.head().unwrap().peel_to_commit().unwrap();
        let count_after = {
            let mut revwalk = repo.revwalk().unwrap();
            revwalk.push(head_after.id()).unwrap();
            revwalk.count()
        };
        assert_eq!(count_after, count_before + 1);

        // Verify commit message
        let latest = repo.head().unwrap().peel_to_commit().unwrap();
        assert_eq!(latest.message().unwrap(), "test: add app config");
    }

    #[tokio::test]
    async fn test_git_delete_creates_commit() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(tmp.path());
        write_yaml(tmp.path(), "app", "host: localhost\nport: 8080\n");

        let store = DirectoryConfigStore::new(git_config(tmp.path()))
            .await
            .unwrap();

        // First: stage the initial file via a set operation so git tracks it
        store
            .set(
                "app",
                "debug",
                serde_yaml_ng::Value::Bool(true),
                Some("add debug flag"),
            )
            .await
            .unwrap();

        // Now delete the key
        store
            .delete_key("app", "debug", Some("remove debug flag"))
            .await
            .unwrap();

        let latest = repo.head().unwrap().peel_to_commit().unwrap();
        assert_eq!(latest.message().unwrap(), "remove debug flag");
    }

    #[tokio::test]
    async fn test_git_switch_branch() {
        let tmp = tempfile::tempdir().unwrap();
        init_git_repo(tmp.path());

        let store = DirectoryConfigStore::new(git_config(tmp.path()))
            .await
            .unwrap();

        // Create and switch to a new branch
        store.switch_branch("feature-test", true).unwrap();
        assert_eq!(store.current_branch(), Some("feature-test".to_string()));

        // Branch should appear in list
        let branches = store.list_branches().unwrap();
        assert!(branches.contains(&"feature-test".to_string()));
    }

    #[tokio::test]
    async fn test_git_switch_back_to_original_branch() {
        let tmp = tempfile::tempdir().unwrap();
        init_git_repo(tmp.path());

        let store = DirectoryConfigStore::new(git_config(tmp.path()))
            .await
            .unwrap();
        let original = store.current_branch().unwrap();

        // Create new branch and switch
        store.switch_branch("other-branch", true).unwrap();
        assert_eq!(store.current_branch(), Some("other-branch".to_string()));

        // Switch back
        store.switch_branch(&original, false).unwrap();
        assert_eq!(store.current_branch(), Some(original));
    }

    #[tokio::test]
    async fn test_git_switch_nonexistent_branch_fails() {
        let tmp = tempfile::tempdir().unwrap();
        init_git_repo(tmp.path());

        let store = DirectoryConfigStore::new(git_config(tmp.path()))
            .await
            .unwrap();
        let result = store.switch_branch("nonexistent", false);
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_git_list_branches_on_non_git_errors() {
        let tmp = tempfile::tempdir().unwrap();
        // No git init — DirectWrite mode
        let config = DirectoryConfigStoreConfig {
            directory: tmp.path().to_path_buf(),
            refresh_interval: Duration::from_millis(100),
            git_enabled: false,
            ..Default::default()
        };
        let store = DirectoryConfigStore::new(config).await.unwrap();
        let result = store.list_branches();
        assert!(matches!(
            result.unwrap_err(),
            DirectoryConfigError::NotGitRepo
        ));
    }

    #[tokio::test]
    async fn test_git_subdirectory_write_creates_commit() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(tmp.path());

        let store = DirectoryConfigStore::new(git_config(tmp.path()))
            .await
            .unwrap();

        let result = store
            .set(
                "loaders/dfe-loader",
                "host",
                serde_yaml_ng::Value::String("dfe-host".to_string()),
                Some("add dfe-loader config"),
            )
            .await
            .unwrap();

        // Should have git metadata
        assert!(result.commit.is_some());

        // Verify commit message
        let latest = repo.head().unwrap().peel_to_commit().unwrap();
        assert_eq!(latest.message().unwrap(), "add dfe-loader config");

        // Verify file exists on disk
        assert!(tmp.path().join("loaders/dfe-loader.yaml").exists());
    }

    #[tokio::test]
    async fn test_git_write_result_includes_commit() {
        let tmp = tempfile::tempdir().unwrap();
        init_git_repo(tmp.path());

        let store = DirectoryConfigStore::new(git_config(tmp.path()))
            .await
            .unwrap();

        let result = store
            .set(
                "svc",
                "port",
                serde_yaml_ng::Value::Number(9090.into()),
                Some("set port"),
            )
            .await
            .unwrap();

        // WriteResult should have git metadata
        assert!(result.commit.is_some());
        let hash = result.commit.unwrap();
        assert!(!hash.is_empty());
        assert!(hash.len() <= 7);
    }
}