zentinel-config 0.6.9

Configuration loading and validation for Zentinel reverse proxy
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
//! Namespace and service configuration for hierarchical organization.
//!
//! This module provides configuration types for organizing Zentinel resources
//! into logical groups using namespaces and services.
//!
//! # Hierarchy
//!
//! ```text
//! Config (root)
//! ├── Global resources (listeners, routes, upstreams, agents, filters)
//! └── namespaces[]
//!     ├── Namespace-level resources
//!     └── services[]
//!         └── Service-level resources
//! ```
//!
//! # Scoping Rules
//!
//! - **Global resources**: Visible everywhere in the configuration
//! - **Namespace resources**: Visible within the namespace and its services
//! - **Service resources**: Local to the specific service
//! - **Exports**: Namespace resources can be exported to make them globally visible
//!
//! Resolution follows "most specific wins": Service → Namespace → Exported → Global

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

use zentinel_common::limits::Limits;

use crate::{AgentConfig, FilterConfig, ListenerConfig, RouteConfig, UpstreamConfig};

// ============================================================================
// Namespace Configuration
// ============================================================================

/// Configuration for a namespace - a logical grouping of related resources.
///
/// Namespaces provide domain-driven boundaries within the configuration,
/// allowing operators to organize resources by team, service domain, or
/// any other logical grouping.
///
/// # Example KDL
///
/// ```kdl
/// namespace "api" {
///     limits {
///         max-body-size 10485760
///     }
///
///     upstreams {
///         upstream "backend" { ... }
///     }
///
///     routes {
///         route "users" {
///             upstream "backend"  // Resolves to api:backend
///         }
///     }
///
///     service "payments" {
///         // Service-specific configuration
///     }
///
///     exports {
///         upstreams "backend"  // Make globally visible
///     }
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct NamespaceConfig {
    /// Unique namespace identifier.
    ///
    /// Must not contain the `:` character as it's reserved for
    /// qualified ID syntax (e.g., `namespace:resource`).
    pub id: String,

    /// Namespace-level limits.
    ///
    /// These limits override global limits and are overridden by
    /// service-level limits. If not specified, global limits apply.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limits: Option<Limits>,

    /// Namespace-level listeners.
    ///
    /// Listeners at the namespace level are shared across all
    /// services within the namespace.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub listeners: Vec<ListenerConfig>,

    /// Namespace-level upstreams.
    ///
    /// These upstreams are visible to all routes within the namespace
    /// and its services. They can be referenced without qualification
    /// from within the namespace.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub upstreams: HashMap<String, UpstreamConfig>,

    /// Namespace-level routes.
    ///
    /// Routes defined at the namespace level can reference namespace
    /// upstreams without qualification.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub routes: Vec<RouteConfig>,

    /// Namespace-level agents.
    ///
    /// Agents at this level are visible to all filters within the
    /// namespace and its services.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub agents: Vec<AgentConfig>,

    /// Namespace-level filters.
    ///
    /// Filters at this level can be referenced by routes within
    /// the namespace and its services.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub filters: HashMap<String, FilterConfig>,

    /// Services within this namespace.
    ///
    /// Services provide more granular grouping within a namespace,
    /// typically representing individual microservices or API groups.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub services: Vec<ServiceConfig>,

    /// Resources exported from this namespace.
    ///
    /// Exported resources become globally visible and can be
    /// referenced from any scope without qualification.
    #[serde(default, skip_serializing_if = "ExportConfig::is_empty")]
    pub exports: ExportConfig,
}

impl NamespaceConfig {
    /// Create a new namespace with the given ID.
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            ..Default::default()
        }
    }

    /// Returns true if this namespace contains no resources.
    pub fn is_empty(&self) -> bool {
        self.listeners.is_empty()
            && self.upstreams.is_empty()
            && self.routes.is_empty()
            && self.agents.is_empty()
            && self.filters.is_empty()
            && self.services.is_empty()
            && self.limits.is_none()
    }

    /// Get a service by ID within this namespace.
    pub fn get_service(&self, id: &str) -> Option<&ServiceConfig> {
        self.services.iter().find(|s| s.id == id)
    }

    /// Get a mutable service by ID within this namespace.
    pub fn get_service_mut(&mut self, id: &str) -> Option<&mut ServiceConfig> {
        self.services.iter_mut().find(|s| s.id == id)
    }
}

// ============================================================================
// Service Configuration
// ============================================================================

/// Configuration for a service within a namespace.
///
/// Services represent individual microservices, API groups, or logical
/// components that need their own listener, routes, and backend configuration.
///
/// # Example KDL
///
/// ```kdl
/// service "payments" {
///     listener {
///         address "0.0.0.0:8443"
///         protocol "https"
///         tls { ... }
///     }
///
///     upstreams {
///         upstream "payments-backend" { ... }
///     }
///
///     routes {
///         route "checkout" {
///             upstream "payments-backend"  // Service-local
///         }
///     }
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ServiceConfig {
    /// Unique service identifier within the namespace.
    ///
    /// Must not contain the `:` character as it's reserved for
    /// qualified ID syntax (e.g., `namespace:service:resource`).
    pub id: String,

    /// Service-specific listener.
    ///
    /// Unlike namespace listeners (which are collections), a service
    /// typically has a single dedicated listener for its traffic.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub listener: Option<ListenerConfig>,

    /// Service-local upstreams.
    ///
    /// These upstreams are only visible within this service.
    /// They shadow any namespace or global upstreams with the same name.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub upstreams: HashMap<String, UpstreamConfig>,

    /// Service-local routes.
    ///
    /// Routes can reference service-local, namespace, or global upstreams.
    /// Resolution follows "most specific wins".
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub routes: Vec<RouteConfig>,

    /// Service-local agents.
    ///
    /// These agents are only visible within this service.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub agents: Vec<AgentConfig>,

    /// Service-local filters.
    ///
    /// These filters can only be referenced by routes within this service.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub filters: HashMap<String, FilterConfig>,

    /// Service-level limits.
    ///
    /// These limits override both global and namespace limits.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limits: Option<Limits>,
}

impl ServiceConfig {
    /// Create a new service with the given ID.
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            ..Default::default()
        }
    }

    /// Returns true if this service contains no resources.
    pub fn is_empty(&self) -> bool {
        self.listener.is_none()
            && self.upstreams.is_empty()
            && self.routes.is_empty()
            && self.agents.is_empty()
            && self.filters.is_empty()
            && self.limits.is_none()
    }
}

// ============================================================================
// Export Configuration
// ============================================================================

/// Configuration for exporting namespace resources globally.
///
/// Exported resources become visible from any scope in the configuration,
/// allowing namespaces to share common resources (like shared auth upstreams
/// or common filters) with other parts of the system.
///
/// # Example KDL
///
/// ```kdl
/// exports {
///     upstreams "shared-auth" "shared-cache"
///     agents "global-waf"
///     filters "rate-limiter"
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ExportConfig {
    /// Upstream IDs to export globally.
    ///
    /// These upstreams become visible from any scope and can be
    /// referenced without namespace qualification.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub upstreams: Vec<String>,

    /// Agent IDs to export globally.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub agents: Vec<String>,

    /// Filter IDs to export globally.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub filters: Vec<String>,
}

impl ExportConfig {
    /// Returns true if no resources are exported.
    pub fn is_empty(&self) -> bool {
        self.upstreams.is_empty() && self.agents.is_empty() && self.filters.is_empty()
    }

    /// Returns the total number of exported resources.
    pub fn len(&self) -> usize {
        self.upstreams.len() + self.agents.len() + self.filters.len()
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{ConnectionPoolConfig, HttpVersionConfig, UpstreamTarget, UpstreamTimeouts};
    use zentinel_common::types::LoadBalancingAlgorithm;

    /// Create a minimal upstream config for testing
    fn test_upstream() -> UpstreamConfig {
        UpstreamConfig {
            id: "test-upstream".to_string(),
            targets: vec![UpstreamTarget {
                address: "127.0.0.1:8080".to_string(),
                weight: 1,
                max_requests: None,
                metadata: HashMap::new(),
            }],
            load_balancing: LoadBalancingAlgorithm::RoundRobin,
            sticky_session: None,
            health_check: None,
            connection_pool: ConnectionPoolConfig::default(),
            timeouts: UpstreamTimeouts::default(),
            tls: None,
            http_version: HttpVersionConfig::default(),
        }
    }

    #[test]
    fn test_namespace_new() {
        let ns = NamespaceConfig::new("api");
        assert_eq!(ns.id, "api");
        assert!(ns.is_empty());
    }

    #[test]
    fn test_namespace_is_empty() {
        let mut ns = NamespaceConfig::new("api");
        assert!(ns.is_empty());

        ns.upstreams.insert("backend".to_string(), test_upstream());
        assert!(!ns.is_empty());
    }

    #[test]
    fn test_service_new() {
        let svc = ServiceConfig::new("payments");
        assert_eq!(svc.id, "payments");
        assert!(svc.is_empty());
    }

    #[test]
    fn test_service_is_empty() {
        let mut svc = ServiceConfig::new("payments");
        assert!(svc.is_empty());

        svc.upstreams.insert("backend".to_string(), test_upstream());
        assert!(!svc.is_empty());
    }

    #[test]
    fn test_export_config_is_empty() {
        let exports = ExportConfig::default();
        assert!(exports.is_empty());
        assert_eq!(exports.len(), 0);
    }

    #[test]
    fn test_export_config_len() {
        let exports = ExportConfig {
            upstreams: vec!["a".to_string(), "b".to_string()],
            agents: vec!["c".to_string()],
            filters: vec![],
        };
        assert!(!exports.is_empty());
        assert_eq!(exports.len(), 3);
    }

    #[test]
    fn test_namespace_get_service() {
        let mut ns = NamespaceConfig::new("api");
        ns.services.push(ServiceConfig::new("payments"));
        ns.services.push(ServiceConfig::new("users"));

        assert!(ns.get_service("payments").is_some());
        assert!(ns.get_service("users").is_some());
        assert!(ns.get_service("orders").is_none());
    }

    #[test]
    fn test_namespace_serialization() {
        let ns = NamespaceConfig {
            id: "api".to_string(),
            limits: None,
            listeners: vec![],
            upstreams: HashMap::new(),
            routes: vec![],
            agents: vec![],
            filters: HashMap::new(),
            services: vec![ServiceConfig::new("payments")],
            exports: ExportConfig::default(),
        };

        let json = serde_json::to_string(&ns).unwrap();
        let parsed: NamespaceConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.id, "api");
        assert_eq!(parsed.services.len(), 1);
        assert_eq!(parsed.services[0].id, "payments");
    }
}