swadhinbiswas WIP save-point: production hardening, H3 removal, fmt gate, and accumulated phase work · 7/15/2026
a293d8c
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
use std::sync::Arc;
use http_body_util::combinators::UnsyncBoxBody;
use http_body_util::BodyExt;
use http_body_util::Full;
use hyper::body::Bytes;
use hyper::{Response, StatusCode};
use crate::serialize;
use crate::ResponseBody;
/// The result of a single health check.
#[derive(Debug, Clone, PartialEq)]
pub enum HealthStatus {
Healthy,
Degraded(String),
Unhealthy(String),
}
/// A single health check probe that can be registered with the registry.
pub trait HealthCheck: Send + Sync {
fn name(&self) -> &'static str;
fn check(&self) -> impl std::future::Future<Output = HealthStatus> + Send;
}
/// A registered health check with its name and probe function.
struct RegisteredCheck {
name: &'static str,
func: Arc<
dyn Fn() -> std::pin::Pin<Box<dyn std::future::Future<Output = HealthStatus> + Send>>
+ Send
+ Sync,
>,
}
/// Registry of health checks that can produce a combined health report.
#[derive(Default)]
pub struct HealthRegistry {
checks: Vec<RegisteredCheck>,
}
impl HealthRegistry {
pub fn new() -> Self {
Self { checks: Vec::new() }
}
/// Register a health check probe.
pub fn register(&mut self, check: impl HealthCheck + 'static) {
let name: &'static str = check.name();
let check = Arc::new(check);
let func: Arc<dyn Fn() -> _ + Send + Sync> = Arc::new(move || {
let check = check.clone();
Box::pin(async move { check.check().await })
as std::pin::Pin<Box<dyn std::future::Future<Output = HealthStatus> + Send>>
});
self.checks.push(RegisteredCheck { name, func });
}
/// Register a health check from a name and async function.
pub fn register_fn<F, Fut>(&mut self, name: &'static str, f: F)
where
F: Fn() -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = HealthStatus> + Send + 'static,
{
let func = Arc::new(
move || -> std::pin::Pin<Box<dyn std::future::Future<Output = HealthStatus> + Send>> {
Box::pin(f())
},
);
self.checks.push(RegisteredCheck { name, func });
}
/// Returns true if no health checks are registered.
pub fn is_empty(&self) -> bool {
self.checks.is_empty()
}
/// Run all registered checks and return a health report.
pub async fn check_all(&self) -> HealthReport {
let mut components = Vec::with_capacity(self.checks.len());
for check in &self.checks {
let status = (check.func)().await;
components.push(ComponentStatus { name: check.name, status });
}
HealthReport { components }
}
/// Produces an HTTP response for the `/health` endpoint.
/// Returns 200 if all checks are healthy, 503 if any are unhealthy.
pub async fn health_response(&self) -> Response<ResponseBody> {
let report = self.check_all().await;
let overall_status = report.overall();
let status_code = match overall_status {
OverallHealth::Healthy => StatusCode::OK,
OverallHealth::Degraded => StatusCode::OK,
OverallHealth::Unhealthy => StatusCode::SERVICE_UNAVAILABLE,
};
let body = serialize::to_json_string(&report).unwrap_or_else(|_| {
r#"{"status":"error","message":"serialization failed"}"#.to_string()
});
Response::builder()
.status(status_code)
.header("content-type", "application/json")
.header("content-length", body.len().to_string())
.body(UnsyncBoxBody::new(
Full::new(Bytes::from(body))
.map_err(|e: std::convert::Infallible| -> anyhow::Error { match e {} }),
))
.unwrap()
}
}
/// The overall health status derived from all components.
#[derive(Debug, Clone, PartialEq)]
pub enum OverallHealth {
Healthy,
Degraded,
Unhealthy,
}
/// Status of a single component.
#[derive(Debug, Clone)]
pub struct ComponentStatus {
pub name: &'static str,
pub status: HealthStatus,
}
/// Full health report containing all component statuses.
#[derive(Debug, Clone)]
pub struct HealthReport {
pub components: Vec<ComponentStatus>,
}
impl HealthReport {
pub fn overall(&self) -> OverallHealth {
let mut has_degraded = false;
for c in &self.components {
match c.status {
HealthStatus::Unhealthy(_) => return OverallHealth::Unhealthy,
HealthStatus::Degraded(_) => has_degraded = true,
HealthStatus::Healthy => {}
}
}
if has_degraded {
OverallHealth::Degraded
} else {
OverallHealth::Healthy
}
}
}
use serde::Serialize;
impl Serialize for HealthStatus {
fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
match self {
HealthStatus::Healthy => {
let mut m = std::collections::BTreeMap::new();
m.insert("status".to_string(), "healthy".to_string());
m.serialize(s)
}
HealthStatus::Degraded(msg) => {
let mut m = std::collections::BTreeMap::new();
m.insert("status".to_string(), "degraded".to_string());
m.insert("message".to_string(), msg.clone());
m.serialize(s)
}
HealthStatus::Unhealthy(msg) => {
let mut m = std::collections::BTreeMap::new();
m.insert("status".to_string(), "unhealthy".to_string());
m.insert("message".to_string(), msg.clone());
m.serialize(s)
}
}
}
}
impl Serialize for ComponentStatus {
fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
use serde::ser::SerializeStruct;
let mut st = s.serialize_struct("ComponentStatus", 2)?;
st.serialize_field("name", self.name)?;
st.serialize_field("status", &self.status)?;
st.end()
}
}
impl Serialize for HealthReport {
fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
use serde::ser::SerializeStruct;
let overall = self.overall();
let status_str = match overall {
OverallHealth::Healthy => "healthy",
OverallHealth::Degraded => "degraded",
OverallHealth::Unhealthy => "unhealthy",
};
let mut st = s.serialize_struct("HealthReport", 3)?;
st.serialize_field("status", status_str)?;
st.serialize_field("components", &self.components)?;
st.end()
}
}
/// A health check that always returns healthy (for testing / fallback).
pub struct AlwaysHealthy {
pub name: &'static str,
}
impl HealthCheck for AlwaysHealthy {
fn name(&self) -> &'static str {
self.name
}
async fn check(&self) -> HealthStatus {
HealthStatus::Healthy
}
}
#[cfg(feature = "db")]
pub mod db_check {
use super::*;
use crate::db::AnyPool;
/// Health check for a database connection pool.
pub struct DbHealthCheck {
name: &'static str,
pool: AnyPool,
}
impl DbHealthCheck {
pub fn new(name: &'static str, pool: AnyPool) -> Self {
Self { name, pool }
}
}
impl HealthCheck for DbHealthCheck {
fn name(&self) -> &'static str {
self.name
}
async fn check(&self) -> HealthStatus {
match self.pool.health_check().await {
Ok(_) => HealthStatus::Healthy,
Err(e) => HealthStatus::Unhealthy(format!("database check failed: {}", e)),
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
struct TestCheck {
name: &'static str,
result: HealthStatus,
}
impl HealthCheck for TestCheck {
fn name(&self) -> &'static str {
self.name
}
async fn check(&self) -> HealthStatus {
self.result.clone()
}
}
#[tokio::test]
async fn test_all_healthy() {
let mut registry = HealthRegistry::new();
registry.register(TestCheck { name: "test1", result: HealthStatus::Healthy });
registry.register(AlwaysHealthy { name: "always" });
let report = registry.check_all().await;
assert_eq!(report.overall(), OverallHealth::Healthy);
assert_eq!(report.components.len(), 2);
}
#[tokio::test]
async fn test_degraded() {
let mut registry = HealthRegistry::new();
registry.register(TestCheck {
name: "test1",
result: HealthStatus::Degraded("slow".to_string()),
});
let report = registry.check_all().await;
assert_eq!(report.overall(), OverallHealth::Degraded);
}
#[tokio::test]
async fn test_unhealthy() {
let mut registry = HealthRegistry::new();
registry.register(TestCheck {
name: "test1",
result: HealthStatus::Unhealthy("down".to_string()),
});
let report = registry.check_all().await;
assert_eq!(report.overall(), OverallHealth::Unhealthy);
}
#[tokio::test]
async fn test_health_response() {
let mut registry = HealthRegistry::new();
registry.register(AlwaysHealthy { name: "test" });
let resp = registry.health_response().await;
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn test_unhealthy_response() {
let mut registry = HealthRegistry::new();
registry.register(TestCheck {
name: "test",
result: HealthStatus::Unhealthy("crash".to_string()),
});
let resp = registry.health_response().await;
assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
}
#[test]
fn test_register_fn() {
let mut registry = HealthRegistry::new();
registry.register_fn("custom", || async { HealthStatus::Healthy });
assert_eq!(registry.checks.len(), 1);
}
}