Skip to main content

agentmux_srv_core/backend/container_status/
run.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The watcher: follows Docker's event stream, rebuilds from a list now and then because a stream can drop,
5//! and pings the runtime so a runtime that stops answering is said. Docker is behind [`Source`], so a test
6//! drives it with a fake.
7
8use std::future::Future;
9use std::sync::Arc;
10use std::time::Duration;
11
12use futures_util::stream::BoxStream;
13use futures_util::StreamExt as _;
14
15use super::{DockerEvent, Hub, Listed};
16
17/// What a look at the container runtime found.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct Probe {
20    pub available: bool,
21    pub runtime: Option<String>,
22    pub detail: Option<String>,
23}
24
25/// Where the containers are read from.
26pub trait Source: Send + Sync + 'static {
27    /// Looks for the runtime and pings it.
28    fn ping(&self) -> impl Future<Output = Probe> + Send;
29    /// Every agent container Docker has, running or not.
30    fn list(&self) -> impl Future<Output = Result<Vec<Listed>, String>> + Send;
31    /// The events of agent containers, from now.
32    fn events(&self) -> impl Future<Output = Result<BoxStream<'static, Result<DockerEvent, String>>, String>> + Send;
33}
34
35/// How often each thing is done.
36#[derive(Debug, Clone, Copy)]
37pub struct Timing {
38    /// A list that rebuilds what the events built, in case the stream missed one.
39    pub reconcile: Duration,
40    /// A ping of the runtime.
41    pub ping: Duration,
42    /// Waiting before the stream or the runtime is tried again.
43    pub retry: Duration,
44}
45
46impl Default for Timing {
47    fn default() -> Self {
48        Self { reconcile: Duration::from_secs(60), ping: Duration::from_secs(30), retry: Duration::from_secs(5) }
49    }
50}
51
52/// Why a session ended.
53#[derive(Debug, PartialEq, Eq)]
54enum End {
55    /// The runtime does not answer.
56    Unavailable,
57    /// The stream or a list failed.
58    Broken,
59}
60
61/// One connection: look at the runtime, subscribe, list, then follow until something breaks. Subscribing
62/// comes before the list, so a change between the two is not missed.
63async fn session<S: Source>(source: &S, hub: &Hub, timing: &Timing) -> End {
64    let probe = source.ping().await;
65    let available = probe.available;
66    hub.on_runtime(probe);
67    if !available {
68        return End::Unavailable;
69    }
70    let mut events = match source.events().await {
71        Ok(events) => events,
72        Err(error) => {
73            tracing::warn!(%error, "container events: could not subscribe");
74            return End::Broken;
75        }
76    };
77    match source.list().await {
78        Ok(listed) => hub.on_listed(listed),
79        Err(error) => {
80            tracing::warn!(%error, "container list failed");
81            return End::Broken;
82        }
83    }
84    let start = tokio::time::Instant::now();
85    let mut reconcile = tokio::time::interval_at(start + timing.reconcile, timing.reconcile);
86    let mut ping = tokio::time::interval_at(start + timing.ping, timing.ping);
87    loop {
88        tokio::select! {
89            event = events.next() => match event {
90                Some(Ok(event)) => hub.on_event(event),
91                Some(Err(error)) => {
92                    tracing::warn!(%error, "container events: the stream failed");
93                    return End::Broken;
94                }
95                None => return End::Broken,
96            },
97            _ = reconcile.tick() => match source.list().await {
98                Ok(listed) => hub.on_listed(listed),
99                Err(error) => {
100                    tracing::warn!(%error, "container list failed");
101                    return End::Broken;
102                }
103            },
104            _ = ping.tick() => {
105                let probe = source.ping().await;
106                let available = probe.available;
107                hub.on_runtime(probe);
108                if !available {
109                    return End::Unavailable;
110                }
111            }
112        }
113    }
114}
115
116/// Watches for the rest of the process. A machine with no container runtime and no container is looked at
117/// once, then left alone until something wakes the hub (a container agent starting, or a reader of the
118/// route that finds a runtime).
119pub async fn run<S: Source>(source: S, hub: Arc<Hub>, timing: Timing) {
120    loop {
121        match session(&source, &hub, &timing).await {
122            End::Unavailable if hub.is_dormant() => hub.dormant_until_woken().await,
123            End::Unavailable => tokio::time::sleep(timing.ping).await,
124            End::Broken => tokio::time::sleep(timing.retry).await,
125        }
126    }
127}
128
129#[cfg(test)]
130mod tests;