Skip to main content

agentmux_srv/server/
muxspect_memory.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! srv's own memory report: logged every few minutes, and served to `muxspect memory`.
5//! What is read, and why those three things side by side: `backend::mem_census`.
6
7use axum::extract::State;
8use axum::http::StatusCode;
9use axum::response::{IntoResponse, Json};
10use serde_json::json;
11
12use crate::backend::mem_census;
13
14use super::AppState;
15
16/// One reading, on the blocking pool: the census walks every counted structure under its own lock.
17async fn reading(state: &AppState) -> Result<mem_census::MemReport, tokio::task::JoinError> {
18    let (broker, dock) = (state.broker.clone(), state.dock_snapshots.clone());
19    tokio::task::spawn_blocking(move || mem_census::collect(&broker, &dock)).await
20}
21
22/// `GET /api/v1/muxspect/memory`: what the operating system has given srv, what srv has allocated
23/// and not freed, and the count and estimated bytes of each structure that grows with use. The same
24/// reading the `srv memory` log line carries, with every structure listed. Read-only.
25pub async fn handle_muxspect_memory(State(state): State<AppState>) -> impl IntoResponse {
26    match reading(&state).await {
27        Ok(report) => Json(report).into_response(),
28        Err(e) => {
29            (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": format!("the memory census did not finish: {e}") }))).into_response()
30        }
31    }
32}
33
34/// Log a reading a minute after start, then one every five minutes for as long as srv runs.
35pub fn spawn_reporter(state: AppState) {
36    tokio::spawn(async move {
37        tokio::time::sleep(mem_census::FIRST_REPORT_AFTER).await;
38        loop {
39            match reading(&state).await {
40                Ok(report) => mem_census::log(&report),
41                Err(e) => tracing::warn!(target: "srv_mem", error = %e, "srv memory: the census did not finish"),
42            }
43            tokio::time::sleep(mem_census::REPORT_EVERY).await;
44        }
45    });
46}