Files
leleka/control-plane/src/request_monitor.rs
T
Pavlo Ratushnyi d9c0c87dcf Narrow the dead glob re-exports of the module splits: pub use x::* becomes use x::* or pub(crate) use x::* (STRA-338)
Where the split left pub use x::* over items that no outside module can name, the compiler said the glob re-exports nothing pub. The glob now has the visibility its items really have: plain use where they are pub(self), pub(crate) where siblings reach them (model.rs file_download, libc-shim launch_interposers). One glob of backend-api scripted.rs was dead and is deleted. 7 globs of control-plane stay with their allow: the compiler calls them unused in the lib build and the lib test build of control-plane cannot be built on Windows, so a test use cannot be ruled out.

cargo check --all-targets on backend-api, control-plane, gateway-domain, gateway-text and libc-shim: no new warning, no new error (the one control-plane lib test error is the pre-existing std::os::unix use).
2026-11-24 08:51:58 +01:00

102 lines
3.6 KiB
Rust

//! The API request monitor: `GET /api/requests`, the opt-in inspection of the last requests' prompts and answers of the
//! Python service (`api_monitor` in its config; `Strata 41cf05a0, serve/server.py` `begin_request` / `request_records`,
//! tests in `serve/test_monitor.py`).
//!
//! It keeps the last [`RETENTION`] requests of the three generation dialects (`/v1/chat/completions`, `/v1/messages`,
//! `/v1/responses`) in memory: the request body as pretty JSON, the generated text and reasoning, the usage, the error,
//! the HTTP status and the wall-clock timings. It is off unless the config sets `"api_monitor": true`, because it holds
//! prompts and answers in memory; nothing is written to disk and request headers (credentials) are never captured.
//! Every captured text is bounded to [`CAP`] bytes and says so (`*_truncated`).
//!
//! The capture is a middleware around the three routes: it reads the request body once (bounded by the 16 MiB route
//! limit), hands the same bytes on, and either collects a JSON response or taps an event stream chunk by chunk without
//! delaying it. A stream whose consumer goes away before it ends is recorded as `disconnected`.
//!
//! Differences from the Python monitor, all deliberate: `/v1/responses` is monitored too; `queue_s` and `load_s` are
//! `null` (a request's wait for the engine is not attributed per request here: see `/metrics` `live.queued`); the state
//! is `queued` until the first generated text, then `generating`, then `completed`, `error` or `disconnected`; there is
//! no HTML page.
use std::{
collections::VecDeque,
pin::Pin,
sync::{Arc, Mutex},
task::{Context, Poll},
time::{Instant, SystemTime, UNIX_EPOCH},
};
use axum::{
body::{Body, Bytes},
extract::{Request, State},
http::{HeaderValue, StatusCode, header},
middleware::Next,
response::{IntoResponse, Response},
};
use futures_core::Stream;
use serde_json::{Map, Value, json};
/// Requests kept.
pub const RETENTION: usize = 100;
/// Bytes kept of each captured text (the request, the output, the reasoning, the response).
pub const CAP: usize = 262_144;
/// Body limit of the generation routes.
const BODY_LIMIT: usize = 16 * 1024 * 1024;
/// A response collected whole (not an event stream) is read up to this size for capture.
const RESPONSE_LIMIT: usize = 64 * 1024 * 1024;
/// A single event line longer than this is dropped from the capture (the stream itself is untouched).
const LINE_LIMIT: usize = 1 << 20;
#[derive(Debug)]
struct Record {
id: String,
path: String,
model: Value,
started_at: f64,
state: &'static str,
outcome: Option<&'static str>,
stream: bool,
response_format: Value,
input: String,
input_truncated: bool,
output: String,
output_truncated: bool,
reasoning: String,
reasoning_truncated: bool,
first_token_s: Option<f64>,
usage: Option<Value>,
error: Option<Value>,
http_status: Option<u16>,
response: Option<String>,
response_truncated: bool,
wallclock_s: Option<f64>,
finished_at: Option<f64>,
clock: Instant,
}
type Shared = Arc<Mutex<Record>>;
/// The monitor: disabled (nothing is kept) or a bounded list of request records.
#[derive(Default)]
pub struct RequestMonitor {
enabled: bool,
records: Mutex<VecDeque<Shared>>,
}
/// An event stream passed through unchanged while its events are read into the record.
struct Tap {
inner: axum::body::BodyDataStream,
record: Shared,
pending: Vec<u8>,
done: bool,
}
#[cfg(test)]
mod tests;
mod captured_text;
use captured_text::*;
mod record;
#[allow(unused_imports)]
pub use record::*;
mod capture;
pub use capture::*;