Skip to main content

agentmux_srv_core/muxbus/cloud_subscriber/
session.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What bounds one WebSocket session of the cloud subscriber: how long it may
5//! take to open and how long it may go without a word from the relay. Without
6//! them a socket that went dead (or a handshake that never finished) held the
7//! session open for good while the status said connected.
8
9use std::sync::{Arc, Mutex};
10use std::time::{Duration, Instant};
11
12use std::collections::HashSet;
13
14use super::supervisor::beat;
15use super::{shared_token_now, CLIENT_PING_INTERVAL_SECS};
16use crate::backend::storage::store::Store;
17
18/// The client of the subscriber's REST calls and token refreshes. A connection that
19/// cannot be made in 10 s is a failure to retry, not a wait.
20pub(super) fn http_client() -> reqwest::Client {
21    crate::http_client::client_with(|b| b.user_agent(crate::muxbus::relay::USER_AGENT).connect_timeout(Duration::from_secs(10)))
22}
23
24/// How long a connection may take to open, and how long it may be silent.
25#[derive(Clone, Copy)]
26pub(super) struct SessionLimits {
27    /// The WebSocket handshake.
28    pub(super) connect: Duration,
29    /// Nothing heard from the relay (a pong to our ping counts): the socket is
30    /// closed and made again. The relay answers every ping, so two unanswered
31    /// ones (and a margin, still under the relay's own 10 minute cut) mean the
32    /// connection is dead whatever the OS still says about it.
33    pub(super) silence: Duration,
34    /// How often the silence is checked.
35    pub(super) check_every: Duration,
36}
37
38impl Default for SessionLimits {
39    fn default() -> Self {
40        SessionLimits {
41            connect: Duration::from_secs(30),
42            silence: Duration::from_secs(2 * CLIENT_PING_INTERVAL_SECS + 60),
43            check_every: Duration::from_secs(30),
44        }
45    }
46}
47
48/// Notices a session that stopped hearing from the relay, and stamps the
49/// subscriber's progress while the session waits.
50pub(super) struct Watchdog {
51    last_heard: Instant,
52    silence: Duration,
53    check: tokio::time::Interval,
54}
55
56impl Watchdog {
57    pub(super) async fn new(limits: SessionLimits) -> Self {
58        let mut check = tokio::time::interval(limits.check_every);
59        check.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
60        check.tick().await; // the first tick is immediate: the session just opened
61        Watchdog { last_heard: Instant::now(), silence: limits.silence, check }
62    }
63
64    /// Something came from the relay: a wake, a pong, a close.
65    pub(super) fn heard(&mut self) {
66        self.last_heard = Instant::now();
67    }
68
69    /// Resolves, with why, once the relay has been silent for too long. A session
70    /// stuck in a handler never gets here, and the supervisor sees the missing stamp.
71    pub(super) async fn silent(&mut self) -> String {
72        loop {
73            self.check.tick().await;
74            beat();
75            if self.last_heard.elapsed() > self.silence {
76                return format!("no word from the relay for {}s", self.last_heard.elapsed().as_secs());
77            }
78        }
79    }
80}
81
82/// An agent went away here: let another instance have it, once the release has a fresh token.
83pub(super) fn release_in_background(id: String, base: String, token: String, http: reqwest::Client, mstore: Arc<Store>, agents: Arc<Mutex<HashSet<String>>>) {
84    tokio::spawn(async move {
85        let token = shared_token_now(&mstore, &token).await;
86        // Skip if it was subscribed again meanwhile: its fresh claim must not be released (#3897).
87        let still_gone = || !agents.lock().unwrap().contains(&id);
88        crate::muxbus::wan_lease::release(&base, &id, &token, &http, still_gone).await
89    });
90}