Skip to main content

agentmux_srv_core/muxbus/cloud_subscriber/
supervisor.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Keeps the cloud subscriber's loop alive. The loop ends only by a panic, and
5//! it can stall in a call that never returns (on 2026-11-11 two hosts stopped
6//! receiving cloud messages for hours while their status said connected). The
7//! loop stamps [`beat`] every time round; a stamp that stops for [`STALL_AFTER`]
8//! means it is stuck, and either way a new loop is started.
9
10use std::sync::atomic::{AtomicI64, Ordering};
11use std::time::Duration;
12
13use agentmux_common::time::now_ms;
14
15use crate::muxbus::delivery_status;
16
17/// When the loop last made progress (ms since the epoch), stamped by [`beat`].
18pub(super) static LOOP_BEAT: AtomicI64 = AtomicI64::new(0);
19
20/// How often the supervisor looks at the loop.
21pub(super) const WATCH_EVERY: Duration = Duration::from_secs(30);
22/// How long the loop may go without a stamp before it counts as stalled. Every
23/// wait inside it is bounded by a minute or two, so a healthy loop stamps far
24/// more often than this.
25pub(super) const STALL_AFTER: Duration = Duration::from_secs(10 * 60);
26/// The pause before a replacement loop starts.
27const RESTART_DELAY: Duration = Duration::from_secs(5);
28
29/// The loop is making progress.
30pub(super) fn beat() {
31    LOOP_BEAT.store(now_ms(), Ordering::Relaxed);
32}
33
34/// Runs the loop `start` makes, and starts another when it ends, panics, or
35/// stops stamping `beat`. Never returns.
36pub(super) async fn supervise<F>(start: F, beat: &AtomicI64, watch_every: Duration, stall_after: Duration, restart_delay: Duration)
37where
38    F: Fn() -> tokio::task::JoinHandle<()>,
39{
40    loop {
41        beat.store(now_ms(), Ordering::Relaxed);
42        let mut task = start();
43        let why = loop {
44            tokio::select! {
45                done = &mut task => {
46                    break match done {
47                        Ok(()) => "ended".to_string(),
48                        Err(e) if e.is_panic() => "panicked".to_string(),
49                        Err(_) => "was cancelled".to_string(),
50                    };
51                }
52                _ = tokio::time::sleep(watch_every) => {
53                    let quiet_ms = now_ms() - beat.load(Ordering::Relaxed);
54                    if quiet_ms > stall_after.as_millis() as i64 {
55                        task.abort();
56                        let _ = (&mut task).await;
57                        break format!("stalled for {}s", quiet_ms / 1000);
58                    }
59                }
60            }
61        };
62        tracing::error!("cloud_subscriber: its loop {why}; starting a new one");
63        // Not "connected": whatever the dead loop last said no longer holds.
64        delivery_status::set_link(delivery_status::Link::Unreachable(format!("the cloud connection's task {why}")));
65        tokio::time::sleep(restart_delay).await;
66    }
67}
68
69/// [`supervise`] with the production timings.
70pub(super) async fn supervise_loop<F>(start: F)
71where
72    F: Fn() -> tokio::task::JoinHandle<()>,
73{
74    supervise(start, &LOOP_BEAT, WATCH_EVERY, STALL_AFTER, RESTART_DELAY).await
75}