zentinel-config 0.6.11

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
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
//! Flattened configuration for runtime consumption.
//!
//! This module provides [`FlattenedConfig`] which transforms the hierarchical
//! namespace/service configuration into a flat structure suitable for runtime
//! lookups with qualified IDs.
//!
//! # Why Flatten?
//!
//! The hierarchical configuration is great for authoring (domain-driven organization),
//! but at runtime we need fast lookups by qualified ID. Flattening:
//!
//! 1. Pre-computes qualified IDs for all resources
//! 2. Collects scope-specific limits for runtime isolation
//! 3. Enables O(1) lookups via HashMap

use std::collections::HashMap;
use zentinel_common::ids::{QualifiedId, Scope};
use zentinel_common::limits::Limits;

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

// ============================================================================
// Flattened Configuration
// ============================================================================

/// Flattened configuration with all resources indexed by qualified IDs.
///
/// This structure is produced by [`Config::flatten()`] and provides efficient
/// runtime lookups for all resource types.
#[derive(Debug, Clone)]
pub struct FlattenedConfig {
    /// All upstreams indexed by their qualified ID
    pub upstreams: HashMap<QualifiedId, UpstreamConfig>,

    /// All routes with their qualified IDs
    pub routes: Vec<(QualifiedId, RouteConfig)>,

    /// All agents indexed by their qualified ID
    pub agents: HashMap<QualifiedId, AgentConfig>,

    /// All filters indexed by their qualified ID
    pub filters: HashMap<QualifiedId, FilterConfig>,

    /// All listeners with their qualified IDs
    pub listeners: Vec<(QualifiedId, ListenerConfig)>,

    /// Limits per scope for runtime isolation
    pub scope_limits: HashMap<Scope, Limits>,

    /// Exported upstream names (for fast lookup)
    pub exported_upstreams: HashMap<String, QualifiedId>,

    /// Exported agent names (for fast lookup)
    pub exported_agents: HashMap<String, QualifiedId>,

    /// Exported filter names (for fast lookup)
    pub exported_filters: HashMap<String, QualifiedId>,
}

impl FlattenedConfig {
    /// Create a new empty flattened config.
    pub fn new() -> Self {
        Self {
            upstreams: HashMap::new(),
            routes: Vec::new(),
            agents: HashMap::new(),
            filters: HashMap::new(),
            listeners: Vec::new(),
            scope_limits: HashMap::new(),
            exported_upstreams: HashMap::new(),
            exported_agents: HashMap::new(),
            exported_filters: HashMap::new(),
        }
    }

    /// Get an upstream by its qualified ID.
    pub fn get_upstream(&self, qid: &QualifiedId) -> Option<&UpstreamConfig> {
        self.upstreams.get(qid)
    }

    /// Get an upstream by its canonical string form.
    pub fn get_upstream_by_canonical(&self, canonical: &str) -> Option<&UpstreamConfig> {
        self.upstreams.get(&QualifiedId::parse(canonical))
    }

    /// Get an agent by its qualified ID.
    pub fn get_agent(&self, qid: &QualifiedId) -> Option<&AgentConfig> {
        self.agents.get(qid)
    }

    /// Get a filter by its qualified ID.
    pub fn get_filter(&self, qid: &QualifiedId) -> Option<&FilterConfig> {
        self.filters.get(qid)
    }

    /// Get limits for a specific scope.
    ///
    /// Returns the limits for the most specific scope that has limits defined.
    /// If no limits are defined for the scope, returns None.
    pub fn get_limits(&self, scope: &Scope) -> Option<&Limits> {
        self.scope_limits.get(scope)
    }

    /// Get effective limits for a scope, falling back through the scope chain.
    ///
    /// Searches from the given scope up through parent scopes until limits are found.
    pub fn get_effective_limits(&self, scope: &Scope) -> Option<&Limits> {
        for s in scope.chain() {
            if let Some(limits) = self.scope_limits.get(&s) {
                return Some(limits);
            }
        }
        None
    }

    /// Get all routes in a specific scope.
    pub fn routes_in_scope<'a>(
        &'a self,
        scope: &'a Scope,
    ) -> impl Iterator<Item = &'a (QualifiedId, RouteConfig)> {
        self.routes
            .iter()
            .filter(move |(qid, _)| &qid.scope == scope)
    }

    /// Get all listeners in a specific scope.
    pub fn listeners_in_scope<'a>(
        &'a self,
        scope: &'a Scope,
    ) -> impl Iterator<Item = &'a (QualifiedId, ListenerConfig)> {
        self.listeners
            .iter()
            .filter(move |(qid, _)| &qid.scope == scope)
    }

    /// Check if an upstream name is exported.
    pub fn is_upstream_exported(&self, name: &str) -> bool {
        self.exported_upstreams.contains_key(name)
    }

    /// Get the qualified ID of an exported upstream by its local name.
    pub fn get_exported_upstream_qid(&self, name: &str) -> Option<&QualifiedId> {
        self.exported_upstreams.get(name)
    }
}

impl Default for FlattenedConfig {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Config Flattening Implementation
// ============================================================================

impl Config {
    /// Flatten the hierarchical configuration into a runtime-friendly structure.
    ///
    /// This converts all namespace/service resources into qualified IDs and
    /// collects them into flat HashMaps for efficient lookup.
    pub fn flatten(&self) -> FlattenedConfig {
        let mut flat = FlattenedConfig::new();

        // Add global limits
        flat.scope_limits.insert(Scope::Global, self.limits.clone());

        // Flatten global resources
        self.flatten_global(&mut flat);

        // Flatten namespaces
        for ns in &self.namespaces {
            self.flatten_namespace(ns, &mut flat);
        }

        flat
    }

    fn flatten_global(&self, flat: &mut FlattenedConfig) {
        // Global upstreams
        for (id, upstream) in &self.upstreams {
            flat.upstreams
                .insert(QualifiedId::global(id), upstream.clone());
        }

        // Global routes
        for route in &self.routes {
            flat.routes
                .push((QualifiedId::global(&route.id), route.clone()));
        }

        // Global agents
        for agent in &self.agents {
            flat.agents
                .insert(QualifiedId::global(&agent.id), agent.clone());
        }

        // Global filters
        for (id, filter) in &self.filters {
            flat.filters.insert(QualifiedId::global(id), filter.clone());
        }

        // Global listeners
        for listener in &self.listeners {
            flat.listeners
                .push((QualifiedId::global(&listener.id), listener.clone()));
        }
    }

    fn flatten_namespace(&self, ns: &crate::NamespaceConfig, flat: &mut FlattenedConfig) {
        let ns_scope = Scope::Namespace(ns.id.clone());

        // Namespace limits (if defined)
        if let Some(ref limits) = ns.limits {
            flat.scope_limits.insert(ns_scope.clone(), limits.clone());
        }

        // Namespace upstreams
        for (id, upstream) in &ns.upstreams {
            let qid = QualifiedId::namespaced(&ns.id, id);
            flat.upstreams.insert(qid.clone(), upstream.clone());

            // Track exports
            if ns.exports.upstreams.contains(id) {
                flat.exported_upstreams.insert(id.clone(), qid);
            }
        }

        // Namespace routes
        for route in &ns.routes {
            flat.routes
                .push((QualifiedId::namespaced(&ns.id, &route.id), route.clone()));
        }

        // Namespace agents
        for agent in &ns.agents {
            let qid = QualifiedId::namespaced(&ns.id, &agent.id);
            flat.agents.insert(qid.clone(), agent.clone());

            // Track exports
            if ns.exports.agents.contains(&agent.id) {
                flat.exported_agents.insert(agent.id.clone(), qid);
            }
        }

        // Namespace filters
        for (id, filter) in &ns.filters {
            let qid = QualifiedId::namespaced(&ns.id, id);
            flat.filters.insert(qid.clone(), filter.clone());

            // Track exports
            if ns.exports.filters.contains(id) {
                flat.exported_filters.insert(id.clone(), qid);
            }
        }

        // Namespace listeners
        for listener in &ns.listeners {
            flat.listeners.push((
                QualifiedId::namespaced(&ns.id, &listener.id),
                listener.clone(),
            ));
        }

        // Flatten services within namespace
        for svc in &ns.services {
            self.flatten_service(&ns.id, svc, flat);
        }
    }

    fn flatten_service(&self, ns_id: &str, svc: &crate::ServiceConfig, flat: &mut FlattenedConfig) {
        let svc_scope = Scope::Service {
            namespace: ns_id.to_string(),
            service: svc.id.clone(),
        };

        // Service limits (if defined)
        if let Some(ref limits) = svc.limits {
            flat.scope_limits.insert(svc_scope.clone(), limits.clone());
        }

        // Service upstreams
        for (id, upstream) in &svc.upstreams {
            flat.upstreams.insert(
                QualifiedId::in_service(ns_id, &svc.id, id),
                upstream.clone(),
            );
        }

        // Service routes
        for route in &svc.routes {
            flat.routes.push((
                QualifiedId::in_service(ns_id, &svc.id, &route.id),
                route.clone(),
            ));
        }

        // Service agents
        for agent in &svc.agents {
            flat.agents.insert(
                QualifiedId::in_service(ns_id, &svc.id, &agent.id),
                agent.clone(),
            );
        }

        // Service filters
        for (id, filter) in &svc.filters {
            flat.filters
                .insert(QualifiedId::in_service(ns_id, &svc.id, id), filter.clone());
        }

        // Service listener (singular)
        if let Some(ref listener) = svc.listener {
            flat.listeners.push((
                QualifiedId::in_service(ns_id, &svc.id, &listener.id),
                listener.clone(),
            ));
        }
    }
}

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

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

    fn test_upstream(id: &str) -> UpstreamConfig {
        UpstreamConfig {
            id: id.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(),
        }
    }

    fn test_config() -> Config {
        let mut config = Config::default_for_testing();

        // Add global upstream
        config.upstreams.insert(
            "global-backend".to_string(),
            test_upstream("global-backend"),
        );

        // Add namespace with upstream
        let mut ns = NamespaceConfig::new("api");
        ns.upstreams
            .insert("ns-backend".to_string(), test_upstream("ns-backend"));
        ns.upstreams.insert(
            "shared-backend".to_string(),
            test_upstream("shared-backend"),
        );
        ns.exports = ExportConfig {
            upstreams: vec!["shared-backend".to_string()],
            agents: vec![],
            filters: vec![],
        };

        // Add service with upstream
        let mut svc = ServiceConfig::new("payments");
        svc.upstreams
            .insert("svc-backend".to_string(), test_upstream("svc-backend"));
        ns.services.push(svc);

        config.namespaces.push(ns);
        config
    }

    #[test]
    fn test_flatten_global_upstreams() {
        let config = test_config();
        let flat = config.flatten();

        // Should have global upstream
        let qid = QualifiedId::global("global-backend");
        assert!(flat.upstreams.contains_key(&qid));
        assert_eq!(flat.get_upstream(&qid).unwrap().id, "global-backend");
    }

    #[test]
    fn test_flatten_namespace_upstreams() {
        let config = test_config();
        let flat = config.flatten();

        // Should have namespace upstream
        let qid = QualifiedId::namespaced("api", "ns-backend");
        assert!(flat.upstreams.contains_key(&qid));
        assert_eq!(flat.get_upstream(&qid).unwrap().id, "ns-backend");
    }

    #[test]
    fn test_flatten_service_upstreams() {
        let config = test_config();
        let flat = config.flatten();

        // Should have service upstream
        let qid = QualifiedId::in_service("api", "payments", "svc-backend");
        assert!(flat.upstreams.contains_key(&qid));
        assert_eq!(flat.get_upstream(&qid).unwrap().id, "svc-backend");
    }

    #[test]
    fn test_flatten_exported_upstreams() {
        let config = test_config();
        let flat = config.flatten();

        // Should track exported upstreams
        assert!(flat.is_upstream_exported("shared-backend"));
        assert!(!flat.is_upstream_exported("ns-backend"));

        let exported_qid = flat.get_exported_upstream_qid("shared-backend").unwrap();
        assert_eq!(exported_qid.canonical(), "api:shared-backend");
    }

    #[test]
    fn test_get_upstream_by_canonical() {
        let config = test_config();
        let flat = config.flatten();

        // Should lookup by canonical string
        let upstream = flat.get_upstream_by_canonical("api:ns-backend").unwrap();
        assert_eq!(upstream.id, "ns-backend");

        let service_upstream = flat
            .get_upstream_by_canonical("api:payments:svc-backend")
            .unwrap();
        assert_eq!(service_upstream.id, "svc-backend");
    }

    #[test]
    fn test_flatten_scope_limits() {
        let mut config = test_config();

        // Add namespace limits
        let ns = config.namespaces.get_mut(0).unwrap();
        ns.limits = Some(Limits::for_testing());

        let flat = config.flatten();

        // Should have global limits
        assert!(flat.scope_limits.contains_key(&Scope::Global));

        // Should have namespace limits
        assert!(flat
            .scope_limits
            .contains_key(&Scope::Namespace("api".to_string())));
    }

    #[test]
    fn test_get_effective_limits() {
        let mut config = test_config();

        // Add namespace limits
        let ns = config.namespaces.get_mut(0).unwrap();
        ns.limits = Some(Limits::for_testing());

        let flat = config.flatten();

        // Service scope should fall back to namespace limits
        let svc_scope = Scope::Service {
            namespace: "api".to_string(),
            service: "payments".to_string(),
        };
        let limits = flat.get_effective_limits(&svc_scope);
        assert!(limits.is_some());
    }

    #[test]
    fn test_routes_in_scope() {
        let config = test_config();
        let flat = config.flatten();

        // Should have global routes (from default_for_testing)
        let global_routes: Vec<_> = flat.routes_in_scope(&Scope::Global).collect();
        assert!(!global_routes.is_empty());
    }

    #[test]
    fn test_flatten_preserves_route_order() {
        let config = test_config();
        let flat = config.flatten();

        // Routes should maintain order within their scope
        let route_ids: Vec<_> = flat.routes.iter().map(|(qid, _)| qid.canonical()).collect();
        assert!(!route_ids.is_empty());
    }
}