jokoway 0.1.0-rc.1

Jokoway is a high-performance API Gateway built on Pingora (Rust) with dead-simple YAML configs.
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
use arc_swap::ArcSwap;
use std::sync::{Arc, Mutex};

use crate::config::models::{JokowayConfig, ServiceProtocol};
use jokoway_rules::parse_rule;
use jokoway_transformer::{
    RequestTransformer, ResponseTransformer, parse_response_transformers, parse_transformers,
};

/// Pre-computed protocol sets for faster lookups
pub const HTTP_PROTOCOLS: [ServiceProtocol; 3] = [
    ServiceProtocol::Http,
    ServiceProtocol::Ws,
    ServiceProtocol::Grpc,
];
pub const HTTPS_PROTOCOLS: [ServiceProtocol; 3] = [
    ServiceProtocol::Https,
    ServiceProtocol::Wss,
    ServiceProtocol::Grpcs,
];
pub const ALL_PROTOCOLS: [ServiceProtocol; 6] = [
    ServiceProtocol::Http,
    ServiceProtocol::Https,
    ServiceProtocol::Ws,
    ServiceProtocol::Wss,
    ServiceProtocol::Grpc,
    ServiceProtocol::Grpcs,
];

use jokoway_rules::Matcher;

pub struct RuntimeRoute {
    pub matcher: Box<dyn Matcher>,
    pub priority: i32,
    pub max_retries: u32,
    pub req_transformer: Option<Arc<dyn RequestTransformer>>,
    pub res_transformer: Option<Arc<dyn ResponseTransformer>>,
}

pub struct RuntimeService {
    pub name: String,
    pub host: Arc<str>, // Upstream name
    pub protocols: Vec<ServiceProtocol>,
    pub routes: Vec<RuntimeRoute>,
    pub config: Arc<crate::config::models::Service>,
}

/// ServiceManager compiles services and rules from config and stores them grouped by protocol.
pub struct ServiceManager {
    /// All compiled services
    services: ArcSwap<Vec<RuntimeService>>,
    /// Callbacks to notify when services change
    callbacks: Mutex<Vec<Box<dyn Fn() + Send + Sync>>>,
}

use crate::error::JokowayError;

fn compile_service(
    service: &Arc<crate::config::models::Service>,
) -> Result<RuntimeService, JokowayError> {
    let total_rules = service.routes.len();
    let mut routes = Vec::with_capacity(total_rules);

    let service_max_retries = service.max_retries.unwrap_or(1);

    for route_config in &service.routes {
        let matcher = match parse_rule(&route_config.rule) {
            Ok(m) => m,
            Err(e) => {
                return Err(JokowayError::Config(format!(
                    "Rule parse error [service={}, route={}, rule={}]: {}",
                    service.name, route_config.name, route_config.rule, e
                )));
            }
        };

        let req_transformer = route_config
            .request_transformer
            .as_ref()
            .and_then(|t_str| match parse_transformers(t_str) {
                Ok(t) => Some(Arc::from(t)),
                Err(e) => {
                    log::error!(
                        "Request transformer parse error [service={}, route={}, transformer={}]: {}",
                        service.name,
                        route_config.name,
                        t_str,
                        e
                    );
                    None
                }
            });

        let res_transformer = route_config
            .response_transformer
            .as_ref()
            .and_then(|t_str| match parse_response_transformers(t_str) {
                Ok(t) => Some(Arc::from(t)),
                Err(e) => {
                    log::error!(
                        "Response transformer parse error [service={}, route={}, transformer={}]: {}",
                        service.name,
                        route_config.name,
                        t_str,
                        e
                    );
                    None
                }
            });

        let effective_max_retries = route_config
            .max_retries
            .or(Some(service_max_retries))
            .unwrap_or(1);

        routes.push(RuntimeRoute {
            matcher,
            priority: route_config.priority.unwrap_or(0),
            max_retries: effective_max_retries,
            req_transformer,
            res_transformer,
        });
    }

    routes.sort_by(|a, b| b.priority.cmp(&a.priority));

    let runtime_service = RuntimeService {
        name: service.name.clone(),
        host: Arc::from(service.host.as_str()),
        protocols: service.protocols.clone(),
        routes,
        config: service.clone(),
    };

    // Register hosts for ACME
    use jokoway_rules::registry::register_hosts;
    let mut hosts = std::collections::HashSet::new();
    for route in &runtime_service.routes {
        for host in route.matcher.get_hosts() {
            hosts.insert(host);
        }
    }
    register_hosts(hosts);

    Ok(runtime_service)
}

impl ServiceManager {
    pub fn new(config: Arc<JokowayConfig>) -> Result<Self, JokowayError> {
        let services = Self::compile_services(&config);
        Ok(Self {
            services: ArcSwap::from_pointee(services),
            callbacks: Mutex::new(Vec::new()),
        })
    }

    fn compile_services(config: &JokowayConfig) -> Vec<RuntimeService> {
        let mut services = Vec::with_capacity(config.services.len());
        for svc_config in &config.services {
            match compile_service(svc_config) {
                Ok(svc) => services.push(svc),
                Err(e) => {
                    log::error!("Failed to compile service {}: {}", svc_config.name, e);
                }
            }
        }
        services
    }

    /// Get indices of services matching allowed protocols.
    /// Services with empty protocols are accessible through all protocols.
    pub fn get_indices_for_protocols(&self, allowed_protocols: &[ServiceProtocol]) -> Vec<usize> {
        let services = self.services.load();
        services
            .iter()
            .enumerate()
            .filter_map(|(idx, svc)| {
                if svc.protocols.is_empty() {
                    // Services with no protocols specified are accessible through all protocols
                    Some(idx)
                } else if svc.protocols.iter().any(|p| allowed_protocols.contains(p)) {
                    Some(idx)
                } else {
                    None
                }
            })
            .collect()
    }

    /// Get all compiled services
    pub fn get_all(&self) -> arc_swap::Guard<Arc<Vec<RuntimeService>>> {
        self.services.load()
    }

    /// Register a callback to be notified when services change
    pub fn add_services_changed_callback<F>(&self, callback: F)
    where
        F: Fn() + Send + Sync + 'static,
    {
        self.callbacks.lock().unwrap().push(Box::new(callback));
    }

    /// Notify all registered callbacks that services have changed
    fn notify_callbacks(&self) {
        let callbacks = self.callbacks.lock().unwrap();
        for callback in callbacks.iter() {
            callback();
        }
    }

    /// List all services
    pub fn list_services(&self) -> Vec<RuntimeService> {
        let services = self.services.load();
        // Clone the services for external use
        services
            .iter()
            .map(|svc| RuntimeService {
                name: svc.name.clone(),
                host: svc.host.clone(),
                protocols: svc.protocols.clone(),
                routes: Vec::new(), // Don't clone routes for listing
                config: svc.config.clone(),
            })
            .collect()
    }

    /// Verify if a service exists
    pub fn verify_service(&self, name: &str) -> bool {
        let services = self.services.load();
        services.iter().any(|svc| svc.name == name)
    }

    /// Add a new service dynamically
    pub fn add_service(&self, service: crate::config::models::Service) -> Result<(), JokowayError> {
        let service = Arc::new(service);
        // Check if service already exists
        if self.verify_service(&service.name) {
            return Err(JokowayError::Config(format!(
                "Service {} already exists",
                service.name
            )));
        }

        // Compile the new service
        let runtime_service = compile_service(&service)?;

        // Add to services
        self.services.rcu(|old| {
            let mut next = Vec::with_capacity(old.len() + 1);
            for svc in old.iter() {
                next.push(RuntimeService {
                    name: svc.name.clone(),
                    host: svc.host.clone(),
                    protocols: svc.protocols.clone(),
                    routes: svc
                        .routes
                        .iter()
                        .map(|r| RuntimeRoute {
                            matcher: r.matcher.clone_box(),
                            priority: r.priority,
                            max_retries: r.max_retries,
                            req_transformer: r.req_transformer.clone(),
                            res_transformer: r.res_transformer.clone(),
                        })
                        .collect(),
                    config: svc.config.clone(),
                });
            }
            next.push(RuntimeService {
                name: runtime_service.name.clone(),
                host: runtime_service.host.clone(),
                protocols: runtime_service.protocols.clone(),
                routes: runtime_service
                    .routes
                    .iter()
                    .map(|r| RuntimeRoute {
                        matcher: r.matcher.clone_box(),
                        priority: r.priority,
                        max_retries: r.max_retries,
                        req_transformer: r.req_transformer.clone(),
                        res_transformer: r.res_transformer.clone(),
                    })
                    .collect(),
                config: runtime_service.config.clone(),
            });
            next
        });

        self.notify_callbacks();
        log::info!("Added service: {}", service.name);
        Ok(())
    }

    /// Update an existing service
    pub fn update_service(
        &self,
        name: &str,
        service: crate::config::models::Service,
    ) -> Result<(), JokowayError> {
        let service = Arc::new(service);
        // Check if service exists
        if !self.verify_service(name) {
            return Err(JokowayError::Config(format!(
                "Service {} does not exist",
                name
            )));
        }

        // Compile the updated service
        let runtime_service = compile_service(&service)?;

        // Update service
        self.services.rcu(|old| {
            let mut next = Vec::with_capacity(old.len());
            for svc in old.iter() {
                if svc.name == name {
                    next.push(RuntimeService {
                        name: runtime_service.name.clone(),
                        host: runtime_service.host.clone(),
                        protocols: runtime_service.protocols.clone(),
                        routes: runtime_service
                            .routes
                            .iter()
                            .map(|r| RuntimeRoute {
                                matcher: r.matcher.clone_box(),
                                priority: r.priority,
                                max_retries: r.max_retries,
                                req_transformer: r.req_transformer.clone(),
                                res_transformer: r.res_transformer.clone(),
                            })
                            .collect(),
                        config: runtime_service.config.clone(),
                    });
                } else {
                    next.push(RuntimeService {
                        name: svc.name.clone(),
                        host: svc.host.clone(),
                        protocols: svc.protocols.clone(),
                        routes: svc
                            .routes
                            .iter()
                            .map(|r| RuntimeRoute {
                                matcher: r.matcher.clone_box(),
                                priority: r.priority,
                                max_retries: r.max_retries,
                                req_transformer: r.req_transformer.clone(),
                                res_transformer: r.res_transformer.clone(),
                            })
                            .collect(),
                        config: svc.config.clone(),
                    });
                }
            }
            next
        });

        self.notify_callbacks();
        log::info!("Updated service: {}", name);
        Ok(())
    }

    /// Remove a service
    pub fn remove_service(&self, name: &str) -> Result<(), JokowayError> {
        // Check if service exists
        if !self.verify_service(name) {
            log::warn!("Service {} does not exist, skipping remove", name);
            return Ok(());
        }

        // Remove service
        self.services.rcu(|old| {
            let mut next = Vec::with_capacity(old.len());
            for svc in old.iter() {
                if svc.name != name {
                    next.push(RuntimeService {
                        name: svc.name.clone(),
                        host: svc.host.clone(),
                        protocols: svc.protocols.clone(),
                        routes: svc
                            .routes
                            .iter()
                            .map(|r| RuntimeRoute {
                                matcher: r.matcher.clone_box(),
                                priority: r.priority,
                                max_retries: r.max_retries,
                                req_transformer: r.req_transformer.clone(),
                                res_transformer: r.res_transformer.clone(),
                            })
                            .collect(),
                        config: svc.config.clone(),
                    });
                }
            }
            next
        });

        self.notify_callbacks();
        log::info!("Removed service: {}", name);
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::models::{JokowayConfig, Route, Service};

    #[test]
    fn test_protocol_filtering() {
        let config = JokowayConfig {
            services: vec![
                Service {
                    name: "http_only".to_string(),
                    host: "http_backend".to_string(),
                    protocols: vec![ServiceProtocol::Http],
                    routes: vec![],
                    ..Default::default()
                },
                Service {
                    name: "https_only".to_string(),
                    host: "https_backend".to_string(),
                    protocols: vec![ServiceProtocol::Https],
                    routes: vec![],
                    ..Default::default()
                },
                Service {
                    name: "dual_protocol".to_string(),
                    host: "dual_backend".to_string(),
                    protocols: vec![ServiceProtocol::Http, ServiceProtocol::Https],
                    routes: vec![],
                    ..Default::default()
                },
                Service {
                    name: "no_protocol".to_string(),
                    host: "default_backend".to_string(),
                    protocols: vec![],
                    routes: vec![],
                    ..Default::default()
                },
            ]
            .into_iter()
            .map(Arc::new)
            .collect(),
            ..Default::default()
        };

        let manager =
            ServiceManager::new(Arc::new(config)).expect("Failed to create ServiceManager");
        let all_services = manager.get_all();

        // Helper to get service names from indices
        let get_names = |indices: Vec<usize>| -> Vec<String> {
            indices
                .iter()
                .map(|&i| all_services[i].name.clone())
                .collect()
        };

        // Test HTTP protocols
        let http_indices = manager.get_indices_for_protocols(&HTTP_PROTOCOLS);
        let http_names = get_names(http_indices.clone());
        assert_eq!(http_indices.len(), 3); // http_only, dual_protocol, no_protocol
        assert!(http_names.contains(&"http_only".to_string()));
        assert!(http_names.contains(&"dual_protocol".to_string()));
        assert!(http_names.contains(&"no_protocol".to_string()));
        assert!(!http_names.contains(&"https_only".to_string()));

        // Test HTTPS protocols
        let https_indices = manager.get_indices_for_protocols(&HTTPS_PROTOCOLS);
        let https_names = get_names(https_indices.clone());
        assert_eq!(https_indices.len(), 3); // https_only, dual_protocol, no_protocol
        assert!(https_names.contains(&"https_only".to_string()));
        assert!(https_names.contains(&"dual_protocol".to_string()));
        assert!(https_names.contains(&"no_protocol".to_string()));
        assert!(!https_names.contains(&"http_only".to_string()));

        // Test all protocols
        let all_indices = manager.get_indices_for_protocols(&ALL_PROTOCOLS);
        assert_eq!(all_indices.len(), 4);
    }

    #[test]
    fn test_service_compilation() {
        let config = JokowayConfig {
            services: vec![Service {
                name: "test_service".to_string(),
                host: "test_backend".to_string(),
                protocols: vec![ServiceProtocol::Http],
                routes: vec![
                    Route {
                        name: "test_route_1".to_string(),
                        rule: "Host(`example.com`)".to_string(),
                        priority: Some(10),
                        ..Default::default()
                    },
                    Route {
                        name: "test_route_2".to_string(),
                        rule: "Host(`api.example.com`)".to_string(),
                        priority: Some(5),
                        ..Default::default()
                    },
                ],
                ..Default::default()
            }]
            .into_iter()
            .map(Arc::new)
            .collect(),
            ..Default::default()
        };

        let manager =
            ServiceManager::new(Arc::new(config)).expect("Failed to create ServiceManager");
        let services = manager.get_all();

        assert_eq!(services.len(), 1);
        assert_eq!(services[0].name, "test_service");
        assert_eq!(services[0].routes.len(), 2);

        // Routes should be sorted by priority (descending)
        assert_eq!(services[0].routes[0].priority, 10);
        assert_eq!(services[0].routes[1].priority, 5);
    }
}