apollo-router 2.10.3

A configurable, high-performance routing runtime for Apollo Federation 🚀
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
//! Health Check plugin
//!
//! Provides liveness and readiness checks for the router.
//!
//! This module needs to be executed prior to traffic shaping so that it can capture the responses
//! of requests which have been load shed.
//!

use std::net::SocketAddr;
use std::str::FromStr;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::time::Duration;

use http::StatusCode;
use multimap::MultiMap;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use tokio::time::Instant;
use tower::BoxError;
use tower::ServiceBuilder;
use tower::ServiceExt;
use tower::service_fn;

use crate::Endpoint;
use crate::configuration::ListenAddr;
use crate::plugin::PluginInit;
use crate::plugin::PluginPrivate;
use crate::register_private_plugin;
use crate::services::router;

#[derive(Debug, Serialize)]
#[serde(rename_all = "UPPERCASE")]
#[allow(dead_code)]
enum HealthStatus {
    Up,
    Down,
}

#[derive(Debug, Serialize)]
struct Health {
    status: HealthStatus,
}

/// Configuration options pertaining to the readiness health interval sub-component.
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[serde(default)]
pub(crate) struct ReadinessIntervalConfig {
    #[serde(deserialize_with = "humantime_serde::deserialize", default)]
    #[serde(serialize_with = "humantime_serde::serialize")]
    #[schemars(with = "Option<String>", default)]
    /// The sampling interval (default: 5s)
    pub(crate) sampling: Duration,

    #[serde(deserialize_with = "humantime_serde::deserialize")]
    #[serde(serialize_with = "humantime_serde::serialize")]
    #[schemars(with = "Option<String>")]
    /// The unready interval (default: 2 * sampling interval)
    pub(crate) unready: Option<Duration>,
}

/// Configuration options pertaining to the readiness health sub-component.
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[serde(default)]
pub(crate) struct ReadinessConfig {
    /// The readiness interval configuration
    pub(crate) interval: ReadinessIntervalConfig,

    /// How many rejections are allowed in an interval (default: 100)
    /// If this number is exceeded, the router will start to report unready.
    pub(crate) allowed: usize,
}

impl Default for ReadinessIntervalConfig {
    fn default() -> Self {
        Self {
            sampling: Duration::from_secs(5),
            unready: None,
        }
    }
}

impl Default for ReadinessConfig {
    fn default() -> Self {
        Self {
            interval: Default::default(),
            allowed: 100,
        }
    }
}

/// Configuration options pertaining to the health component.
#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[serde(default)]
#[schemars(rename = "HealthCheckConfig")]
pub(crate) struct Config {
    /// The socket address and port to listen on
    /// Defaults to 127.0.0.1:8088
    pub(crate) listen: ListenAddr,

    /// Set to false to disable the health check
    pub(crate) enabled: bool,

    /// Optionally set a custom healthcheck path
    /// Defaults to /health
    pub(crate) path: String,

    /// Optionally specify readiness configuration
    pub(crate) readiness: ReadinessConfig,
}

#[cfg(test)]
pub(crate) fn test_listen() -> ListenAddr {
    SocketAddr::from_str("127.0.0.1:0").unwrap().into()
}

fn default_health_check_listen() -> ListenAddr {
    SocketAddr::from_str("127.0.0.1:8088").unwrap().into()
}

fn default_health_check_enabled() -> bool {
    true
}

fn default_health_check_path() -> String {
    "/health".to_string()
}

#[buildstructor::buildstructor]
impl Config {
    #[builder]
    pub(crate) fn new(
        listen: Option<ListenAddr>,
        enabled: Option<bool>,
        path: Option<String>,
        readiness: Option<ReadinessConfig>,
    ) -> Self {
        let mut path = path.unwrap_or_else(default_health_check_path);
        if !path.starts_with('/') {
            path = format!("/{path}");
        }

        Self {
            listen: listen.unwrap_or_else(default_health_check_listen),
            enabled: enabled.unwrap_or_else(default_health_check_enabled),
            path,
            readiness: readiness.unwrap_or_default(),
        }
    }
}

impl Default for Config {
    fn default() -> Self {
        Self::builder().build()
    }
}

struct HealthCheck {
    config: Config,
    live: Arc<AtomicBool>,
    ready: Arc<AtomicBool>,
    rejected: Arc<AtomicUsize>,
    ticker: tokio::task::JoinHandle<()>,
}

#[async_trait::async_trait]
impl PluginPrivate for HealthCheck {
    type Config = Config;

    async fn new(init: PluginInit<Self::Config>) -> Result<Self, BoxError> {
        // We always do the work to track readiness and liveness because we
        // need that data to implement our `router_service`. We only log out
        // our health tracing message if our health check is enabled.
        if init.config.enabled {
            tracing::info!(
                "Health check exposed at {}{}",
                init.config.listen,
                init.config.path
            );
        }
        let live = Arc::new(AtomicBool::new(false));
        let ready = Arc::new(AtomicBool::new(false));
        let rejected = Arc::new(AtomicUsize::new(0));

        let allowed = init.config.readiness.allowed;
        let my_sampling_interval = init.config.readiness.interval.sampling;
        let my_recovery_interval = init
            .config
            .readiness
            .interval
            .unready
            .unwrap_or(2 * my_sampling_interval);
        let my_rejected = rejected.clone();
        let my_ready = ready.clone();

        let ticker = tokio::spawn(async move {
            loop {
                let start = Instant::now() + my_sampling_interval;
                let mut interval = tokio::time::interval_at(start, my_sampling_interval);
                loop {
                    interval.tick().await;
                    if my_rejected.load(Ordering::Relaxed) > allowed {
                        my_ready.store(false, Ordering::SeqCst);
                        tokio::time::sleep(my_recovery_interval).await;
                        my_rejected.store(0, Ordering::Relaxed);
                        my_ready.store(true, Ordering::SeqCst);
                        break;
                    }
                }
            }
        });
        Ok(Self {
            config: init.config,
            live,
            ready,
            rejected,
            ticker,
        })
    }

    // Track rejected requests due to traffic shaping.
    // We always do this; even if the health check is disabled.
    fn router_service(&self, service: router::BoxService) -> router::BoxService {
        let my_rejected = self.rejected.clone();

        ServiceBuilder::new()
            .map_response(move |res: router::Response| {
                if res.response.status() == StatusCode::SERVICE_UNAVAILABLE
                    || res.response.status() == StatusCode::GATEWAY_TIMEOUT
                {
                    my_rejected.fetch_add(1, Ordering::Relaxed);
                }
                res
            })
            .service(service)
            .boxed()
    }

    // Support the health-check endpoint for the router, incorporating both live and ready.
    fn web_endpoints(&self) -> MultiMap<ListenAddr, Endpoint> {
        let mut map = MultiMap::new();

        if self.config.enabled {
            let my_ready = self.ready.clone();
            let my_live = self.live.clone();

            let endpoint = Endpoint::from_router_service(
                self.config.path.clone(),
                service_fn(move |req: router::Request| {
                    let mut status_code = StatusCode::OK;
                    let health = if let Some(query) = req.router_request.uri().query() {
                        let query_upper = query.to_ascii_uppercase();
                        // Could be more precise, but sloppy match is fine for this use case
                        if query_upper.starts_with("READY") {
                            let status = if my_ready.load(Ordering::SeqCst) {
                                HealthStatus::Up
                            } else {
                                // It's hard to get k8s to parse payloads. Especially since we
                                // can't install curl or jq into our docker images because of CVEs.
                                // So, compromise, k8s will interpret this as probe fail.
                                status_code = StatusCode::SERVICE_UNAVAILABLE;
                                HealthStatus::Down
                            };
                            Health { status }
                        } else if query_upper.starts_with("LIVE") {
                            let status = if my_live.load(Ordering::SeqCst) {
                                HealthStatus::Up
                            } else {
                                // It's hard to get k8s to parse payloads. Especially since we
                                // can't install curl or jq into our docker images because of CVEs.
                                // So, compromise, k8s will interpret this as probe fail.
                                status_code = StatusCode::SERVICE_UNAVAILABLE;
                                HealthStatus::Down
                            };
                            Health { status }
                        } else {
                            Health {
                                status: HealthStatus::Up,
                            }
                        }
                    } else {
                        Health {
                            status: HealthStatus::Up,
                        }
                    };
                    tracing::trace!(?health, request = ?req.router_request, "health check");
                    async move {
                        router::Response::http_response_builder()
                            .response(http::Response::builder().status(status_code).body(
                                router::body::from_bytes(
                                    serde_json::to_vec(&health).map_err(BoxError::from)?,
                                ),
                            )?)
                            .context(req.context)
                            .build()
                    }
                })
                .boxed(),
            );

            map.insert(self.config.listen.clone(), endpoint);
        }

        map
    }

    /// The point of no return this plugin is about to go live
    fn activate(&self) {
        self.live.store(true, Ordering::SeqCst);
        self.ready.store(true, Ordering::SeqCst);
    }
}

// When a new configuration is made available we need to drop our old ticker.
impl Drop for HealthCheck {
    fn drop(&mut self) {
        self.ticker.abort();
    }
}

register_private_plugin!("apollo", "health_check", HealthCheck);

#[cfg(test)]
mod test {
    use serde_json::json;
    use tower::Service;
    use tower::ServiceExt;

    use super::*;
    use crate::plugins::test::PluginTestHarness;
    use crate::plugins::test::ServiceHandle;

    // Create a base for testing. Even though we don't use the test_harness once this function
    // completes, we return it because we need to keep it alive to prevent the ticker from being
    // dropped.
    async fn get_axum_router(
        listen_addr: ListenAddr,
        config: &'static str,
        response_status_code: StatusCode,
    ) -> (
        Option<Endpoint>,
        Option<ServiceHandle<router::Request, router::BoxService>>,
        PluginTestHarness<HealthCheck>,
    ) {
        let test_harness: PluginTestHarness<HealthCheck> = PluginTestHarness::builder()
            .config(config)
            .build()
            .await
            .expect("test harness");

        test_harness.activate();

        // Limitations in the plugin test harness (requires an Fn function)
        // mean we need to create our responses here...
        let svc = match response_status_code {
            StatusCode::OK => test_harness.router_service(|_req| async {
                router::Response::fake_builder()
                    .data(serde_json::json!({"data": {"field": "value"}}))
                    .header("x-custom-header", "test-value")
                    .build()
            }),
            StatusCode::GATEWAY_TIMEOUT => test_harness.router_service(|_req| async {
                router::Response::fake_builder()
                    .data(serde_json::json!({"data": {"field": "value"}}))
                    .header("x-custom-header", "test-value")
                    .status_code(StatusCode::GATEWAY_TIMEOUT)
                    .build()
            }),
            StatusCode::SERVICE_UNAVAILABLE => test_harness.router_service(|_req| async {
                router::Response::fake_builder()
                    .data(serde_json::json!({"data": {"field": "value"}}))
                    .header("x-custom-header", "test-value")
                    .status_code(StatusCode::SERVICE_UNAVAILABLE)
                    .build()
            }),
            _ => panic!("unsupported status code"),
        };

        let endpoints = test_harness.web_endpoints();

        let endpoint = endpoints.get(&listen_addr);

        (endpoint.cloned(), Some(svc), test_harness)
    }

    // This could be improved. It makes assumptions about the content of config files regarding how
    // many fails are allowed and unready durations. A better test would either parse the config to
    // extract those values or (not as good) take extra parameters specifying them.
    async fn base_test_health_check(
        router_addr: &str,
        config: &'static str,
        status_string: &str,
        response_status_code: StatusCode,
        expect_endpoint: bool,
    ) {
        let listen_addr: ListenAddr = SocketAddr::from_str(router_addr).unwrap().into();

        let (axum_router_opt, pipeline_svc_opt, _test_harness) =
            get_axum_router(listen_addr, config, response_status_code).await;

        let request = http::Request::builder()
            .uri(format!("http://{router_addr}/health?ready="))
            .body(http_body_util::Empty::new())
            .expect("valid request");

        // Make more than 10 requests to trigger our condition
        if let Some(pipeline_svc) = pipeline_svc_opt {
            for _ in 0..20 {
                let _response = pipeline_svc.call_default().await.unwrap();
            }
            // Wait for 3 second so that our condition is recognised
            tokio::time::sleep(Duration::from_secs(3)).await;
        }

        if expect_endpoint {
            let mut axum_router = axum_router_opt.expect("it better be there").into_router();
            // This creates our web_endpoint (in this case the health check) so that we can call it
            let mut svc = axum_router.as_service();
            let response = svc
                .ready()
                .await
                .expect("readied")
                .call(request)
                .await
                .expect("called it");

            let expected_code = if status_string == "DOWN" {
                StatusCode::SERVICE_UNAVAILABLE
            } else {
                StatusCode::OK
            };

            assert_eq!(expected_code, response.status());

            let j: serde_json::Value = serde_json::from_slice(
                &crate::services::router::body::into_bytes(response)
                    .await
                    .expect("we have a body"),
            )
            .expect("some json");
            assert_eq!(json!({"status": status_string }), j)
        } else {
            assert!(axum_router_opt.is_none())
        }
    }

    #[tokio::test]
    async fn test_health_check() {
        let router_addr = "127.0.0.1:8088";
        base_test_health_check(
            router_addr,
            include_str!("testdata/default_listener.router.yaml"),
            "UP",
            StatusCode::OK,
            true,
        )
        .await;
    }

    #[tokio::test]
    async fn test_health_check_custom_listener() {
        let router_addr = "127.0.0.1:4012";
        base_test_health_check(
            router_addr,
            include_str!("testdata/custom_listener.router.yaml"),
            "UP",
            StatusCode::OK,
            true,
        )
        .await;
    }

    #[tokio::test]
    async fn test_health_check_timeout_unready() {
        let router_addr = "127.0.0.1:8088";
        base_test_health_check(
            router_addr,
            include_str!("testdata/allowed_ten_per_second.router.yaml"),
            "DOWN",
            StatusCode::GATEWAY_TIMEOUT,
            true,
        )
        .await;
    }

    #[tokio::test]
    async fn test_health_check_unavailable_unready() {
        let router_addr = "127.0.0.1:8088";
        base_test_health_check(
            router_addr,
            include_str!("testdata/allowed_ten_per_second.router.yaml"),
            "DOWN",
            StatusCode::SERVICE_UNAVAILABLE,
            true,
        )
        .await;
    }

    #[tokio::test]
    async fn test_health_check_timeout_ready() {
        let router_addr = "127.0.0.1:8088";
        base_test_health_check(
            router_addr,
            include_str!("testdata/allowed_fifty_per_second.router.yaml"),
            "UP",
            StatusCode::GATEWAY_TIMEOUT,
            true,
        )
        .await;
    }

    #[tokio::test]
    async fn test_health_check_unavailable_ready() {
        let router_addr = "127.0.0.1:8088";
        base_test_health_check(
            router_addr,
            include_str!("testdata/allowed_fifty_per_second.router.yaml"),
            "UP",
            StatusCode::SERVICE_UNAVAILABLE,
            true,
        )
        .await;
    }

    #[tokio::test]
    async fn test_health_check_disabled() {
        let router_addr = "127.0.0.1:8088";
        base_test_health_check(
            router_addr,
            include_str!("testdata/disabled_listener.router.yaml"),
            "UP",
            StatusCode::SERVICE_UNAVAILABLE,
            false,
        )
        .await;
    }
}