agentmux_common/
srv_estart_wait.rs1use std::time::Duration;
12
13use tokio::sync::mpsc;
14use tokio::time::{sleep_until, Instant};
15
16pub const NORMAL_TIMEOUT: Duration = Duration::from_secs(30);
18pub const MIGRATION_TIMEOUT: Duration = Duration::from_secs(1800);
20
21pub enum EstartWait<T> {
23 Ready(Option<T>),
25 Timeout,
26 MigrationFailed(String),
28 NeedsPrepare(String),
30}
31
32pub struct EstartChannels<T> {
34 pub ready: mpsc::Receiver<T>,
35 pub migrating: mpsc::Receiver<()>,
36 pub failed: mpsc::Receiver<String>,
37 pub needs_prepare: Option<mpsc::Receiver<String>>,
38}
39
40async fn recv_prepare(rx: &mut Option<mpsc::Receiver<String>>) -> Option<String> {
41 match rx {
42 Some(rx) => rx.recv().await,
43 None => std::future::pending().await,
44 }
45}
46
47fn prefer_buffered_failure<T>(outcome: EstartWait<T>, failed: &mut mpsc::Receiver<String>) -> EstartWait<T> {
53 match outcome {
54 EstartWait::Ready(None) => match failed.try_recv() {
55 Ok(reason) => EstartWait::MigrationFailed(reason),
56 Err(_) => EstartWait::Ready(None),
57 },
58 other => other,
59 }
60}
61
62pub async fn wait_for_estart<T>(ch: &mut EstartChannels<T>, mut on_extend: impl FnMut()) -> EstartWait<T> {
65 let mut deadline = Instant::now() + NORMAL_TIMEOUT;
66 let sleep = sleep_until(deadline);
67 tokio::pin!(sleep);
68 let outcome = loop {
69 tokio::select! {
70 biased;
75 Some(reason) = ch.failed.recv() => break EstartWait::MigrationFailed(reason),
76 Some(reason) = recv_prepare(&mut ch.needs_prepare) => break EstartWait::NeedsPrepare(reason),
77 result = ch.ready.recv() => break EstartWait::Ready(result),
78 _ = &mut sleep => break EstartWait::Timeout,
79 Some(()) = ch.migrating.recv() => {
80 let new_deadline = Instant::now() + MIGRATION_TIMEOUT;
81 if new_deadline > deadline {
82 deadline = new_deadline;
83 sleep.as_mut().reset(deadline);
84 on_extend();
85 }
86 }
87 }
88 };
89 prefer_buffered_failure(outcome, &mut ch.failed)
90}
91
92#[cfg(test)]
93mod tests {
94 use super::*;
95
96 type Senders<T> = (mpsc::Sender<T>, mpsc::Sender<String>, mpsc::Sender<()>);
97
98 fn channels<T>() -> (EstartChannels<T>, Senders<T>) {
99 let (ready_tx, ready) = mpsc::channel(1);
100 let (migrating_tx, migrating) = mpsc::channel(4);
101 let (failed_tx, failed) = mpsc::channel(1);
102 (EstartChannels { ready, migrating, failed, needs_prepare: None }, (ready_tx, failed_tx, migrating_tx))
103 }
104
105 #[test]
106 fn closed_ready_channel_with_buffered_failure_becomes_migration_failed() {
107 let (tx, mut rx) = mpsc::channel::<String>(1);
108 tx.try_send("migration 0007 failed: disk I/O error".into()).unwrap();
110 drop(tx);
111 match prefer_buffered_failure(EstartWait::<u8>::Ready(None), &mut rx) {
112 EstartWait::MigrationFailed(r) => assert_eq!(r, "migration 0007 failed: disk I/O error"),
113 _ => panic!("buffered failure reason must win over a closed ready channel"),
114 }
115 }
116
117 #[test]
118 fn closed_ready_channel_without_failure_stays_channel_closed() {
119 let (tx, mut rx) = mpsc::channel::<String>(1);
120 drop(tx); assert!(matches!(prefer_buffered_failure(EstartWait::<u8>::Ready(None), &mut rx), EstartWait::Ready(None)));
122 }
123
124 #[test]
125 fn other_outcomes_pass_through_untouched() {
126 let (tx, mut rx) = mpsc::channel::<String>(1);
127 tx.try_send("should not be consumed".into()).unwrap();
128 assert!(matches!(prefer_buffered_failure(EstartWait::<u8>::Timeout, &mut rx), EstartWait::Timeout));
129 assert!(matches!(
130 prefer_buffered_failure(EstartWait::<u8>::MigrationFailed("x".into()), &mut rx),
131 EstartWait::MigrationFailed(_)
132 ));
133 }
134
135 #[tokio::test]
136 async fn a_ready_line_ends_the_wait() {
137 let (mut ch, (ready_tx, _failed_tx, _migrating_tx)) = channels::<u8>();
138 ready_tx.send(7).await.unwrap();
139 assert!(matches!(wait_for_estart(&mut ch, || {}).await, EstartWait::Ready(Some(7))));
140 }
141
142 #[tokio::test]
143 async fn a_failure_then_a_closed_reader_is_the_failure() {
144 let (mut ch, (ready_tx, failed_tx, migrating_tx)) = channels::<u8>();
145 failed_tx.send("disk full".into()).await.unwrap();
146 drop((ready_tx, failed_tx, migrating_tx));
147 match wait_for_estart(&mut ch, || {}).await {
148 EstartWait::MigrationFailed(r) => assert_eq!(r, "disk full"),
149 _ => panic!("the reason must win over the closed channels"),
150 }
151 }
152
153 #[tokio::test]
154 async fn a_closed_reader_with_nothing_buffered_is_a_closed_channel() {
155 let (mut ch, senders) = channels::<u8>();
156 drop(senders);
157 assert!(matches!(wait_for_estart(&mut ch, || {}).await, EstartWait::Ready(None)));
158 }
159
160 #[tokio::test]
161 async fn a_prepare_line_ends_the_wait_when_the_caller_listens_for_it() {
162 let (mut ch, _senders) = channels::<u8>();
163 let (prepare_tx, prepare_rx) = mpsc::channel(1);
164 ch.needs_prepare = Some(prepare_rx);
165 prepare_tx.send("old schema".into()).await.unwrap();
166 match wait_for_estart(&mut ch, || {}).await {
167 EstartWait::NeedsPrepare(r) => assert_eq!(r, "old schema"),
168 _ => panic!("expected NeedsPrepare"),
169 }
170 }
171
172 #[tokio::test]
173 async fn a_migrating_line_extends_the_deadline_only_once_per_push() {
174 let (mut ch, (ready_tx, _failed_tx, migrating_tx)) = channels::<u8>();
175 migrating_tx.send(()).await.unwrap();
176 ready_tx.send(1).await.unwrap();
177 let mut extended = 0;
178 let outcome = wait_for_estart(&mut ch, || extended += 1).await;
180 assert!(matches!(outcome, EstartWait::Ready(Some(1))));
181 assert!(extended <= 1);
182 }
183}