athena_rs 3.3.0

Database gateway API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
//! 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};

/// 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 backup: Vec<HashMap<String, String>>,
}

pub const DEFAULT_CONFIG_FILE_NAME: &str = "config.yaml";
const DEFAULT_CONFIG_TEMPLATE: &str = include_str!("../config.yaml");

#[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 {
    /// 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
    }

    /// 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 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 API port from configuration.
    pub fn get_api(&self) -> Option<&String> {
        self.api.iter().find_map(|map| map.get("port"))
    }

    /// Get the immortal cache setting from configuration.
    pub fn get_immortal_cache(&self) -> Option<&String> {
        self.api.iter().find_map(|map| map.get("immortal_cache"))
    }

    /// Get the cache TTL (time to live) from configuration.
    pub fn get_cache_ttl(&self) -> Option<&String> {
        self.api.iter().find_map(|map| map.get("cache_ttl"))
    }

    /// Get the connection pool idle timeout from configuration.
    pub fn get_pool_idle_timeout(&self) -> Option<&String> {
        self.api.iter().find_map(|map| map.get("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.iter().find_map(|map| map.get("keep_alive_secs"))
    }

    /// Get the client disconnect timeout in seconds from configuration.
    pub fn get_client_disconnect_timeout_secs(&self) -> Option<&String> {
        self.api
            .iter()
            .find_map(|map| map.get("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
            .iter()
            .find_map(|map| map.get("client_request_timeout_secs"))
    }

    /// Get the number of HTTP workers from configuration.
    pub fn get_http_workers(&self) -> Option<&String> {
        self.api.iter().find_map(|map| map.get("http_workers"))
    }

    /// Get the maximum number of HTTP connections from configuration.
    pub fn get_http_max_connections(&self) -> Option<&String> {
        self.api
            .iter()
            .find_map(|map| map.get("http_max_connections"))
    }

    /// Get the HTTP backlog from configuration.
    pub fn get_http_backlog(&self) -> Option<&String> {
        self.api.iter().find_map(|map| map.get("http_backlog"))
    }

    /// Get the TCP keepalive timeout in seconds from configuration.
    pub fn get_tcp_keepalive_secs(&self) -> Option<&String> {
        self.api
            .iter()
            .find_map(|map| map.get("tcp_keepalive_secs"))
    }

    /// 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 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 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
            .iter()
            .find_map(|map| map.get("force_camel_case_to_snake_case"))
            .and_then(|value| value.parse().ok())
            .unwrap_or(false)
    }

    /// Get the configured logging client name for gateway activity.
    pub fn get_gateway_logging_client(&self) -> Option<&String> {
        self.gateway
            .iter()
            .find_map(|map| map.get("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> {
        if let Some(value) = self
            .gateway
            .iter()
            .find_map(|map| map.get("logging_pg_uri"))
            .map(|value| crate::parser::resolve_postgres_uri(value))
            .filter(|value| !value.trim().is_empty())
        {
            return Some(value);
        }

        self.gateway
            .iter()
            .find_map(|map| map.get("logging_pg_uri_env_var"))
            .map(|value| value.trim())
            .filter(|value| !value.is_empty())
            .map(|env_var| crate::parser::resolve_postgres_uri(&format!("${{{}}}", env_var)))
            .filter(|value| !value.trim().is_empty())
    }

    /// 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
            .iter()
            .find_map(|map| map.get("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
            .iter()
            .find_map(|map| map.get("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.gateway
            .iter()
            .find_map(|map| map.get("insert_execution_window_ms"))
            .and_then(|value| value.parse().ok())
            .unwrap_or(0)
    }

    /// Max rows per merged bulk insert in the insert window (`1`–`10000`).
    pub fn get_gateway_insert_window_max_batch(&self) -> usize {
        self.gateway
            .iter()
            .find_map(|map| map.get("insert_window_max_batch"))
            .and_then(|value| value.parse().ok())
            .unwrap_or(100)
            .clamp(1, 10_000)
    }

    /// Max queued insert-window jobs before falling back to direct execution.
    pub fn get_gateway_insert_window_max_queued(&self) -> usize {
        self.gateway
            .iter()
            .find_map(|map| map.get("insert_window_max_queued"))
            .and_then(|value| value.parse().ok())
            .unwrap_or(10_000)
            .max(1)
    }

    /// 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
            .iter()
            .find_map(|map| map.get("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 `true` for backward compatibility when not configured.
    pub fn get_gateway_jdbc_allow_private_hosts(&self) -> bool {
        self.gateway
            .iter()
            .find_map(|map| map.get("jdbc_allow_private_hosts"))
            .and_then(|value| value.parse().ok())
            .unwrap_or(true)
    }

    /// 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
            .iter()
            .find_map(|map| map.get("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.gateway
            .iter()
            .find_map(|map| map.get("resilience_timeout_secs"))
            .and_then(|value| value.parse().ok())
            .unwrap_or(30)
    }

    /// 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.gateway
            .iter()
            .find_map(|map| map.get("resilience_read_max_retries"))
            .and_then(|value| value.parse().ok())
            .unwrap_or(1)
    }

    /// 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.gateway
            .iter()
            .find_map(|map| map.get("resilience_initial_backoff_ms"))
            .and_then(|value| value.parse().ok())
            .unwrap_or(100)
    }

    /// 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.gateway
            .iter()
            .find_map(|map| map.get("admission_global_requests_per_window"))
            .and_then(|value| value.parse().ok())
            .unwrap_or(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.gateway
            .iter()
            .find_map(|map| map.get("admission_per_client_requests_per_window"))
            .and_then(|value| value.parse().ok())
            .unwrap_or(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.gateway
            .iter()
            .find_map(|map| map.get("admission_window_secs"))
            .and_then(|value| value.parse().ok())
            .unwrap_or(1)
    }

    /// 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
            .iter()
            .find_map(|map| map.get("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.gateway
            .iter()
            .find_map(|map| map.get("deferred_query_worker_poll_ms"))
            .and_then(|value| value.parse().ok())
            .unwrap_or(1000)
    }

    /// 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"))
            .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())
    }

    /// 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)
    }
}

#[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 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 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);
    }
}