Files
leleka/control-plane/src/app/admin_routes.rs
T
Pavlo Ratushnyi 51a4eceff0 control-plane: the request counters of /metrics belong to Services, not a process cell (STRA-338)
The request middleware, the backend worker and the metrics handler now share one RequestMetrics value that Services holds, so the LazyLock registry of request_log.rs and its architecture.json exception are gone. The middleware gets it through Observe, the worker through BackendWorkerConfig, and prometheus::render takes it as an argument; the counters, histograms, labels and log lines are unchanged, and the unit tests now count into a registry of their own instead of one shared by the whole test process.
2026-11-24 03:44:23 +01:00

89 lines
3.9 KiB
Rust

//! Liveness, lifecycle (drain/resume) and `GET /metrics`.
use super::{
AppState, HeaderMap, HealthResponse, IntoResponse, Json, RawQuery, Response, State, StatusCode, WorkerState,
metrics_document,
};
pub(super) async fn health() -> Json<HealthResponse> {
Json(HealthResponse { status: "ok" })
}
pub(super) async fn lifecycle_status(State(state): State<AppState>) -> Json<serde_json::Value> {
let worker = *state.engine.worker.read().await;
let lifecycle = state.lifecycle.snapshot();
let drained = lifecycle.draining
&& lifecycle.requests_in_flight == 0
&& lifecycle.generation_jobs == 0
&& worker.metrics.active_since.is_none()
&& matches!(worker.state, WorkerState::Ready | WorkerState::Unconfigured | WorkerState::Unloaded);
Json(
serde_json::json!({"service":"leleka-control-plane", "server_pid":std::process::id(), "model":state.model.name,
"draining":lifecycle.draining,
"shutting_down":lifecycle.shutting_down,
"max_in_flight_requests":lifecycle.max_in_flight_requests,
"available_request_slots":lifecycle.max_in_flight_requests.saturating_sub(lifecycle.requests_in_flight),
"requests_in_flight":lifecycle.requests_in_flight, "generation_jobs":lifecycle.generation_jobs,
"drained":drained, "worker":worker.state}),
)
}
pub(super) fn lifecycle_precondition(headers: &HeaderMap) -> Option<Response> {
let mut values = headers.get_all("x-strata-expected-pid").iter();
let value = values.next()?;
let pid = value
.to_str()
.ok()
.filter(|s| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()))
.and_then(|s| s.parse::<u32>().ok())
.filter(|n| *n > 0);
if values.next().is_some() || pid.is_none() {
let body = serde_json::json!({"error": {
"code": "invalid_expected_pid", "message": "expected PID must be one positive integer",
}});
return Some((StatusCode::BAD_REQUEST, Json(body)).into_response());
}
if pid != Some(std::process::id()) {
let body = serde_json::json!({"error": {
"code": "process_identity_changed",
"message": "native process no longer matches expected PID; admission unchanged",
}});
return Some((StatusCode::CONFLICT, Json(body)).into_response());
}
None
}
pub(super) async fn drain(State(state): State<AppState>, headers: HeaderMap) -> Response {
if let Some(response) = lifecycle_precondition(&headers) {
return response;
}
state.lifecycle.set_draining(true);
lifecycle_status(State(state)).await.into_response()
}
pub(super) async fn resume(State(state): State<AppState>, headers: HeaderMap) -> Response {
if let Some(response) = lifecycle_precondition(&headers) {
return response;
}
state.lifecycle.set_draining(false);
lifecycle_status(State(state)).await.into_response()
}
/// `GET /metrics`: the native JSON document, or its Prometheus text exposition (`?format=prometheus`, or an `Accept`
/// that asks for `text/plain` / OpenMetrics, as a Prometheus scraper sends). `?requests=all` lists every kept
/// generation, not the last 12.
pub(super) async fn metrics(State(state): State<AppState>, RawQuery(query): RawQuery, headers: HeaderMap) -> Response {
let accept = headers.get(axum::http::header::ACCEPT).and_then(|v| v.to_str().ok());
let all = query.as_deref().is_some_and(|q| q.split('&').any(|pair| pair == "requests=all"));
let document = metrics_document(&state, all).await;
if crate::prometheus::wanted(query.as_deref(), accept) {
let mut response = crate::prometheus::render(&document, &state.services.request_metrics).into_response();
response.headers_mut().insert(
axum::http::header::CONTENT_TYPE,
axum::http::HeaderValue::from_static(crate::prometheus::CONTENT_TYPE),
);
return response;
}
Json(document).into_response()
}