agentmux_srv/server/service/
stop_requests.rs1use std::collections::{HashMap, VecDeque};
9use std::sync::{LazyLock, Mutex};
10
11use crate::backend::obj::Block;
12use crate::backend::service::WebReturnType;
13use crate::server::AppState;
14use agentmux_common::time::now_ms;
15
16const WINDOW_MS: i64 = 60_000;
18const AGENT_OPENS: usize = 10;
19
20#[derive(Default)]
22struct Limiter(Mutex<HashMap<String, VecDeque<i64>>>);
23
24impl Limiter {
25 fn room(&self, key: &str, limit: usize, now: i64) -> Result<(), i64> {
27 let mut map = self.0.lock().unwrap_or_else(|e| e.into_inner());
28 Self::forget_old(&mut map, now);
29 match map.get(key) {
30 Some(opened) if opened.len() >= limit => Err(WINDOW_MS - (now - opened[0])),
31 _ => Ok(()),
32 }
33 }
34
35 fn charge(&self, key: &str, now: i64) {
37 let mut map = self.0.lock().unwrap_or_else(|e| e.into_inner());
38 Self::forget_old(&mut map, now);
39 map.entry(key.to_string()).or_default().push_back(now);
40 }
41
42 fn forget_old(map: &mut HashMap<String, VecDeque<i64>>, now: i64) {
43 map.retain(|_, opened| {
44 while opened.front().is_some_and(|t| now - t >= WINDOW_MS) {
45 opened.pop_front();
46 }
47 !opened.is_empty()
48 });
49 }
50}
51
52static LIMITER: LazyLock<Limiter> = LazyLock::new(Default::default);
53
54fn refused(text: String) -> WebReturnType {
55 WebReturnType::error(text)
56}
57
58fn agent_of(state: &AppState, block_id: &str) -> Option<String> {
60 let from_meta = || {
61 let block = state.mstore.get::<Block>(block_id).ok().flatten()?;
62 Some(crate::backend::obj::meta_get_string(&block.meta, "agentId", "")).filter(|id| !id.is_empty())
63 };
64 state.reactive_handler.get_agent_by_block(block_id).map(|a| a.agent_id).or_else(from_meta)
65}
66
67pub(super) fn own_pane_only(state: &AppState, block_id: &str, caller_uid: Option<&str>, method: &str) -> Result<(), WebReturnType> {
70 let Some(uid) = caller_uid else { return Ok(()) };
71 let Some(slug) = state.mstore.agent_names_by_id(uid).ok().flatten().map(|row| row.slug).filter(|slug| !slug.is_empty()) else {
72 return Err(refused(format!("{method}: FORBIDDEN: the token's agent is unknown")));
73 };
74 if agent_of(state, block_id).is_some_and(|owner| owner == uid || owner == slug) {
75 return Ok(());
76 }
77 Err(refused(format!("{method}: FORBIDDEN: an agent may read only its own pane; to see another agent's work use Agents list")))
78}
79
80pub(super) fn ask_the_person_to_stop(state: &AppState, block_id: &str, caller_uid: Option<&str>, method: &str) -> Result<WebReturnType, WebReturnType> {
83 let Some(uid) = caller_uid else {
84 return Err(refused(format!(
85 "{method}: FORBIDDEN: the request must carry an agent's token (AGENTMUX_AGENT_TOKEN), as Stop agents does; or the person stops the agent from the window"
86 )));
87 };
88 if crate::backend::blockcontroller::get_controller(block_id).is_none() {
89 return Err(refused(format!("{method}: no running agent in block {block_id}")));
90 }
91 if !crate::sagas::orphan_reaper::is_agent_block(state, block_id) {
92 return Err(refused(format!("{method}: not an agent pane: close it with Stop with action \"pane\"")));
93 }
94 let Some(by) = state.mstore.agent_names_by_id(uid).ok().flatten().map(|row| row.slug).filter(|slug| !slug.is_empty()) else {
95 return Err(refused(format!("{method}: FORBIDDEN: the token's agent is unknown")));
96 };
97 if agent_of(state, block_id).is_some_and(|target| target == uid || target == by) {
98 return Err(refused(format!("{method}: your own block: to end your own session use Stop with action \"self\"")));
99 }
100 if crate::sagas::pending_shutdown::active_for(block_id).is_none() {
103 if let Err(wait_ms) = LIMITER.room(uid, AGENT_OPENS, now_ms()) {
104 return Err(refused(format!(
105 "{method}: RATE_LIMITED: {by} has opened {AGENT_OPENS} stop countdowns in the last minute; wait {} s, or leave it to the person",
106 wait_ms / 1000 + 1
107 )));
108 }
109 }
110 let action = crate::sagas::pending_shutdown::Action::CloseTab { detail: format!("asked by {by} ({method}, on the service route)") };
111 let pending = crate::sagas::pending_shutdown::request(state, block_id, &by, "Service", "", action);
112 if !pending.joined {
113 LIMITER.charge(uid, now_ms());
114 }
115 crate::sagas::pending_shutdown::tell_when_settled(state, &pending.request_id, &by, method);
118 let note = answer_note(block_id, pending.joined);
119 Ok(WebReturnType::success(serde_json::json!({ "status": "pending_user_override", "note": note, "pending": pending })))
120}
121
122fn answer_note(block_id: &str, joined: bool) -> String {
124 let open = if joined { "A countdown was already open for the agent in this block, and this request joined it" } else { "A countdown is open for the agent in this block" };
125 format!(
126 "{open} ({block_id}): nothing is stopped yet, and the person can keep it running. See Agents list for the outcome; if the person keeps it running or the close fails, one [AgentMux] note tells you."
127 )
128}
129
130#[cfg(test)]
131mod tests {
132 use super::*;
133
134 #[test]
135 fn a_caller_may_open_its_limit_in_a_minute_and_a_slot_frees_as_the_oldest_leaves() {
136 let limiter = Limiter::default();
137 for t in 0..3 {
138 assert!(limiter.room("a", 3, t * 1_000).is_ok());
139 limiter.charge("a", t * 1_000);
140 }
141 assert_eq!(limiter.room("a", 3, 10_000), Err(WINDOW_MS - 10_000), "the fourth waits for the first to leave the minute");
142 assert!(limiter.room("b", 3, 10_000).is_ok(), "another caller has its own count");
143 assert!(limiter.room("a", 3, WINDOW_MS).is_ok(), "the first has left the window");
144 limiter.charge("a", WINDOW_MS);
145 assert!(limiter.room("a", 3, WINDOW_MS + 500).is_err(), "and the one that took its place counts");
146 }
147
148 #[test]
149 fn asking_for_room_counts_nothing() {
150 let limiter = Limiter::default();
151 for _ in 0..10 {
152 assert!(limiter.room("a", 1, 0).is_ok());
153 }
154 }
155}