cf-gears-toolkit 0.6.17

Core ToolKit library
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
//! REST readiness healthcheck infrastructure for probing gear health.
//!
//! This module provides concurrent healthcheck execution with timeout protection.
//! Gears implement [`Healthcheck`] and register themselves via [`RestHealthcheckRegistry`].
//! The API Gateway calls [`report()`](RestHealthcheckRegistry::report) on `/health` and `/readyz`
//! requests to aggregate per-component readiness status.
//!
//! # Usage
//!
//! ```rust,ignore
//! use async_trait::async_trait;
//! use std::sync::Arc;
//! use toolkit::{Healthcheck, HealthcheckResult, contracts::RestApiCapability};
//!
//! struct MyHealthcheck;
//!
//! #[async_trait]
//! impl Healthcheck for MyHealthcheck {
//!     fn name(&self) -> &'static str {
//!         "my-gear-readiness"
//!     }
//!
//!     async fn check(&self) -> HealthcheckResult {
//!         HealthcheckResult::healthy()
//!     }
//! }
//!
//! impl RestApiCapability for MyGear {
//!     fn healthcheck(
//!         &self,
//!         _ctx: &toolkit::context::GearCtx,
//!     ) -> Option<Arc<dyn Healthcheck>> {
//!         Some(Arc::new(MyHealthcheck))
//!     }
//!
//!     fn register_rest(
//!         &self,
//!         ctx: &toolkit::context::GearCtx,
//!         router: axum::Router,
//!         openapi: &dyn toolkit::contracts::OpenApiRegistry,
//!     ) -> anyhow::Result<axum::Router> {
//!         Ok(router)
//!     }
//! }
//! ```
//!
//! # Kubernetes probe configuration
//!
//! ```yaml
//! livenessProbe:
//!   httpGet:
//!     path: /healthz
//!     port: http
//!   periodSeconds: 10
//!   timeoutSeconds: 2
//!   failureThreshold: 3
//!
//! readinessProbe:
//!   httpGet:
//!     path: /readyz
//!     port: http
//!   periodSeconds: 5
//!   timeoutSeconds: 2
//!   failureThreshold: 3
//! ```
//!
//! `/healthz` is liveness — always shallow, never runs user checks.
//! `/readyz` is readiness — runs user REST healthchecks and removes the pod
//! from traffic when unhealthy without triggering a restart.
//! `/health` is the detailed diagnostic endpoint — its JSON body includes per-component
//! check names and messages.
//!
//! Probe port and path depend on the serving mode (`api-gateway` `health.serve`): with `main`
//! or `both` the endpoints ride the main gateway listener (target the main `http` port) and
//! inherit `prefix_path` like any other route (e.g. `/cf/healthz`); with `separate` they are
//! served only on the health listener (`health.bind_addr`) at unprefixed paths, so probes must
//! target that port and the bare `/healthz`/`/readyz`/`/health` paths.
//!
//! # Threat model
//!
//! All three endpoints are **unauthenticated in every serving mode**: on the main listener
//! they are registered as explicit public routes so the auth layer waves them through without
//! a bearer token, and the separate listener runs no auth at all. They are protected by
//! deployment controls, not credentials: a `separate` health listener is expected to sit on a
//! private/management network, and `main`-mounted endpoints inherit whatever network placement
//! the main gateway has.
//! Because `/health` can expose per-component names and messages without auth, check messages
//! are sanitized (see [`sanitize_message`]) so a secret, DSN, credential, or panic backtrace
//! cannot leak to an unauthenticated caller.

use async_trait::async_trait;
use parking_lot::RwLock;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::Mutex as AsyncMutex;
use tokio_util::sync::CancellationToken;

/// Single-check and aggregate readiness status.
/// Serialized lowercase into `/health`/`/readyz`; variants are a stable API contract.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum HealthcheckStatus {
    Healthy,
    Degraded,
    Unhealthy,
}

/// Result of one [`Healthcheck::check`]; fields are part of the stable `/health` JSON contract.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthcheckResult {
    pub status: HealthcheckStatus,
    pub message: Option<String>,
    /// Stable, machine-readable code (e.g. `"db_unreachable"`), surfaced on `/health`. Lets
    /// operators alert on a stable signal even when the human-readable `message` is collapsed
    /// by sanitization. Because `/health` is unauthenticated, the code is constrained (see
    /// [`sanitize_code`]) to a short `[a-z0-9_.-]` identifier and dropped if it does not
    /// conform — it must never carry secrets or free-form detail.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub code: Option<String>,
}

impl HealthcheckResult {
    #[must_use]
    pub fn healthy() -> Self {
        Self {
            status: HealthcheckStatus::Healthy,
            message: None,
            code: None,
        }
    }

    #[must_use]
    pub fn degraded(message: impl Into<String>) -> Self {
        Self {
            status: HealthcheckStatus::Degraded,
            message: Some(message.into()),
            code: None,
        }
    }

    #[must_use]
    pub fn unhealthy(message: impl Into<String>) -> Self {
        Self {
            status: HealthcheckStatus::Unhealthy,
            message: Some(message.into()),
            code: None,
        }
    }

    /// Attach a stable machine-readable code (see [`HealthcheckResult::code`]).
    #[must_use]
    pub fn with_code(mut self, code: impl Into<String>) -> Self {
        self.code = Some(code.into());
        self
    }
}

impl Default for HealthcheckResult {
    fn default() -> Self {
        Self::healthy()
    }
}

/// Readiness probe implemented by a gear.
///
/// `name` must be an explicit human-readable id (no type paths); it is exposed on
/// `/health`. `check` must be cancellation-safe and should not leak secrets in its
/// message (the registry sanitises anyway); panics and per-check timeouts are caught
/// and mapped to [`HealthcheckStatus::Unhealthy`]. Default `check` returns healthy.
#[async_trait]
pub trait Healthcheck: Send + Sync + 'static {
    /// Human-readable check name, exposed verbatim in `/health` JSON.
    fn name(&self) -> &'static str;

    async fn check(&self) -> HealthcheckResult {
        HealthcheckResult::healthy()
    }
}

/// One gear's healthcheck result. All fields are part of the stable `/health` JSON contract.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthcheckComponentReport {
    pub gear: String,
    pub check: String,
    pub status: HealthcheckStatus,
    /// Sanitized (see [`sanitize_message`]).
    pub message: Option<String>,
    /// Stable machine-readable code from [`HealthcheckResult::code`]; passed through unsanitized.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub code: Option<String>,
    pub latency_ms: u64,
}

/// Aggregate report from [`RestHealthcheckRegistry::report`]; stable `/health`/`/readyz` JSON contract.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthcheckReport {
    pub status: HealthcheckStatus,
    pub components: Vec<HealthcheckComponentReport>,
}

impl HealthcheckReport {
    /// Ready unless `Unhealthy` (`Healthy` and `Degraded` both keep the pod in rotation).
    #[must_use]
    pub fn is_ready(&self) -> bool {
        self.status != HealthcheckStatus::Unhealthy
    }
}

struct RegistryEntry {
    gear: String,
    check: Arc<dyn Healthcheck>,
}

/// Bursty probes within this window reuse the last report instead of re-running checks.
/// Kept > the default per-check timeout (500 ms) so a timed-out check still buffers.
const REPORT_CACHE_TTL: Duration = Duration::from_secs(2);

/// Holds the REST healthchecks registered during REST wiring; the gateway calls
/// [`report`](Self::report) on every `/readyz` and `/health` request.
#[derive(Default)]
pub struct RestHealthcheckRegistry {
    entries: RwLock<Vec<RegistryEntry>>,
    cached_report: AsyncMutex<Option<(Instant, HealthcheckReport)>>,
    /// Runtime shutdown token; aborts in-flight checks. Default never fires.
    cancel: CancellationToken,
}

impl RestHealthcheckRegistry {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Registry whose in-flight checks are aborted when `cancel` fires.
    #[must_use]
    pub fn with_cancellation(cancel: CancellationToken) -> Self {
        Self {
            cancel,
            ..Self::default()
        }
    }

    /// Register a healthcheck for the given gear.
    pub fn register(&self, gear: impl Into<String>, check: Arc<dyn Healthcheck>) {
        self.entries.write().push(RegistryEntry {
            gear: gear.into(),
            check,
        });
    }

    /// Run all checks concurrently, aggregate, and cache for [`REPORT_CACHE_TTL`].
    /// Panics and per-check timeouts map to [`HealthcheckStatus::Unhealthy`]. The cache
    /// lock is held across the compute so concurrent cache-misses coalesce into one fan-out.
    pub async fn report(&self, timeout_per_check: Duration) -> HealthcheckReport {
        let mut guard = self.cached_report.lock().await;
        if let Some((ts, cached)) = guard.as_ref()
            && ts.elapsed() < REPORT_CACHE_TTL
        {
            return cached.clone();
        }

        let entries: Vec<(_, _)> = {
            let r = self.entries.read();
            r.iter()
                .map(|e| (e.gear.clone(), e.check.clone()))
                .collect()
        };

        let report = if entries.is_empty() {
            HealthcheckReport {
                status: HealthcheckStatus::Healthy,
                components: vec![],
            }
        } else {
            let cancel = &self.cancel;
            let checks = entries
                .into_iter()
                .map(|(gear, check)| run_one_check(gear, check, timeout_per_check, cancel));
            let components = futures_util::future::join_all(checks).await;
            let aggregate = compute_aggregate(&components);
            HealthcheckReport {
                status: aggregate,
                components,
            }
        };

        *guard = Some((Instant::now(), report.clone()));
        report
    }
}

async fn run_one_check(
    gear: String,
    check: Arc<dyn Healthcheck>,
    timeout_per_check: Duration,
    cancel: &CancellationToken,
) -> HealthcheckComponentReport {
    let name = check.name();
    let start = Instant::now();

    let mut handle = tokio::spawn(async move { check.check().await });

    let (status, message, code) = tokio::select! {
        result = &mut handle => match result {
            Ok(r) => (
                r.status,
                r.message.as_deref().map(sanitize_message),
                r.code.as_deref().and_then(sanitize_code),
            ),
            Err(join_err) => {
                tracing::error!(gear = %gear, check = name, error = %join_err, "healthcheck task panicked");
                (
                    HealthcheckStatus::Unhealthy,
                    Some("health check failed".to_owned()),
                    None,
                )
            }
        },
        () = tokio::time::sleep(timeout_per_check) => {
            handle.abort();
            if let Err(join_err) = handle.await
                && !join_err.is_cancelled()
            {
                tracing::warn!(gear = %gear, check = name, error = %join_err, "healthcheck task join error after timeout abort");
            }
            tracing::warn!(gear = %gear, check = name, timeout_ms = timeout_per_check.as_millis(), "healthcheck timed out");
            (
                HealthcheckStatus::Unhealthy,
                Some("health check timed out".to_owned()),
                None,
            )
        }
        () = cancel.cancelled() => {
            handle.abort();
            if let Err(join_err) = handle.await
                && !join_err.is_cancelled()
            {
                tracing::warn!(gear = %gear, check = name, error = %join_err, "healthcheck task join error after shutdown abort");
            }
            tracing::warn!(gear = %gear, check = name, "healthcheck cancelled by runtime shutdown");
            (
                HealthcheckStatus::Unhealthy,
                Some("health check cancelled".to_owned()),
                None,
            )
        }
    };

    HealthcheckComponentReport {
        gear,
        check: name.to_owned(),
        status,
        message,
        code,
        latency_ms: u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX),
    }
}

fn compute_aggregate(components: &[HealthcheckComponentReport]) -> HealthcheckStatus {
    let mut status = HealthcheckStatus::Healthy;
    for c in components {
        match c.status {
            HealthcheckStatus::Unhealthy => return HealthcheckStatus::Unhealthy,
            HealthcheckStatus::Degraded => {
                status = HealthcheckStatus::Degraded;
            }
            HealthcheckStatus::Healthy => {}
        }
    }
    status
}

const MAX_MESSAGE_LEN: usize = 256;

// Blocklist targeting the actual threat: `/health` is unauthenticated (protected only by
// private listener/network placement), so a check message must never carry a secret, DSN,
// credential, or panic backtrace to an anonymous caller. Deliberately excludes operator-useful
// terms (tenant ids, SQL verbs, "private" network hints) that are not secrets — keeping them
// readable makes the endpoint actually diagnostic. Matched substrings collapse the message to
// the generic string.
static SUSPICIOUS_SUBSTRINGS: &[&str] = &[
    "password",
    "passwd",
    "secret",
    "token",
    "bearer",
    "authorization",
    "api_key",
    "apikey",
    "private_key",
    "credential",
    "access_key",
    "aws_",
    "client_secret",
    "postgres://",
    "postgresql://",
    "mysql://",
    "sqlite://",
    "mongodb://",
    "redis://",
    "amqp://",
    "jdbc:",
    "panic",
    "stack backtrace",
];

fn sanitize_message(msg: &str) -> String {
    if msg.len() > MAX_MESSAGE_LEN {
        return "health check failed".to_owned();
    }
    let lower = msg.to_lowercase();
    for sub in SUSPICIOUS_SUBSTRINGS {
        if lower.contains(sub) {
            return "health check failed".to_owned();
        }
    }
    msg.to_owned()
}

const MAX_CODE_LEN: usize = 64;

/// Validate a health `code` for exposure on the unauthenticated `/health` endpoint.
///
/// A code must be a short machine identifier, not free text — so unlike `message` (which is
/// scrubbed by a blocklist), `code` is validated by an allowlist: non-empty, `<= MAX_CODE_LEN`,
/// and only `[a-z0-9_.-]`. Non-conforming codes are dropped (`None`) rather than surfaced,
/// closing the hole where a permissive code could smuggle a secret past `sanitize_message`.
fn sanitize_code(code: &str) -> Option<String> {
    let ok = !code.is_empty()
        && code.len() <= MAX_CODE_LEN
        && code.bytes().all(|b| {
            b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'.' | b'-')
        });
    if ok {
        Some(code.to_owned())
    } else {
        tracing::debug!(
            code,
            "health check code dropped: not a [a-z0-9_.-] identifier"
        );
        None
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::time::Duration;
    use tokio::sync::Notify;

    struct AlwaysDegraded;
    #[async_trait]
    impl Healthcheck for AlwaysDegraded {
        fn name(&self) -> &'static str {
            "always-degraded"
        }
        async fn check(&self) -> HealthcheckResult {
            HealthcheckResult::degraded("cache warming")
        }
    }

    struct AlwaysUnhealthy;
    #[async_trait]
    impl Healthcheck for AlwaysUnhealthy {
        fn name(&self) -> &'static str {
            "always-unhealthy"
        }
        async fn check(&self) -> HealthcheckResult {
            HealthcheckResult::unhealthy("database unreachable")
        }
    }

    struct SlowCheck;
    #[async_trait]
    impl Healthcheck for SlowCheck {
        fn name(&self) -> &'static str {
            "slow-check"
        }
        async fn check(&self) -> HealthcheckResult {
            tokio::time::sleep(Duration::from_secs(10)).await;
            HealthcheckResult::healthy()
        }
    }

    struct AbortTrackingCheck {
        entered: Arc<Notify>,
        dropped: Arc<AtomicBool>,
    }

    #[async_trait]
    impl Healthcheck for AbortTrackingCheck {
        fn name(&self) -> &'static str {
            "abort-tracking-check"
        }
        async fn check(&self) -> HealthcheckResult {
            struct DropFlag(Arc<AtomicBool>);
            impl Drop for DropFlag {
                fn drop(&mut self) {
                    self.0.store(true, Ordering::SeqCst);
                }
            }

            let _drop_flag = DropFlag(self.dropped.clone());
            self.entered.notify_one();
            std::future::pending::<HealthcheckResult>().await
        }
    }

    struct PanickingCheck;
    #[async_trait]
    impl Healthcheck for PanickingCheck {
        fn name(&self) -> &'static str {
            "panicking-check"
        }
        async fn check(&self) -> HealthcheckResult {
            panic!("intentional panic in healthcheck");
        }
    }

    #[test]
    fn healthcheck_result_default_is_healthy() {
        let r = HealthcheckResult::default();
        assert_eq!(r.status, HealthcheckStatus::Healthy);
        assert!(r.message.is_none());
    }

    #[tokio::test]
    async fn empty_registry_report_is_healthy_and_ready() {
        let registry = RestHealthcheckRegistry::new();
        let report = registry.report(Duration::from_millis(500)).await;
        assert_eq!(report.status, HealthcheckStatus::Healthy);
        assert!(report.is_ready());
        assert!(report.components.is_empty());
    }

    #[tokio::test]
    async fn unhealthy_component_makes_aggregate_unhealthy_and_not_ready() {
        let registry = RestHealthcheckRegistry::new();
        registry.register("my-gear", Arc::new(AlwaysUnhealthy));
        let report = registry.report(Duration::from_millis(500)).await;
        assert_eq!(report.status, HealthcheckStatus::Unhealthy);
        assert!(!report.is_ready());
    }

    #[tokio::test]
    async fn mixed_degraded_and_unhealthy_aggregate_is_unhealthy() {
        let registry = RestHealthcheckRegistry::new();
        registry.register("degraded-gear", Arc::new(AlwaysDegraded));
        registry.register("unhealthy-gear", Arc::new(AlwaysUnhealthy));
        let report = registry.report(Duration::from_millis(500)).await;
        assert_eq!(
            report.status,
            HealthcheckStatus::Unhealthy,
            "unhealthy must take priority over degraded"
        );
        assert!(!report.is_ready());
    }

    #[tokio::test]
    async fn slow_check_times_out_and_becomes_unhealthy() {
        let registry = RestHealthcheckRegistry::new();
        registry.register("slow-gear", Arc::new(SlowCheck));
        let report = registry.report(Duration::from_millis(100)).await;
        assert_eq!(report.status, HealthcheckStatus::Unhealthy);
        let comp = &report.components[0];
        assert_eq!(comp.status, HealthcheckStatus::Unhealthy);
        assert_eq!(comp.message.as_deref(), Some("health check timed out"));
    }

    #[tokio::test]
    async fn timed_out_check_is_aborted() {
        let registry = RestHealthcheckRegistry::new();
        let entered = Arc::new(Notify::new());
        let dropped = Arc::new(AtomicBool::new(false));
        registry.register(
            "slow-gear",
            Arc::new(AbortTrackingCheck {
                entered: entered.clone(),
                dropped: dropped.clone(),
            }),
        );

        let report_task =
            tokio::spawn(async move { registry.report(Duration::from_millis(10)).await });
        entered.notified().await;
        let report = report_task.await.expect("report task panicked");

        assert_eq!(report.status, HealthcheckStatus::Unhealthy);
        assert!(
            dropped.load(Ordering::SeqCst),
            "timed-out healthcheck future must be dropped after abort"
        );
    }

    #[tokio::test]
    async fn cancelled_registry_aborts_in_flight_check_and_reports_unhealthy() {
        let cancel = CancellationToken::new();
        let registry = RestHealthcheckRegistry::with_cancellation(cancel.clone());
        let entered = Arc::new(Notify::new());
        let dropped = Arc::new(AtomicBool::new(false));
        registry.register(
            "slow-gear",
            Arc::new(AbortTrackingCheck {
                entered: entered.clone(),
                dropped: dropped.clone(),
            }),
        );

        // Long per-check timeout so cancellation, not the timeout, ends the check.
        let report_task =
            tokio::spawn(async move { registry.report(Duration::from_mins(1)).await });
        entered.notified().await;
        cancel.cancel();
        let report = report_task.await.expect("report task panicked");

        assert_eq!(report.status, HealthcheckStatus::Unhealthy);
        assert_eq!(
            report.components[0].message.as_deref(),
            Some("health check cancelled")
        );
        assert!(
            dropped.load(Ordering::SeqCst),
            "cancelled healthcheck future must be dropped after abort"
        );
    }

    #[tokio::test]
    async fn panicking_check_becomes_unhealthy_without_panicking_caller() {
        let registry = RestHealthcheckRegistry::new();
        registry.register("panic-gear", Arc::new(PanickingCheck));
        let report = registry.report(Duration::from_millis(500)).await;
        assert_eq!(report.status, HealthcheckStatus::Unhealthy);
    }

    #[tokio::test]
    async fn second_call_within_ttl_reuses_cached_report_without_rerunning_checks() {
        use std::sync::atomic::AtomicUsize;

        struct CountingCheck(Arc<AtomicUsize>);
        #[async_trait]
        impl Healthcheck for CountingCheck {
            fn name(&self) -> &'static str {
                "counting-check"
            }
            async fn check(&self) -> HealthcheckResult {
                self.0.fetch_add(1, Ordering::SeqCst);
                HealthcheckResult::healthy()
            }
        }

        let calls = Arc::new(AtomicUsize::new(0));
        let registry = RestHealthcheckRegistry::new();
        registry.register("counted-gear", Arc::new(CountingCheck(calls.clone())));

        let first = registry.report(Duration::from_millis(500)).await;
        let second = registry.report(Duration::from_millis(500)).await;

        assert_eq!(first.status, HealthcheckStatus::Healthy);
        assert_eq!(second.status, HealthcheckStatus::Healthy);
        assert_eq!(
            calls.load(Ordering::SeqCst),
            1,
            "second report() within REPORT_CACHE_TTL must reuse the cached result"
        );
    }

    #[test]
    fn sensitive_message_is_sanitized() {
        assert_eq!(
            sanitize_message("connection to postgres://user:pass@host/db failed"),
            "health check failed"
        );
        assert_eq!(
            sanitize_message("invalid token in header"),
            "health check failed"
        );
        assert_eq!(
            sanitize_message("thread panicked at some_file.rs:42"),
            "health check failed"
        );
        assert_eq!(
            sanitize_message("invalid api_key provided"),
            "health check failed"
        );
        assert_eq!(
            sanitize_message("connection to mongodb://host/db failed"),
            "health check failed"
        );
    }

    #[test]
    fn long_message_is_sanitized() {
        let long = "x".repeat(257);
        assert_eq!(sanitize_message(&long), "health check failed");
    }

    #[test]
    fn clean_message_passes_through() {
        assert_eq!(
            sanitize_message("upstream service unavailable"),
            "upstream service unavailable"
        );
    }

    #[test]
    fn operator_useful_messages_pass_through() {
        // These are not secrets and are useful when diagnosing an unhealthy pod, so the
        // narrowed blocklist deliberately leaves them intact.
        for msg in [
            "tenant acme-corp migration pending",
            "SELECT on read replica timed out",
            "private subnet route unreachable",
        ] {
            assert_eq!(sanitize_message(msg), msg);
        }
    }

    #[test]
    fn code_allowlist_accepts_identifiers_and_drops_the_rest() {
        assert_eq!(
            sanitize_code("db_unreachable"),
            Some("db_unreachable".to_owned())
        );
        assert_eq!(sanitize_code("v1.2-beta_3"), Some("v1.2-beta_3".to_owned()));
        // Rejected: empty, uppercase, whitespace/free text, over length.
        assert_eq!(sanitize_code(""), None);
        assert_eq!(sanitize_code("DB_UNREACHABLE"), None);
        assert_eq!(sanitize_code("postgres://user:pw@host/db"), None);
        assert_eq!(sanitize_code("connection failed"), None);
        assert_eq!(sanitize_code(&"a".repeat(MAX_CODE_LEN + 1)), None);
    }

    #[tokio::test]
    async fn component_report_carries_conforming_code() {
        struct CodedUnhealthy;
        #[async_trait]
        impl Healthcheck for CodedUnhealthy {
            fn name(&self) -> &'static str {
                "coded"
            }
            async fn check(&self) -> HealthcheckResult {
                HealthcheckResult::unhealthy("database unreachable").with_code("db_unreachable")
            }
        }

        let registry = RestHealthcheckRegistry::new();
        registry.register("gear", Arc::new(CodedUnhealthy));
        let report = registry.report(Duration::from_millis(500)).await;
        assert_eq!(report.components[0].code.as_deref(), Some("db_unreachable"));
    }

    #[tokio::test]
    async fn component_report_drops_nonconforming_code() {
        struct BadCode;
        #[async_trait]
        impl Healthcheck for BadCode {
            fn name(&self) -> &'static str {
                "bad-code"
            }
            async fn check(&self) -> HealthcheckResult {
                // A code carrying free-form detail (a DSN) must never reach the report.
                HealthcheckResult::unhealthy("down").with_code("postgres://u:p@host/db")
            }
        }

        let registry = RestHealthcheckRegistry::new();
        registry.register("gear", Arc::new(BadCode));
        let report = registry.report(Duration::from_millis(500)).await;
        assert!(report.components[0].code.is_none());
    }
}