athena_rs 3.26.1

Hyper performant polyglot Database driver
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
//! Configuration management for the application.
//!
//! This module provides utilities for loading and accessing application configuration
//! from YAML files. It includes settings for URLs, hosts, API configuration, authentication,
//! PostgreSQL clients, and gateway behavior.

use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::env;
use std::error::Error as stdError;
use std::fmt;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};

use crate::config_validation::{
    NumericRange, ValidationRanges, normalize_config_u16, normalize_config_u32,
    normalize_config_u64, normalize_config_usize,
};

/// Application configuration loaded from a YAML file.
///
/// Contains all configurable settings including service URLs, hosts, API parameters,
/// authenticator configurations, PostgreSQL client URIs, and gateway settings.
///
/// # Examples
///
/// ```no_run
/// use athena_rs::config::Config;
///
/// let config = Config::load()?;
/// let url = config.get_url("service_name");
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    pub urls: Vec<HashMap<String, String>>,
    pub hosts: Vec<HashMap<String, String>>,
    pub api: Vec<HashMap<String, String>>,
    pub authenticator: Vec<HashMap<String, HashMap<String, String>>>,
    pub postgres_clients: Vec<HashMap<String, String>>,
    #[serde(default)]
    pub gateway: Vec<HashMap<String, String>>,
    #[serde(default)]
    pub storage: Vec<HashMap<String, String>>,
    #[serde(default)]
    pub provisioning: Vec<HashMap<String, String>>,
    #[serde(default)]
    pub backup: Vec<HashMap<String, String>>,
    #[serde(default)]
    pub daemon: Vec<HashMap<String, String>>,
    /// CDC (Change Data Capture) runtime behavior configuration.
    #[serde(default)]
    pub cdc: Vec<HashMap<String, String>>,
    /// Typesense sync/worker behavior configuration.
    #[serde(default)]
    pub typesense: Vec<HashMap<String, String>>,
    /// Optional Grafana Loki log-shipping configuration.
    ///
    /// Resolved at startup via
    /// [`crate::features::loki::LokiConfig::resolve`]. Each `${VAR}` is
    /// expanded against the process environment at load time. Env vars
    /// `ATHENA_LOKI_*` override matching YAML keys.
    #[serde(default)]
    pub loki: Vec<HashMap<String, String>>,
    /// Deferred write-through cache configuration.
    ///
    /// When `enabled: true`, gateway mutations bypass the database and are
    /// written to an in-memory buffer and optional WAL first. A background
    /// flush executor drains the buffer into Postgres on a configurable
    /// schedule. Reads continue to be served from cache while the batch is
    /// pending.
    #[serde(default)]
    pub deferred_writes: Vec<HashMap<String, String>>,
    #[serde(default)]
    pub validation_ranges: ValidationRanges,
}

pub const DEFAULT_CONFIG_FILE_NAME: &str = "config.yaml";
const DEFAULT_CONFIG_TEMPLATE: &str = include_str!("../config.yaml");
const DEFAULT_PROVISIONING_EXPECTED_TABLES: &[&str] = &[
    "account",
    "accounts",
    "admin_audit_logs",
    "api_keys",
    "apikey",
    "athena_clients",
    "audit_log",
    "audit_log_files",
    "chat_message_attachments",
    "chat_message_reactions",
    "chat_messages",
    "chat_outbox",
    "chat_room_members",
    "chat_rooms",
    "chat_session_auth_log",
    "email_event_types",
    "email_send_failures",
    "email_templates",
    "emails",
    "event_log_files",
    "file_permissions",
    "files",
    "gateway_webhook",
    "gateway_webhook_delivery",
    "gateway_webhook_state_ledger",
    "invitation",
    "ip_profiles",
    "member",
    "oauth_clients",
    "organization",
    "passkeys",
    "s3",
    "s3_credentials",
    "s3_url_cache",
    "session_ip_profiles",
    "sessions",
    "storage_audit_events",
    "two_factor",
    "user_permission_scopes",
    "users",
    "verifications",
];
const DEFAULT_PROVISIONING_POSTGRES_IMAGE: &str = "postgres:16-alpine";
const DEFAULT_PROVISIONING_INSTANCE_HOST: &str = "127.0.0.1";
const DEFAULT_PROVISIONING_STARTUP_TIMEOUT_SECS: u64 = 60;
const DEFAULT_PROVISIONING_NEON_API_BASE_URL: &str = "https://console.neon.tech/api/v2";
const DEFAULT_PROVISIONING_RAILWAY_GRAPHQL_URL: &str = "https://backboard.railway.app/graphql/v2";
const DEFAULT_PROVISIONING_RENDER_API_BASE_URL: &str = "https://api.render.com/v1";

#[derive(Clone, Debug)]
pub struct ConfigLocation {
    pub label: String,
    pub path: PathBuf,
}

impl ConfigLocation {
    pub fn new(label: String, path: PathBuf) -> Self {
        Self { label, path }
    }

    pub fn describe(&self) -> String {
        format!("{} ({})", self.label, self.path.display())
    }

    fn write_default(&self) -> io::Result<()> {
        if let Some(parent) = self.path.parent() {
            fs::create_dir_all(parent)?;
        }
        fs::write(&self.path, DEFAULT_CONFIG_TEMPLATE)?;
        Ok(())
    }
}

#[derive(Debug)]
pub struct ConfigLoadOutcome {
    pub config: Config,
    pub path: PathBuf,
    pub attempted_locations: Vec<ConfigLocation>,
    pub seeded_default: bool,
}

#[derive(Debug)]
pub struct ConfigLoadError {
    pub attempted_locations: Vec<ConfigLocation>,
    pub source: Option<Box<dyn stdError>>,
}

impl ConfigLoadError {
    fn with_source(
        source: Option<Box<dyn stdError>>,
        attempted_locations: Vec<ConfigLocation>,
    ) -> Self {
        Self {
            source,
            attempted_locations,
        }
    }
}

impl fmt::Display for ConfigLoadError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(source) = &self.source {
            write!(f, "{}", source)
        } else {
            write!(f, "no configuration file could be found or created")
        }
    }
}

impl std::error::Error for ConfigLoadError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.source.as_deref()
    }
}

impl Config {
    /// Build an in-memory empty config fallback.
    ///
    /// Useful when boot should proceed in degraded mode even if `config.yaml`
    /// cannot be loaded.
    pub fn empty_fallback() -> Self {
        Self {
            urls: Vec::new(),
            hosts: Vec::new(),
            api: Vec::new(),
            authenticator: Vec::new(),
            postgres_clients: Vec::new(),
            gateway: Vec::new(),
            storage: Vec::new(),
            provisioning: Vec::new(),
            backup: Vec::new(),
            daemon: Vec::new(),
            cdc: Vec::new(),
            typesense: Vec::new(),
            loki: Vec::new(),
            deferred_writes: Vec::new(),
            validation_ranges: ValidationRanges::default(),
        }
    }

    /// Load configuration from the default `config.yaml` file.
    pub fn load() -> Result<Self, Box<dyn stdError>> {
        Self::load_default()
            .map(|outcome| outcome.config)
            .map_err(|err| Box::new(err) as Box<dyn stdError>)
    }

    /// Load configuration from a specified file path.
    ///
    /// # Arguments
    ///
    /// * `path` - The file path to load the configuration from.
    pub fn load_from<P: AsRef<Path>>(path: P) -> Result<Self, Box<dyn stdError>> {
        let path_ref: &Path = path.as_ref();
        let content: String = fs::read_to_string(path_ref)?;
        let config: Config = serde_yaml::from_str(&content)?;
        Ok(config)
    }

    /// Load configuration from the OS-aware defaults and fallback locations.
    pub fn load_default() -> Result<ConfigLoadOutcome, ConfigLoadError> {
        let locations: Vec<ConfigLocation> = Self::config_locations();
        let mut attempts: Vec<ConfigLocation> = Vec::new();

        for location in &locations {
            attempts.push(location.clone());
            if location.path.is_file() {
                return Self::load_from_location(location, attempts, false);
            }
        }

        let mut last_write_error: Option<Box<dyn stdError>> = None;
        for location in &locations {
            match location.write_default() {
                Ok(_) => return Self::load_from_location(location, attempts, true),
                Err(err) => last_write_error = Some(Box::new(err)),
            }
        }

        Err(ConfigLoadError::with_source(last_write_error, attempts))
    }

    fn load_from_location(
        location: &ConfigLocation,
        attempts: Vec<ConfigLocation>,
        seeded_default: bool,
    ) -> Result<ConfigLoadOutcome, ConfigLoadError> {
        match Self::load_from(&location.path) {
            Ok(config) => Ok(ConfigLoadOutcome {
                config,
                path: location.path.clone(),
                attempted_locations: attempts,
                seeded_default,
            }),
            Err(err) => Err(ConfigLoadError::with_source(Some(err), attempts)),
        }
    }

    fn config_locations() -> Vec<ConfigLocation> {
        let mut locations: Vec<ConfigLocation> = Vec::new();
        let mut push = |label: &str, path: PathBuf| {
            if path.as_os_str().is_empty() {
                return;
            }
            if locations.iter().any(|candidate| candidate.path == path) {
                return;
            }
            locations.push(ConfigLocation::new(label.to_string(), path));
        };

        if cfg!(target_os = "windows") {
            if let Some(appdata) = env::var_os("APPDATA") {
                let path: PathBuf = PathBuf::from(appdata)
                    .join("athena")
                    .join(DEFAULT_CONFIG_FILE_NAME);
                push("Windows AppData", path);
            }
            if let Some(local_appdata) = env::var_os("LOCALAPPDATA") {
                let path: PathBuf = PathBuf::from(local_appdata)
                    .join("athena")
                    .join(DEFAULT_CONFIG_FILE_NAME);
                push("Windows Local AppData", path);
            }
            if let Some(userprofile) = env::var_os("USERPROFILE") {
                let path: PathBuf = PathBuf::from(userprofile)
                    .join(".athena")
                    .join(DEFAULT_CONFIG_FILE_NAME);
                push("Windows user profile", path);
            }
        }

        if let Some(xdg) = env::var_os("XDG_CONFIG_HOME") {
            let path: PathBuf = PathBuf::from(xdg)
                .join("athena")
                .join(DEFAULT_CONFIG_FILE_NAME);
            push("XDG config home", path);
        }

        if let Some(home) = env::var_os("HOME") {
            let base: PathBuf = PathBuf::from(home);
            push(
                "Home config (.config)",
                base.join(".config")
                    .join("athena")
                    .join(DEFAULT_CONFIG_FILE_NAME),
            );
            push(
                "Home config (.athena)",
                base.join(".athena").join(DEFAULT_CONFIG_FILE_NAME),
            );
        }

        #[cfg(target_os = "macos")]
        {
            if let Some(home) = env::var_os("HOME") {
                let path = PathBuf::from(home)
                    .join("Library")
                    .join("Application Support")
                    .join("athena")
                    .join(DEFAULT_CONFIG_FILE_NAME);
                push("macOS Application Support", path);
            }
        }

        if let Ok(current_dir) = env::current_dir() {
            push(
                "Current working directory",
                current_dir.join(DEFAULT_CONFIG_FILE_NAME),
            );
        }

        locations
    }

    fn normalize_env_segment(input: &str) -> String {
        let mut normalized = String::with_capacity(input.len());
        let mut previous_was_underscore = false;

        for ch in input.chars() {
            let mapped = if ch.is_ascii_alphanumeric() {
                previous_was_underscore = false;
                ch.to_ascii_uppercase()
            } else {
                if previous_was_underscore {
                    continue;
                }
                previous_was_underscore = true;
                '_'
            };
            normalized.push(mapped);
        }

        normalized.trim_matches('_').to_string()
    }

    fn section_env_key(section: &str, key: &str) -> String {
        format!(
            "ATHENA_{}_{}",
            Self::normalize_env_segment(section),
            Self::normalize_env_segment(key)
        )
    }

    fn section_value(
        entries: &[HashMap<String, String>],
        section: &str,
        key: &str,
    ) -> Option<String> {
        let env_key = Self::section_env_key(section, key);
        if let Ok(value) = env::var(&env_key) {
            let trimmed = value.trim();
            if !trimmed.is_empty() {
                return Some(trimmed.to_string());
            }
        }

        entries
            .iter()
            .find_map(|map| map.get(key))
            .map(|value| value.trim().to_string())
            .filter(|value| !value.is_empty())
    }

    fn api_value(&self, key: &str) -> Option<String> {
        Self::section_value(&self.api, "api", key)
    }

    fn gateway_value(&self, key: &str) -> Option<String> {
        Self::section_value(&self.gateway, "gateway", key)
    }

    fn storage_value(&self, key: &str) -> Option<String> {
        Self::section_value(&self.storage, "storage", key)
    }

    fn provisioning_value(&self, key: &str) -> Option<String> {
        Self::section_value(&self.provisioning, "provisioning", key)
    }

    fn cdc_value(&self, key: &str) -> Option<String> {
        Self::section_value(&self.cdc, "cdc", key)
    }

    fn typesense_value(&self, key: &str) -> Option<String> {
        Self::section_value(&self.typesense, "typesense", key)
    }

    fn backup_value(&self, key: &str) -> Option<String> {
        Self::section_value(&self.backup, "backup", key)
    }

    fn daemon_value(&self, key: &str) -> Option<String> {
        Self::section_value(&self.daemon, "daemon", key)
    }

    /// Resolves optional `${ENV_VAR}` placeholders used in `config.yaml` string fields.
    ///
    /// Returns `None` when the source value is empty, or when the placeholder
    /// points at an unset/empty environment variable.
    fn resolve_env_placeholder(raw: Option<&String>) -> Option<String> {
        let trimmed = raw?.trim();
        if trimmed.is_empty() {
            return None;
        }

        if let Some(env_name) = crate::parser::parse_env_reference(trimmed) {
            return env::var(env_name)
                .ok()
                .map(|value| value.trim().to_string())
                .filter(|value| !value.is_empty());
        }

        Some(trimmed.to_string())
    }

    fn normalized_u16(&self, key: &str, raw: Option<String>, fallback_range: NumericRange) -> u16 {
        normalize_config_u16(&self.validation_ranges, key, raw.as_ref(), fallback_range)
    }

    fn normalized_u32(&self, key: &str, raw: Option<String>, fallback_range: NumericRange) -> u32 {
        normalize_config_u32(&self.validation_ranges, key, raw.as_ref(), fallback_range)
    }

    fn normalized_u64(&self, key: &str, raw: Option<String>, fallback_range: NumericRange) -> u64 {
        normalize_config_u64(&self.validation_ranges, key, raw.as_ref(), fallback_range)
    }

    fn normalized_usize(
        &self,
        key: &str,
        raw: Option<String>,
        fallback_range: NumericRange,
    ) -> usize {
        normalize_config_usize(&self.validation_ranges, key, raw.as_ref(), fallback_range)
    }

    /// Get the URL for a given service name.
    ///
    /// # Arguments
    ///
    /// * `service` - The name of the service to look up.
    pub fn get_url(&self, service: &str) -> Option<&String> {
        self.urls.iter().find_map(|map| map.get(service))
    }

    /// Get the URL for a service with optional `${ENV_VAR}` resolution.
    pub fn get_url_resolved(&self, service: &str) -> Option<String> {
        Self::resolve_env_placeholder(self.get_url(service))
    }

    /// Get the host for a given service name.
    ///
    /// # Arguments
    ///
    /// * `service` - The name of the service to look up.
    pub fn get_host(&self, service: &str) -> Option<&String> {
        self.hosts.iter().find_map(|map| map.get(service))
    }

    /// Get the host for a service with optional `${ENV_VAR}` resolution.
    pub fn get_host_resolved(&self, service: &str) -> Option<String> {
        Self::resolve_env_placeholder(self.get_host(service))
    }

    /// Get the API port from configuration.
    pub fn get_api(&self) -> Option<String> {
        self.api_value("port")
    }

    /// Get the immortal cache setting from configuration.
    pub fn get_immortal_cache(&self) -> Option<String> {
        self.api_value("immortal_cache")
    }

    /// Get the cache TTL (time to live) from configuration.
    pub fn get_cache_ttl(&self) -> Option<String> {
        self.api_value("cache_ttl")
    }

    /// Get the connection pool idle timeout from configuration.
    pub fn get_pool_idle_timeout(&self) -> Option<String> {
        self.api_value("pool_idle_timeout")
    }

    /// Get the HTTP keep-alive timeout in seconds from configuration.
    pub fn get_http_keep_alive_secs(&self) -> Option<String> {
        self.api_value("keep_alive_secs")
    }

    /// Get the client disconnect timeout in seconds from configuration.
    pub fn get_client_disconnect_timeout_secs(&self) -> Option<String> {
        self.api_value("client_disconnect_timeout_secs")
    }

    /// Get the client request timeout in seconds from configuration.
    pub fn get_client_request_timeout_secs(&self) -> Option<String> {
        self.api_value("client_request_timeout_secs")
    }

    /// Get the number of HTTP workers from configuration.
    pub fn get_http_workers(&self) -> Option<String> {
        self.api_value("http_workers")
    }

    /// Get the maximum number of HTTP connections from configuration.
    pub fn get_http_max_connections(&self) -> Option<String> {
        self.api_value("http_max_connections")
    }

    /// Get the HTTP backlog from configuration.
    pub fn get_http_backlog(&self) -> Option<String> {
        self.api_value("http_backlog")
    }

    /// Get the TCP keepalive timeout in seconds from configuration.
    pub fn get_tcp_keepalive_secs(&self) -> Option<String> {
        self.api_value("tcp_keepalive_secs")
    }

    /// Returns the validated API port.
    pub fn get_api_port(&self) -> u16 {
        self.normalized_u16(
            "api.port",
            self.get_api(),
            NumericRange::new(4052.0, 65_535.0),
        )
    }

    /// Returns the validated cache TTL in seconds.
    pub fn get_cache_ttl_secs(&self) -> u64 {
        self.normalized_u64(
            "api.cache_ttl",
            self.get_cache_ttl(),
            NumericRange::new(240.0, 86_400.0),
        )
    }

    /// Returns the validated HTTP client pool idle timeout in seconds.
    pub fn get_pool_idle_timeout_secs(&self) -> u64 {
        self.normalized_u64(
            "api.pool_idle_timeout",
            self.get_pool_idle_timeout(),
            NumericRange::new(90.0, 86_400.0),
        )
    }

    /// Returns the validated keep-alive timeout in seconds.
    pub fn get_http_keep_alive_timeout_secs(&self) -> u64 {
        self.normalized_u64(
            "api.keep_alive_secs",
            self.get_http_keep_alive_secs(),
            NumericRange::new(15.0, 3_600.0),
        )
    }

    /// Returns the validated client disconnect timeout in seconds.
    pub fn get_client_disconnect_timeout_value_secs(&self) -> u64 {
        self.normalized_u64(
            "api.client_disconnect_timeout_secs",
            self.get_client_disconnect_timeout_secs(),
            NumericRange::new(60.0, 3_600.0),
        )
    }

    /// Returns the validated client request timeout in seconds.
    pub fn get_client_request_timeout_value_secs(&self) -> u64 {
        self.normalized_u64(
            "api.client_request_timeout_secs",
            self.get_client_request_timeout_secs(),
            NumericRange::new(60.0, 3_600.0),
        )
    }

    /// Returns the validated HTTP worker count.
    pub fn get_http_worker_count(&self) -> usize {
        self.normalized_usize(
            "api.http_workers",
            self.get_http_workers(),
            NumericRange::new(8.0, 256.0),
        )
    }

    /// Returns the validated maximum HTTP connections.
    pub fn get_http_max_connections_value(&self) -> usize {
        self.normalized_usize(
            "api.http_max_connections",
            self.get_http_max_connections(),
            NumericRange::new(10_000.0, 1_000_000.0),
        )
    }

    /// Returns the validated HTTP listener backlog.
    pub fn get_http_backlog_value(&self) -> usize {
        self.normalized_usize(
            "api.http_backlog",
            self.get_http_backlog(),
            NumericRange::new(2_048.0, 65_535.0),
        )
    }

    /// Returns the validated TCP keepalive in seconds.
    pub fn get_tcp_keepalive_timeout_secs(&self) -> u64 {
        self.normalized_u64(
            "api.tcp_keepalive_secs",
            self.get_tcp_keepalive_secs(),
            NumericRange::new(75.0, 3_600.0),
        )
    }

    /// Returns whether CORS should allow all origins.
    ///
    /// Defaults to `false` for explicit allowlist-based security.
    pub fn get_cors_allow_any_origin(&self) -> bool {
        self.api
            .iter()
            .find_map(|map| map.get("cors_allow_any_origin"))
            .and_then(|value| value.parse().ok())
            .unwrap_or(false)
    }

    /// Returns configured CORS origins as a comma-separated list.
    ///
    /// Origins from `api.cors_allowed_origins` in `config.yaml` are merged with
    /// `ATHENA_CORS_ALLOWED_ORIGINS` (comma-separated) when set, without duplicates.
    pub fn get_cors_allowed_origins(&self) -> Vec<String> {
        let mut origins: Vec<String> = self
            .api
            .iter()
            .find_map(|map| map.get("cors_allowed_origins"))
            .map(|value| {
                value
                    .split(',')
                    .map(|origin| origin.trim().to_string())
                    .filter(|origin| !origin.is_empty())
                    .collect()
            })
            .unwrap_or_default();

        if let Ok(extra) = env::var("ATHENA_CORS_ALLOWED_ORIGINS") {
            for part in extra.split(',') {
                let trimmed: String = part.trim().to_string();
                if trimmed.is_empty() {
                    continue;
                }
                if !origins.iter().any(|o| o == &trimmed) {
                    origins.push(trimmed);
                }
            }
        }

        origins
    }

    /// Get the authenticator configuration for a given service.
    ///
    /// # Arguments
    ///
    /// * `service` - The name of the service to look up.
    pub fn get_authenticator(&self, service: &str) -> Option<&HashMap<String, String>> {
        self.authenticator.iter().find_map(|map| map.get(service))
    }

    /// Get authenticator settings with optional `${ENV_VAR}` resolution per field.
    ///
    /// Fields resolving to empty values are omitted.
    pub fn get_authenticator_resolved(&self, service: &str) -> Option<HashMap<String, String>> {
        let raw = self.get_authenticator(service)?;
        let mut resolved: HashMap<String, String> = HashMap::new();
        for (key, value) in raw {
            if let Some(parsed) = Self::resolve_env_placeholder(Some(value)) {
                resolved.insert(key.clone(), parsed);
            }
        }
        Some(resolved)
    }

    /// Get the PostgreSQL URI for a given client name.
    ///
    /// # Arguments
    ///
    /// * `client` - The name of the PostgreSQL client to look up.
    pub fn get_postgres_uri(&self, client: &str) -> Option<&String> {
        self.postgres_clients.iter().find_map(|map| map.get(client))
    }

    /// Get a Postgres URI with optional `${ENV_VAR}` resolution.
    pub fn get_postgres_uri_resolved(&self, client: &str) -> Option<String> {
        Self::resolve_env_placeholder(self.get_postgres_uri(client))
    }

    /// Get whether to force camelCase to snake_case conversion in the gateway.
    pub fn get_gateway_force_camel_case_to_snake_case(&self) -> bool {
        self.gateway_value("force_camel_case_to_snake_case")
            .and_then(|value| value.parse().ok())
            .unwrap_or(false)
    }

    /// Returns the expected Athena schema tables for provisioning status checks.
    ///
    /// Config key: `provisioning.expected_tables` (comma-separated table names).
    pub fn get_provisioning_expected_tables(&self) -> Vec<String> {
        let configured: Vec<String> = self
            .provisioning_value("expected_tables")
            .map(|value| {
                value
                    .split(',')
                    .map(|table| table.trim().to_string())
                    .filter(|table| !table.is_empty())
                    .collect()
            })
            .unwrap_or_default();

        if configured.is_empty() {
            DEFAULT_PROVISIONING_EXPECTED_TABLES
                .iter()
                .map(|table| (*table).to_string())
                .collect()
        } else {
            configured
        }
    }

    /// Returns the default Docker Postgres image used by provisioning APIs.
    ///
    /// Config key: `provisioning.default_postgres_image`.
    pub fn get_provisioning_default_postgres_image(&self) -> String {
        self.provisioning_value("default_postgres_image")
            .map(|value| value.trim().to_string())
            .filter(|value| !value.is_empty())
            .unwrap_or_else(|| DEFAULT_PROVISIONING_POSTGRES_IMAGE.to_string())
    }

    /// Returns the default host for local managed Postgres instances.
    ///
    /// Config key: `provisioning.default_instance_host`.
    pub fn get_provisioning_default_instance_host(&self) -> String {
        self.provisioning_value("default_instance_host")
            .map(|value| value.trim().to_string())
            .filter(|value| !value.is_empty())
            .unwrap_or_else(|| DEFAULT_PROVISIONING_INSTANCE_HOST.to_string())
    }

    /// Returns the default startup timeout in seconds for local Postgres provisioning.
    ///
    /// Config key: `provisioning.default_startup_timeout_secs`.
    pub fn get_provisioning_default_startup_timeout_secs(&self) -> u64 {
        self.provisioning_value("default_startup_timeout_secs")
            .and_then(|value| value.trim().parse::<u64>().ok())
            .filter(|value| *value > 0)
            .unwrap_or(DEFAULT_PROVISIONING_STARTUP_TIMEOUT_SECS)
    }

    /// Returns the default Neon API base URL for provisioning.
    ///
    /// Config key: `provisioning.default_neon_api_base_url`.
    pub fn get_provisioning_default_neon_api_base_url(&self) -> String {
        self.provisioning_value("default_neon_api_base_url")
            .map(|value| value.trim().to_string())
            .filter(|value| !value.is_empty())
            .unwrap_or_else(|| DEFAULT_PROVISIONING_NEON_API_BASE_URL.to_string())
    }

    /// Returns the default Railway GraphQL URL for provisioning.
    ///
    /// Config key: `provisioning.default_railway_graphql_url`.
    pub fn get_provisioning_default_railway_graphql_url(&self) -> String {
        self.provisioning_value("default_railway_graphql_url")
            .map(|value| value.trim().to_string())
            .filter(|value| !value.is_empty())
            .unwrap_or_else(|| DEFAULT_PROVISIONING_RAILWAY_GRAPHQL_URL.to_string())
    }

    /// Returns the default Render API base URL for provisioning.
    ///
    /// Config key: `provisioning.default_render_api_base_url`.
    pub fn get_provisioning_default_render_api_base_url(&self) -> String {
        self.provisioning_value("default_render_api_base_url")
            .map(|value| value.trim().to_string())
            .filter(|value| !value.is_empty())
            .unwrap_or_else(|| DEFAULT_PROVISIONING_RENDER_API_BASE_URL.to_string())
    }

    /// Returns the sudo password used to escalate Docker commands on Linux when
    /// the process user lacks direct daemon socket access.
    ///
    /// Evaluated in order: `ATHENA_DOCKER_SUDO_PASSWORD` env var →
    /// `provisioning.docker_sudo_password` config key → `None`.
    pub fn get_provisioning_docker_sudo_password(&self) -> Option<String> {
        if let Ok(val) = std::env::var("ATHENA_DOCKER_SUDO_PASSWORD") {
            let trimmed = val.trim().to_string();
            if !trimmed.is_empty() {
                return Some(trimmed);
            }
        }
        self.provisioning_value("docker_sudo_password")
            .map(|value| value.trim().to_string())
            .filter(|value| !value.is_empty())
    }

    /// Returns whether Athena should attempt to self-heal Docker group membership
    /// by running `usermod -aG docker <current-user>` and restarting when it
    /// encounters a daemon permission-denied error.
    ///
    /// Config key: `provisioning.docker_self_heal_group` (bool, default `false`).
    /// Can also be set via env `ATHENA_DOCKER_SELF_HEAL_GROUP=true`.
    pub fn get_provisioning_docker_self_heal_group(&self) -> bool {
        if let Ok(val) = std::env::var("ATHENA_DOCKER_SELF_HEAL_GROUP") {
            let v = val.trim().to_lowercase();
            if v == "true" || v == "1" || v == "yes" {
                return true;
            }
            if v == "false" || v == "0" || v == "no" {
                return false;
            }
        }
        self.provisioning_value("docker_self_heal_group")
            .and_then(|value| match value.trim().to_lowercase().as_str() {
                "true" | "1" | "yes" => Some(true),
                "false" | "0" | "no" => Some(false),
                _ => None,
            })
            .unwrap_or(false)
    }

    /// Allows plain HTTP Typesense URLs in development-only environments.
    ///
    /// Config key: `typesense.allow_http` (default `false`).
    pub fn get_typesense_allow_http(&self) -> bool {
        self.typesense_value("allow_http")
            .map(|value| matches!(value.trim(), "1" | "true" | "TRUE" | "yes" | "YES"))
            .unwrap_or(false)
    }

    /// Allows legacy Axum wildcard route syntax (`/*name`) to be auto-converted
    /// to `/{*name}` for CDC WebSocket route registration.
    ///
    /// Config key: `cdc.allow_legacy_axum_wildcards` (default `false`).
    pub fn get_cdc_allow_legacy_axum_wildcards(&self) -> bool {
        self.cdc_value("allow_legacy_axum_wildcards")
            .map(|value| matches!(value.trim(), "1" | "true" | "TRUE" | "yes" | "YES"))
            .unwrap_or(false)
    }

    /// Enables the background Typesense scheduled-sync worker.
    ///
    /// Config key: `typesense.sync_worker_enabled` (default `true`).
    pub fn get_typesense_sync_worker_enabled(&self) -> bool {
        self.typesense_value("sync_worker_enabled")
            .map(|value| !matches!(value.trim(), "0" | "false" | "FALSE" | "off" | "OFF"))
            .unwrap_or(true)
    }

    /// Poll interval in milliseconds for the background Typesense sync worker.
    ///
    /// Config key: `typesense.sync_worker_poll_ms` (default `30000`, minimum `1000`).
    pub fn get_typesense_sync_worker_poll_ms(&self) -> u64 {
        self.typesense_value("sync_worker_poll_ms")
            .and_then(|value| value.trim().parse::<u64>().ok())
            .filter(|value| *value >= 1_000)
            .unwrap_or(30_000)
    }

    /// Maximum attempts for retryable Typesense import operations.
    ///
    /// Config key: `typesense.import_max_attempts` (default `3`, clamped `1..=10`).
    pub fn get_typesense_import_max_attempts(&self) -> usize {
        self.typesense_value("import_max_attempts")
            .and_then(|value| value.trim().parse::<usize>().ok())
            .map(|value| value.clamp(1, 10))
            .unwrap_or(3)
    }

    /// Base retry delay in milliseconds for Typesense import retry backoff.
    ///
    /// Config key: `typesense.import_retry_base_ms` (default `400`, clamped `100..=5000`).
    pub fn get_typesense_import_retry_base_ms(&self) -> u64 {
        self.typesense_value("import_retry_base_ms")
            .and_then(|value| value.trim().parse::<u64>().ok())
            .map(|value| value.clamp(100, 5_000))
            .unwrap_or(400)
    }

    /// Enables saga-style per-batch backup snapshots for compensation rollback.
    ///
    /// Config key: `typesense.sync_saga_backup_enabled` (default `true`).
    pub fn get_typesense_sync_saga_backup_enabled(&self) -> bool {
        self.typesense_value("sync_saga_backup_enabled")
            .map(|value| !matches!(value.trim(), "0" | "false" | "FALSE" | "off" | "OFF"))
            .unwrap_or(true)
    }

    /// Enables the backup schedule/enqueue/execution workers.
    ///
    /// Config key: `backup.worker_enabled` (default `true`).
    pub fn get_backup_worker_enabled(&self) -> bool {
        self.backup_value("worker_enabled")
            .map(|value| !matches!(value.trim(), "0" | "false" | "FALSE" | "off" | "OFF"))
            .unwrap_or(true)
    }

    /// Poll interval in milliseconds for queued backup/restore execution.
    ///
    /// Config key: `backup.execution_worker_poll_ms` (default `1500`, minimum `250`).
    pub fn get_backup_execution_worker_poll_ms(&self) -> u64 {
        self.backup_value("execution_worker_poll_ms")
            .and_then(|value| value.trim().parse::<u64>().ok())
            .filter(|value| *value >= 250)
            .unwrap_or(1_500)
    }

    /// Poll interval in milliseconds for due backup schedules.
    ///
    /// Config key: `backup.schedule_worker_poll_ms` (default `30000`, minimum `1000`).
    pub fn get_backup_schedule_worker_poll_ms(&self) -> u64 {
        self.backup_value("schedule_worker_poll_ms")
            .and_then(|value| value.trim().parse::<u64>().ok())
            .filter(|value| *value >= 1_000)
            .unwrap_or(30_000)
    }

    /// Max attempts for queued backup/restore jobs.
    ///
    /// Config key: `backup.worker_max_attempts` (default `3`, clamped `1..=10`).
    pub fn get_backup_worker_max_attempts(&self) -> i32 {
        self.backup_value("worker_max_attempts")
            .and_then(|value| value.trim().parse::<i32>().ok())
            .map(|value| value.clamp(1, 10))
            .unwrap_or(3)
    }

    /// Lease TTL in minutes for backup/restore job ownership.
    ///
    /// Config key: `backup.worker_lease_ttl_minutes` (default `15`, clamped `1..=120`).
    pub fn get_backup_worker_lease_ttl_minutes(&self) -> i32 {
        self.backup_value("worker_lease_ttl_minutes")
            .and_then(|value| value.trim().parse::<i32>().ok())
            .map(|value| value.clamp(1, 120))
            .unwrap_or(15)
    }

    /// Enables separate daemon ownership of background workers.
    ///
    /// Config key: `daemon.enabled` (default `false`).
    pub fn get_daemon_enabled(&self) -> bool {
        self.daemon_value("enabled")
            .map(|value| matches!(value.trim(), "1" | "true" | "TRUE" | "yes" | "YES"))
            .unwrap_or(false)
    }

    /// Optional daemon id override.
    ///
    /// Config key: `daemon.id`.
    pub fn get_daemon_id(&self) -> Option<String> {
        self.daemon_value("id")
            .map(|value| value.trim().to_string())
            .filter(|value| !value.is_empty())
    }

    /// Enables the dedicated clone worker in the daemon runtime.
    ///
    /// Config key: `daemon.clone_worker_enabled` (default `true`).
    pub fn get_daemon_clone_worker_enabled(&self) -> bool {
        self.daemon_value("clone_worker_enabled")
            .map(|value| !matches!(value.trim(), "0" | "false" | "FALSE" | "no" | "NO"))
            .unwrap_or(true)
    }

    /// Clone worker poll interval in milliseconds.
    ///
    /// Config key: `daemon.clone_worker_poll_ms` (default `3000`, minimum `500`).
    pub fn get_daemon_clone_worker_poll_ms(&self) -> u64 {
        self.daemon_value("clone_worker_poll_ms")
            .and_then(|value| value.trim().parse::<u64>().ok())
            .filter(|value| *value >= 500)
            .unwrap_or(3_000)
    }

    /// Clone worker lease TTL in seconds.
    ///
    /// Config key: `daemon.clone_worker_lease_ttl_secs` (default `900`, minimum `60`).
    pub fn get_daemon_clone_worker_lease_ttl_secs(&self) -> i64 {
        self.daemon_value("clone_worker_lease_ttl_secs")
            .and_then(|value| value.trim().parse::<i64>().ok())
            .filter(|value| *value >= 60)
            .unwrap_or(900)
    }

    /// Get the configured logging client name for gateway activity.
    ///
    /// Env `ATHENA_GATEWAY_LOGGING_CLIENT` overrides `gateway.logging_client`
    /// when set to a non-empty value.
    pub fn get_gateway_logging_client(&self) -> Option<String> {
        self.gateway_value("logging_client")
    }

    /// Get an optional explicit Postgres URI override for the gateway logging
    /// client.
    ///
    /// This is useful when operators want Athena's logging/auth catalog to use a
    /// dedicated database connection independent of other `postgres_clients`
    /// entries. Supports either a direct URI (`logging_pg_uri`) or an env-var
    /// indirection (`logging_pg_uri_env_var`).
    pub fn get_gateway_logging_pg_uri(&self) -> Option<String> {
        fn usable_resolved_logging_uri(raw: Option<String>) -> Option<String> {
            let raw = raw?;
            let template = raw.trim();
            if template.is_empty() {
                return None;
            }
            let resolved = crate::parser::resolve_postgres_uri(template);
            if resolved.trim().is_empty() {
                return None;
            }
            if crate::parser::describe_postgres_uri_problem(&resolved).is_some() {
                return None;
            }
            Some(resolved)
        }

        if let Some(uri) = usable_resolved_logging_uri(self.gateway_value("logging_pg_uri")) {
            return Some(uri);
        }

        self.gateway_value("logging_pg_uri_env_var")
            .map(|value| value.trim().to_string())
            .filter(|value| !value.is_empty())
            .and_then(|env_var| {
                let placeholder = format!("${{{env_var}}}");
                usable_resolved_logging_uri(Some(placeholder))
            })
    }

    /// Background `client_statistics` / `client_table_statistics` refresh at API startup.
    ///
    /// When `true`, startup uses the same full recompute as
    /// `POST /admin/clients/statistics/refresh` (percentiles + orphan cleanup).
    /// When `false` (default), startup uses a fast counters-only upsert path.
    ///
    /// Config key: `gateway.client_statistics_startup_refresh_mode` — value `full`
    /// enables full mode; any other value or omission selects fast mode.
    pub fn get_gateway_client_statistics_startup_refresh_full(&self) -> bool {
        self.gateway_value("client_statistics_startup_refresh_mode")
            .is_some_and(|value| value.eq_ignore_ascii_case("full"))
    }

    /// Optional lookback window in days for **startup** client statistics refresh only.
    ///
    /// When set to a positive integer, only `gateway_*_log` rows with
    /// `created_at >= now() - interval 'N days'` are aggregated. When unset or
    /// zero, all log rows are included (subject to the usual non-null filters).
    ///
    /// Config key: `gateway.client_statistics_startup_refresh_lookback_days`.
    pub fn get_gateway_client_statistics_startup_refresh_lookback_days(&self) -> Option<u32> {
        self.gateway_value("client_statistics_startup_refresh_lookback_days")
            .and_then(|value| value.trim().parse::<u32>().ok())
            .filter(|days| *days > 0)
    }

    /// Get whether UUID-like gateway filter values should be cast to text when
    /// Athena also casts the column side of the comparison to text.
    pub fn get_gateway_auto_cast_uuid_filter_values_to_text(&self) -> bool {
        self.gateway_value("auto_cast_uuid_filter_values_to_text")
            .and_then(|value| value.parse().ok())
            .unwrap_or(true)
    }

    /// Returns whether `public.`-prefixed table names should be normalized to
    /// unqualified table names for information_schema column lookups.
    ///
    /// Defaults to `true` so `public.table_name` resolves as `table_name`.
    pub fn get_gateway_allow_schema_names_prefixed_as_table_name(&self) -> bool {
        self.gateway_value("allow_schema_names_prefixed_as_table_name")
            .and_then(|value| value.parse().ok())
            .unwrap_or(true)
    }

    /// Milliseconds to accumulate `/gateway/insert` Postgres requests before flush (`0` = disabled).
    ///
    /// Per-request `X-Athena-Insert-Window` can enable or override when non-zero.
    pub fn get_gateway_insert_execution_window_ms(&self) -> u64 {
        self.normalized_u64(
            "gateway.insert_execution_window_ms",
            self.gateway_value("insert_execution_window_ms"),
            NumericRange::new(0.0, 60_000.0),
        )
    }

    /// Max rows per merged bulk insert in the insert window (`1`–`10000`).
    pub fn get_gateway_insert_window_max_batch(&self) -> usize {
        self.normalized_usize(
            "gateway.insert_window_max_batch",
            self.gateway_value("insert_window_max_batch"),
            NumericRange::new(100.0, 10_000.0),
        )
    }

    /// Max queued insert-window jobs before falling back to direct execution.
    pub fn get_gateway_insert_window_max_queued(&self) -> usize {
        self.normalized_usize(
            "gateway.insert_window_max_queued",
            self.gateway_value("insert_window_max_queued"),
            NumericRange::new(10_000.0, 1_000_000.0),
        )
    }

    /// Comma-separated table names that must not participate in bulk merge (still windowed).
    pub fn get_gateway_insert_merge_deny_tables(&self) -> HashSet<String> {
        self.gateway_value("insert_merge_deny_tables")
            .map(|value| {
                value
                    .split(',')
                    .map(|t| t.trim().to_string())
                    .filter(|t| !t.is_empty())
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Returns whether JDBC connections to private/local hosts are allowed.
    ///
    /// Defaults to `false` when not configured.
    pub fn get_gateway_jdbc_allow_private_hosts(&self) -> bool {
        self.gateway_value("jdbc_allow_private_hosts")
            .and_then(|value| value.parse().ok())
            .unwrap_or(false)
    }

    /// Returns a host allowlist for `X-JDBC-URL` direct connections.
    ///
    /// When non-empty, all JDBC hosts must be included in this list.
    pub fn get_gateway_jdbc_allowed_hosts(&self) -> Vec<String> {
        self.gateway_value("jdbc_allowed_hosts")
            .map(|value| {
                value
                    .split(',')
                    .map(|host| host.trim().to_ascii_lowercase())
                    .filter(|host| !host.is_empty())
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Returns the gateway resilience operation timeout in seconds.
    ///
    /// Defaults to 30 when not configured.
    pub fn get_gateway_resilience_timeout_secs(&self) -> u64 {
        self.normalized_u64(
            "gateway.resilience_timeout_secs",
            self.gateway_value("resilience_timeout_secs"),
            NumericRange::new(30.0, 600.0),
        )
    }

    /// Returns the max retries for read operations on transient failures.
    ///
    /// Defaults to 1 when not configured. Writes do not retry.
    pub fn get_gateway_resilience_read_max_retries(&self) -> u32 {
        self.normalized_u32(
            "gateway.resilience_read_max_retries",
            self.gateway_value("resilience_read_max_retries"),
            NumericRange::new(1.0, 20.0),
        )
    }

    /// Returns the initial backoff between retries in milliseconds.
    ///
    /// Defaults to 100 when not configured.
    pub fn get_gateway_resilience_initial_backoff_ms(&self) -> u64 {
        self.normalized_u64(
            "gateway.resilience_initial_backoff_ms",
            self.gateway_value("resilience_initial_backoff_ms"),
            NumericRange::new(100.0, 60_000.0),
        )
    }

    /// Returns whether gateway admission limiting middleware is enabled.
    ///
    /// Defaults to `false` when not configured.
    pub fn get_gateway_admission_limit_enabled(&self) -> bool {
        self.gateway
            .iter()
            .find_map(|map| map.get("admission_limit_enabled"))
            .and_then(|value| value.parse().ok())
            .unwrap_or(false)
    }

    /// Returns the global admission budget in requests per window.
    ///
    /// Defaults to `0` (unlimited) when not configured.
    pub fn get_gateway_admission_global_requests_per_window(&self) -> u64 {
        self.normalized_u64(
            "gateway.admission_global_requests_per_window",
            self.gateway_value("admission_global_requests_per_window"),
            NumericRange::new(0.0, 10_000_000.0),
        )
    }

    /// Returns the per-client admission budget in requests per window.
    ///
    /// Defaults to `0` (unlimited) when not configured.
    pub fn get_gateway_admission_per_client_requests_per_window(&self) -> u64 {
        self.normalized_u64(
            "gateway.admission_per_client_requests_per_window",
            self.gateway_value("admission_per_client_requests_per_window"),
            NumericRange::new(0.0, 1_000_000.0),
        )
    }

    /// Returns the admission limiter window size in seconds.
    ///
    /// Defaults to `1` second when not configured.
    pub fn get_gateway_admission_window_secs(&self) -> u64 {
        self.normalized_u64(
            "gateway.admission_window_secs",
            self.gateway_value("admission_window_secs"),
            NumericRange::new(1.0, 3_600.0),
        )
    }

    /// Returns whether limiter overflow should enqueue deferrable requests.
    ///
    /// Defaults to `false` when not configured.
    pub fn get_gateway_admission_defer_on_limit_enabled(&self) -> bool {
        self.gateway
            .iter()
            .find_map(|map| map.get("admission_defer_on_limit_enabled"))
            .and_then(|value| value.parse().ok())
            .unwrap_or(false)
    }

    /// Returns route path prefixes eligible for deferral on limiter overflow.
    ///
    /// Uses a comma-separated list of route prefixes (for example:
    /// `/gateway/query,/pipelines`).
    pub fn get_gateway_admission_defer_route_prefixes(&self) -> Vec<String> {
        self.gateway_value("admission_defer_route_prefixes")
            .map(|value| {
                value
                    .split(',')
                    .map(str::trim)
                    .filter(|prefix| !prefix.is_empty())
                    .map(ToString::to_string)
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Returns whether the deferred query worker is enabled.
    ///
    /// Defaults to `true` when not configured.
    pub fn get_gateway_deferred_query_worker_enabled(&self) -> bool {
        self.gateway
            .iter()
            .find_map(|map| map.get("deferred_query_worker_enabled"))
            .and_then(|value| value.parse().ok())
            .unwrap_or(true)
    }

    /// Returns the deferred query worker poll interval in milliseconds.
    ///
    /// Defaults to `1000` when not configured.
    pub fn get_gateway_deferred_query_worker_poll_ms(&self) -> u64 {
        self.normalized_u64(
            "gateway.deferred_query_worker_poll_ms",
            self.gateway_value("deferred_query_worker_poll_ms"),
            NumericRange::new(1_000.0, 120_000.0),
        )
    }

    /// Returns the retention horizon for completed/dead-letter deferred jobs.
    ///
    /// `0` disables retention cleanup. When omitted, defaults to 30 days.
    pub fn get_gateway_deferred_query_retention_secs(&self) -> u64 {
        let raw = self.gateway_value("deferred_query_retention_secs");
        if raw.is_none() {
            return 2_592_000;
        }

        self.normalized_u64(
            "gateway.deferred_query_retention_secs",
            raw,
            NumericRange::new(0.0, 31_536_000.0),
        )
    }

    /// Returns the retention horizon for gateway log tables (`gateway_request_log`,
    /// `gateway_operation_log`). `0` disables cleanup. Defaults to 14 days.
    pub fn get_gateway_log_retention_secs(&self) -> u64 {
        let raw = self.gateway_value("log_retention_secs");
        if raw.is_none() {
            return 1_209_600;
        }

        self.normalized_u64(
            "gateway.log_retention_secs",
            raw,
            NumericRange::new(0.0, 31_536_000.0),
        )
    }

    /// Returns the interval in milliseconds between deferred queue cleanup passes.
    ///
    /// When omitted, defaults to 60 seconds.
    pub fn get_gateway_deferred_query_cleanup_interval_ms(&self) -> u64 {
        let raw = self.gateway_value("deferred_query_cleanup_interval_ms");
        if raw.is_none() {
            return 60_000;
        }

        self.normalized_u64(
            "gateway.deferred_query_cleanup_interval_ms",
            raw,
            NumericRange::new(1_000.0, 86_400_000.0),
        )
    }

    /// Get the configured auth client name for gateway API key storage.
    ///
    /// Falls back to the gateway logging client when `auth_client` is not set so
    /// installs can keep auth tables and gateway logs in the same database.
    pub fn get_gateway_auth_client(&self) -> Option<String> {
        self.gateway
            .iter()
            .find_map(|map| map.get("auth_client"))
            .map(|value| value.trim().to_string())
            .filter(|value| !value.is_empty())
            .or_else(|| self.get_gateway_logging_client())
    }

    /// Returns whether storage routes may accept deprecated raw identity headers.
    ///
    /// Config key: `storage.allow_legacy_identity_headers` (default `false`).
    pub fn get_storage_allow_legacy_identity_headers(&self) -> bool {
        self.storage_value("allow_legacy_identity_headers")
            .map(|value| {
                matches!(
                    value.to_ascii_lowercase().as_str(),
                    "1" | "true" | "yes" | "on"
                )
            })
            .unwrap_or(false)
    }

    /// Client name used for gateway end-to-end benchmarks and local performance tooling.
    ///
    /// When `benchmark_client` is unset, falls back to the gateway logging client so
    /// `cargo bench --bench gateway_e2e` targets the same database as logging by default.
    pub fn get_gateway_benchmark_client(&self) -> Option<String> {
        self.gateway
            .iter()
            .find_map(|map| map.get("benchmark_client"))
            .map(|value| value.trim().to_string())
            .filter(|value| !value.is_empty())
            .or_else(|| self.get_gateway_logging_client())
    }

    /// Returns the API key fail mode for gateway authorization.
    ///
    /// Supported values:
    /// - `fail_closed`: reject protected requests when auth store/policy is unavailable.
    /// - `fail_open`: allow protected requests when auth store is unavailable.
    ///
    /// Defaults to `fail_closed`.
    pub fn get_gateway_api_key_fail_mode(&self) -> String {
        self.gateway
            .iter()
            .find_map(|map| map.get("api_key_fail_mode"))
            .map(|value| value.trim().to_ascii_lowercase())
            .filter(|value| value == "fail_open" || value == "fail_closed")
            .unwrap_or_else(|| "fail_closed".to_string())
    }

    /// When true, the first hop of `X-Forwarded-For` is used as the inbound rate-limit key.
    pub fn get_gateway_rate_limit_trust_x_forwarded_for(&self) -> bool {
        if let Ok(value) = env::var("ATHENA_RATE_LIMIT_TRUST_X_FORWARDED_FOR") {
            return value == "1" || value.eq_ignore_ascii_case("true");
        }
        self.gateway_value("rate_limit_trust_x_forwarded_for")
            .map(|value| value == "1" || value.eq_ignore_ascii_case("true"))
            .unwrap_or(false)
    }

    /// When true, `extract_client_ip` may use `X-Forwarded-For` for gateway request logs,
    /// API auth logs, and audit entries (independent of rate-limit trust).
    pub fn get_gateway_logging_trust_x_forwarded_for(&self) -> bool {
        if let Ok(value) = env::var("ATHENA_LOGGING_TRUST_X_FORWARDED_FOR") {
            return value == "1" || value.eq_ignore_ascii_case("true");
        }
        self.gateway_value("logging_trust_x_forwarded_for")
            .map(|value| value == "1" || value.eq_ignore_ascii_case("true"))
            .unwrap_or(true)
    }

    /// Linux-only: append gateway request/operation logs and API key auth logs as NDJSON under a directory.
    ///
    /// Env `ATHENA_GATEWAY_LINUX_FILE_LOGGING_ENABLED` overrides the `linux_file_logging_enabled`
    /// gateway key.
    pub fn get_gateway_linux_file_logging_enabled(&self) -> bool {
        if let Ok(value) = env::var("ATHENA_GATEWAY_LINUX_FILE_LOGGING_ENABLED") {
            return value == "1" || value.eq_ignore_ascii_case("true");
        }
        self.gateway_value("linux_file_logging_enabled")
            .map(|value| value == "1" || value.eq_ignore_ascii_case("true"))
            .unwrap_or(false)
    }

    /// Directory for [`crate::utils::linux_gateway_file_log::LinuxGatewayFileLog`] when enabled on Linux.
    ///
    /// Env `ATHENA_GATEWAY_LINUX_FILE_LOGGING_DIR` overrides `linux_file_logging_dir`. Defaults to
    /// `/var/log/athena` when the gateway key is unset or empty.
    pub fn get_gateway_linux_file_logging_dir_or_default(&self) -> String {
        if let Ok(value) = env::var("ATHENA_GATEWAY_LINUX_FILE_LOGGING_DIR") {
            let trimmed = value.trim();
            if !trimmed.is_empty() {
                return trimmed.to_string();
            }
        }
        self.gateway_value("linux_file_logging_dir")
            .map(|value| value.trim().to_string())
            .filter(|value| !value.is_empty())
            .unwrap_or_else(|| "/var/log/athena".to_string())
    }

    fn rate_limit_inbound_enabled(&self, group: &str) -> bool {
        let key: String = format!("rate_limit_inbound_{group}_enabled");
        let env_key: String = format!(
            "ATHENA_RATE_LIMIT_INBOUND_{}_ENABLED",
            group.to_ascii_uppercase()
        );
        if let Ok(value) = env::var(env_key) {
            return value == "1" || value.eq_ignore_ascii_case("true");
        }
        self.gateway_value(&key)
            .map(|value| value == "1" || value.eq_ignore_ascii_case("true"))
            .unwrap_or(false)
    }

    fn rate_limit_inbound_per_second(&self, group: &str, default: u32) -> u32 {
        let key: String = format!("rate_limit_inbound_{group}_per_second");
        let env_key: String = format!(
            "ATHENA_RATE_LIMIT_INBOUND_{}_PER_SECOND",
            group.to_ascii_uppercase()
        );
        env::var(env_key)
            .ok()
            .and_then(|value| value.parse().ok())
            .or_else(|| {
                self.gateway_value(&key)
                    .and_then(|value| value.parse().ok())
            })
            .unwrap_or(default)
    }

    fn rate_limit_inbound_burst(&self, group: &str, default: u32) -> u32 {
        let key: String = format!("rate_limit_inbound_{group}_burst");
        let env_key: String = format!(
            "ATHENA_RATE_LIMIT_INBOUND_{}_BURST",
            group.to_ascii_uppercase()
        );
        env::var(env_key)
            .ok()
            .and_then(|value| value.parse().ok())
            .or_else(|| {
                self.gateway_value(&key)
                    .and_then(|value| value.parse().ok())
            })
            .unwrap_or(default)
    }

    pub fn get_gateway_rate_limit_inbound_storage_enabled(&self) -> bool {
        self.rate_limit_inbound_enabled("storage")
    }

    pub fn get_gateway_rate_limit_inbound_storage_per_second(&self) -> u32 {
        self.rate_limit_inbound_per_second("storage", 50)
    }

    pub fn get_gateway_rate_limit_inbound_storage_burst(&self) -> u32 {
        self.rate_limit_inbound_burst("storage", 100)
    }

    pub fn get_gateway_rate_limit_inbound_schema_enabled(&self) -> bool {
        self.rate_limit_inbound_enabled("schema")
    }

    pub fn get_gateway_rate_limit_inbound_schema_per_second(&self) -> u32 {
        self.rate_limit_inbound_per_second("schema", 30)
    }

    pub fn get_gateway_rate_limit_inbound_schema_burst(&self) -> u32 {
        self.rate_limit_inbound_burst("schema", 60)
    }

    pub fn get_gateway_rate_limit_inbound_raw_sql_enabled(&self) -> bool {
        self.rate_limit_inbound_enabled("raw_sql")
    }

    pub fn get_gateway_rate_limit_inbound_raw_sql_per_second(&self) -> u32 {
        self.rate_limit_inbound_per_second("raw_sql", 20)
    }

    pub fn get_gateway_rate_limit_inbound_raw_sql_burst(&self) -> u32 {
        self.rate_limit_inbound_burst("raw_sql", 40)
    }

    pub fn get_gateway_rate_limit_inbound_backup_admin_enabled(&self) -> bool {
        self.rate_limit_inbound_enabled("backup_admin")
    }

    pub fn get_gateway_rate_limit_inbound_backup_admin_per_second(&self) -> u32 {
        self.rate_limit_inbound_per_second("backup_admin", 30)
    }

    pub fn get_gateway_rate_limit_inbound_backup_admin_burst(&self) -> u32 {
        self.rate_limit_inbound_burst("backup_admin", 60)
    }

    pub fn get_gateway_rate_limit_outbound_supabase_enabled(&self) -> bool {
        if let Ok(value) = env::var("ATHENA_RATE_LIMIT_OUTBOUND_SUPABASE_ENABLED") {
            return value == "1" || value.eq_ignore_ascii_case("true");
        }
        self.gateway_value("rate_limit_outbound_supabase_enabled")
            .map(|value| value == "1" || value.eq_ignore_ascii_case("true"))
            .unwrap_or(false)
    }

    pub fn get_gateway_rate_limit_outbound_supabase_per_second(&self) -> u32 {
        env::var("ATHENA_RATE_LIMIT_OUTBOUND_SUPABASE_PER_SECOND")
            .ok()
            .and_then(|value| value.parse().ok())
            .or_else(|| {
                self.gateway_value("rate_limit_outbound_supabase_per_second")
                    .and_then(|value| value.parse().ok())
            })
            .unwrap_or(50)
    }

    pub fn get_gateway_rate_limit_outbound_supabase_burst(&self) -> u32 {
        env::var("ATHENA_RATE_LIMIT_OUTBOUND_SUPABASE_BURST")
            .ok()
            .and_then(|value| value.parse().ok())
            .or_else(|| {
                self.gateway_value("rate_limit_outbound_supabase_burst")
                    .and_then(|value| value.parse().ok())
            })
            .unwrap_or(100)
    }

    /// Returns the admission store backend.
    ///
    /// Supported values: `memory` or `redis`.
    /// Defaults to `redis`.
    pub fn get_gateway_admission_store_backend(&self) -> String {
        self.gateway
            .iter()
            .find_map(|map| map.get("admission_store_backend"))
            .map(|value| value.trim().to_ascii_lowercase())
            .filter(|value| value == "memory" || value == "redis")
            .unwrap_or_else(|| "redis".to_string())
    }

    /// Returns admission limiter fail mode when the backing store is unavailable.
    ///
    /// Supported values:
    /// - `fail_closed`: reject requests on limiter-store outages.
    /// - `fail_open`: allow requests on limiter-store outages.
    ///
    /// Defaults to `fail_closed`.
    pub fn get_gateway_admission_store_fail_mode(&self) -> String {
        self.gateway
            .iter()
            .find_map(|map| map.get("admission_store_fail_mode"))
            .map(|value| value.trim().to_ascii_lowercase())
            .filter(|value| value == "fail_open" || value == "fail_closed")
            .unwrap_or_else(|| "fail_closed".to_string())
    }

    /// Returns whether the Prometheus exporter route should be enabled.
    pub fn get_prometheus_metrics_enabled(&self) -> bool {
        self.api
            .iter()
            .find_map(|map| map.get("prometheus_metrics_enabled"))
            .and_then(|value| value.parse().ok())
            .unwrap_or(true)
    }

    /// Returns whether database-backed client catalog loading is enabled.
    ///
    /// When `false`, Athena skips querying `athena_clients` from the logging
    /// database during bootstrap and operates only with clients from `config.yaml`.
    /// Defaults to `true` for backward compatibility when not configured.
    pub fn get_gateway_database_backed_client_loading_enabled(&self) -> bool {
        self.gateway
            .iter()
            .find_map(|map| map.get("database_backed_client_loading"))
            .and_then(|value| value.parse().ok())
            .unwrap_or(true)
    }

    /// Returns whether Athena may continue booting without any connected Postgres clients.
    ///
    /// Env only: `ATHENA_ALLOW_START_WITHOUT_POSTGRES=true`.
    ///
    /// Defaults to `false` so request handling, logging, auth, and catalog-backed
    /// client loading do not start in a silently broken state.
    pub fn get_allow_start_without_postgres(&self) -> bool {
        let _ = self;
        env::var("ATHENA_ALLOW_START_WITHOUT_POSTGRES")
            .ok()
            .map(|value| {
                matches!(
                    value.trim().to_ascii_lowercase().as_str(),
                    "1" | "true" | "yes" | "on"
                )
            })
            .unwrap_or(false)
    }

    // -------------------------------------------------------------------------
    // Deferred writes
    // -------------------------------------------------------------------------

    fn deferred_writes_value(&self, key: &str) -> Option<&String> {
        self.deferred_writes.iter().find_map(|map| map.get(key))
    }

    /// Returns whether deferred write mode is enabled.
    ///
    /// When `true`, gateway mutations bypass the database and are written to an
    /// in-memory buffer and optional WAL. A background flush executor drains the
    /// buffer into Postgres on the configured schedule.
    pub fn get_deferred_writes_enabled(&self) -> bool {
        self.deferred_writes_value("enabled")
            .and_then(|v| v.parse::<bool>().ok())
            .unwrap_or(false)
    }

    /// Milliseconds between automatic flush runs.
    ///
    /// `0` disables the timer-based flush trigger. Defaults to `1000`.
    pub fn get_deferred_writes_batch_window_ms(&self) -> u64 {
        self.deferred_writes_value("batch_window_ms")
            .and_then(|v| v.parse::<u64>().ok())
            .filter(|v| *v >= 100 && *v <= 60_000)
            .unwrap_or(1000)
    }

    /// Flush the buffer when it reaches this many pending entries.
    ///
    /// `0` disables the size-based trigger. Defaults to `100`.
    pub fn get_deferred_writes_batch_max_size(&self) -> usize {
        self.deferred_writes_value("batch_max_size")
            .and_then(|v| v.parse::<usize>().ok())
            .filter(|v| *v <= 100_000)
            .unwrap_or(100)
    }

    /// Returns whether the WAL is enabled for crash-safe deferred write recovery.
    pub fn get_deferred_writes_wal_enabled(&self) -> bool {
        self.deferred_writes_value("wal_enabled")
            .and_then(|v| v.parse::<bool>().ok())
            .unwrap_or(true)
    }

    /// Directory where WAL files are written.
    ///
    /// Relative to CWD or an absolute path. Defaults to `"./data/wal"`.
    pub fn get_deferred_writes_wal_dir(&self) -> String {
        self.deferred_writes_value("wal_dir")
            .cloned()
            .unwrap_or_else(|| "./data/wal".to_string())
    }

    /// When `true`, cache invalidation is skipped after mutations even when
    /// deferred mode is off. Useful to keep the cache hot during write storms
    /// at the cost of short-lived staleness until TTL expiry.
    pub fn get_deferred_writes_skip_cache_invalidation(&self) -> bool {
        self.deferred_writes_value("skip_cache_invalidation")
            .and_then(|v| v.parse::<bool>().ok())
            .unwrap_or(false)
    }
}

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

    fn config_from_yaml(yaml: &str) -> Config {
        serde_yaml::from_str(yaml).expect("invalid test YAML")
    }

    fn minimal_yaml() -> &'static str {
        r#"
            urls: []
            hosts: []
            api:
            - port: "4052"
            - cache_ttl: "240"
            - pool_idle_timeout: "90"
            authenticator: []
            postgres_clients: []
            gateway: []
            backup: []
            "#
    }

    #[test]
    fn database_backed_client_loading_defaults_to_true() {
        let cfg = config_from_yaml(minimal_yaml());
        assert!(cfg.get_gateway_database_backed_client_loading_enabled());
    }

    #[test]
    fn database_backed_client_loading_explicit_false() {
        let yaml: &str = r#"
            urls: []
            hosts: []
            api:
            - port: "4052"
            - cache_ttl: "240"
            - pool_idle_timeout: "90"
            authenticator: []
            postgres_clients: []
            gateway:
            - database_backed_client_loading: false
            backup: []
            "#;
        let cfg: Config = config_from_yaml(yaml);
        assert!(!cfg.get_gateway_database_backed_client_loading_enabled());
    }

    #[test]
    fn database_backed_client_loading_explicit_true() {
        let yaml: &str = r#"
            urls: []
            hosts: []
            api:
            - port: "4052"
            - cache_ttl: "240"
            - pool_idle_timeout: "90"
            authenticator: []
            postgres_clients: []
            gateway:
            - database_backed_client_loading: true
            backup: []
            "#;
        let cfg = config_from_yaml(yaml);
        assert!(cfg.get_gateway_database_backed_client_loading_enabled());
    }

    #[test]
    fn start_without_postgres_defaults_to_false() {
        let _guard =
            crate::test_support::TestEnvGuard::unset("ATHENA_ALLOW_START_WITHOUT_POSTGRES");
        let cfg = config_from_yaml(minimal_yaml());
        assert!(!cfg.get_allow_start_without_postgres());
    }

    #[test]
    fn start_without_postgres_env_override_enables_opt_in() {
        let _guard =
            crate::test_support::TestEnvGuard::set("ATHENA_ALLOW_START_WITHOUT_POSTGRES", "true");
        let cfg = config_from_yaml(minimal_yaml());
        assert!(cfg.get_allow_start_without_postgres());
    }

    #[test]
    fn gateway_logging_pg_uri_uses_direct_value() {
        let yaml: &str = r#"
            urls: []
            hosts: []
            api:
            - port: "4052"
            - cache_ttl: "240"
            - pool_idle_timeout: "90"
            authenticator: []
            postgres_clients: []
            gateway:
            - logging_pg_uri: "postgres://athena:athena@localhost:5433/athena_logging"
            backup: []
            "#;

        let cfg = config_from_yaml(yaml);
        let uri = cfg
            .get_gateway_logging_pg_uri()
            .expect("expected logging_pg_uri override");
        assert_eq!(
            uri,
            "postgres://athena:athena@localhost:5433/athena_logging"
        );
    }

    #[test]
    fn gateway_logging_pg_uri_uses_env_var_reference() {
        let env_key: &str = "ATHENA_TEST_LOGGING_URI";
        unsafe {
            std::env::set_var(env_key, "postgres://env:env@localhost:5434/env_logging");
        }

        let yaml: String = format!(
            r#"
            urls: []
            hosts: []
            api:
            - port: "4052"
            - cache_ttl: "240"
            - pool_idle_timeout: "90"
            authenticator: []
            postgres_clients: []
            gateway:
            - logging_pg_uri_env_var: "{env_key}"
            backup: []
            "#
        );

        let cfg = config_from_yaml(&yaml);
        let uri = cfg
            .get_gateway_logging_pg_uri()
            .expect("expected logging_pg_uri_env_var override");
        assert_eq!(uri, "postgres://env:env@localhost:5434/env_logging");

        unsafe {
            std::env::remove_var(env_key);
        }
    }

    #[test]
    fn gateway_logging_pg_uri_skips_unresolved_direct_for_env_var_fallback() {
        let bad_key: &str = "ATHENA_TEST_LOGGING_URI_UNSET_FALLBACK";
        let good_key: &str = "ATHENA_TEST_LOGGING_URI_GOOD_FALLBACK";
        unsafe {
            std::env::remove_var(bad_key);
            std::env::set_var(good_key, "postgres://good:good@localhost:5435/good_logging");
        }

        let yaml: String = format!(
            r#"
            urls: []
            hosts: []
            api:
            - port: "4052"
            - cache_ttl: "240"
            - pool_idle_timeout: "90"
            authenticator: []
            postgres_clients: []
            gateway:
            - logging_pg_uri: "${{{0}}}"
            - logging_pg_uri_env_var: "{1}"
            backup: []
            "#,
            bad_key, good_key
        );

        let cfg = config_from_yaml(&yaml);
        let uri = cfg
            .get_gateway_logging_pg_uri()
            .expect("expected logging_pg_uri_env_var after direct placeholder unresolved");
        assert_eq!(uri, "postgres://good:good@localhost:5435/good_logging");

        unsafe {
            std::env::remove_var(good_key);
        }
    }

    #[test]
    fn cors_allow_any_origin_defaults_to_false_when_absent() {
        let cfg: Config = config_from_yaml(minimal_yaml());
        assert!(!cfg.get_cors_allow_any_origin());
    }

    #[test]
    fn api_key_fail_mode_defaults_to_fail_closed() {
        let cfg: Config = config_from_yaml(minimal_yaml());
        assert_eq!(cfg.get_gateway_api_key_fail_mode(), "fail_closed");
    }

    #[test]
    fn admission_store_defaults_are_redis_and_fail_closed() {
        let cfg: Config = config_from_yaml(minimal_yaml());
        assert_eq!(cfg.get_gateway_admission_store_backend(), "redis");
        assert_eq!(cfg.get_gateway_admission_store_fail_mode(), "fail_closed");
    }

    #[test]
    fn cors_allowed_origins_empty_when_not_set() {
        let cfg: Config = config_from_yaml(minimal_yaml());
        assert!(cfg.get_cors_allowed_origins().is_empty());
    }

    #[test]
    fn cors_allowed_origins_parsed_from_multiple_api_route_entries() {
        // Matches `config.yaml` `api:` shape: many `-` maps; values are strings.
        // `cors_allowed_origins` is comma-separated (see `get_cors_allowed_origins`).
        unsafe {
            std::env::remove_var("ATHENA_CORS_ALLOWED_ORIGINS");
        }

        let yaml: &str = r#"
            urls: []
            hosts: []
            api:
            - port: "4052"
            - cors_allow_any_origin: "false"
            - cache_ttl: "240"
            - pool_idle_timeout: "90"
            - cors_allowed_origins: "https://athena-db.com, https://studio.athena-db.com,http://localhost:3000"
            - http_workers: "8"
            authenticator: []
            postgres_clients: []
            gateway: []
            backup: []
            "#;

        let cfg: Config = config_from_yaml(yaml);
        assert_eq!(
            cfg.get_cors_allowed_origins(),
            vec![
                "https://athena-db.com".to_string(),
                "https://studio.athena-db.com".to_string(),
                "http://localhost:3000".to_string(),
            ]
        );
    }

    #[test]
    fn resilience_timeout_defaults_to_30() {
        let cfg: Config = config_from_yaml(minimal_yaml());
        assert_eq!(cfg.get_gateway_resilience_timeout_secs(), 30);
    }

    #[test]
    fn resilience_backoff_defaults_to_100ms() {
        let cfg: Config = config_from_yaml(minimal_yaml());
        assert_eq!(cfg.get_gateway_resilience_initial_backoff_ms(), 100);
    }

    #[test]
    fn deferred_queue_cleanup_defaults_are_stable() {
        let cfg: Config = config_from_yaml(minimal_yaml());
        assert_eq!(cfg.get_gateway_deferred_query_retention_secs(), 2_592_000);
        assert_eq!(cfg.get_gateway_deferred_query_cleanup_interval_ms(), 60_000);
    }

    #[test]
    fn gateway_log_retention_defaults_are_stable() {
        let cfg: Config = config_from_yaml(minimal_yaml());
        assert_eq!(cfg.get_gateway_log_retention_secs(), 1_209_600);
    }

    #[test]
    fn deferred_queue_cleanup_values_can_be_configured() {
        let yaml: &str = r#"
            urls: []
            hosts: []
            api:
            - port: "4052"
            - cache_ttl: "240"
            - pool_idle_timeout: "90"
            authenticator: []
            postgres_clients: []
            gateway:
            - deferred_query_retention_secs: 120
            - deferred_query_cleanup_interval_ms: 2500
            - log_retention_secs: 3600
            backup: []
            "#;

        let cfg: Config = config_from_yaml(yaml);
        assert_eq!(cfg.get_gateway_deferred_query_retention_secs(), 120);
        assert_eq!(cfg.get_gateway_deferred_query_cleanup_interval_ms(), 2500);
        assert_eq!(cfg.get_gateway_log_retention_secs(), 3600);
    }

    #[test]
    fn config_numeric_getter_clamps_to_override_max() {
        let yaml: &str = r#"
            urls: []
            hosts: []
            api:
            - port: "4052"
            - cache_ttl: "240"
            - pool_idle_timeout: "90"
            authenticator: []
            postgres_clients: []
            gateway:
            - admission_window_secs: "500"
            backup: []
            validation_ranges:
              config:
                gateway.admission_window_secs:
                  min: 1
                  max: 5
            "#;
        let cfg: Config = config_from_yaml(yaml);
        assert_eq!(cfg.get_gateway_admission_window_secs(), 5);
    }

    #[test]
    fn config_numeric_getter_uses_range_min_when_missing() {
        let yaml: &str = r#"
            urls: []
            hosts: []
            api:
            - port: "4052"
            - pool_idle_timeout: "90"
            authenticator: []
            postgres_clients: []
            gateway: []
            backup: []
            validation_ranges:
              config:
                api.cache_ttl:
                  min: 17
                  max: 300
            "#;
        let cfg: Config = config_from_yaml(yaml);
        assert_eq!(cfg.get_cache_ttl_secs(), 17);
    }

    #[test]
    fn provisioning_expected_tables_defaults_when_not_configured() {
        let cfg: Config = config_from_yaml(minimal_yaml());
        assert!(
            cfg.get_provisioning_expected_tables()
                .contains(&"gateway_request_log".to_string())
        );
    }

    #[test]
    fn provisioning_expected_tables_can_be_overridden() {
        let yaml: &str = r#"
            urls: []
            hosts: []
            api:
            - port: "4052"
            - cache_ttl: "240"
            - pool_idle_timeout: "90"
            authenticator: []
            postgres_clients: []
            gateway: []
            provisioning:
            - expected_tables: "custom_table_a,custom_table_b"
            backup: []
            "#;

        let cfg: Config = config_from_yaml(yaml);
        assert_eq!(
            cfg.get_provisioning_expected_tables(),
            vec!["custom_table_a".to_string(), "custom_table_b".to_string()]
        );
    }

    #[test]
    fn provisioning_defaults_can_be_overridden() {
        let yaml: &str = r#"
            urls: []
            hosts: []
            api:
            - port: "4052"
            - cache_ttl: "240"
            - pool_idle_timeout: "90"
            authenticator: []
            postgres_clients: []
            gateway: []
            provisioning:
            - default_postgres_image: "postgres:17-alpine"
            - default_instance_host: "0.0.0.0"
            - default_startup_timeout_secs: "120"
            - default_neon_api_base_url: "https://example-neon.local/v2"
            - default_railway_graphql_url: "https://example-railway.local/graphql"
            - default_render_api_base_url: "https://example-render.local/v1"
            backup: []
            "#;

        let cfg: Config = config_from_yaml(yaml);
        assert_eq!(
            cfg.get_provisioning_default_postgres_image(),
            "postgres:17-alpine"
        );
        assert_eq!(cfg.get_provisioning_default_instance_host(), "0.0.0.0");
        assert_eq!(cfg.get_provisioning_default_startup_timeout_secs(), 120);
        assert_eq!(
            cfg.get_provisioning_default_neon_api_base_url(),
            "https://example-neon.local/v2"
        );
        assert_eq!(
            cfg.get_provisioning_default_railway_graphql_url(),
            "https://example-railway.local/graphql"
        );
        assert_eq!(
            cfg.get_provisioning_default_render_api_base_url(),
            "https://example-render.local/v1"
        );
    }

    #[test]
    fn deferred_writes_defaults_are_safe() {
        let cfg: Config = config_from_yaml(minimal_yaml());
        assert!(!cfg.get_deferred_writes_enabled());
        assert_eq!(cfg.get_deferred_writes_batch_window_ms(), 1000);
        assert_eq!(cfg.get_deferred_writes_batch_max_size(), 100);
        assert!(cfg.get_deferred_writes_wal_enabled());
        assert_eq!(cfg.get_deferred_writes_wal_dir(), "./data/wal".to_string());
        assert!(!cfg.get_deferred_writes_skip_cache_invalidation());
    }

    #[test]
    fn deferred_writes_explicit_values_are_respected() {
        let yaml: &str = r#"
            urls: []
            hosts: []
            api:
            - port: "4052"
            - cache_ttl: "240"
            - pool_idle_timeout: "90"
            authenticator: []
            postgres_clients: []
            gateway: []
            deferred_writes:
            - enabled: true
            - batch_window_ms: 2500
            - batch_max_size: 250
            - wal_enabled: false
            - wal_dir: "./tmp/athena-wal"
            - skip_cache_invalidation: true
            backup: []
            "#;

        let cfg: Config = config_from_yaml(yaml);
        assert!(cfg.get_deferred_writes_enabled());
        assert_eq!(cfg.get_deferred_writes_batch_window_ms(), 2500);
        assert_eq!(cfg.get_deferred_writes_batch_max_size(), 250);
        assert!(!cfg.get_deferred_writes_wal_enabled());
        assert_eq!(cfg.get_deferred_writes_wal_dir(), "./tmp/athena-wal");
        assert!(cfg.get_deferred_writes_skip_cache_invalidation());
    }

    #[test]
    fn host_resolved_reads_env_placeholder() {
        let key = "ATHENA_TEST_SCYLLA_HOST";
        unsafe {
            std::env::set_var(key, "10.1.2.3:9042");
        }

        let yaml: String = format!(
            r#"
            urls: []
            hosts:
            - scylladb: "${{{key}}}"
            api:
            - port: "4052"
            - cache_ttl: "240"
            - pool_idle_timeout: "90"
            authenticator: []
            postgres_clients: []
            gateway: []
            backup: []
            "#
        );

        let cfg: Config = config_from_yaml(&yaml);
        assert_eq!(
            cfg.get_host_resolved("scylladb"),
            Some("10.1.2.3:9042".to_string())
        );

        unsafe {
            std::env::remove_var(key);
        }
    }

    #[test]
    fn authenticator_resolved_reads_env_placeholders() {
        let user_key = "ATHENA_TEST_SCYLLA_USER";
        let pass_key = "ATHENA_TEST_SCYLLA_PASS";
        unsafe {
            std::env::set_var(user_key, "cassandra");
            std::env::set_var(pass_key, "secret");
        }

        let yaml: String = format!(
            r#"
            urls: []
            hosts: []
            api:
            - port: "4052"
            - cache_ttl: "240"
            - pool_idle_timeout: "90"
            authenticator:
            - scylladb:
                username: "${{{user_key}}}"
                password: "${{{pass_key}}}"
                keyspace: "analytics"
            postgres_clients: []
            gateway: []
            backup: []
            "#
        );

        let cfg: Config = config_from_yaml(&yaml);
        let auth = cfg
            .get_authenticator_resolved("scylladb")
            .expect("resolved authenticator expected");
        assert_eq!(auth.get("username"), Some(&"cassandra".to_string()));
        assert_eq!(auth.get("password"), Some(&"secret".to_string()));
        assert_eq!(auth.get("keyspace"), Some(&"analytics".to_string()));

        unsafe {
            std::env::remove_var(user_key);
            std::env::remove_var(pass_key);
        }
    }

    #[test]
    fn postgres_uri_resolved_reads_env_placeholder() {
        let key = "ATHENA_TEST_LOGGING_URI_RESOLVED";
        unsafe {
            std::env::set_var(key, "postgres://user:pass@localhost:5432/athena_logging");
        }

        let yaml: String = format!(
            r#"
            urls: []
            hosts: []
            api:
            - port: "4052"
            - cache_ttl: "240"
            - pool_idle_timeout: "90"
            authenticator: []
            postgres_clients:
            - athena_logging: "${{{key}}}"
            gateway: []
            backup: []
            "#
        );

        let cfg: Config = config_from_yaml(&yaml);
        assert_eq!(
            cfg.get_postgres_uri_resolved("athena_logging"),
            Some("postgres://user:pass@localhost:5432/athena_logging".to_string())
        );

        unsafe {
            std::env::remove_var(key);
        }
    }

    #[test]
    fn gateway_linux_file_logging_config_resolution() {
        let key_dir = "ATHENA_GATEWAY_LINUX_FILE_LOGGING_DIR";

        let cfg = config_from_yaml(minimal_yaml());
        assert_eq!(
            cfg.get_gateway_linux_file_logging_dir_or_default(),
            "/var/log/athena"
        );
        assert!(!cfg.get_gateway_linux_file_logging_enabled());

        let yaml_gateway: &str = r#"
            urls: []
            hosts: []
            api:
            - port: "4052"
            - cache_ttl: "240"
            - pool_idle_timeout: "90"
            authenticator: []
            postgres_clients: []
            gateway:
            - linux_file_logging_enabled: true
            - linux_file_logging_dir: "/srv/athena/logs"
            backup: []
            "#;
        let cfg = config_from_yaml(yaml_gateway);
        assert!(cfg.get_gateway_linux_file_logging_enabled());
        assert_eq!(
            cfg.get_gateway_linux_file_logging_dir_or_default(),
            "/srv/athena/logs"
        );

        unsafe {
            std::env::set_var(key_dir, "/env/logs");
        }
        let yaml_override: &str = r#"
            urls: []
            hosts: []
            api:
            - port: "4052"
            - cache_ttl: "240"
            - pool_idle_timeout: "90"
            authenticator: []
            postgres_clients: []
            gateway:
            - linux_file_logging_dir: "/yaml/logs"
            backup: []
            "#;
        let cfg = config_from_yaml(yaml_override);
        assert_eq!(
            cfg.get_gateway_linux_file_logging_dir_or_default(),
            "/env/logs"
        );
        unsafe {
            std::env::remove_var(key_dir);
        }

        let cfg = config_from_yaml(minimal_yaml());
        assert_eq!(
            cfg.get_gateway_linux_file_logging_dir_or_default(),
            "/var/log/athena"
        );
    }

    #[test]
    fn gateway_logging_client_env_override_wins_over_yaml() {
        let key = "ATHENA_GATEWAY_LOGGING_CLIENT";
        unsafe {
            std::env::set_var(key, "env_logging_client");
        }

        let yaml_gateway: &str = r#"
            urls: []
            hosts: []
            api:
            - port: "4052"
            - cache_ttl: "240"
            - pool_idle_timeout: "90"
            authenticator: []
            postgres_clients: []
            gateway:
            - logging_client: "yaml_logging_client"
            backup: []
            "#;
        let cfg = config_from_yaml(yaml_gateway);
        assert_eq!(
            cfg.get_gateway_logging_client(),
            Some("env_logging_client".to_string())
        );

        unsafe {
            std::env::remove_var(key);
        }
    }

    #[test]
    fn api_scalar_env_override_is_parsed() {
        let key = "ATHENA_API_PORT";
        unsafe {
            std::env::set_var(key, "4123");
        }

        let cfg = config_from_yaml(minimal_yaml());
        assert_eq!(cfg.get_api_port(), 4123);

        unsafe {
            std::env::remove_var(key);
        }
    }

    #[test]
    fn backup_scalar_env_override_is_parsed() {
        let key = "ATHENA_BACKUP_WORKER_ENABLED";
        unsafe {
            std::env::set_var(key, "false");
        }

        let yaml: &str = r#"
            urls: []
            hosts: []
            api:
            - port: "4052"
            - cache_ttl: "240"
            - pool_idle_timeout: "90"
            authenticator: []
            postgres_clients: []
            gateway: []
            backup:
            - worker_enabled: true
            "#;
        let cfg = config_from_yaml(yaml);
        assert!(!cfg.get_backup_worker_enabled());

        unsafe {
            std::env::remove_var(key);
        }
    }

    #[test]
    fn typesense_worker_defaults_are_stable() {
        let cfg = config_from_yaml(minimal_yaml());
        assert!(!cfg.get_typesense_allow_http());
        assert!(cfg.get_typesense_sync_worker_enabled());
        assert_eq!(cfg.get_typesense_sync_worker_poll_ms(), 30_000);
        assert_eq!(cfg.get_typesense_import_max_attempts(), 3);
        assert_eq!(cfg.get_typesense_import_retry_base_ms(), 400);
        assert!(cfg.get_typesense_sync_saga_backup_enabled());
    }

    #[test]
    fn typesense_worker_values_can_be_overridden() {
        let yaml: &str = r#"
            urls: []
            hosts: []
            api:
            - port: "4052"
            - cache_ttl: "240"
            - pool_idle_timeout: "90"
            authenticator: []
            postgres_clients: []
            gateway: []
            typesense:
            - allow_http: true
            - sync_worker_enabled: false
            - sync_worker_poll_ms: 45000
            - import_max_attempts: 8
            - import_retry_base_ms: 700
            - sync_saga_backup_enabled: false
            backup: []
            "#;

        let cfg = config_from_yaml(yaml);
        assert!(cfg.get_typesense_allow_http());
        assert!(!cfg.get_typesense_sync_worker_enabled());
        assert_eq!(cfg.get_typesense_sync_worker_poll_ms(), 45_000);
        assert_eq!(cfg.get_typesense_import_max_attempts(), 8);
        assert_eq!(cfg.get_typesense_import_retry_base_ms(), 700);
        assert!(!cfg.get_typesense_sync_saga_backup_enabled());
    }

    #[test]
    fn backup_worker_defaults_are_stable() {
        let cfg = config_from_yaml(minimal_yaml());
        assert!(cfg.get_backup_worker_enabled());
        assert_eq!(cfg.get_backup_execution_worker_poll_ms(), 1_500);
        assert_eq!(cfg.get_backup_schedule_worker_poll_ms(), 30_000);
        assert_eq!(cfg.get_backup_worker_max_attempts(), 3);
        assert_eq!(cfg.get_backup_worker_lease_ttl_minutes(), 15);
    }

    #[test]
    fn backup_worker_values_can_be_overridden() {
        let yaml: &str = r#"
            urls: []
            hosts: []
            api:
            - port: "4052"
            - cache_ttl: "240"
            - pool_idle_timeout: "90"
            authenticator: []
            postgres_clients: []
            gateway: []
            typesense: []
            backup:
            - worker_enabled: false
            - execution_worker_poll_ms: 2500
            - schedule_worker_poll_ms: 45000
            - worker_max_attempts: 8
            - worker_lease_ttl_minutes: 30
            "#;

        let cfg = config_from_yaml(yaml);
        assert!(!cfg.get_backup_worker_enabled());
        assert_eq!(cfg.get_backup_execution_worker_poll_ms(), 2_500);
        assert_eq!(cfg.get_backup_schedule_worker_poll_ms(), 45_000);
        assert_eq!(cfg.get_backup_worker_max_attempts(), 8);
        assert_eq!(cfg.get_backup_worker_lease_ttl_minutes(), 30);
    }

    #[test]
    fn cdc_legacy_axum_wildcard_opt_in_defaults_to_false() {
        let cfg = config_from_yaml(minimal_yaml());
        assert!(!cfg.get_cdc_allow_legacy_axum_wildcards());
    }

    #[test]
    fn cdc_legacy_axum_wildcard_opt_in_can_be_enabled() {
        let yaml: &str = r#"
            urls: []
            hosts: []
            api:
            - port: "4052"
            - cache_ttl: "240"
            - pool_idle_timeout: "90"
            authenticator: []
            postgres_clients: []
            gateway: []
            cdc:
            - allow_legacy_axum_wildcards: true
            backup: []
            "#;
        let cfg = config_from_yaml(yaml);
        assert!(cfg.get_cdc_allow_legacy_axum_wildcards());
    }
}