|
| 1 | +//! Per-loop consumer side of the shutdown watch. |
| 2 | +//! |
| 3 | +//! Held by every background loop. Expected usage pattern: |
| 4 | +//! |
| 5 | +//! ```ignore |
| 6 | +//! loop { |
| 7 | +//! tokio::select! { |
| 8 | +//! _ = shutdown.wait_cancelled() => break, |
| 9 | +//! _ = tick.tick() => { /* work */ } |
| 10 | +//! } |
| 11 | +//! } |
| 12 | +//! ``` |
| 13 | +//! |
| 14 | +//! `wait_cancelled` is cancel-safe — dropping the future in a |
| 15 | +//! `select!` losing arm does not miss a subsequent signal |
| 16 | +//! because the underlying `watch::Receiver::changed` is itself |
| 17 | +//! cancel-safe and the state is re-checked on every poll. |
| 18 | +
|
| 19 | +use tokio::sync::watch; |
| 20 | + |
| 21 | +/// Consumer handle for [`super::ShutdownWatch`]. One per |
| 22 | +/// subscribed loop — clone-cheap but there is no reason to |
| 23 | +/// clone: each loop gets its own handle from `subscribe()`. |
| 24 | +#[derive(Debug)] |
| 25 | +pub struct ShutdownReceiver { |
| 26 | + rx: watch::Receiver<bool>, |
| 27 | +} |
| 28 | + |
| 29 | +impl ShutdownReceiver { |
| 30 | + /// Internal constructor used by [`super::ShutdownWatch::subscribe`]. |
| 31 | + /// Not public — the canonical way to obtain a receiver is |
| 32 | + /// through `ShutdownWatch::subscribe` so the subscribe-fresh |
| 33 | + /// guarantee is preserved. |
| 34 | + pub(super) fn from_watch(rx: watch::Receiver<bool>) -> Self { |
| 35 | + Self { rx } |
| 36 | + } |
| 37 | + |
| 38 | + /// Resolves as soon as the watch reports the shutdown flag. |
| 39 | + /// Cancel-safe for use inside `tokio::select!`. |
| 40 | + /// |
| 41 | + /// If the watch has already been signaled before this is |
| 42 | + /// first polled, it returns immediately — the subscribe-fresh |
| 43 | + /// guarantee on `ShutdownWatch` means `*rx.borrow() == true` |
| 44 | + /// on the first check fires without waiting for a future |
| 45 | + /// `changed()` notification. |
| 46 | + pub async fn wait_cancelled(&mut self) { |
| 47 | + // Fast path: already signaled. |
| 48 | + if *self.rx.borrow() { |
| 49 | + return; |
| 50 | + } |
| 51 | + // Slow path: wait for a state change, then re-check. |
| 52 | + // `changed()` can return `Err` if every sender was |
| 53 | + // dropped — treat that as "shutdown is no longer |
| 54 | + // observable", which in practice only happens during |
| 55 | + // destructor races. Returning from the future preserves |
| 56 | + // the "loop exits promptly" contract. |
| 57 | + while self.rx.changed().await.is_ok() { |
| 58 | + if *self.rx.borrow() { |
| 59 | + return; |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + /// Non-blocking check. Useful in the prelude of an expensive |
| 65 | + /// operation — "don't start a compaction if we're already |
| 66 | + /// shutting down". |
| 67 | + pub fn is_cancelled(&self) -> bool { |
| 68 | + *self.rx.borrow() |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +#[cfg(test)] |
| 73 | +mod tests { |
| 74 | + use super::super::ShutdownWatch; |
| 75 | + use std::time::Duration; |
| 76 | + |
| 77 | + #[tokio::test] |
| 78 | + async fn wait_cancelled_returns_on_signal() { |
| 79 | + let watch = ShutdownWatch::new(); |
| 80 | + let mut rx = watch.subscribe(); |
| 81 | + |
| 82 | + let handle = tokio::spawn(async move { |
| 83 | + rx.wait_cancelled().await; |
| 84 | + }); |
| 85 | + |
| 86 | + // Let the task park on wait_cancelled. |
| 87 | + tokio::time::sleep(Duration::from_millis(10)).await; |
| 88 | + assert!(!handle.is_finished()); |
| 89 | + |
| 90 | + watch.signal(); |
| 91 | + tokio::time::timeout(Duration::from_millis(100), handle) |
| 92 | + .await |
| 93 | + .expect("task did not wake after signal") |
| 94 | + .expect("task panicked"); |
| 95 | + } |
| 96 | + |
| 97 | + #[tokio::test] |
| 98 | + async fn wait_cancelled_returns_immediately_if_already_signaled() { |
| 99 | + let watch = ShutdownWatch::new(); |
| 100 | + watch.signal(); |
| 101 | + |
| 102 | + let mut rx = watch.subscribe(); |
| 103 | + tokio::time::timeout(Duration::from_millis(10), rx.wait_cancelled()) |
| 104 | + .await |
| 105 | + .expect("already-signaled receiver did not return immediately"); |
| 106 | + } |
| 107 | + |
| 108 | + #[tokio::test] |
| 109 | + async fn wait_cancelled_survives_select() { |
| 110 | + // Prove the drop-on-losing-arm semantics: a signal that |
| 111 | + // never arrives leaves the select free to resolve the |
| 112 | + // other future. This is the primary usage pattern in |
| 113 | + // real loops. |
| 114 | + let watch = ShutdownWatch::new(); |
| 115 | + let mut rx = watch.subscribe(); |
| 116 | + |
| 117 | + let result = tokio::select! { |
| 118 | + _ = rx.wait_cancelled() => "shutdown", |
| 119 | + _ = tokio::time::sleep(Duration::from_millis(20)) => "tick", |
| 120 | + }; |
| 121 | + assert_eq!(result, "tick"); |
| 122 | + assert!(!rx.is_cancelled()); |
| 123 | + } |
| 124 | + |
| 125 | + #[tokio::test] |
| 126 | + async fn is_cancelled_reflects_state() { |
| 127 | + let watch = ShutdownWatch::new(); |
| 128 | + let rx = watch.subscribe(); |
| 129 | + assert!(!rx.is_cancelled()); |
| 130 | + watch.signal(); |
| 131 | + assert!(rx.is_cancelled()); |
| 132 | + } |
| 133 | +} |
0 commit comments