cf-api-gateway 0.2.1

API Gateway module
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
#![allow(clippy::unwrap_used, clippy::expect_used)]

//! Integration tests for HTTP metrics middleware.
//!
//! Verifies that the metrics middleware (now a `layer()` instead of `route_layer()`)
//! captures responses from all middleware layers — including auth, rate-limit, MIME,
//! and timeout — and that `http.route` uses the route template (not raw path).

use anyhow::Result;
use axum::{
    Router,
    body::Body,
    http::{Request, StatusCode},
    response::IntoResponse,
};
use modkit::{
    Module, api::OperationBuilder, config::ConfigProvider, context::ModuleCtx,
    contracts::ApiGatewayCapability,
};
use opentelemetry_sdk::metrics::{
    InMemoryMetricExporter, Instrument, PeriodicReader, SdkMeterProvider, Stream,
    data::{AggregatedMetrics, MetricData},
};
use serde_json::json;
use std::sync::Arc;
use tokio::sync::Mutex;
use tower::ServiceExt;
use uuid::Uuid;

/// Global lock to serialize tests that mutate the OpenTelemetry global meter provider.
static METER_LOCK: Mutex<()> = Mutex::const_new(());

struct TestConfigProvider {
    config: serde_json::Value,
}

impl ConfigProvider for TestConfigProvider {
    fn get_module_config(&self, module: &str) -> Option<&serde_json::Value> {
        self.config.get(module)
    }
}

fn create_api_gateway_ctx(config: serde_json::Value) -> ModuleCtx {
    let hub = Arc::new(modkit::ClientHub::new());
    ModuleCtx::new(
        "api-gateway",
        Uuid::new_v4(),
        Arc::new(TestConfigProvider { config }),
        hub,
        tokio_util::sync::CancellationToken::new(),
        None,
    )
}

/// Install an in-memory meter provider as the OpenTelemetry global so that
/// `HttpMetrics::new` (which uses `opentelemetry::global::meter_with_scope`)
/// records into our exporter.
fn install_test_meter_provider() -> (SdkMeterProvider, InMemoryMetricExporter) {
    let exporter = InMemoryMetricExporter::default();
    let provider = SdkMeterProvider::builder()
        .with_reader(PeriodicReader::builder(exporter.clone()).build())
        .with_view(|_: &Instrument| Stream::builder().with_cardinality_limit(2000).build().ok())
        .build();
    opentelemetry::global::set_meter_provider(provider.clone());
    (provider, exporter)
}

/// Check whether a metric with the given name exists in the exported data (any type).
fn metric_exists(exporter: &InMemoryMetricExporter, name: &str) -> bool {
    let metrics = exporter.get_finished_metrics().unwrap();
    metrics.iter().any(|rm| {
        rm.scope_metrics()
            .any(|sm| sm.metrics().any(|m| m.name() == name))
    })
}

/// Extract the sum of all histogram data point counts for the named metric.
fn histogram_count(exporter: &InMemoryMetricExporter, name: &str) -> u64 {
    let metrics = exporter.get_finished_metrics().unwrap();
    let mut total = 0u64;
    for resource_metrics in &metrics {
        for scope_metrics in resource_metrics.scope_metrics() {
            for metric in scope_metrics.metrics() {
                if metric.name() == name
                    && let AggregatedMetrics::F64(MetricData::Histogram(hist)) = metric.data()
                {
                    for dp in hist.data_points() {
                        total += dp.count();
                    }
                }
            }
        }
    }
    total
}

/// Check whether a histogram data point exists with the given attribute values.
fn histogram_has_attributes(
    exporter: &InMemoryMetricExporter,
    name: &str,
    expected_attrs: &[(&str, &str)],
) -> bool {
    let metrics = exporter.get_finished_metrics().unwrap();
    for resource_metrics in &metrics {
        for scope_metrics in resource_metrics.scope_metrics() {
            for metric in scope_metrics.metrics() {
                if metric.name() == name
                    && let AggregatedMetrics::F64(MetricData::Histogram(hist)) = metric.data()
                {
                    for dp in hist.data_points() {
                        let attrs: Vec<_> = dp.attributes().collect();
                        let all_match = expected_attrs.iter().all(|(key, val)| {
                            attrs
                                .iter()
                                .any(|kv| kv.key.as_str() == *key && kv.value.as_str() == *val)
                        });
                        if all_match {
                            return true;
                        }
                    }
                }
            }
        }
    }
    false
}

async fn ok_handler() -> impl IntoResponse {
    StatusCode::OK
}

fn base_config() -> serde_json::Value {
    json!({
        "api-gateway": {
            "config": {
                "bind_addr": "127.0.0.1:0",
                "cors_enabled": false,
                "auth_disabled": true,
                "defaults": {
                    "rate_limit": { "rps": 1000, "burst": 1000, "in_flight": 64 }
                },
            }
        }
    })
}

#[tokio::test]
async fn metrics_capture_successful_request() -> Result<()> {
    let _lock = METER_LOCK.lock().await;
    let (provider, exporter) = install_test_meter_provider();
    let ctx = create_api_gateway_ctx(base_config());
    let api = api_gateway::ApiGateway::default();
    api.init(&ctx).await?;

    let router = OperationBuilder::get("/tests/v1/items")
        .operation_id("test:list-items")
        .summary("List items")
        .public()
        .json_response(StatusCode::OK, "OK")
        .handler(axum::routing::get(ok_handler))
        .register(Router::new(), &api);
    let app = api.rest_finalize(&ctx, router)?;

    let res = app
        .oneshot(
            Request::builder()
                .method("GET")
                .uri("/tests/v1/items")
                .body(Body::empty())?,
        )
        .await?;
    assert_eq!(res.status(), StatusCode::OK);

    provider.force_flush().unwrap();

    let count = histogram_count(&exporter, "http.server.request.duration");
    assert!(
        count >= 1,
        "expected at least 1 duration data point, got {count}"
    );

    assert!(
        histogram_has_attributes(
            &exporter,
            "http.server.request.duration",
            &[
                ("http.request.method", "GET"),
                ("http.route", "/tests/v1/items"),
                ("http.response.status_code", "200"),
            ]
        ),
        "duration histogram should have correct method/route/status attributes"
    );

    Ok(())
}

#[tokio::test]
async fn metrics_capture_mime_rejection() -> Result<()> {
    let _lock = METER_LOCK.lock().await;
    let (provider, exporter) = install_test_meter_provider();
    let ctx = create_api_gateway_ctx(base_config());
    let api = api_gateway::ApiGateway::default();
    api.init(&ctx).await?;

    let mut builder = OperationBuilder::post("/tests/v1/items");
    builder.require_rate_limit(1000, 1000, 64);
    let router = builder
        .operation_id("test:create-item")
        .summary("Create item")
        .public()
        .allow_content_types(&["application/json"])
        .json_response(StatusCode::OK, "OK")
        .handler(axum::routing::post(ok_handler))
        .register(Router::new(), &api);
    let app = api.rest_finalize(&ctx, router)?;

    let res = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/tests/v1/items")
                .header("content-type", "text/plain")
                .body(Body::from("hi"))?,
        )
        .await?;
    assert_eq!(res.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);

    provider.force_flush().unwrap();

    let count = histogram_count(&exporter, "http.server.request.duration");
    assert!(
        count >= 1,
        "MIME rejection (415) must be captured by metrics, got {count} data points"
    );

    assert!(
        histogram_has_attributes(
            &exporter,
            "http.server.request.duration",
            &[("http.response.status_code", "415"),]
        ),
        "duration histogram should record 415 status from MIME rejection"
    );

    Ok(())
}

#[tokio::test]
async fn metrics_capture_rate_limit() -> Result<()> {
    let _lock = METER_LOCK.lock().await;
    let cfg = json!({
        "api-gateway": {
            "config": {
                "bind_addr": "127.0.0.1:0",
                "cors_enabled": false,
                "auth_disabled": true,
                "defaults": {
                    "rate_limit": { "rps": 1, "burst": 1, "in_flight": 64 }
                },
            }
        }
    });

    let (provider, exporter) = install_test_meter_provider();
    let ctx = create_api_gateway_ctx(cfg);
    let api = api_gateway::ApiGateway::default();
    api.init(&ctx).await?;

    let mut builder = OperationBuilder::get("/tests/v1/limited");
    builder.require_rate_limit(1, 1, 64);
    let router = builder
        .operation_id("test:limited")
        .summary("Rate-limited endpoint")
        .public()
        .json_response(StatusCode::OK, "OK")
        .handler(axum::routing::get(ok_handler))
        .register(Router::new(), &api);
    let app = api.rest_finalize(&ctx, router)?;

    // First request — succeeds and consumes the token
    let res1 = app
        .clone()
        .oneshot(
            Request::builder()
                .method("GET")
                .uri("/tests/v1/limited")
                .body(Body::empty())?,
        )
        .await?;
    assert_eq!(res1.status(), StatusCode::OK);

    // Second request immediately — rate-limited
    let res2 = app
        .oneshot(
            Request::builder()
                .method("GET")
                .uri("/tests/v1/limited")
                .body(Body::empty())?,
        )
        .await?;
    assert_eq!(res2.status(), StatusCode::TOO_MANY_REQUESTS);

    provider.force_flush().unwrap();

    let count = histogram_count(&exporter, "http.server.request.duration");
    assert!(
        count >= 2,
        "both 200 and 429 must be captured by metrics, got {count} data points"
    );

    assert!(
        histogram_has_attributes(
            &exporter,
            "http.server.request.duration",
            &[("http.response.status_code", "429"),]
        ),
        "duration histogram should record 429 from rate limiting"
    );

    Ok(())
}

#[tokio::test]
async fn metrics_route_attribute_uses_template() -> Result<()> {
    let _lock = METER_LOCK.lock().await;
    let (provider, exporter) = install_test_meter_provider();
    let ctx = create_api_gateway_ctx(base_config());
    let api = api_gateway::ApiGateway::default();
    api.init(&ctx).await?;

    let router = OperationBuilder::get("/tests/v1/items/{id}")
        .operation_id("test:get-item")
        .summary("Get item")
        .public()
        .json_response(StatusCode::OK, "OK")
        .handler(axum::routing::get(ok_handler))
        .register(Router::new(), &api);
    let app = api.rest_finalize(&ctx, router)?;

    let res = app
        .oneshot(
            Request::builder()
                .method("GET")
                .uri("/tests/v1/items/42")
                .body(Body::empty())?,
        )
        .await?;
    assert_eq!(res.status(), StatusCode::OK);

    provider.force_flush().unwrap();

    // Must use the template "/tests/v1/items/{id}", NOT the raw path "/tests/v1/items/42"
    assert!(
        histogram_has_attributes(
            &exporter,
            "http.server.request.duration",
            &[("http.route", "/tests/v1/items/{id}"),]
        ),
        "http.route must be the template, not the concrete path"
    );

    // Verify it does NOT record the raw path
    assert!(
        !histogram_has_attributes(
            &exporter,
            "http.server.request.duration",
            &[("http.route", "/tests/v1/items/42"),]
        ),
        "http.route must NOT contain the concrete path (cardinality explosion)"
    );

    Ok(())
}

#[tokio::test]
async fn metrics_unmatched_route() -> Result<()> {
    let _lock = METER_LOCK.lock().await;
    let (provider, exporter) = install_test_meter_provider();
    let ctx = create_api_gateway_ctx(base_config());
    let api = api_gateway::ApiGateway::default();
    api.init(&ctx).await?;

    let router = OperationBuilder::get("/tests/v1/items")
        .operation_id("test:list-items")
        .summary("List items")
        .public()
        .json_response(StatusCode::OK, "OK")
        .handler(axum::routing::get(ok_handler))
        .register(Router::new(), &api);
    let app = api.rest_finalize(&ctx, router)?;

    let res = app
        .oneshot(
            Request::builder()
                .method("GET")
                .uri("/no/such/route")
                .body(Body::empty())?,
        )
        .await?;
    assert_eq!(res.status(), StatusCode::NOT_FOUND);

    provider.force_flush().unwrap();

    let count = histogram_count(&exporter, "http.server.request.duration");
    assert!(
        count >= 1,
        "unmatched route 404 must be captured by metrics, got {count} data points"
    );

    assert!(
        histogram_has_attributes(
            &exporter,
            "http.server.request.duration",
            &[
                ("http.route", "unmatched"),
                ("http.response.status_code", "404"),
            ]
        ),
        "unmatched route should have http.route='unmatched' and status 404"
    );

    Ok(())
}

fn prefixed_config() -> serde_json::Value {
    json!({
        "api-gateway": {
            "config": {
                "bind_addr": "127.0.0.1:0",
                "cors_enabled": false,
                "auth_disabled": true,
                "metrics": { "prefix": "myapp" },
                "defaults": {
                    "rate_limit": { "rps": 1000, "burst": 1000, "in_flight": 64 }
                },
            }
        }
    })
}

#[tokio::test]
async fn metrics_prefix_applied_to_instrument_names() -> Result<()> {
    let _lock = METER_LOCK.lock().await;
    let (provider, exporter) = install_test_meter_provider();
    let ctx = create_api_gateway_ctx(prefixed_config());
    let api = api_gateway::ApiGateway::default();
    api.init(&ctx).await?;

    let router = OperationBuilder::get("/tests/v1/items")
        .operation_id("test:list-items")
        .summary("List items")
        .public()
        .json_response(StatusCode::OK, "OK")
        .handler(axum::routing::get(ok_handler))
        .register(Router::new(), &api);
    let app = api.rest_finalize(&ctx, router)?;

    let res = app
        .oneshot(
            Request::builder()
                .method("GET")
                .uri("/tests/v1/items")
                .body(Body::empty())?,
        )
        .await?;
    assert_eq!(res.status(), StatusCode::OK);

    provider.force_flush().unwrap();

    let count = histogram_count(&exporter, "myapp.http.server.request.duration");
    assert!(
        count >= 1,
        "expected at least 1 data point for prefixed metric name, got {count}"
    );

    // Verify active_requests counter is also prefixed
    assert!(
        metric_exists(&exporter, "myapp.http.server.active_requests"),
        "active_requests counter should use the configured prefix"
    );

    // The unprefixed names should NOT exist when prefix is configured
    assert!(
        !metric_exists(&exporter, "http.server.request.duration"),
        "unprefixed duration should not exist when prefix is configured"
    );
    assert!(
        !metric_exists(&exporter, "http.server.active_requests"),
        "unprefixed active_requests should not exist when prefix is configured"
    );

    Ok(())
}