dgate 2.1.0

DGate API Gateway - High-performance API gateway with JavaScript module support
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
//! Configuration module for DGate
//!
//! Handles loading and parsing configuration from YAML files and environment variables.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;

/// Main DGate configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DGateConfig {
    #[serde(default = "default_version")]
    pub version: String,

    #[serde(default = "default_log_level")]
    pub log_level: String,

    #[serde(default)]
    pub log_json: bool,

    #[serde(default)]
    pub debug: bool,

    #[serde(default)]
    pub disable_default_namespace: bool,

    #[serde(default)]
    pub disable_metrics: bool,

    #[serde(default)]
    pub tags: Vec<String>,

    #[serde(default)]
    pub storage: StorageConfig,

    #[serde(default)]
    pub proxy: ProxyConfig,

    #[serde(default)]
    pub admin: Option<AdminConfig>,

    #[serde(default)]
    pub test_server: Option<TestServerConfig>,

    /// Cluster configuration for distributed mode
    #[serde(default)]
    pub cluster: Option<ClusterConfig>,

    /// Directory where the config file is located (for resolving relative paths)
    #[serde(skip)]
    pub config_dir: std::path::PathBuf,
}

fn default_version() -> String {
    "v1".to_string()
}

fn default_log_level() -> String {
    "info".to_string()
}

impl Default for DGateConfig {
    fn default() -> Self {
        Self {
            version: default_version(),
            log_level: default_log_level(),
            log_json: false,
            debug: false,
            disable_default_namespace: false,
            disable_metrics: false,
            tags: Vec::new(),
            storage: StorageConfig::default(),
            proxy: ProxyConfig::default(),
            admin: None,
            test_server: None,
            cluster: None,
            config_dir: std::env::current_dir().unwrap_or_default(),
        }
    }
}

impl DGateConfig {
    /// Load configuration from a YAML file
    pub fn load_from_file(path: impl AsRef<Path>) -> anyhow::Result<Self> {
        let path = path.as_ref();
        let content = std::fs::read_to_string(path)?;
        let content = Self::expand_env_vars(&content);
        let mut config: Self = serde_yaml::from_str(&content)?;

        // Set the config directory for resolving relative paths
        config.config_dir = path
            .parent()
            .map(|p| p.to_path_buf())
            .unwrap_or_else(|| std::env::current_dir().unwrap_or_default());

        Ok(config)
    }

    /// Expand environment variables in format ${VAR:-default}
    fn expand_env_vars(content: &str) -> String {
        let re = regex::Regex::new(r"\$\{([^}:]+)(?::-([^}]*))?\}").unwrap();
        re.replace_all(content, |caps: &regex::Captures| {
            let var_name = &caps[1];
            let default_value = caps.get(2).map(|m| m.as_str()).unwrap_or("");
            std::env::var(var_name).unwrap_or_else(|_| default_value.to_string())
        })
        .to_string()
    }

    /// Load configuration from path or use defaults
    pub fn load(path: Option<&str>) -> anyhow::Result<Self> {
        match path {
            Some(p) if !p.is_empty() => Self::load_from_file(p),
            _ => {
                // Try common config locations
                let paths = ["config.dgate.yaml", "dgate.yaml", "/etc/dgate/config.yaml"];
                for path in paths {
                    if Path::new(path).exists() {
                        return Self::load_from_file(path);
                    }
                }
                Ok(Self::default())
            }
        }
    }
}

/// Storage configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StorageConfig {
    #[serde(rename = "type", default = "default_storage_type")]
    pub storage_type: StorageType,

    #[serde(default)]
    pub dir: Option<String>,

    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

fn default_storage_type() -> StorageType {
    StorageType::Memory
}

impl Default for StorageConfig {
    fn default() -> Self {
        Self {
            storage_type: StorageType::Memory,
            dir: None,
            extra: HashMap::new(),
        }
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Default)]
#[serde(rename_all = "lowercase")]
pub enum StorageType {
    #[default]
    Memory,
    File,
}

/// Proxy configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProxyConfig {
    #[serde(default = "default_proxy_host")]
    pub host: String,

    #[serde(default = "default_proxy_port")]
    pub port: u16,

    #[serde(default)]
    pub tls: Option<TlsConfig>,

    #[serde(default)]
    pub enable_h2c: bool,

    #[serde(default)]
    pub enable_http2: bool,

    #[serde(default = "default_console_log_level")]
    pub console_log_level: String,

    #[serde(default)]
    pub redirect_https: Vec<String>,

    #[serde(default)]
    pub allowed_domains: Vec<String>,

    #[serde(default)]
    pub global_headers: HashMap<String, String>,

    #[serde(default)]
    pub strict_mode: bool,

    #[serde(default)]
    pub disable_x_forwarded_headers: bool,

    #[serde(default)]
    pub x_forwarded_for_depth: usize,

    #[serde(default)]
    pub allow_list: Vec<String>,

    #[serde(default)]
    pub client_transport: TransportConfig,

    #[serde(default)]
    pub init_resources: Option<InitResources>,
}

fn default_proxy_host() -> String {
    "0.0.0.0".to_string()
}

fn default_proxy_port() -> u16 {
    80
}

fn default_console_log_level() -> String {
    "info".to_string()
}

impl Default for ProxyConfig {
    fn default() -> Self {
        Self {
            host: default_proxy_host(),
            port: default_proxy_port(),
            tls: None,
            enable_h2c: false,
            enable_http2: false,
            console_log_level: default_console_log_level(),
            redirect_https: Vec::new(),
            allowed_domains: Vec::new(),
            global_headers: HashMap::new(),
            strict_mode: false,
            disable_x_forwarded_headers: false,
            x_forwarded_for_depth: 0,
            allow_list: Vec::new(),
            client_transport: TransportConfig::default(),
            init_resources: None,
        }
    }
}

/// TLS configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TlsConfig {
    #[serde(default = "default_tls_port")]
    pub port: u16,
    pub cert_file: Option<String>,
    pub key_file: Option<String>,
    #[serde(default)]
    pub auto_generate: bool,
}

fn default_tls_port() -> u16 {
    443
}

impl Default for TlsConfig {
    fn default() -> Self {
        Self {
            port: default_tls_port(),
            cert_file: None,
            key_file: None,
            auto_generate: false,
        }
    }
}

/// HTTP transport configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TransportConfig {
    #[serde(default)]
    pub dns_server: Option<String>,

    #[serde(default)]
    pub dns_timeout_ms: Option<u64>,

    #[serde(default)]
    pub dns_prefer_go: bool,

    #[serde(default)]
    pub max_idle_conns: Option<usize>,

    #[serde(default)]
    pub max_idle_conns_per_host: Option<usize>,

    #[serde(default)]
    pub max_conns_per_host: Option<usize>,

    #[serde(default)]
    pub idle_conn_timeout_ms: Option<u64>,

    #[serde(default)]
    pub disable_compression: bool,

    #[serde(default)]
    pub disable_keep_alives: bool,

    #[serde(default)]
    pub disable_private_ips: bool,
}

/// Admin API configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AdminConfig {
    #[serde(default = "default_admin_host")]
    pub host: String,

    #[serde(default = "default_admin_port")]
    pub port: u16,

    #[serde(default)]
    pub allow_list: Vec<String>,

    #[serde(default)]
    pub x_forwarded_for_depth: usize,

    #[serde(default)]
    pub watch_only: bool,

    #[serde(default)]
    pub tls: Option<TlsConfig>,

    #[serde(default)]
    pub auth_method: AuthMethod,

    #[serde(default)]
    pub basic_auth: Option<BasicAuthConfig>,

    #[serde(default)]
    pub key_auth: Option<KeyAuthConfig>,
}

fn default_admin_host() -> String {
    "0.0.0.0".to_string()
}

fn default_admin_port() -> u16 {
    9080
}

impl Default for AdminConfig {
    fn default() -> Self {
        Self {
            host: default_admin_host(),
            port: default_admin_port(),
            allow_list: Vec::new(),
            x_forwarded_for_depth: 0,
            watch_only: false,
            tls: None,
            auth_method: AuthMethod::None,
            basic_auth: None,
            key_auth: None,
        }
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Default)]
#[serde(rename_all = "lowercase")]
pub enum AuthMethod {
    #[default]
    None,
    Basic,
    Key,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct BasicAuthConfig {
    #[serde(default)]
    pub users: Vec<UserCredentials>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserCredentials {
    pub username: String,
    pub password: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct KeyAuthConfig {
    pub query_param_name: Option<String>,
    pub header_name: Option<String>,
    #[serde(default)]
    pub keys: Vec<String>,
}

/// Test server configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TestServerConfig {
    #[serde(default = "default_proxy_host")]
    pub host: String,

    #[serde(default = "default_test_port")]
    pub port: u16,

    #[serde(default)]
    pub enable_h2c: bool,

    #[serde(default)]
    pub enable_http2: bool,

    #[serde(default)]
    pub enable_env_vars: bool,

    #[serde(default)]
    pub global_headers: HashMap<String, String>,
}

fn default_test_port() -> u16 {
    8888
}

impl Default for TestServerConfig {
    fn default() -> Self {
        Self {
            host: default_proxy_host(),
            port: default_test_port(),
            enable_h2c: false,
            enable_http2: false,
            enable_env_vars: false,
            global_headers: HashMap::new(),
        }
    }
}

/// Initial resources loaded from config file
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct InitResources {
    #[serde(default)]
    pub skip_validation: bool,

    #[serde(default)]
    pub namespaces: Vec<crate::resources::Namespace>,

    #[serde(default)]
    pub services: Vec<crate::resources::Service>,

    #[serde(default)]
    pub routes: Vec<crate::resources::Route>,

    #[serde(default)]
    pub modules: Vec<ModuleSpec>,

    #[serde(default)]
    pub domains: Vec<DomainSpec>,

    #[serde(default)]
    pub collections: Vec<crate::resources::Collection>,

    #[serde(default)]
    pub documents: Vec<crate::resources::Document>,

    #[serde(default)]
    pub secrets: Vec<crate::resources::Secret>,
}

/// Module specification with optional file loading
///
/// Supports three ways to specify module code:
/// 1. `payload` - base64 encoded module code
/// 2. `payloadRaw` - plain text module code (will be base64 encoded automatically)  
/// 3. `payloadFile` - path to a file containing the module code (relative to config file)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModuleSpec {
    pub name: String,
    pub namespace: String,

    /// Base64 encoded payload (original format)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub payload: Option<String>,

    /// Raw JavaScript/TypeScript code (plain text, will be encoded)
    #[serde(
        default,
        rename = "payloadRaw",
        skip_serializing_if = "Option::is_none"
    )]
    pub payload_raw: Option<String>,

    /// Path to file containing module code (relative to config file location)
    #[serde(
        default,
        rename = "payloadFile",
        skip_serializing_if = "Option::is_none"
    )]
    pub payload_file: Option<String>,

    #[serde(default, rename = "moduleType")]
    pub module_type: crate::resources::ModuleType,

    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<String>,
}

impl ModuleSpec {
    /// Resolve the module payload from the various input options.
    /// Priority: payload_file > payload_raw > payload
    pub fn resolve_payload(&self, config_dir: &std::path::Path) -> anyhow::Result<String> {
        use base64::Engine;

        // Priority 1: File path (relative to config)
        if let Some(ref file_path) = self.payload_file {
            let full_path = config_dir.join(file_path);
            let content = std::fs::read_to_string(&full_path).map_err(|e| {
                anyhow::anyhow!(
                    "Failed to read module file '{}': {}",
                    full_path.display(),
                    e
                )
            })?;
            return Ok(base64::engine::general_purpose::STANDARD.encode(content));
        }

        // Priority 2: Raw payload (plain text)
        if let Some(ref raw) = self.payload_raw {
            return Ok(base64::engine::general_purpose::STANDARD.encode(raw));
        }

        // Priority 3: Base64 encoded payload
        if let Some(ref payload) = self.payload {
            return Ok(payload.clone());
        }

        // No payload specified
        Err(anyhow::anyhow!(
            "Module '{}' has no payload specified (use payload, payloadRaw, or payloadFile)",
            self.name
        ))
    }

    /// Convert to a Module resource with resolved payload
    pub fn to_module(
        &self,
        config_dir: &std::path::Path,
    ) -> anyhow::Result<crate::resources::Module> {
        Ok(crate::resources::Module {
            name: self.name.clone(),
            namespace: self.namespace.clone(),
            payload: self.resolve_payload(config_dir)?,
            module_type: self.module_type,
            tags: self.tags.clone(),
        })
    }
}

/// Domain specification with optional file loading for certs
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DomainSpec {
    #[serde(flatten)]
    pub domain: crate::resources::Domain,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub cert_file: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub key_file: Option<String>,
}

/// Cluster replication mode
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Default)]
#[serde(rename_all = "lowercase")]
pub enum ClusterMode {
    /// Simple HTTP replication - all nodes can accept writes
    /// Uses direct HTTP calls to replicate changes to peer nodes.
    /// Simple and effective for most use cases.
    #[default]
    Simple,

    /// Full Raft consensus with leader election
    /// Complete openraft integration with leader election, log replication.
    /// Provides stronger consistency guarantees.
    /// Only the leader can accept writes.
    Raft,

    /// Tempo consensus algorithm for multi-master replication
    /// A leaderless protocol that provides better scalability than Raft
    /// by allowing any node to accept writes. Uses timestamp-based ordering
    /// and quorum-based coordination for consistency.
    /// Reference: https://github.com/vitorenesduarte/fantoch
    Tempo,
}

/// Cluster configuration for distributed mode
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClusterConfig {
    /// Enable cluster mode
    #[serde(default)]
    pub enabled: bool,

    /// Cluster replication mode (simple, raft, or tempo)
    #[serde(default)]
    pub mode: ClusterMode,

    /// Unique node ID for this instance
    #[serde(default = "default_node_id")]
    pub node_id: u64,

    /// Address this node advertises to other nodes
    #[serde(default = "default_advertise_addr")]
    pub advertise_addr: String,

    /// Bootstrap a new cluster (only for first node)
    #[serde(default)]
    pub bootstrap: bool,

    /// Initial cluster members (for joining existing cluster)
    #[serde(default)]
    pub initial_members: Vec<ClusterMember>,

    /// Node discovery configuration
    #[serde(default)]
    pub discovery: Option<DiscoveryConfig>,

    /// Tempo-specific configuration
    #[serde(default)]
    pub tempo: Option<TempoConfig>,
}

/// Tempo consensus algorithm configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TempoConfig {
    /// Fast quorum size (f+1 for optimal fast path, where f is max failures)
    /// If not set, calculated from cluster size
    #[serde(default)]
    pub fast_quorum_size: Option<usize>,

    /// Write quorum size for slow path
    /// If not set, calculated from cluster size
    #[serde(default)]
    pub write_quorum_size: Option<usize>,

    /// Interval for clock bump periodic event (in milliseconds)
    /// Helps synchronize clocks across nodes
    #[serde(default = "default_clock_bump_interval")]
    pub clock_bump_interval_ms: u64,

    /// Interval for sending detached votes (in milliseconds)
    #[serde(default = "default_detached_send_interval")]
    pub detached_send_interval_ms: u64,

    /// Interval for garbage collection (in milliseconds)
    #[serde(default = "default_gc_interval")]
    pub gc_interval_ms: u64,

    /// Whether to skip fast ack optimization
    #[serde(default)]
    pub skip_fast_ack: bool,
}

fn default_clock_bump_interval() -> u64 {
    50 // 50ms
}

fn default_detached_send_interval() -> u64 {
    100 // 100ms
}

fn default_gc_interval() -> u64 {
    1000 // 1 second
}

impl Default for TempoConfig {
    fn default() -> Self {
        Self {
            fast_quorum_size: None,
            write_quorum_size: None,
            clock_bump_interval_ms: default_clock_bump_interval(),
            detached_send_interval_ms: default_detached_send_interval(),
            gc_interval_ms: default_gc_interval(),
            skip_fast_ack: false,
        }
    }
}

fn default_node_id() -> u64 {
    1
}

fn default_advertise_addr() -> String {
    "127.0.0.1:9090".to_string()
}

impl Default for ClusterConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            mode: ClusterMode::default(),
            node_id: default_node_id(),
            advertise_addr: default_advertise_addr(),
            bootstrap: false,
            initial_members: Vec::new(),
            discovery: None,
            tempo: None,
        }
    }
}

/// Cluster member information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClusterMember {
    /// Node ID
    pub id: u64,
    /// Node address (host:port) for Raft communication
    pub addr: String,
    /// Admin API port for internal replication (optional, defaults to deriving from addr)
    #[serde(default)]
    pub admin_port: Option<u16>,
    /// Whether to use TLS/HTTPS for internal replication (default: false)
    #[serde(default)]
    pub tls: bool,
}

/// Node discovery configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiscoveryConfig {
    /// Discovery type
    #[serde(default, rename = "type")]
    pub discovery_type: DiscoveryType,

    /// DNS name to resolve for node discovery
    #[serde(default)]
    pub dns_name: Option<String>,

    /// Port to use for discovered nodes
    #[serde(default = "default_dns_port")]
    pub dns_port: u16,

    /// How often to refresh discovery (in seconds)
    #[serde(default = "default_refresh_interval")]
    pub refresh_interval_secs: u64,
}

fn default_dns_port() -> u16 {
    9090
}

fn default_refresh_interval() -> u64 {
    30
}

impl Default for DiscoveryConfig {
    fn default() -> Self {
        Self {
            discovery_type: DiscoveryType::default(),
            dns_name: None,
            dns_port: default_dns_port(),
            refresh_interval_secs: default_refresh_interval(),
        }
    }
}

/// Discovery type
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Default)]
#[serde(rename_all = "lowercase")]
pub enum DiscoveryType {
    #[default]
    Static,
    Dns,
}

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

    #[test]
    fn test_env_var_expansion() {
        std::env::set_var("TEST_VAR", "hello");
        let content = "value: ${TEST_VAR:-default}";
        let expanded = DGateConfig::expand_env_vars(content);
        assert_eq!(expanded, "value: hello");

        let content_default = "value: ${NONEXISTENT:-default}";
        let expanded_default = DGateConfig::expand_env_vars(content_default);
        assert_eq!(expanded_default, "value: default");
    }

    #[test]
    fn test_default_config() {
        let config = DGateConfig::default();
        assert_eq!(config.version, "v1");
        assert_eq!(config.proxy.port, 80);
        assert!(!config.debug);
    }
}