a3s-gateway 0.2.1

A3S Gateway - AI-native API gateway with reverse proxy, routing, and agent orchestration
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
//! Kubernetes IngressRoute CRD provider
//!
//! Custom `IngressRoute` CRD for advanced routing beyond standard K8s Ingress.
//! Provides a Traefik-style CRD that maps directly to gateway routing concepts.
//!
//! Feature-gated behind `kube`. Conversion logic is pure and testable
//! without a real K8s cluster.

#![cfg_attr(not(feature = "kube"), allow(dead_code))]
use crate::config::{
    GatewayConfig, LoadBalancerConfig, RouterConfig, ServerConfig, ServiceConfig, Strategy,
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

// -----------------------------------------------------------------------
// IngressRoute CRD model
// -----------------------------------------------------------------------

/// IngressRoute custom resource — advanced routing configuration
///
/// # Example YAML
///
/// ```yaml
/// apiVersion: a3s-gateway.io/v1alpha1
/// kind: IngressRoute
/// metadata:
///   name: my-app
///   namespace: default
/// spec:
///   entrypoints:
///     - web
///     - websecure
///   routes:
///     - match: "Host(`app.example.com`) && PathPrefix(`/api`)"
///       middlewares:
///         - name: rate-limit
///       services:
///         - name: api-svc
///           port: 8080
///           weight: 1
///   tls:
///     secret_name: my-tls-secret
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IngressRouteResource {
    /// Resource name
    pub name: String,
    /// Namespace
    #[serde(default = "super::kubernetes::default_namespace")]
    pub namespace: String,
    /// IngressRoute spec
    pub spec: IngressRouteSpec,
}

/// IngressRoute spec
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IngressRouteSpec {
    /// Entrypoint names this route applies to
    #[serde(default)]
    pub entrypoints: Vec<String>,
    /// Route definitions
    #[serde(default)]
    pub routes: Vec<IngressRouteEntry>,
    /// TLS configuration
    #[serde(default)]
    pub tls: Option<IngressRouteTls>,
}

/// A single route entry in an IngressRoute
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IngressRouteEntry {
    /// Traefik-style match rule (e.g., "Host(`example.com`) && PathPrefix(`/api`)")
    #[serde(rename = "match")]
    pub match_rule: String,
    /// Priority (higher = matched first)
    #[serde(default)]
    pub priority: i32,
    /// Middleware references
    #[serde(default)]
    pub middlewares: Vec<IngressRouteMiddlewareRef>,
    /// Backend services
    #[serde(default)]
    pub services: Vec<IngressRouteServiceRef>,
}

/// Middleware reference in an IngressRoute
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IngressRouteMiddlewareRef {
    /// Middleware name
    pub name: String,
}

/// Service reference in an IngressRoute
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IngressRouteServiceRef {
    /// K8s Service name
    pub name: String,
    /// Service port
    #[serde(default = "default_port")]
    pub port: u16,
    /// Weight for load balancing (default: 1)
    #[serde(default = "default_weight")]
    pub weight: u32,
    /// Load balancing strategy override
    #[serde(default)]
    pub strategy: Option<String>,
}

fn default_port() -> u16 {
    80
}

fn default_weight() -> u32 {
    1
}

/// TLS configuration for IngressRoute
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IngressRouteTls {
    /// K8s Secret name containing the TLS certificate
    #[serde(default)]
    pub secret_name: String,
}

// -----------------------------------------------------------------------
// Conversion: IngressRoute → GatewayConfig
// -----------------------------------------------------------------------

/// Convert a list of IngressRoute resources into a partial GatewayConfig
pub fn ingress_routes_to_config(routes: &[IngressRouteResource]) -> GatewayConfig {
    let mut routers = HashMap::new();
    let mut services = HashMap::new();

    for ir in routes {
        let entrypoints = ir.spec.entrypoints.clone();

        for (idx, route) in ir.spec.routes.iter().enumerate() {
            let middlewares: Vec<String> =
                route.middlewares.iter().map(|m| m.name.clone()).collect();

            // Build a combined service from all backends in this route
            let svc_name = if route.services.len() == 1 {
                format!("{}-{}-{}", ir.namespace, ir.name, route.services[0].name)
            } else {
                format!("{}-{}-route-{}", ir.namespace, ir.name, idx)
            };

            let router_name = svc_name.clone();

            routers.insert(
                router_name,
                RouterConfig {
                    rule: route.match_rule.clone(),
                    service: svc_name.clone(),
                    entrypoints: entrypoints.clone(),
                    middlewares,
                    priority: route.priority,
                },
            );

            // Build service with all backends as servers
            let strategy = route
                .services
                .first()
                .and_then(|s| s.strategy.as_deref())
                .and_then(|s| s.parse().ok())
                .unwrap_or(Strategy::RoundRobin);

            let servers: Vec<ServerConfig> = route
                .services
                .iter()
                .map(|s| {
                    let port = if s.port > 0 { s.port } else { 80 };
                    ServerConfig {
                        url: format!(
                            "http://{}.{}.svc.cluster.local:{}",
                            s.name, ir.namespace, port
                        ),
                        weight: s.weight,
                    }
                })
                .collect();

            services.insert(
                svc_name,
                ServiceConfig {
                    load_balancer: LoadBalancerConfig {
                        strategy,
                        servers,
                        health_check: None,
                        sticky: None,
                    },
                    scaling: None,
                    revisions: vec![],
                    rollout: None,
                    mirror: None,
                    failover: None,
                },
            );
        }
    }

    GatewayConfig {
        entrypoints: HashMap::new(),
        routers,
        services,
        middlewares: HashMap::new(),
        providers: Default::default(),
        shutdown_timeout_secs: 30,
    }
}

// -----------------------------------------------------------------------
// K8s CRD watcher — feature-gated behind `kube`
// -----------------------------------------------------------------------

#[cfg(feature = "kube")]
pub fn spawn_crd_watch(
    config: crate::config::KubernetesProviderConfig,
    base_config: GatewayConfig,
    tx: tokio::sync::mpsc::Sender<GatewayConfig>,
) -> tokio::task::JoinHandle<()> {
    use crate::provider::kubernetes::merge_k8s_config;
    use std::time::Duration;

    tokio::spawn(async move {
        let client = match kube::Client::try_default().await {
            Ok(c) => c,
            Err(e) => {
                tracing::error!(error = %e, "Failed to create K8s client for CRD watcher");
                return;
            }
        };

        let interval = Duration::from_secs(config.watch_interval_secs);

        loop {
            match poll_ingress_routes(&client, &config).await {
                Ok(routes) => {
                    let discovered = ingress_routes_to_config(&routes);
                    let merged = merge_k8s_config(&base_config, &discovered);
                    if tx.send(merged).await.is_err() {
                        tracing::debug!("CRD watcher channel closed");
                        return;
                    }
                }
                Err(e) => {
                    tracing::warn!(error = %e, "Failed to poll IngressRoute CRDs");
                }
            }

            tokio::time::sleep(interval).await;
        }
    })
}

/// Poll K8s API for IngressRoute CRDs
/// Note: This requires the CRD to be installed in the cluster.
/// For now, we use a ConfigMap-based approach as a fallback.
#[cfg(feature = "kube")]
async fn poll_ingress_routes(
    client: &kube::Client,
    config: &crate::config::KubernetesProviderConfig,
) -> crate::error::Result<Vec<IngressRouteResource>> {
    use k8s_openapi::api::core::v1::ConfigMap;
    use kube::api::{Api, ListParams};

    // Look for ConfigMaps with label "a3s-gateway.io/type=ingressroute"
    let api: Api<ConfigMap> = if config.namespace.is_empty() {
        Api::all(client.clone())
    } else {
        Api::namespaced(client.clone(), &config.namespace)
    };

    let lp = ListParams::default().labels("a3s-gateway.io/type=ingressroute");
    let list = api.list(&lp).await.map_err(|e| {
        crate::error::GatewayError::Other(format!("Failed to list IngressRoute ConfigMaps: {}", e))
    })?;

    let mut result = Vec::new();
    for cm in list.items {
        if let Some(data) = &cm.data {
            if let Some(spec_json) = data.get("spec") {
                match serde_json::from_str::<IngressRouteResource>(spec_json) {
                    Ok(route) => result.push(route),
                    Err(e) => {
                        let name = cm.metadata.name.as_deref().unwrap_or("unknown");
                        tracing::warn!(
                            configmap = name,
                            error = %e,
                            "Failed to parse IngressRoute from ConfigMap"
                        );
                    }
                }
            }
        }
    }

    Ok(result)
}

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

    fn make_route(
        name: &str,
        ns: &str,
        match_rule: &str,
        svc_name: &str,
        port: u16,
    ) -> IngressRouteResource {
        IngressRouteResource {
            name: name.to_string(),
            namespace: ns.to_string(),
            spec: IngressRouteSpec {
                entrypoints: vec!["web".to_string()],
                routes: vec![IngressRouteEntry {
                    match_rule: match_rule.to_string(),
                    priority: 0,
                    middlewares: vec![],
                    services: vec![IngressRouteServiceRef {
                        name: svc_name.to_string(),
                        port,
                        weight: 1,
                        strategy: None,
                    }],
                }],
                tls: None,
            },
        }
    }

    // --- ingress_routes_to_config ---

    #[test]
    fn test_single_route_conversion() {
        let route = make_route("app", "default", "Host(`app.example.com`)", "api-svc", 8080);
        let config = ingress_routes_to_config(&[route]);

        assert_eq!(config.routers.len(), 1);
        assert_eq!(config.services.len(), 1);

        let router = config.routers.get("default-app-api-svc").unwrap();
        assert_eq!(router.rule, "Host(`app.example.com`)");
        assert_eq!(router.entrypoints, vec!["web"]);

        let svc = config.services.get("default-app-api-svc").unwrap();
        assert_eq!(svc.load_balancer.servers.len(), 1);
        assert_eq!(
            svc.load_balancer.servers[0].url,
            "http://api-svc.default.svc.cluster.local:8080"
        );
    }

    #[test]
    fn test_multiple_routes() {
        let routes = vec![
            make_route("app1", "ns1", "Host(`a.com`)", "svc-a", 80),
            make_route("app2", "ns2", "PathPrefix(`/api`)", "svc-b", 3000),
        ];
        let config = ingress_routes_to_config(&routes);
        assert_eq!(config.routers.len(), 2);
        assert_eq!(config.services.len(), 2);
    }

    #[test]
    fn test_route_with_middlewares() {
        let route = IngressRouteResource {
            name: "app".to_string(),
            namespace: "default".to_string(),
            spec: IngressRouteSpec {
                entrypoints: vec!["websecure".to_string()],
                routes: vec![IngressRouteEntry {
                    match_rule: "Host(`secure.example.com`)".to_string(),
                    priority: 5,
                    middlewares: vec![
                        IngressRouteMiddlewareRef {
                            name: "auth".to_string(),
                        },
                        IngressRouteMiddlewareRef {
                            name: "rate-limit".to_string(),
                        },
                    ],
                    services: vec![IngressRouteServiceRef {
                        name: "secure-svc".to_string(),
                        port: 443,
                        weight: 1,
                        strategy: None,
                    }],
                }],
                tls: Some(IngressRouteTls {
                    secret_name: "tls-secret".to_string(),
                }),
            },
        };

        let config = ingress_routes_to_config(&[route]);
        let router = config.routers.values().next().unwrap();
        assert_eq!(router.middlewares, vec!["auth", "rate-limit"]);
        assert_eq!(router.entrypoints, vec!["websecure"]);
        assert_eq!(router.priority, 5);
    }

    #[test]
    fn test_route_with_multiple_backends() {
        let route = IngressRouteResource {
            name: "split".to_string(),
            namespace: "prod".to_string(),
            spec: IngressRouteSpec {
                entrypoints: vec![],
                routes: vec![IngressRouteEntry {
                    match_rule: "Host(`app.com`)".to_string(),
                    priority: 0,
                    middlewares: vec![],
                    services: vec![
                        IngressRouteServiceRef {
                            name: "svc-v1".to_string(),
                            port: 8080,
                            weight: 3,
                            strategy: Some("weighted".to_string()),
                        },
                        IngressRouteServiceRef {
                            name: "svc-v2".to_string(),
                            port: 8080,
                            weight: 1,
                            strategy: None,
                        },
                    ],
                }],
                tls: None,
            },
        };

        let config = ingress_routes_to_config(&[route]);
        assert_eq!(config.services.len(), 1);

        let svc = config.services.get("prod-split-route-0").unwrap();
        assert_eq!(svc.load_balancer.servers.len(), 2);
        assert_eq!(svc.load_balancer.strategy, Strategy::Weighted);
        assert_eq!(svc.load_balancer.servers[0].weight, 3);
        assert_eq!(svc.load_balancer.servers[1].weight, 1);
    }

    #[test]
    fn test_route_with_strategy_override() {
        let route = IngressRouteResource {
            name: "app".to_string(),
            namespace: "default".to_string(),
            spec: IngressRouteSpec {
                entrypoints: vec![],
                routes: vec![IngressRouteEntry {
                    match_rule: "Host(`app.com`)".to_string(),
                    priority: 0,
                    middlewares: vec![],
                    services: vec![IngressRouteServiceRef {
                        name: "svc".to_string(),
                        port: 80,
                        weight: 1,
                        strategy: Some("least-connections".to_string()),
                    }],
                }],
                tls: None,
            },
        };

        let config = ingress_routes_to_config(&[route]);
        let svc = config.services.values().next().unwrap();
        assert_eq!(svc.load_balancer.strategy, Strategy::LeastConnections);
    }

    #[test]
    fn test_empty_routes() {
        let config = ingress_routes_to_config(&[]);
        assert!(config.routers.is_empty());
        assert!(config.services.is_empty());
    }

    #[test]
    fn test_route_default_port() {
        let route = make_route("app", "default", "Host(`app.com`)", "svc", 0);
        let config = ingress_routes_to_config(&[route]);
        let svc = config.services.values().next().unwrap();
        assert!(svc.load_balancer.servers[0].url.ends_with(":80"));
    }

    // --- Serialization ---

    #[test]
    fn test_ingress_route_serialization() {
        let route = make_route("test", "ns", "Host(`test.com`)", "svc", 8080);
        let json = serde_json::to_string(&route).unwrap();
        let parsed: IngressRouteResource = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.name, "test");
        assert_eq!(parsed.spec.routes.len(), 1);
        assert_eq!(parsed.spec.routes[0].match_rule, "Host(`test.com`)");
    }

    #[test]
    fn test_ingress_route_tls() {
        let route = IngressRouteResource {
            name: "tls-app".to_string(),
            namespace: "default".to_string(),
            spec: IngressRouteSpec {
                entrypoints: vec!["websecure".to_string()],
                routes: vec![],
                tls: Some(IngressRouteTls {
                    secret_name: "my-cert".to_string(),
                }),
            },
        };
        assert_eq!(route.spec.tls.unwrap().secret_name, "my-cert");
    }

    // --- Strategy::from_str ---

    #[test]
    fn test_strategy_from_str_all() {
        assert_eq!("round-robin".parse::<Strategy>(), Ok(Strategy::RoundRobin));
        assert_eq!("weighted".parse::<Strategy>(), Ok(Strategy::Weighted));
        assert_eq!("random".parse::<Strategy>(), Ok(Strategy::Random));
        assert!("unknown".parse::<Strategy>().is_err());
    }

    #[test]
    fn test_multiple_routes_in_single_resource() {
        let route = IngressRouteResource {
            name: "multi".to_string(),
            namespace: "default".to_string(),
            spec: IngressRouteSpec {
                entrypoints: vec!["web".to_string()],
                routes: vec![
                    IngressRouteEntry {
                        match_rule: "PathPrefix(`/api`)".to_string(),
                        priority: 10,
                        middlewares: vec![],
                        services: vec![IngressRouteServiceRef {
                            name: "api-svc".to_string(),
                            port: 8080,
                            weight: 1,
                            strategy: None,
                        }],
                    },
                    IngressRouteEntry {
                        match_rule: "PathPrefix(`/web`)".to_string(),
                        priority: 5,
                        middlewares: vec![],
                        services: vec![IngressRouteServiceRef {
                            name: "web-svc".to_string(),
                            port: 3000,
                            weight: 1,
                            strategy: None,
                        }],
                    },
                ],
                tls: None,
            },
        };

        let config = ingress_routes_to_config(&[route]);
        assert_eq!(config.routers.len(), 2);
        assert_eq!(config.services.len(), 2);

        // First route has single service → named by service
        assert!(config.routers.contains_key("default-multi-api-svc"));
        assert!(config.routers.contains_key("default-multi-web-svc"));
    }
}