agentmux_srv/server/
browser_capture_shape.rs1use std::collections::HashMap;
20use std::sync::{Mutex, OnceLock};
21use std::time::{Duration, Instant};
22
23const SHAPED: usize = 10;
25const MISSES: usize = 3;
26const WINDOW: Duration = Duration::from_secs(60 * 60);
27
28#[derive(Default)]
29struct Agent {
30 shaped: Vec<Instant>,
31 misses: Vec<Instant>,
32 locked_until: Option<Instant>,
34}
35
36#[derive(Default)]
38pub(super) struct Ledger(HashMap<String, Agent>);
39
40impl Ledger {
41 fn start(&mut self, agent: &str, now: Instant) -> Result<(), String> {
43 let a = self.0.entry(agent.to_string()).or_default();
44 a.shaped.retain(|t| now.duration_since(*t) < WINDOW);
45 a.misses.retain(|t| now.duration_since(*t) < WINDOW);
46 if let Some(until) = a.locked_until.filter(|u| *u > now) {
47 return Err(format!("{}: shapes are refused for you for another {} minutes. Capture without a shape, or ask the person", LOCKED, (until - now).as_secs() / 60 + 1));
48 }
49 a.locked_until = None;
50 if a.shaped.len() >= SHAPED {
51 return Err(format!("{SHAPED} captures with a shape in the last hour: a shape is for choosing between values, not for testing what one says. Capture without a shape, or ask the person"));
52 }
53 a.shaped.push(now);
54 Ok(())
55 }
56
57 fn miss(&mut self, agent: &str, now: Instant) -> bool {
59 let a = self.0.entry(agent.to_string()).or_default();
60 a.misses.retain(|t| now.duration_since(*t) < WINDOW);
61 a.misses.push(now);
62 if a.misses.len() > MISSES {
63 a.locked_until = Some(now + WINDOW);
64 return true;
65 }
66 false
67 }
68}
69
70const LOCKED: &str = "too many captures with a shape did not match";
71
72fn ledger() -> &'static Mutex<Ledger> {
73 static LEDGER: OnceLock<Mutex<Ledger>> = OnceLock::new();
74 LEDGER.get_or_init(Mutex::default)
75}
76
77pub(super) fn start(agent: &str) -> Result<(), String> {
79 ledger().lock().unwrap_or_else(|p| p.into_inner()).start(&agent.to_lowercase(), Instant::now())
80}
81
82pub(super) fn miss(agent: &str) -> &'static str {
85 if ledger().lock().unwrap_or_else(|p| p.into_inner()).miss(&agent.to_lowercase(), Instant::now()) {
86 " That was one miss too many: shapes are refused for you for an hour."
87 } else {
88 ""
89 }
90}
91
92#[cfg(test)]
93#[path = "browser_capture_shape_tests.rs"]
94mod tests;