Skip to main content

agentmux_srv/server/
lan_watch.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! One WARN line for an incoming LAN request that is refused, hangs or times out.
5//!
6//! On 2026-11-12 a machine refused or never answered every remote operation from another for 17
7//! hours, and its log had nothing about it: srv logs inbound LAN HTTP at INFO only when a request
8//! is delivered, so the one request that matters, the one that never gets through, left no line.
9//! A middleware on the three routes a LAN peer posts to (`/agentmux/reactive/inject`,
10//! `/agentmux/remote/op`, `/agentmux/reactive/inject-files`) writes the line, and handlers mark
11//! the stage they are at ([`stage`]) where they wait on something, so a hang names what it waits on.
12//!
13//! A line names the route, the peer's address and machine, the agent the request *claims* to come
14//! from (nothing is proven yet at most stages), the stage, how long, and why. Never a request body,
15//! a key or a token. A peer retrying every few seconds writes one line a minute per reason, with
16//! how many it stood for. `App health` carries the counts since start (`lan_refusals`).
17
18use std::collections::HashMap;
19use std::future::Future;
20use std::net::SocketAddr;
21use std::sync::atomic::{AtomicU64, Ordering};
22use std::sync::{Arc, LazyLock, Mutex};
23use std::time::{Duration, Instant};
24
25use axum::body::Body;
26use axum::extract::{ConnectInfo, State};
27use axum::http::Request;
28use axum::middleware::Next;
29use axum::response::Response;
30use serde_json::{json, Value};
31
32use super::AppState;
33
34/// The routes watched, and how long each may go unanswered before a line says so. A file transfer
35/// streams for as long as its files take, so its wait is far longer than a jekt's.
36const WATCHED: [(&str, Duration); 3] = [
37    ("/agentmux/reactive/inject", Duration::from_secs(5)),
38    ("/agentmux/remote/op", Duration::from_secs(5)),
39    ("/agentmux/reactive/inject-files", Duration::from_secs(60)),
40];
41
42/// A line per source and reason at most this often; the ones left out are counted on the next.
43const LINE_EVERY_SECS: i64 = 60;
44/// Source-and-reason pairs remembered; a peer that makes up reasons cannot grow the table.
45const MAX_KEYS: usize = 256;
46/// The longest answer read to see why it refused: the answers of these routes are a line of JSON.
47const MAX_ANSWER_BYTES: usize = 64 * 1024;
48/// What a reason or stage keeps of the text it was made from.
49const MAX_TEXT_CHARS: usize = 80;
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub(crate) enum Kind {
53    /// Answered, with a refusal.
54    Refused,
55    /// Still being handled after the route's wait; the answer, if any, comes later.
56    Unanswered,
57    /// The handler gave up waiting on something.
58    TimedOut,
59}
60
61impl Kind {
62    fn words(self) -> &'static str {
63        match self {
64            Kind::Refused => "refused",
65            Kind::Unanswered => "still unanswered",
66            Kind::TimedOut => "timed out",
67        }
68    }
69}
70
71/// What one watched request has said about itself so far.
72struct Watch {
73    stage: Mutex<String>,
74    claimed: Mutex<String>,
75    timed_out: Mutex<bool>,
76}
77
78tokio::task_local! {
79    static WATCH: Arc<Watch>;
80}
81
82fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
83    m.lock().unwrap_or_else(|e| e.into_inner())
84}
85
86/// `text` as one short line a log can carry: printable ASCII and a few separators, the rest an
87/// underscore, cut at [`MAX_TEXT_CHARS`].
88fn clean(text: &str) -> String {
89    text.trim()
90        .chars()
91        .take(MAX_TEXT_CHARS)
92        .map(|c| if c.is_ascii_alphanumeric() || " ._-@:/,()'".contains(c) { c } else { '_' })
93        .collect()
94}
95
96/// The request being handled is at `name`: the check or wait it is in (the last one entered, so a refusal
97/// later on can still name an earlier one). Does nothing outside a watched request.
98pub(crate) fn stage(name: &str) {
99    let _ = WATCH.try_with(|w| *lock(&w.stage) = clean(name));
100}
101
102/// The agent the request says it comes from, unproven. Does nothing outside a watched request.
103pub(crate) fn claimed(agent: &str) {
104    let _ = WATCH.try_with(|w| *lock(&w.claimed) = clean(agent));
105}
106
107/// `refusal`, after noting that the handler gave up waiting: the line says timed out, not refused.
108pub(crate) fn timed_out<T>(refusal: T) -> T {
109    let _ = WATCH.try_with(|w| *lock(&w.timed_out) = true);
110    refusal
111}
112
113/// `fut`, run with the request marked as being at `name`: the check or wait it is in.
114pub(crate) async fn during<F: Future>(name: &str, fut: F) -> F::Output {
115    stage(name);
116    fut.await
117}
118
119/// [`during`] "actor check", for a request that claims to come from `agent`.
120pub(crate) async fn acting<F: Future>(agent: Option<&str>, fut: F) -> F::Output {
121    claimed(agent.unwrap_or(""));
122    during("actor check", fut).await
123}
124
125/// `fut`, run in the watched request this is called from, if any: a task spawned for the request
126/// otherwise would lose it and its stages would go unseen.
127pub(crate) fn carry<F: Future>(fut: F) -> impl Future<Output = F::Output> {
128    let current = WATCH.try_with(Arc::clone).ok();
129    async move {
130        match current {
131            Some(watch) => WATCH.scope(watch, fut).await,
132            None => fut.await,
133        }
134    }
135}
136
137// ── Rate limit ───────────────────────────────────────────────────────────────
138
139/// When a line was last written for each source and reason, and how many were left out since.
140#[derive(Default)]
141struct Limits {
142    last: HashMap<String, (i64, u32)>,
143}
144
145impl Limits {
146    /// `Some(n)` when a line is due for `key` at `now`: `n` is this one and every one left out since the
147    /// last. `None` when one was written less than a minute ago (this one is counted for the next).
148    fn due(&mut self, key: &str, now: i64) -> Option<u32> {
149        if let Some((at, left_out)) = self.last.get_mut(key) {
150            if now - *at < LINE_EVERY_SECS {
151                *left_out += 1;
152                return None;
153            }
154            let count = 1 + *left_out;
155            *at = now;
156            *left_out = 0;
157            return Some(count);
158        }
159        if self.last.len() >= MAX_KEYS {
160            // Entries past their minute with nothing left out are the ones to forget.
161            self.last.retain(|_, (at, left_out)| now - *at < LINE_EVERY_SECS || *left_out > 0);
162            if self.last.len() >= MAX_KEYS {
163                return None;
164            }
165        }
166        self.last.insert(key.to_string(), (now, 0));
167        Some(1)
168    }
169}
170
171static LIMITS: LazyLock<Mutex<Limits>> = LazyLock::new(Default::default);
172
173static REFUSED: AtomicU64 = AtomicU64::new(0);
174static UNANSWERED: AtomicU64 = AtomicU64::new(0);
175static TIMED_OUT: AtomicU64 = AtomicU64::new(0);
176
177/// What `App health` reports: requests of each kind since this srv started, counted before the line limit.
178pub(crate) fn counts() -> Value {
179    json!({
180        "refused": REFUSED.load(Ordering::Relaxed),
181        "unanswered": UNANSWERED.load(Ordering::Relaxed),
182        "timed_out": TIMED_OUT.load(Ordering::Relaxed),
183    })
184}
185
186// ── The line ─────────────────────────────────────────────────────────────────
187
188/// Everything one line says.
189struct Event<'a> {
190    kind: Kind,
191    route: &'a str,
192    address: String,
193    machine: String,
194    agent: String,
195    stage: String,
196    reason: String,
197    took_ms: u64,
198}
199
200impl Event<'_> {
201    /// The line, with how many requests it stands for when more than one.
202    fn message(&self, count: u32) -> String {
203        let agent = if self.agent.is_empty() { "no agent named".to_string() } else { format!("claiming to be agent {}", self.agent) };
204        let mut line = format!(
205            "incoming LAN request {}: {} from {} ({}), {}, at stage \"{}\" after {} ms",
206            self.kind.words(),
207            self.route,
208            self.machine,
209            self.address,
210            agent,
211            self.stage,
212            self.took_ms,
213        );
214        if !self.reason.is_empty() {
215            line.push_str(&format!(", reason: {}", self.reason));
216        }
217        if count > 1 {
218            line.push_str(&format!(" ({count} like it in the last minute)"));
219        }
220        line
221    }
222
223    /// What decides whether two events are the same to the limit: one source, one kind, one reason.
224    fn limit_key(&self) -> String {
225        format!("{}|{:?}|{}|{}", self.address, self.kind, self.route, self.reason)
226    }
227}
228
229/// Why `status` and the JSON `body` an answer carried say the request was refused or timed out, if they do.
230/// The routes answer a refusal as 200 with `success: false` (a jekt) or `status: "refused"` (a remote
231/// operation), so the status alone does not tell.
232fn classify(status: u16, body: &[u8]) -> Option<(Kind, String)> {
233    let json: Option<Value> = serde_json::from_slice(body).ok();
234    let text = |key: &str| json.as_ref().and_then(|j| j.get(key)).and_then(Value::as_str).map(clean).filter(|s| !s.is_empty());
235    if status == 408 || status == 504 {
236        return Some((Kind::TimedOut, text("error").unwrap_or_else(|| format!("http {status}"))));
237    }
238    if status >= 400 {
239        return Some((Kind::Refused, text("error").unwrap_or_else(|| format!("http {status}"))));
240    }
241    let json = json.as_ref()?;
242    if json.get("success").and_then(Value::as_bool) == Some(false) {
243        return Some((Kind::Refused, text("error").unwrap_or_else(|| "no reason given".into())));
244    }
245    if json.get("status").and_then(Value::as_str) == Some("refused") {
246        return Some((Kind::Refused, text("refused_reason").unwrap_or_else(|| "no reason given".into())));
247    }
248    None
249}
250
251fn watched(path: &str) -> Option<Duration> {
252    WATCHED.iter().find(|(route, _)| *route == path).map(|(_, wait)| *wait)
253}
254
255/// Count it, and write its line unless one for the same source and reason was written lately.
256fn report(state: &AppState, from: Option<SocketAddr>, route: &str, watch: &Watch, kind: Kind, reason: String, started: Instant) {
257    let counter = match kind {
258        Kind::Refused => &REFUSED,
259        Kind::Unanswered => &UNANSWERED,
260        Kind::TimedOut => &TIMED_OUT,
261    };
262    counter.fetch_add(1, Ordering::Relaxed);
263    let event = Event {
264        kind,
265        route,
266        address: from.map(|a| a.ip().to_string()).unwrap_or_else(|| "unknown address".into()),
267        machine: super::remote_ops::receive::machine_in(&state.lan_discovery.get_all_instances(), from),
268        agent: lock(&watch.claimed).clone(),
269        stage: lock(&watch.stage).clone(),
270        reason,
271        took_ms: started.elapsed().as_millis() as u64,
272    };
273    let Some(count) = lock(&LIMITS).due(&event.limit_key(), agentmux_common::time::now_secs()) else { return };
274    let message = event.message(count);
275    #[cfg(test)]
276    lock(&EMITTED).push(message.clone());
277    tracing::warn!(target: "lan-watch", "{message}");
278}
279
280#[cfg(test)]
281static EMITTED: Mutex<Vec<String>> = Mutex::new(Vec::new());
282
283// ── The middleware ───────────────────────────────────────────────────────────
284
285/// Watches a request to one of [`WATCHED`]: a line when it is refused, unanswered after the route's
286/// wait, or its handler timed out. Outside every other layer, so an authentication refusal is seen too.
287pub(super) async fn watch(State(state): State<AppState>, req: Request<Body>, next: Next) -> Response {
288    let route = req.uri().path().to_string();
289    let Some(hang_after) = watched(&route) else { return next.run(req).await };
290    let from = req.extensions().get::<ConnectInfo<SocketAddr>>().map(|c| c.0);
291    let watch = Arc::new(Watch { stage: Mutex::new("request checks".into()), claimed: Mutex::new(String::new()), timed_out: Mutex::new(false) });
292    let started = Instant::now();
293
294    let handling = WATCH.scope(watch.clone(), next.run(req));
295    tokio::pin!(handling);
296    let response = match tokio::time::timeout(hang_after, &mut handling).await {
297        Ok(response) => response,
298        Err(_) => {
299            report(&state, from, &route, &watch, Kind::Unanswered, "no answer yet".into(), started);
300            handling.await
301        }
302    };
303
304    let (response, verdict) = judge(response).await;
305    let verdict = match (*lock(&watch.timed_out), verdict) {
306        (true, Some((_, reason))) => Some((Kind::TimedOut, reason)),
307        (true, None) => Some((Kind::TimedOut, "the operation did not finish in time".into())),
308        (false, verdict) => verdict,
309    };
310    if let Some((kind, reason)) = verdict {
311        report(&state, from, &route, &watch, kind, reason, started);
312    }
313    response
314}
315
316/// The answer, unchanged, and why it says refused or timed out, if it does. Its body is read when it is a small
317/// JSON one, and put back.
318async fn judge(response: Response) -> (Response, Option<(Kind, String)>) {
319    let (parts, body) = response.into_parts();
320    let status = parts.status.as_u16();
321    // The size is the body's own, not a Content-Length header: hyper adds that after the answer leaves here.
322    let small_json = parts.headers.get(axum::http::header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).is_some_and(|v| v.contains("json"))
323        && axum::body::HttpBody::size_hint(&body).upper().is_some_and(|n| n <= MAX_ANSWER_BYTES as u64);
324    if !small_json {
325        return (Response::from_parts(parts, body), classify(status, &[]));
326    }
327    match axum::body::to_bytes(body, MAX_ANSWER_BYTES).await {
328        Ok(bytes) => {
329            let verdict = classify(status, &bytes);
330            (Response::from_parts(parts, Body::from(bytes)), verdict)
331        }
332        Err(_) => (Response::from_parts(parts, Body::empty()), classify(status, &[])),
333    }
334}
335
336#[cfg(test)]
337mod tests {
338    use super::*;
339
340    fn event(kind: Kind, stage: &str, reason: &str) -> Event<'static> {
341        Event {
342            kind,
343            route: "/agentmux/remote/op",
344            address: "203.0.113.7".into(),
345            machine: "narko".into(),
346            agent: "agenty".into(),
347            stage: stage.into(),
348            reason: reason.into(),
349            took_ms: 5012,
350        }
351    }
352
353    #[test]
354    fn a_refusal_names_the_route_the_source_the_stage_and_the_reason() {
355        let line = event(Kind::Refused, "sender key lookup", "unknown_sender").message(1);
356        assert_eq!(
357            line,
358            "incoming LAN request refused: /agentmux/remote/op from narko (203.0.113.7), claiming to be agent agenty, \
359             at stage \"sender key lookup\" after 5012 ms, reason: unknown_sender"
360        );
361    }
362
363    #[test]
364    fn a_request_still_unanswered_names_the_stage_it_waits_in() {
365        let line = event(Kind::Unanswered, "sender key lookup", "no answer yet").message(1);
366        assert!(line.starts_with("incoming LAN request still unanswered: /agentmux/remote/op from narko"), "{line}");
367        assert!(line.contains("at stage \"sender key lookup\" after 5012 ms, reason: no answer yet"), "{line}");
368    }
369
370    #[test]
371    fn a_timeout_says_so_and_a_request_naming_no_agent_says_that() {
372        let mut e = event(Kind::TimedOut, "operation app.health", "the operation did not finish in time");
373        e.agent.clear();
374        let line = e.message(1);
375        assert!(line.starts_with("incoming LAN request timed out: "), "{line}");
376        assert!(line.contains("no agent named, at stage \"operation app.health\""), "{line}");
377    }
378
379    #[test]
380    fn a_line_standing_for_several_says_how_many() {
381        assert!(event(Kind::Refused, "x", "y").message(14).ends_with("(14 like it in the last minute)"));
382        assert!(!event(Kind::Refused, "x", "y").message(1).contains("like it"));
383    }
384
385    #[test]
386    fn a_peer_retrying_writes_one_line_a_minute_with_the_count() {
387        let mut limits = Limits::default();
388        assert_eq!(limits.due("a|refused", 1000), Some(1));
389        for second in 1..=59 {
390            assert_eq!(limits.due("a|refused", 1000 + second), None, "second {second}");
391        }
392        // The minute is up: the line says it stands for this one and the 59 left out.
393        assert_eq!(limits.due("a|refused", 1060), Some(60));
394        assert_eq!(limits.due("a|refused", 1061), None);
395    }
396
397    #[test]
398    fn each_source_and_reason_has_its_own_line() {
399        let mut limits = Limits::default();
400        assert_eq!(limits.due("a|refused|x", 1000), Some(1));
401        assert_eq!(limits.due("b|refused|x", 1000), Some(1));
402        assert_eq!(limits.due("a|timed_out|x", 1000), Some(1));
403        assert_eq!(limits.due("a|refused|x", 1001), None);
404    }
405
406    #[test]
407    fn a_peer_making_up_reasons_cannot_grow_the_table() {
408        let mut limits = Limits::default();
409        for n in 0..MAX_KEYS {
410            assert_eq!(limits.due(&format!("k{n}"), 1000), Some(1));
411        }
412        assert_eq!(limits.due("one-more", 1001), None, "full, and every entry is within its minute");
413        assert_eq!(limits.last.len(), MAX_KEYS);
414        // A minute later the quiet ones are forgotten and a new one fits.
415        assert_eq!(limits.due("one-more", 1100), Some(1));
416        assert!(limits.last.len() <= MAX_KEYS);
417    }
418
419    #[test]
420    fn a_refused_remote_operation_a_refused_jekt_and_a_bad_status_are_refusals() {
421        assert_eq!(classify(200, br#"{"status":"refused","refused_reason":"unknown_sender","audit_id":""}"#), Some((Kind::Refused, "unknown_sender".into())));
422        assert_eq!(classify(200, br#"{"success":false,"error":"agent not found: x"}"#), Some((Kind::Refused, "agent not found: x".into())));
423        assert_eq!(classify(401, b"unauthorized"), Some((Kind::Refused, "http 401".into())));
424        assert_eq!(classify(503, br#"{"success":false,"error":"busy receiving other files"}"#), Some((Kind::Refused, "busy receiving other files".into())));
425    }
426
427    #[test]
428    fn a_gateway_or_request_timeout_is_a_timeout() {
429        assert_eq!(classify(504, b""), Some((Kind::TimedOut, "http 504".into())));
430        assert_eq!(classify(408, br#"{"error":"request timed out"}"#), Some((Kind::TimedOut, "request timed out".into())));
431    }
432
433    #[test]
434    fn a_delivered_jekt_and_a_done_or_failed_operation_are_not_refusals() {
435        assert_eq!(classify(200, br#"{"success":true,"request_id":"r"}"#), None);
436        assert_eq!(classify(200, br#"{"status":"done","result":{}}"#), None);
437        assert_eq!(classify(200, br#"{"status":"failed","result":{"error":"disk full"}}"#), None);
438        assert_eq!(classify(200, b"not json"), None);
439    }
440
441    #[test]
442    fn a_reason_is_one_short_printable_line() {
443        let reason = clean("bad\nsecret: \u{1b}[31m token=abc\t");
444        assert!(!reason.contains('\n') && !reason.contains('\u{1b}') && !reason.contains('\t'), "{reason:?}");
445        assert_eq!(clean(&"x".repeat(500)).chars().count(), MAX_TEXT_CHARS);
446    }
447
448    #[tokio::test]
449    async fn stages_and_the_claimed_agent_are_kept_for_the_watched_request_only() {
450        stage("outside: nothing to keep"); // no request: a no-op, not a panic
451        let watch = Arc::new(Watch { stage: Mutex::new("request checks".into()), claimed: Mutex::new(String::new()), timed_out: Mutex::new(false) });
452        WATCH
453            .scope(watch.clone(), async {
454                stage("sender key lookup");
455                claimed("Agent Y");
456                assert_eq!(timed_out(7), 7);
457                // A task spawned for the request keeps it only through `carry`.
458                tokio::spawn(carry(async { stage("delivery") })).await.unwrap();
459                tokio::spawn(async { stage("lost") }).await.unwrap();
460            })
461            .await;
462        assert_eq!(*lock(&watch.stage), "delivery");
463        assert_eq!(*lock(&watch.claimed), "Agent Y");
464        assert!(*lock(&watch.timed_out));
465    }
466
467    use axum::routing::post;
468    use tower::ServiceExt;
469
470    async fn answered(body: serde_json::Value, wait: Duration, at: &'static str, agent: &'static str) -> axum::response::Response {
471        let state = crate::server::tests::test_state();
472        let app = axum::Router::new()
473            .route(
474                "/agentmux/remote/op",
475                post(move || async move {
476                    claimed(agent);
477                    stage(at);
478                    tokio::time::sleep(wait).await;
479                    axum::Json(body)
480                }),
481            )
482            .layer(axum::middleware::from_fn_with_state(state, watch));
483        app.oneshot(Request::post("/agentmux/remote/op").body(Body::empty()).unwrap()).await.unwrap()
484    }
485
486    fn emitted_for(agent: &str) -> Vec<String> {
487        lock(&EMITTED).iter().filter(|m| m.contains(&format!("claiming to be agent {agent}"))).cloned().collect()
488    }
489
490    #[tokio::test(start_paused = true)]
491    async fn a_refused_request_leaves_a_line_and_its_answer_still_reaches_the_peer() {
492        let response = answered(json!({"status":"refused","refused_reason":"unverified_sender"}), Duration::ZERO, "sender key lookup", "watch-refused").await;
493        let bytes = axum::body::to_bytes(response.into_body(), 1024).await.unwrap();
494        assert_eq!(serde_json::from_slice::<Value>(&bytes).unwrap()["refused_reason"], "unverified_sender");
495        let lines = emitted_for("watch-refused");
496        assert_eq!(lines.len(), 1, "{lines:?}");
497        assert!(lines[0].contains("refused") && lines[0].contains("at stage \"sender key lookup\"") && lines[0].contains("reason: unverified_sender"), "{lines:?}");
498    }
499
500    #[tokio::test(start_paused = true)]
501    async fn a_request_unanswered_after_its_wait_leaves_a_line_naming_where_it_waits() {
502        let response = answered(json!({"status":"done","result":{}}), Duration::from_secs(8), "sender key lookup", "watch-hangs").await;
503        assert_eq!(response.status(), 200);
504        let lines = emitted_for("watch-hangs");
505        assert_eq!(lines.len(), 1, "an answer that came, and was fine, adds no second line: {lines:?}");
506        assert!(lines[0].contains("still unanswered") && lines[0].contains("at stage \"sender key lookup\""), "{lines:?}");
507    }
508
509    #[tokio::test(start_paused = true)]
510    async fn a_request_that_is_answered_in_time_and_well_leaves_nothing() {
511        let response = answered(json!({"status":"done","result":{}}), Duration::from_secs(1), "operation app.health", "watch-quiet").await;
512        assert_eq!(response.status(), 200);
513        assert!(emitted_for("watch-quiet").is_empty());
514    }
515
516    #[test]
517    fn the_watched_routes_are_the_three_a_peer_posts_to() {
518        assert_eq!(watched("/agentmux/reactive/inject"), Some(Duration::from_secs(5)));
519        assert_eq!(watched("/agentmux/remote/op"), Some(Duration::from_secs(5)));
520        assert_eq!(watched("/agentmux/reactive/inject-files"), Some(Duration::from_secs(60)));
521        assert_eq!(watched("/agentmux/fleet/events"), None, "a stream is open for as long as its reader is");
522    }
523}