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
|
use axum::extract::State;
use axum::response::Json;
use axum::routing::get;
use axum::Router;
use serde_json::{json, Value};
use std::sync::Arc;
use std::time::Instant;
use tokio::sync::watch;
pub struct HealthState {
pub started_at: Instant,
pub cycle_count: watch::Receiver<u64>,
pub last_cycle_ok: watch::Receiver<bool>,
pub db_path: String,
pub nip46_client: Option<Arc<crate::nip46::Nip46Client>>,
}
pub async fn start_health_server(port: u16, state: Arc<HealthState>) -> anyhow::Result<()> {
let app = Router::new()
.route("/health", get(health_handler))
.route("/api/mirror-health", get(health_handler))
.with_state(state);
let listener = tokio::net::TcpListener::bind(format!("127.0.0.1:{}", port)).await?;
tracing::info!(port, "health server listening");
axum::serve(listener, app).await?;
Ok(())
}
async fn health_handler(State(state): State<Arc<HealthState>>) -> Json<Value> {
let uptime = state.started_at.elapsed();
let cycle_count = *state.cycle_count.borrow();
let last_ok = *state.last_cycle_ok.borrow();
let nip46_sessions = if let Some(ref client) = state.nip46_client {
let statuses = client.get_status().await;
statuses
.into_iter()
.map(|s| {
json!({
"npub": s.npub,
"connected": s.connected,
"pairing_uri": s.pairing_uri,
})
})
.collect::<Vec<_>>()
} else {
vec![]
};
Json(json!({
"status": if last_ok || cycle_count == 0 { "ok" } else { "degraded" },
"uptime_secs": uptime.as_secs(),
"cycle_count": cycle_count,
"last_cycle_ok": last_ok,
"nip46": nip46_sessions,
}))
}
|