agentmux_srv/server/app_api/
container_caches.rs1use std::collections::HashSet;
14use std::sync::{Arc, Mutex};
15
16use axum::extract::State;
17use axum::http::StatusCode;
18use axum::response::{IntoResponse, Response};
19use axum::{Extension, Json};
20use serde::Deserialize;
21use serde_json::{json, Value};
22
23use crate::backend::container::{container_name_for_slug, ContainerManager};
24use crate::backend::rpc_types::{AgentContainerCachesResult, ContainerCacheVolume};
25use crate::server::app_api::container_limits::{container_agent, Refusal};
26use crate::server::caller::Caller;
27use crate::server::state::AppState;
28
29pub(crate) const WARN_BYTES: u64 = 20 * 1024 * 1024 * 1024;
31
32static WARNED: Mutex<Option<HashSet<String>>> = Mutex::new(None);
34
35fn first_warning(container_name: &str) -> bool {
37 WARNED.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(HashSet::new).insert(container_name.to_string())
38}
39
40fn forget_warning(container_name: &str) {
42 if let Some(set) = WARNED.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {
43 set.remove(container_name);
44 }
45}
46
47pub(crate) async fn note_if_large(
50 cm: &ContainerManager,
51 container_name: &str,
52 block_id: &str,
53 broker: &Arc<crate::backend::mps::Broker>,
54 filestore: &Arc<crate::backend::storage::filestore::FileStore>,
55 mstore: &Arc<crate::backend::storage::store::Store>,
56) {
57 if WARNED.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|set| set.contains(container_name)) {
58 return;
59 }
60 let Ok(volumes) = cm.cache_volumes(container_name).await else { return };
61 let total: u64 = volumes.iter().map(|v| v.bytes).sum();
62 if total < WARN_BYTES || !first_warning(container_name) {
63 return;
64 }
65 let meta = |key: &str, default: &str| match mstore.get::<crate::backend::obj::Block>(block_id) {
66 Ok(Some(block)) => crate::backend::obj::meta_get_string(&block.meta, key, default),
67 _ => default.to_string(),
68 };
69 let (provider, agent_id, agent_name) = (meta("agentProvider", "claude"), meta("agentId", ""), meta("agentName", ""));
70 tracing::warn!(container = container_name, bytes = total, "a container agent's cache volumes are large");
71 let frame = crate::backend::cli_notice::container_caches_frame(&provider, block_id, (&agent_id, &agent_name), total);
72 crate::backend::cli_notice::append_to_pane(broker, filestore, mstore, block_id, &frame);
73}
74
75fn refuse(status: StatusCode, message: impl Into<String>) -> Refusal {
76 (status, message.into())
77}
78
79fn result_of(volumes: Vec<ContainerCacheVolume>, freed: Option<u64>) -> AgentContainerCachesResult {
80 let total_bytes = volumes.iter().map(|v| v.bytes).sum();
81 AgentContainerCachesResult {
82 volumes,
83 total_bytes,
84 warn_bytes: WARN_BYTES,
85 freed_bytes: freed,
86 }
87}
88
89pub(crate) async fn view(state: &AppState, uid: &str) -> Result<AgentContainerCachesResult, Refusal> {
91 let Some(cm) = state.container_manager.get().await else {
92 return Err(refuse(StatusCode::SERVICE_UNAVAILABLE, "Docker is not available on this machine"));
93 };
94 let volumes = cm.cache_volumes(&container_name_for_slug(uid)).await.map_err(|e| refuse(StatusCode::BAD_GATEWAY, e))?;
95 Ok(result_of(volumes, None))
96}
97
98pub(crate) async fn clear(state: &AppState, uid: &str) -> Result<AgentContainerCachesResult, Refusal> {
100 let Some(cm) = state.container_manager.get().await else {
101 return Err(refuse(StatusCode::SERVICE_UNAVAILABLE, "Docker is not available on this machine"));
102 };
103 let name = container_name_for_slug(uid);
104 let gate = crate::backend::container::drift::update_gate(&name);
106 let _clearing = gate.try_write_owned().map_err(|_| refuse(StatusCode::CONFLICT, "a turn is running; clear the caches when it has finished"))?;
107 let removed = cm.clear_caches(&name).await.map_err(|e| refuse(StatusCode::BAD_GATEWAY, e))?;
108 let freed = removed.iter().map(|v| v.bytes).sum();
109 forget_warning(&name);
110 tracing::info!(container = %name, volumes = removed.len(), freed_bytes = freed, "cleared a container agent's cache volumes");
111 Ok(result_of(Vec::new(), Some(freed)))
112}
113
114#[derive(Debug, Deserialize)]
116pub(crate) struct CachesRequest {
117 agent: String,
118 #[serde(default)]
119 clear: bool,
120}
121
122async fn run(state: &AppState, caller: Option<&Caller>, req: CachesRequest) -> Result<Value, Refusal> {
123 let (uid, def) = container_agent(state, &req.agent)?;
124 if let Some(caller_uid) = caller.and_then(Caller::uid) {
125 let caller_def = state
126 .mstore
127 .agent_def_get(caller_uid)
128 .ok()
129 .flatten()
130 .ok_or_else(|| refuse(StatusCode::UNAUTHORIZED, "the agent token names no agent on this machine"))?;
131 if req.clear && caller_def.runtime().is_container() {
132 return Err(refuse(
133 StatusCode::FORBIDDEN,
134 "CONTAINER_AGENT: a container agent cannot clear a container's caches, its own included: it is the container \
135 being removed. Ask a host agent, your steward or the operator to clear them",
136 ));
137 }
138 }
139 let caches = if req.clear { clear(state, &uid).await? } else { view(state, &uid).await? };
140 Ok(json!({
141 "agent": def.name,
142 "caches": caches,
143 "note": "bytes are what Docker reports for each volume; total_bytes above warn_bytes is a lot. With clear, the container is \
144 removed with the volumes and starts again at the agent's next message, filling them again (the first build is cold)",
145 }))
146}
147
148pub(crate) async fn handle_container_caches(
149 State(state): State<AppState>,
150 caller: Option<Extension<Caller>>,
151 Json(req): Json<CachesRequest>,
152) -> Response {
153 let caller = caller.map(|Extension(c)| c);
154 match run(&state, caller.as_ref(), req).await {
155 Ok(body) => Json(body).into_response(),
156 Err((status, message)) => (status, Json(json!({ "error": message }))).into_response(),
157 }
158}
159
160#[cfg(test)]
161mod tests {
162 use super::*;
163
164 #[test]
165 fn the_answer_totals_the_volumes_and_carries_the_warning_level() {
166 let r = result_of(vec![ContainerCacheVolume { name: "a".into(), bytes: 3 }, ContainerCacheVolume { name: "b".into(), bytes: 4 }], None);
167 assert_eq!((r.total_bytes, r.warn_bytes, r.freed_bytes), (7, WARN_BYTES, None));
168 assert_eq!(r.volumes.len(), 2);
169 let cleared = result_of(Vec::new(), Some(7));
170 assert_eq!((cleared.total_bytes, cleared.freed_bytes), (0, Some(7)));
171 }
172
173 #[test]
174 fn an_agent_is_told_once_until_its_caches_are_cleared() {
175 assert!(first_warning("agentmux-test-warned"));
176 assert!(!first_warning("agentmux-test-warned"), "the second start says nothing");
177 forget_warning("agentmux-test-warned");
178 assert!(first_warning("agentmux-test-warned"), "after a clear it may say so again");
179 forget_warning("agentmux-test-warned");
180 }
181}