Skip to main content

camber/
resource.rs

1use crate::RuntimeError;
2use std::sync::Arc;
3use std::sync::atomic::AtomicBool;
4use std::time::Duration;
5
6/// Minimum allowed interval for resource health checks.
7pub(crate) const MIN_HEALTH_INTERVAL: Duration = Duration::from_secs(1);
8
9/// Shared health state for all registered resources.
10/// Fixed-size array allocated once from the resource registry. Each entry is
11/// (resource name, healthy flag). Health check tasks write the AtomicBool;
12/// the `/health` endpoint reads it. Zero allocation at request time.
13pub(crate) type HealthState = Arc<[(Box<str>, AtomicBool)]>;
14
15/// A managed external resource that participates in the runtime lifecycle.
16///
17/// Implement this trait on database pools, caches, message brokers, or any
18/// long-lived resource that needs health checking and graceful shutdown.
19///
20/// All methods are synchronous. Health checks run via `block_in_place` on a
21/// background thread. Shutdown runs during runtime teardown before Tokio
22/// shuts down.
23pub trait Resource: Send + Sync + 'static {
24    /// Human-readable name for health reporting and error messages.
25    fn name(&self) -> &str;
26
27    /// Check whether the resource is healthy. Called on a background interval.
28    fn health_check(&self) -> Result<(), RuntimeError>;
29
30    /// Graceful shutdown. Called in reverse registration order during teardown.
31    fn shutdown(&self) -> Result<(), RuntimeError>;
32}