//! 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; `engine/strata/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, usage: Option, error: Option, http_status: Option, response: Option, response_truncated: bool, wallclock_s: Option, finished_at: Option, clock: Instant, } type Shared = Arc>; /// The monitor: disabled (nothing is kept) or a bounded list of request records. #[derive(Default)] pub struct RequestMonitor { enabled: bool, records: Mutex>, } /// An event stream passed through unchanged while its events are read into the record. struct Tap { inner: axum::body::BodyDataStream, record: Shared, pending: Vec, done: bool, } #[cfg(test)] mod tests; mod now_unix; #[allow(unused_imports)] pub use now_unix::*; mod impl_record; #[allow(unused_imports)] pub use impl_record::*; mod impl_requestmonitor; #[allow(unused_imports)] pub use impl_requestmonitor::*;