Skip to main content

agentmux_srv/server/app_api/
record_read.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `GET /api/v1/app/record`: this machine's record of AgentMux's own size over weeks, for the `App` tool's
5//! `record` action and the panel (docs/specs/SPEC_LONG_RUNNING_ZERO_DEGRADATION_2026_11_16.md ยง6, task #47820).
6//! It reads the files `backend::record` writes; nothing is sent anywhere, and a line holds numbers and
7//! stable keys only (no names, titles or paths).
8
9use std::collections::HashMap;
10
11use axum::extract::Query;
12use axum::response::{IntoResponse, Response};
13use serde_json::json;
14
15use crate::backend::record;
16
17/// Lines an answer may carry: an hourly rollup is about 1 KB and a five-minute line about 2 KB.
18const MAX_ROLLUPS: usize = 1_000;
19const MAX_RAW: usize = 600;
20const DEFAULT_ROLLUPS: usize = 24;
21const DEFAULT_RAW: usize = 12;
22const MAX_EVENTS: usize = 500;
23const DEFAULT_EVENTS: usize = 50;
24const DAY_MS: u64 = 86_400_000;
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub(crate) enum Kind {
28    Rollup,
29    Raw,
30    Events,
31}
32
33/// What was asked: `kind` (`rollup`, the default, `raw` or `events`), the window `from_ms` to `to_ms` (or one UTC
34/// `day`) and how many of its newest lines (`limit`).
35#[derive(Debug, PartialEq)]
36pub(crate) struct Ask {
37    pub kind: Kind,
38    pub from_ms: u64,
39    pub to_ms: u64,
40    pub limit: usize,
41}
42
43pub(crate) fn parse_ask(query: &HashMap<String, String>) -> Result<Ask, String> {
44    let kind = match query.get("kind").map(String::as_str) {
45        None | Some("rollup") => Kind::Rollup,
46        Some("raw") => Kind::Raw,
47        Some("events") => Kind::Events,
48        Some(other) => return Err(format!("kind is \"rollup\", \"raw\" or \"events\", not {other:?}")),
49    };
50    let num = |key: &str| query.get(key).map(|v| v.parse::<u64>().map_err(|_| format!("{key} is a number of milliseconds, not {v:?}")));
51    let (max, default) = match kind {
52        Kind::Raw => (MAX_RAW, DEFAULT_RAW),
53        Kind::Rollup => (MAX_ROLLUPS, DEFAULT_ROLLUPS),
54        Kind::Events => (MAX_EVENTS, DEFAULT_EVENTS),
55    };
56    let limit = match query.get("limit") {
57        Some(v) => v.parse::<usize>().map_err(|_| format!("limit is a number, not {v:?}"))?.clamp(1, max),
58        None => default,
59    };
60    let (mut from_ms, mut to_ms) = (num("from_ms").transpose()?.unwrap_or(0), num("to_ms").transpose()?.unwrap_or(u64::MAX));
61    // A day is the UTC day of its file: `2026-11-16`.
62    if let Some(day) = query.get("day") {
63        let start = chrono::NaiveDate::parse_from_str(day, "%Y-%m-%d")
64            .ok()
65            .and_then(|d| d.and_hms_opt(0, 0, 0))
66            .map(|t| t.and_utc().timestamp_millis())
67            .filter(|ms| *ms >= 0)
68            .ok_or_else(|| format!("day is a date like 2026-11-16, not {day:?}"))? as u64;
69        (from_ms, to_ms) = (start, start + DAY_MS - 1);
70    }
71    Ok(Ask { kind, from_ms, to_ms, limit })
72}
73
74/// The answer for `ask` read from `dir`: what the record holds, the lines, and `matched`: how many lines the window
75/// holds in all (more than `lines` when the limit cut it).
76pub(crate) fn answer(dir: &std::path::Path, ask: &Ask) -> serde_json::Value {
77    let inventory = record::inventory(dir);
78    match ask.kind {
79        Kind::Raw => {
80            let (matched, lines) = record::read_raw(dir, ask.from_ms, ask.to_ms, ask.limit);
81            json!({ "kind": "raw", "inventory": inventory, "matched": matched, "lines": lines })
82        }
83        Kind::Rollup => {
84            let (matched, lines) = record::read_rollups(dir, ask.from_ms, ask.to_ms, ask.limit);
85            json!({ "kind": "rollup", "inventory": inventory, "matched": matched, "lines": lines })
86        }
87        Kind::Events => {
88            let (matched, lines) = record::read_events(dir, ask.from_ms, ask.to_ms, ask.limit);
89            json!({ "kind": "events", "inventory": inventory, "matched": matched, "lines": lines })
90        }
91    }
92}
93
94pub(crate) async fn handle_record(Query(query): Query<HashMap<String, String>>) -> Response {
95    let ask = match parse_ask(&query) {
96        Ok(ask) => ask,
97        Err(error) => return (axum::http::StatusCode::BAD_REQUEST, axum::Json(json!({ "error": error }))).into_response(),
98    };
99    let Some(dir) = record::default_dir() else {
100        return (axum::http::StatusCode::NOT_FOUND, axum::Json(json!({ "error": "this AgentMux has no data folder" }))).into_response();
101    };
102    match tokio::task::spawn_blocking(move || answer(&dir, &ask)).await {
103        Ok(body) => axum::Json(body).into_response(),
104        Err(e) => (axum::http::StatusCode::INTERNAL_SERVER_ERROR, axum::Json(json!({ "error": format!("reading the record: {e}") }))).into_response(),
105    }
106}
107
108#[cfg(test)]
109mod tests {
110    use super::*;
111
112    fn q(pairs: &[(&str, &str)]) -> HashMap<String, String> {
113        pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()
114    }
115
116    #[test]
117    fn what_is_asked_has_defaults_and_limits() {
118        assert_eq!(parse_ask(&q(&[])).unwrap(), Ask { kind: Kind::Rollup, from_ms: 0, to_ms: u64::MAX, limit: DEFAULT_ROLLUPS });
119        let raw = parse_ask(&q(&[("kind", "raw"), ("limit", "99999"), ("from_ms", "5")])).unwrap();
120        assert_eq!((raw.kind, raw.from_ms, raw.limit), (Kind::Raw, 5, MAX_RAW));
121        let events = parse_ask(&q(&[("kind", "events"), ("limit", "99999")])).unwrap();
122        assert_eq!((events.kind, events.limit), (Kind::Events, MAX_EVENTS));
123        assert_eq!(parse_ask(&q(&[("kind", "events")])).unwrap().limit, DEFAULT_EVENTS);
124        assert_eq!(parse_ask(&q(&[("limit", "0")])).unwrap().limit, 1);
125        assert!(parse_ask(&q(&[("kind", "all")])).unwrap_err().contains("\"events\""));
126        assert!(parse_ask(&q(&[("from_ms", "yesterday")])).unwrap_err().contains("from_ms"));
127        // A day is its UTC day: 2026-11-16 starts at 1_794_787_200_000.
128        let day = parse_ask(&q(&[("day", "2026-11-16")])).unwrap();
129        assert_eq!((day.from_ms, day.to_ms), (1_794_787_200_000, 1_794_787_200_000 + DAY_MS - 1));
130        assert!(parse_ask(&q(&[("day", "16/11")])).unwrap_err().contains("day"));
131    }
132
133    #[test]
134    fn an_empty_record_answers_with_nothing_in_it() {
135        let tmp = tempfile::tempdir().unwrap();
136        let body = answer(&tmp.path().join("none"), &parse_ask(&q(&[])).unwrap());
137        assert_eq!(body["kind"], "rollup");
138        assert_eq!((body["lines"].clone(), body["matched"].clone()), (json!([]), json!(0)));
139        assert_eq!(body["inventory"]["raw_days"], 0);
140    }
141}