agentmux_srv_core/backend/container_status/
run.rs1use 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#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct Probe {
20 pub available: bool,
21 pub runtime: Option<String>,
22 pub detail: Option<String>,
23}
24
25pub trait Source: Send + Sync + 'static {
27 fn ping(&self) -> impl Future<Output = Probe> + Send;
29 fn list(&self) -> impl Future<Output = Result<Vec<Listed>, String>> + Send;
31 fn events(&self) -> impl Future<Output = Result<BoxStream<'static, Result<DockerEvent, String>>, String>> + Send;
33}
34
35#[derive(Debug, Clone, Copy)]
37pub struct Timing {
38 pub reconcile: Duration,
40 pub ping: Duration,
42 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#[derive(Debug, PartialEq, Eq)]
54enum End {
55 Unavailable,
57 Broken,
59}
60
61async 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
116pub 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;