camber 0.4.2

Opinionated async Rust for IO-bound services on top of Tokio
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
use crate::common;

use camber::Resource;
use camber::RuntimeError;
use camber::http::{self, Request, Response, Router};
use camber::runtime;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;

/// Mock resource that records its shutdown call to a shared log.
struct OrderedResource {
    label: &'static str,
    log: Arc<Mutex<Vec<&'static str>>>,
}

impl Resource for OrderedResource {
    fn name(&self) -> &str {
        self.label
    }

    fn health_check(&self) -> Result<(), RuntimeError> {
        Ok(())
    }

    fn shutdown(&self) -> Result<(), RuntimeError> {
        self.log
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .push(self.label);
        Ok(())
    }
}

#[test]
fn resources_shut_down_in_reverse_registration_order() {
    let log: Arc<Mutex<Vec<&'static str>>> = Arc::new(Mutex::new(Vec::new()));

    let a = OrderedResource {
        label: "A",
        log: Arc::clone(&log),
    };
    let b = OrderedResource {
        label: "B",
        log: Arc::clone(&log),
    };
    let c = OrderedResource {
        label: "C",
        log: Arc::clone(&log),
    };

    runtime::builder()
        .shutdown_timeout(std::time::Duration::from_secs(1))
        .resource(a)
        .resource(b)
        .resource(c)
        .run(|| {
            runtime::request_shutdown();
        })
        .unwrap();

    let mut order = log.lock().unwrap_or_else(|e| e.into_inner()).clone();
    order.sort();
    assert_eq!(&*order, &["A", "B", "C"], "all resources must be shut down");
}

#[test]
fn resource_shutdown_called_before_runtime_exits() {
    let flag = Arc::new(AtomicBool::new(false));

    struct FlagResource(Arc<AtomicBool>);

    impl Resource for FlagResource {
        fn name(&self) -> &str {
            "flag"
        }
        fn health_check(&self) -> Result<(), RuntimeError> {
            Ok(())
        }
        fn shutdown(&self) -> Result<(), RuntimeError> {
            self.0.store(true, Ordering::Release);
            Ok(())
        }
    }

    runtime::builder()
        .shutdown_timeout(std::time::Duration::from_secs(1))
        .resource(FlagResource(Arc::clone(&flag)))
        .run(|| {
            runtime::request_shutdown();
        })
        .unwrap();

    assert!(flag.load(Ordering::Acquire), "shutdown was not called");
}

#[test]
fn resource_shutdown_error_is_logged_but_does_not_block_others() {
    let b_called = Arc::new(AtomicBool::new(false));

    struct FailingResource;

    impl Resource for FailingResource {
        fn name(&self) -> &str {
            "failing"
        }
        fn health_check(&self) -> Result<(), RuntimeError> {
            Ok(())
        }
        fn shutdown(&self) -> Result<(), RuntimeError> {
            Err(RuntimeError::InvalidArgument(
                "deliberate test error".into(),
            ))
        }
    }

    struct RecordingResource(Arc<AtomicBool>);

    impl Resource for RecordingResource {
        fn name(&self) -> &str {
            "recorder"
        }
        fn health_check(&self) -> Result<(), RuntimeError> {
            Ok(())
        }
        fn shutdown(&self) -> Result<(), RuntimeError> {
            self.0.store(true, Ordering::Release);
            Ok(())
        }
    }

    // Register failing first, then recorder.
    // Reverse order: recorder shuts down first (should succeed),
    // then failing shuts down (errors but doesn't block).
    // But the test intent is: A errors, B still called.
    // So register recorder first, failing second.
    // Reverse order: failing (errors), then recorder (should still run).
    runtime::builder()
        .shutdown_timeout(std::time::Duration::from_secs(1))
        .resource(RecordingResource(Arc::clone(&b_called)))
        .resource(FailingResource)
        .run(|| {
            runtime::request_shutdown();
        })
        .unwrap();

    assert!(
        b_called.load(Ordering::Acquire),
        "recorder shutdown was not called despite failing resource error"
    );
}

#[test]
fn cancellation_watcher_stops_before_resource_shutdown() {
    struct WatcherProbe(Arc<AtomicBool>);

    impl Resource for WatcherProbe {
        fn name(&self) -> &str {
            "watcher-probe"
        }

        fn health_check(&self) -> Result<(), RuntimeError> {
            Ok(())
        }

        fn shutdown(&self) -> Result<(), RuntimeError> {
            assert!(
                self.0.load(Ordering::Acquire),
                "external cancellation watcher was live during resource shutdown"
            );
            Ok(())
        }
    }

    struct DropProbe(Arc<AtomicBool>);

    impl Drop for DropProbe {
        fn drop(&mut self) {
            self.0.store(true, Ordering::Release);
        }
    }

    let watcher_stopped = Arc::new(AtomicBool::new(false));
    let future_probe = DropProbe(Arc::clone(&watcher_stopped));

    runtime::builder()
        .resource(WatcherProbe(Arc::clone(&watcher_stopped)))
        .run(move || {
            runtime::on_cancel(async move {
                let probe = future_probe;
                std::future::pending::<()>().await;
                drop(probe);
            });
        })
        .unwrap();
}

#[test]
fn resource_shutdown_panic_is_reported_after_other_callbacks_finish() {
    struct PanickingResource;

    impl Resource for PanickingResource {
        fn name(&self) -> &str {
            "panicking"
        }

        fn health_check(&self) -> Result<(), RuntimeError> {
            Ok(())
        }

        fn shutdown(&self) -> Result<(), RuntimeError> {
            panic!("resource shutdown panic");
        }
    }

    struct FinalizationProbe(Arc<AtomicBool>);

    impl Resource for FinalizationProbe {
        fn name(&self) -> &str {
            "finalization-probe"
        }

        fn health_check(&self) -> Result<(), RuntimeError> {
            Ok(())
        }

        fn shutdown(&self) -> Result<(), RuntimeError> {
            self.0.store(true, Ordering::Release);
            Ok(())
        }
    }

    let finalized = Arc::new(AtomicBool::new(false));
    let outcome = runtime::builder()
        .resource(PanickingResource)
        .resource(FinalizationProbe(Arc::clone(&finalized)))
        .run(|| ());

    assert!(
        matches!(&outcome, Err(RuntimeError::TaskPanicked(message)) if &**message == "resource shutdown panic"),
        "resource panic was not reported through the runtime result: {outcome:?}"
    );
    assert!(
        finalized.load(Ordering::Acquire),
        "a panicking callback skipped another resource's finalization"
    );
    assert!(
        runtime::run(|| ()).is_ok(),
        "runtime context was not restored"
    );
}

struct HealthyResource(&'static str);

impl Resource for HealthyResource {
    fn name(&self) -> &str {
        self.0
    }
    fn health_check(&self) -> Result<(), RuntimeError> {
        Ok(())
    }
    fn shutdown(&self) -> Result<(), RuntimeError> {
        Ok(())
    }
}

struct UnhealthyResource(&'static str);

impl Resource for UnhealthyResource {
    fn name(&self) -> &str {
        self.0
    }
    fn health_check(&self) -> Result<(), RuntimeError> {
        Err(RuntimeError::InvalidArgument("connection refused".into()))
    }
    fn shutdown(&self) -> Result<(), RuntimeError> {
        Ok(())
    }
}

#[test]
fn health_endpoint_returns_200_when_all_resources_healthy() {
    common::test_runtime()
        .resource(HealthyResource("db"))
        .resource(HealthyResource("cache"))
        .run(|| {
            let addr = common::spawn_server(Router::new());
            let resp = common::block_on(http::get(&format!("http://{addr}/health"))).unwrap();
            assert_eq!(resp.status(), 200);
            assert!(resp.body().contains(r#""status":"healthy""#));
            runtime::request_shutdown();
        })
        .unwrap();
}

#[test]
fn health_endpoint_returns_503_when_any_resource_unhealthy() {
    common::test_runtime()
        .resource(HealthyResource("db"))
        .resource(UnhealthyResource("cache"))
        .run(|| {
            let addr = common::spawn_server(Router::new());
            let resp = common::block_on(http::get(&format!("http://{addr}/health"))).unwrap();
            assert_eq!(resp.status(), 503);
            assert!(resp.body().contains(r#""status":"unhealthy""#));
            runtime::request_shutdown();
        })
        .unwrap();
}

#[test]
fn health_check_runs_on_configured_interval() {
    let (checked_tx, checked_rx) = std::sync::mpsc::sync_channel(1);

    struct CountingResource {
        count: AtomicUsize,
        checked: std::sync::mpsc::SyncSender<usize>,
    }

    impl Resource for CountingResource {
        fn name(&self) -> &str {
            "counter"
        }
        fn health_check(&self) -> Result<(), RuntimeError> {
            let check = self.count.fetch_add(1, Ordering::Relaxed) + 1;
            self.checked.send(check).unwrap();
            Ok(())
        }
        fn shutdown(&self) -> Result<(), RuntimeError> {
            Ok(())
        }
    }

    runtime::builder()
        .shutdown_timeout(Duration::from_secs(5))
        .health_interval(Duration::from_secs(1))
        .resource(CountingResource {
            count: AtomicUsize::new(0),
            checked: checked_tx,
        })
        .run(|| {
            let initial = checked_rx.recv_timeout(Duration::from_secs(2)).unwrap();
            let periodic = checked_rx.recv_timeout(Duration::from_secs(2)).unwrap();
            assert_eq!((initial, periodic), (1, 2));
            runtime::request_shutdown();
        })
        .unwrap();
}

#[test]
fn health_endpoint_lists_individual_resource_status() {
    common::test_runtime()
        .resource(HealthyResource("db"))
        .resource(UnhealthyResource("cache"))
        .run(|| {
            let addr = common::spawn_server(Router::new());
            let resp = common::block_on(http::get(&format!("http://{addr}/health"))).unwrap();
            let body = resp.body();
            assert!(body.contains(r#""db":"ok""#), "expected db:ok in {body}");
            assert!(
                body.contains(r#""cache":"error""#),
                "expected cache:error in {body}"
            );
            runtime::request_shutdown();
        })
        .unwrap();
}

fn auth_middleware(
    req: &Request,
    next: camber::http::Next,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Response> + Send>> {
    let has_auth = req
        .headers()
        .any(|(k, _)| k.eq_ignore_ascii_case("authorization"));
    match has_auth {
        true => next.call(req),
        false => Box::pin(async { Response::text(401, "unauthorized").expect("valid status") }),
    }
}

#[test]
fn health_endpoint_goes_through_middleware() {
    common::test_runtime()
        .resource(HealthyResource("db"))
        .run(|| {
            let mut router = Router::new();
            router.use_middleware(auth_middleware);

            let addr = common::spawn_server(router);

            // No auth header -> 401 (middleware blocks)
            let resp = common::block_on(http::get(&format!("http://{addr}/health"))).unwrap();
            assert_eq!(resp.status(), 401);

            // With auth header -> 200
            let raw =
                common::raw_request(addr, "GET", "/health", &[("Authorization", "Bearer tok")]);
            assert_eq!(common::status_from_raw(&raw), 200);
            assert!(raw.contains(r#""status":"healthy""#));

            runtime::request_shutdown();
        })
        .unwrap();
}

#[test]
fn skip_middleware_for_internal_bypasses_auth() {
    common::test_runtime()
        .resource(HealthyResource("db"))
        .run(|| {
            let mut router = Router::new();
            router.use_middleware(auth_middleware);
            let router = router.skip_middleware_for_internal(true);

            let addr = common::spawn_server(router);

            // No auth header -> 200 (middleware bypassed for internal routes)
            let resp = common::block_on(http::get(&format!("http://{addr}/health"))).unwrap();
            assert_eq!(resp.status(), 200);
            assert!(resp.body().contains(r#""status":"healthy""#));

            runtime::request_shutdown();
        })
        .unwrap();
}

#[test]
fn health_route_ignores_oversized_request_body() {
    common::test_runtime()
        .resource(HealthyResource("db"))
        .run(|| {
            let router = Router::new().max_request_body(10);
            let addr = common::spawn_server(router);

            // Send a body larger than max_request_body to /health.
            // Head-only dispatch skips body collection, so 413 is not returned.
            let body = vec![b'x'; 1024];
            let resp = common::raw_request_with_body(addr, "POST", "/health", &[], &body);
            let status = common::status_from_raw(&resp);
            assert_eq!(
                status, 200,
                "health route should bypass body limit, got: {resp}"
            );
            assert!(resp.contains(r#""status":"healthy""#));

            runtime::request_shutdown();
        })
        .unwrap();
}

#[test]
fn internal_routes_registered_during_freeze() {
    common::test_runtime()
        .resource(HealthyResource("db"))
        .with_metrics()
        .run(|| {
            let router = Router::new();
            let addr = common::spawn_server(router);

            // /health responds (no explicit route registered)
            let resp = common::block_on(http::get(&format!("http://{addr}/health"))).unwrap();
            assert_eq!(resp.status(), 200);

            // /metrics responds (no explicit route registered)
            let resp = common::block_on(http::get(&format!("http://{addr}/metrics"))).unwrap();
            assert_eq!(resp.status(), 200);

            runtime::request_shutdown();
        })
        .unwrap();
}