Skip to main content

infr_server/
status.rs

1//! `GET /status`: one JSON snapshot of the running server — each hosted model's backend, device,
2//! context window, slots and device memory, plus the request gauges. It answers what an OpenAI
3//! client cannot ask: where is this model running, and how much room is left there.
4//!
5//! Every value is read when the request arrives. Fields a backend cannot report are `null`, never
6//! a zero that would read as a measurement.
7
8use axum::{
9    extract::State,
10    http::HeaderMap,
11    response::{IntoResponse, Response},
12    Json,
13};
14use serde::Serialize;
15use std::sync::atomic::Ordering;
16
17use crate::{auth_gate, AppState};
18
19/// Where a generator runs and how much room it has there, as [`crate::ChatGenerator::status`]
20/// reports it.
21#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
22pub struct GeneratorStatus {
23    /// The backend serving the model: `"vulkan"`, `"cpu"` or `"metal"`.
24    pub backend: &'static str,
25    /// The physical device's name, when the backend binds one.
26    pub device: Option<String>,
27    /// The context window each slot holds, in tokens.
28    pub ctx_per_slot: Option<usize>,
29    /// The device's memory as this process sees it.
30    pub memory: Option<DeviceMemory>,
31}
32
33/// A device memory snapshot.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
35pub struct DeviceMemory {
36    pub total_bytes: u64,
37    /// What this process could still allocate there, by the driver's own budget, which accounts
38    /// for other processes' use.
39    pub available_bytes: u64,
40    /// `false` when the driver has no live budget to report, so `available_bytes` is only the
41    /// heap size and does not move as memory is used.
42    pub live: bool,
43    /// The device shares system memory (an integrated GPU), so both figures cover that pool.
44    pub unified: bool,
45}
46
47#[derive(Serialize)]
48struct StatusResponse {
49    version: &'static str,
50    uptime_seconds: f64,
51    requests: Requests,
52    models: Vec<ModelStatus>,
53}
54
55#[derive(Serialize)]
56struct Requests {
57    running: u64,
58    waiting: u64,
59}
60
61#[derive(Serialize)]
62struct ModelStatus {
63    id: String,
64    slots: Slots,
65    /// Absent only for a state built without a generator (tests).
66    #[serde(flatten)]
67    generator: Option<GeneratorStatus>,
68}
69
70#[derive(Serialize)]
71struct Slots {
72    total: usize,
73    busy: usize,
74}
75
76/// Gated by the API key like `/v1/models`: it names every model and the hardware under them.
77pub(crate) async fn status_handler(State(state): State<AppState>, headers: HeaderMap) -> Response {
78    if let Some(denied) = auth_gate(&state.cfg, &headers) {
79        return denied;
80    }
81    Json(StatusResponse {
82        version: env!("CARGO_PKG_VERSION"),
83        uptime_seconds: state.started.elapsed().as_secs_f64(),
84        requests: Requests {
85            running: state.stats.active.load(Ordering::Relaxed),
86            waiting: state.stats.queued.load(Ordering::Relaxed),
87        },
88        models: state
89            .models
90            .iter()
91            .map(|m| ModelStatus {
92                id: m.id.to_string(),
93                slots: Slots {
94                    total: m.capacity,
95                    busy: m.busy(),
96                },
97                generator: m.engine.as_ref().map(|e| e.status()),
98            })
99            .collect(),
100    })
101    .into_response()
102}
103
104#[cfg(test)]
105mod tests {
106    use crate::{build_router, AppState, ChatGenerator, Config};
107    use axum::{body::Body, http::Request, http::StatusCode};
108    use http_body_util::BodyExt;
109    use std::sync::Arc;
110    use tower::ServiceExt;
111
112    async fn get_status(state: AppState, auth: Option<&str>) -> (StatusCode, serde_json::Value) {
113        let mut b = Request::builder().uri("/status");
114        if let Some(a) = auth {
115            b = b.header("authorization", a);
116        }
117        let resp = build_router(state)
118            .oneshot(b.body(Body::empty()).unwrap())
119            .await
120            .unwrap();
121        let status = resp.status();
122        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
123        (status, serde_json::from_slice(&bytes).unwrap())
124    }
125
126    /// Each model carries its own generator's report and its live slot occupancy.
127    #[tokio::test]
128    async fn every_model_reports_its_generator_and_slots() {
129        let a: Arc<dyn ChatGenerator> = Arc::new(crate::tests::EchoGen("alpha"));
130        let b: Arc<dyn ChatGenerator> = Arc::new(crate::tests::EchoGen("beta"));
131        let state = AppState::multi(
132            vec![("alpha".into(), a, 2), ("beta".into(), b, 1)],
133            Arc::new(Config::default()),
134        );
135        let _held = state.models[1].slots.clone().acquire_owned().await.unwrap();
136
137        let (code, v) = get_status(state, None).await;
138        assert_eq!(code, StatusCode::OK);
139        assert_eq!(v["version"], env!("CARGO_PKG_VERSION"));
140        assert!(v["uptime_seconds"].as_f64().unwrap() >= 0.0);
141        assert_eq!(v["requests"]["running"], 0);
142        let models = v["models"].as_array().unwrap();
143        assert_eq!(models.len(), 2);
144        assert_eq!(models[0]["id"], "alpha");
145        assert_eq!(models[0]["device"], "dev-alpha");
146        assert_eq!(models[0]["backend"], "vulkan");
147        assert_eq!(models[0]["ctx_per_slot"], 4096);
148        assert_eq!(models[0]["memory"]["available_bytes"], 6u64 << 30);
149        assert_eq!(models[0]["slots"]["total"], 2);
150        assert_eq!(models[0]["slots"]["busy"], 0);
151        assert_eq!(models[1]["device"], "dev-beta");
152        assert_eq!(models[1]["slots"]["busy"], 1);
153    }
154
155    #[tokio::test]
156    async fn status_needs_the_api_key_when_one_is_set() {
157        let mut cfg = Config::default();
158        cfg.serve.api_key = Some("s3cret".into());
159        let state = AppState::headless("hidden-model", Arc::new(cfg));
160
161        let (code, v) = get_status(state.clone(), None).await;
162        assert_eq!(code, StatusCode::UNAUTHORIZED);
163        assert!(!v.to_string().contains("hidden-model"));
164
165        let (code, v) = get_status(state, Some("Bearer s3cret")).await;
166        assert_eq!(code, StatusCode::OK);
167        assert_eq!(v["models"][0]["id"], "hidden-model");
168    }
169}