Skip to main content

waratah_storage/
warm_state.rs

1//! Startup cache-warm lifecycle shared by the partition, registry, and
2//! standalone launch paths.
3//!
4//! Warm walks run on detached background threads (fast startup); this type
5//! makes their completion observable so `/health` can gate on it instead of
6//! answering "ok" while the first queries still race the walk. Usage: create
7//! one shared [`WarmState`] per process, [`track`](Self::track) a name before
8//! spawning each walk, and [`complete`](Self::complete) it when the walk
9//! finishes — on success **and** failure (a failed walk must never hold
10//! readiness forever).
11
12use std::sync::{Arc, Mutex};
13use std::time::{Duration, Instant};
14
15/// Longest wait for a warm walk before callers stop gating readiness on it.
16/// Past this the walk is reported stuck (stderr once, plus the health body)
17/// and the server serves without a full warm — correct results, cold blocks.
18pub const WARM_MAX_WAIT: Duration = Duration::from_secs(30);
19
20/// Tracks named cache-warm walks and whether they have all finished.
21#[derive(Debug)]
22pub struct WarmState {
23    inner: Mutex<WarmInner>,
24    max_wait: Duration,
25}
26
27#[derive(Debug)]
28struct WarmInner {
29    /// Walk names still running, in tracking order.
30    pending: Vec<String>,
31    /// When the first walk was tracked (the readiness clock). `None` until
32    /// then: DB-open time before the first `track` must not count against
33    /// the stuck threshold.
34    started: Option<Instant>,
35    /// The stuck warning goes to stderr once, even if health is polled often.
36    warned_stuck: bool,
37}
38
39impl WarmState {
40    /// Shared state with nothing tracked — the create-then-track pattern
41    /// (`track` before spawning each walk). Done from the start, so health
42    /// gates only on walks that actually spawn.
43    pub fn empty() -> Arc<Self> {
44        Self::with_max_wait(Vec::<String>::new(), WARM_MAX_WAIT)
45    }
46
47    /// Shared state tracking `names` (e.g. `"axis-s"`, `"registry"`), with
48    /// the default [`WARM_MAX_WAIT`].
49    pub fn new(names: impl IntoIterator<Item = impl Into<String>>) -> Arc<Self> {
50        Self::with_max_wait(names, WARM_MAX_WAIT)
51    }
52
53    /// [`Self::new`] with an explicit stuck threshold (tests, tuning).
54    pub fn with_max_wait(
55        names: impl IntoIterator<Item = impl Into<String>>,
56        max_wait: Duration,
57    ) -> Arc<Self> {
58        let pending: Vec<String> = names.into_iter().map(Into::into).collect();
59        Arc::new(Self {
60            inner: Mutex::new(WarmInner {
61                // Pre-seeded names (the create-then-walk pattern) start the
62                // clock here; an empty tracker starts it at the first `track`.
63                started: if pending.is_empty() {
64                    None
65                } else {
66                    Some(Instant::now())
67                },
68                pending,
69                warned_stuck: false,
70            }),
71            max_wait,
72        })
73    }
74
75    /// Register a walk before spawning its thread. Readiness gates on every
76    /// tracked name until it completes. The readiness clock starts here — at
77    /// the empty → first-pending transition — so time spent opening the DB
78    /// before this call does not count against [`WARM_MAX_WAIT`].
79    pub fn track(&self, name: impl Into<String>) {
80        let mut inner = self.lock();
81        if inner.pending.is_empty() {
82            inner.started = Some(Instant::now());
83        }
84        inner.pending.push(name.into());
85    }
86
87    /// Mark a walk finished — on success and on failure.
88    pub fn complete(&self, name: &str) {
89        self.lock().pending.retain(|pending| pending != name);
90    }
91
92    /// All walks finished? (An empty tracker — warm disabled — is done.)
93    pub fn is_done(&self) -> bool {
94        self.lock().pending.is_empty()
95    }
96
97    /// Names still walking (for the `/health` body).
98    pub fn pending(&self) -> Vec<String> {
99        self.lock().pending.clone()
100    }
101
102    /// Time since the first walk was tracked (zero before any `track`).
103    pub fn elapsed(&self) -> Duration {
104        let inner = self.lock();
105        inner
106            .started
107            .map(|started| started.elapsed())
108            .unwrap_or_default()
109    }
110
111    /// The stuck report once `elapsed` exceeds the max wait and walks are
112    /// still pending: prints a stderr warning on the first call and returns
113    /// the message (for the health body) on every call while stuck.
114    /// `None` while done or inside the wait window.
115    pub fn stuck_warning(&self) -> Option<String> {
116        let mut inner = self.lock();
117        let started = match inner.started {
118            Some(started) if !inner.pending.is_empty() => started,
119            _ => return None,
120        };
121        if started.elapsed() < self.max_wait {
122            return None;
123        }
124        let message = format!(
125            "cache-warm stuck for {:?}; pending: {:?} — serving without a full warm",
126            started.elapsed(),
127            inner.pending
128        );
129        if !inner.warned_stuck {
130            inner.warned_stuck = true;
131            eprintln!("warning: {message}");
132        }
133        Some(message)
134    }
135
136    fn lock(&self) -> std::sync::MutexGuard<'_, WarmInner> {
137        // A panicking warm thread must not poison readiness for the process.
138        self.inner
139            .lock()
140            .unwrap_or_else(|poisoned| poisoned.into_inner())
141    }
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147
148    #[test]
149    fn track_complete_and_done() {
150        let warm = WarmState::new(["axis-s", "registry"]);
151        assert!(!warm.is_done());
152        assert_eq!(
153            warm.pending(),
154            vec!["axis-s".to_owned(), "registry".to_owned()]
155        );
156        warm.complete("axis-s");
157        assert!(!warm.is_done());
158        warm.complete("registry");
159        assert!(warm.is_done());
160        assert!(warm.pending().is_empty());
161        assert!(warm.stuck_warning().is_none());
162    }
163
164    #[test]
165    fn empty_tracker_is_done_immediately() {
166        // Warm disabled (or memory backend): no walks tracked, health never
167        // gates.
168        let warm = WarmState::empty();
169        assert!(warm.is_done());
170        assert!(warm.pending().is_empty());
171        assert!(warm.stuck_warning().is_none());
172    }
173
174    #[test]
175    fn clock_starts_at_first_track_not_at_construction() {
176        // The launch paths build `empty()` before opening RocksDB; that open
177        // time must not count against WARM_MAX_WAIT (here 10 ms).
178        let warm = WarmState::with_max_wait(Vec::<String>::new(), Duration::from_millis(10));
179        std::thread::sleep(Duration::from_millis(15));
180        // Construction-time delay elapsed, but nothing is pending yet.
181        assert!(warm.stuck_warning().is_none());
182        warm.track("axis-s");
183        // The clock restarted at track: still inside the wait window.
184        assert!(warm.stuck_warning().is_none());
185        std::thread::sleep(Duration::from_millis(15));
186        assert!(warm.stuck_warning().is_some());
187    }
188
189    #[test]
190    fn stuck_warning_fires_past_max_wait_and_clears_on_complete() {
191        let warm = WarmState::with_max_wait(["axis-p"], Duration::from_millis(1));
192        assert!(!warm.is_done());
193        std::thread::sleep(Duration::from_millis(5));
194        // First call past the max wait prints the stderr warning and returns
195        // the message; later calls return it without re-printing.
196        let first = warm.stuck_warning().expect("stuck past max wait");
197        assert!(first.contains("axis-p"));
198        assert!(warm.stuck_warning().is_some());
199        // Completing the walk clears the stuck state.
200        warm.complete("axis-p");
201        assert!(warm.is_done());
202        assert!(warm.stuck_warning().is_none());
203    }
204}