Skip to main content

agentmux_srv_core/broker/
scheduler.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Generic, single-flight-guarded, proactively-scheduled credential refresh.
5//!
6//! One `RefreshScheduler` instance can manage any number of independently
7//! keyed credentials. It holds no credential state itself — callers supply
8//! `is_fresh`/`refresh` closures that read/write through to the real backing
9//! store (e.g. `Store::muxbus_load`/`muxbus_save`) — the scheduler only owns
10//! refresh *coordination*.
11//!
12//! This closes two related gaps:
13//! 1. **Concurrent-refresh races.** Without a lock, two callers that both
14//!    observe a stale credential at the same time both attempt to refresh it
15//!    independently. For providers that rotate refresh tokens on use, this
16//!    can revoke the entire token family. Claude Code itself has two open
17//!    production issues from exactly this failure mode (concurrent CLI
18//!    sessions racing to refresh a shared credentials file with no lock).
19//!    `ensure_fresh` collapses concurrent callers for the same id onto one
20//!    in-flight refresh.
21//! 2. **Reactive-only refresh.** `run_sweep_loop` proactively walks every
22//!    registered credential on a timer instead of only refreshing when
23//!    something happens to ask for one.
24//!
25//! Coordination state (fresh / refreshing / failed / needs-reauth) is owned
26//! by the pure reducer in `super::state` — this module is a thin async
27//! orchestrator: dispatch a command, execute whatever the returned events
28//! say to do (call `is_fresh()`/`refresh()`), dispatch the result back in.
29//! Same split as every other reducer in this codebase (e.g. `agentmux-cef`'s
30//! host reducer emitting `WindowOpacityApplied`, which its IPC handler applies
31//! after dispatch).
32//!
33//! Preserve-on-failure (never overwrite a valid stored credential with a
34//! failed/partial refresh result) is NOT enforced here — it's the
35//! responsibility of each registered `refresh` closure, since only the
36//! caller knows its own store's write semantics. See `broker::mod` doc.
37
38use std::collections::HashMap;
39use std::future::Future;
40use std::pin::Pin;
41use std::sync::{Arc, Mutex};
42use std::time::Duration;
43
44use tokio::sync::{Mutex as AsyncMutex, Notify};
45
46use super::state::{self, Command, CredentialState, Event, RefreshErrorKind};
47
48pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
49
50struct RegisteredClosures {
51    is_fresh: Box<dyn Fn() -> BoxFuture<'static, bool> + Send + Sync>,
52    refresh: Box<dyn Fn() -> BoxFuture<'static, Result<(), RefreshErrorKind>> + Send + Sync>,
53}
54
55// Bundled behind ONE mutex (not three) so `states`/`generations`/
56// `next_generation` are always read and written atomically — the reducer
57// needs all three together to tell a stale, superseded-registration
58// completion apart from a current one (see `state::update`'s doc comment).
59#[derive(Default)]
60struct ReducerTables {
61    states: HashMap<String, CredentialState>,
62    generations: HashMap<String, u64>,
63    next_generation: u64,
64}
65
66/// How long the single-flight refresh may take at each step before the caller
67/// that runs it reports a failure, and how long the others wait behind it. A
68/// hung request must cost a failed refresh that is retried, never every caller.
69#[derive(Debug, Clone, Copy)]
70pub struct Limits {
71    /// The `is_fresh` closure (a store read).
72    pub check: Duration,
73    /// The `refresh` closure (the request and the save).
74    pub refresh: Duration,
75    /// A caller waiting behind the one in flight. Longer than `check` + `refresh`,
76    /// so a bounded refresher always finishes first.
77    pub wait: Duration,
78}
79
80impl Default for Limits {
81    fn default() -> Self {
82        Limits { check: Duration::from_secs(30), refresh: Duration::from_secs(75), wait: Duration::from_secs(120) }
83    }
84}
85
86/// The caller that owns a credential's in-flight state. Dropped before it has
87/// reported (its future was cancelled), it reports a failure itself, so the
88/// state does not stay `Refreshing` and park every later caller.
89struct Flight<'a> {
90    scheduler: &'a RefreshScheduler,
91    id: &'a str,
92    generation: u64,
93    armed: bool,
94}
95
96impl Flight<'_> {
97    fn report(&self, cmd: Command) {
98        let events = {
99            let mut tables = self.scheduler.tables.lock().unwrap();
100            let ReducerTables { states, generations, next_generation } = &mut *tables;
101            state::update(states, generations, next_generation, cmd)
102        };
103        self.scheduler.trace(&events);
104        self.scheduler.wake(self.id);
105    }
106
107    fn finish(mut self, cmd: Command, failure: Option<String>) -> Result<(), String> {
108        self.armed = false;
109        self.report(cmd);
110        match failure {
111            None => Ok(()),
112            Some(message) => Err(message),
113        }
114    }
115
116    fn fail(self, error: RefreshErrorKind) -> Result<(), String> {
117        let message = match &error {
118            RefreshErrorKind::Transient(m) | RefreshErrorKind::Unreachable(m) | RefreshErrorKind::PermanentAuthFailure(m) => m.clone(),
119        };
120        let cmd = Command::RefreshFailed { id: self.id.to_string(), error, generation: self.generation };
121        self.finish(cmd, Some(message))
122    }
123}
124
125impl Drop for Flight<'_> {
126    fn drop(&mut self) {
127        if self.armed {
128            self.report(Command::RefreshFailed {
129                id: self.id.to_string(),
130                error: RefreshErrorKind::Unreachable("the refresh was cancelled before it finished".to_string()),
131                generation: self.generation,
132            });
133        }
134    }
135}
136
137pub struct RefreshScheduler {
138    limits: Limits,
139    closures: AsyncMutex<HashMap<String, Arc<RegisteredClosures>>>,
140    // Reducer-owned coordination state. std::sync::Mutex, not AsyncMutex —
141    // the reducer never awaits, every hold is sub-millisecond, matching the
142    // discipline every other reducer in this codebase follows.
143    tables: Mutex<ReducerTables>,
144    // Per-id wake signal for concurrent `ensure_fresh` callers waiting on an
145    // in-flight check/refresh (the reducer decides single-flight; this just
146    // wakes waiters once that decision resolves).
147    notifiers: Mutex<HashMap<String, Arc<Notify>>>,
148}
149
150impl Default for RefreshScheduler {
151    fn default() -> Self {
152        Self::new()
153    }
154}
155
156impl RefreshScheduler {
157    pub fn new() -> Self {
158        Self::with_limits(Limits::default())
159    }
160
161    pub fn with_limits(limits: Limits) -> Self {
162        Self {
163            limits,
164            closures: AsyncMutex::new(HashMap::new()),
165            tables: Mutex::new(ReducerTables::default()),
166            notifiers: Mutex::new(HashMap::new()),
167        }
168    }
169
170    /// Register (or replace) a credential for proactive management.
171    /// `is_fresh` must be side-effect-free (may be called on every
172    /// `ensure_fresh`/sweep tick) — async so a caller whose freshness check
173    /// needs a blocking read (e.g. an OS keychain call, which can hang on a
174    /// slow/unresponsive Secret Service D-Bus daemon on headless Linux) can
175    /// route it through `tokio::task::spawn_blocking` instead of stalling
176    /// the tokio worker thread this scheduler's own async tasks run on
177    /// (reagent P1 on #2260). `refresh` performs the actual refresh and is
178    /// responsible for persisting the result itself (and for NOT persisting
179    /// anything on failure) — and for classifying a failure as
180    /// `RefreshErrorKind::Transient` (worth retrying), `::Unreachable` (no
181    /// answer at all; never counts toward needs-reauth) or
182    /// `::PermanentAuthFailure` (the credential itself is rejected; only a
183    /// fresh login can fix it — see that type's own doc comment).
184    pub async fn register(
185        &self,
186        credential_id: impl Into<String>,
187        is_fresh: impl Fn() -> BoxFuture<'static, bool> + Send + Sync + 'static,
188        refresh: impl Fn() -> BoxFuture<'static, Result<(), RefreshErrorKind>> + Send + Sync + 'static,
189    ) {
190        let id: String = credential_id.into();
191        {
192            let mut closures = self.closures.lock().await;
193            closures.insert(
194                id.clone(),
195                Arc::new(RegisteredClosures {
196                    is_fresh: Box::new(is_fresh),
197                    refresh: Box::new(refresh),
198                }),
199            );
200        }
201        {
202            let mut tables = self.tables.lock().unwrap();
203            let ReducerTables { states, generations, next_generation } = &mut *tables;
204            state::update(states, generations, next_generation, Command::Register { id: id.clone() });
205        }
206        self.notifiers
207            .lock()
208            .unwrap()
209            .entry(id.clone())
210            .or_insert_with(|| Arc::new(Notify::new()));
211        // Callers parked behind the state this replaces would otherwise wait for
212        // a completion the new registration discards.
213        self.wake(&id);
214    }
215
216    #[cfg(test)]
217    pub async fn unregister(&self, credential_id: &str) {
218        self.closures.lock().await.remove(credential_id);
219        let events = {
220            let mut tables = self.tables.lock().unwrap();
221            let ReducerTables { states, generations, next_generation } = &mut *tables;
222            state::update(
223                states,
224                generations,
225                next_generation,
226                Command::Unregister { id: credential_id.to_string() },
227            )
228        };
229        self.trace(&events);
230        // A caller elsewhere may be parked on notified().await after seeing
231        // AlreadyInFlight for this id; nothing else will ever wake it once
232        // the entry is gone (reagent re-review on #2275).
233        self.wake(credential_id);
234    }
235
236    /// The credential's current coordination state, if registered. Read by
237    /// `muxbus::stale_sign_in` to surface `NeedsReauth` distinctly from a
238    /// routine in-progress refresh. Not used by `ensure_fresh` itself, which
239    /// always dispatches through the reducer regardless.
240    pub fn state(&self, credential_id: &str) -> Option<CredentialState> {
241        self.tables.lock().unwrap().states.get(credential_id).cloned()
242    }
243
244    /// Ensure `credential_id` is fresh, single-flight-guarded. If another
245    /// caller is already mid-refresh for this id, this waits for that
246    /// attempt to finish, then re-checks freshness rather than starting a
247    /// second refresh. Returns `Err` if the id was never registered.
248    pub async fn ensure_fresh(&self, credential_id: &str) -> Result<(), String> {
249        let id = credential_id.to_string();
250        loop {
251            // Create the Notified future *before* dispatching CheckRequested
252            // (and thus before releasing the states lock that gates whether
253            // we're about to become the AlreadyInFlight waiter). Tokio
254            // guarantees a Notified future observes any notify_waiters()
255            // issued after it is created, even before its first poll — so
256            // creating it here closes the lost-wakeup window where the
257            // in-flight refresh finishes and calls wake() between our
258            // CheckRequested dispatch and a `.notified()` call made only
259            // after we see AlreadyInFlight (reagent P1 on #2275: notify_
260            // waiters() retains no permit for a waiter not yet registered).
261            let notify = self.notifier_for(&id);
262            let notified = notify.notified();
263
264            let events = {
265                let mut tables = self.tables.lock().unwrap();
266                let ReducerTables { states, generations, next_generation } = &mut *tables;
267                state::update(states, generations, next_generation, Command::CheckRequested { id: id.clone() })
268            };
269            match events.as_slice() {
270                [Event::Unregistered { .. }] => {
271                    return Err(format!("no credential registered as '{id}'"));
272                }
273                [Event::AlreadyInFlight { .. }] => {
274                    // The refresh in flight is bounded (`Limits`) and frees its
275                    // state if it is dropped, so this wait ends. The limit is
276                    // the last bound: a waiter must never be parked for good
277                    // (2026-11-11: the refresher hung, and every caller of this
278                    // function on two hosts waited behind it for hours).
279                    if tokio::time::timeout(self.limits.wait, notified).await.is_err() {
280                        return Err(format!(
281                            "another refresh of '{id}' has not finished after {}s",
282                            self.limits.wait.as_secs()
283                        ));
284                    }
285                    continue;
286                }
287                [Event::RunFreshnessCheck { generation, .. }] => return self.lead(&id, *generation).await,
288                other => unreachable!("unexpected reducer events for CheckRequested: {other:?}"),
289            }
290        }
291    }
292
293    /// The caller that got `RunFreshnessCheck`: runs the freshness check and, when the
294    /// credential is stale, the refresh, each within its limit, and reports the outcome.
295    async fn lead(&self, id: &str, generation: u64) -> Result<(), String> {
296        // From here this caller owns the in-flight state. If its future is
297        // dropped before it reports (an HTTP handler whose client left, a
298        // caller's own timeout), the guard reports a failure so the state does
299        // not stay `Refreshing` for good.
300        let mut flight = Flight { scheduler: self, id, generation, armed: true };
301        let Some(closures) = self.closures.lock().await.get(id).cloned() else {
302            // Unregistered concurrently between the dispatch in `ensure_fresh`
303            // and this lookup. Wake any other caller parked on AlreadyInFlight
304            // for this id — this path owns the only Refreshing state that
305            // existed for it, so nothing else will ever notify them (#2275).
306            flight.armed = false;
307            self.wake(id);
308            return Err(format!("no credential registered as '{id}'"));
309        };
310        let is_fresh = match tokio::time::timeout(self.limits.check, (closures.is_fresh)()).await {
311            Ok(fresh) => fresh,
312            Err(_) => {
313                return flight.fail(RefreshErrorKind::Unreachable(format!(
314                    "the credential check took longer than {}s",
315                    self.limits.check.as_secs()
316                )));
317            }
318        };
319        let events = {
320            let mut tables = self.tables.lock().unwrap();
321            let ReducerTables { states, generations, next_generation } = &mut *tables;
322            state::update(states, generations, next_generation, Command::FreshnessChecked { id: id.to_string(), is_fresh, generation })
323        };
324        self.trace(&events);
325        if is_fresh {
326            flight.armed = false;
327            self.wake(id);
328            return Ok(());
329        }
330        // `events` is normally [RunRefresh{..}], but can be empty if this
331        // completion lost a race with a concurrent register()/unregister() —
332        // the reducer discards a stale-epoch result rather than let it clobber
333        // newer state (see state::Event::RunFreshnessCheck's doc comment).
334        // Either way THIS caller still proceeds with its own refresh using its
335        // own already-captured closures; its return value reflects what it
336        // actually observed regardless of whether the broker's shared state
337        // accepted the transition.
338        match tokio::time::timeout(self.limits.refresh, (closures.refresh)()).await {
339            Ok(Ok(())) => flight.finish(Command::RefreshSucceeded { id: id.to_string(), generation }, None),
340            Ok(Err(error)) => flight.fail(error),
341            Err(_) => flight.fail(RefreshErrorKind::Unreachable(format!(
342                "the refresh took longer than {}s",
343                self.limits.refresh.as_secs()
344            ))),
345        }
346    }
347
348    /// Background sweep — checks every registered credential every
349    /// `interval` and proactively refreshes anything stale. Skips entries
350    /// the server refused (`NeedsReauth { rejected: true }`): retrying a
351    /// credential known to need a fresh human login just hammers the backing
352    /// server; `ensure_fresh` called on-demand still re-checks those (see
353    /// `state`'s own doc comment). A credential that reached `NeedsReauth`
354    /// only through failures the server answered (5xx, rate limits) is still
355    /// retried each tick: nothing said it is dead. Spawn once via
356    /// `tokio::spawn`; runs until the process exits.
357    pub async fn run_sweep_loop(self: Arc<Self>, interval: Duration) {
358        let mut tick = tokio::time::interval(interval);
359        tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
360        loop {
361            tick.tick().await;
362            let ids: Vec<String> = {
363                let closures = self.closures.lock().await;
364                closures.keys().cloned().collect()
365            };
366            for id in ids {
367                let refused = matches!(
368                    self.tables.lock().unwrap().states.get(&id),
369                    Some(CredentialState::NeedsReauth { rejected: true, .. })
370                );
371                if refused {
372                    continue;
373                }
374                if let Err(e) = self.ensure_fresh(&id).await {
375                    tracing::warn!(credential_id = %id, error = %e, "broker: proactive refresh failed");
376                }
377            }
378        }
379    }
380
381    fn notifier_for(&self, id: &str) -> Arc<Notify> {
382        self.notifiers
383            .lock()
384            .unwrap()
385            .entry(id.to_string())
386            .or_insert_with(|| Arc::new(Notify::new()))
387            .clone()
388    }
389
390    fn wake(&self, id: &str) {
391        if let Some(n) = self.notifiers.lock().unwrap().get(id) {
392            n.notify_waiters();
393        }
394    }
395
396    /// Map diagnostics-only reducer events to `tracing` — `auth.broker.*`
397    /// message prefixes land in `muxlog auth`'s existing filter regex
398    /// (`\bauth\.\w+|...`) with zero changes needed there. Control-flow
399    /// events (`RunFreshnessCheck`/`RunRefresh`/`AlreadyInFlight`/
400    /// `Unregistered`) are acted on directly by callers and not
401    /// double-logged here — every `ensure_fresh` call would otherwise emit
402    /// noise even when nothing changed.
403    fn trace(&self, events: &[Event]) {
404        for event in events {
405            match event {
406                Event::BecameFresh { id } => {
407                    tracing::info!(target: "identity", credential_id = %id, "auth.broker.fresh: credential is fresh");
408                }
409                Event::BecameFailed {
410                    id,
411                    consecutive_failures,
412                    error,
413                } => {
414                    tracing::warn!(
415                        target: "identity",
416                        credential_id = %id,
417                        consecutive_failures,
418                        error = %error,
419                        "auth.broker.failed: refresh attempt failed, will retry"
420                    );
421                }
422                Event::BecameUnreachable { id, error } => {
423                    tracing::warn!(
424                        target: "identity",
425                        credential_id = %id,
426                        error = %error,
427                        "auth.broker.unreachable: couldn't reach the server to refresh; offline, will keep retrying"
428                    );
429                }
430                Event::BecameNeedsReauth { id, reason, rejected: true } => {
431                    tracing::warn!(
432                        target: "identity",
433                        credential_id = %id,
434                        reason = %reason,
435                        "auth.broker.needs_reauth: the server refused the credential; it needs a fresh login"
436                    );
437                }
438                Event::BecameNeedsReauth { id, reason, rejected: false } => {
439                    tracing::warn!(
440                        target: "identity",
441                        credential_id = %id,
442                        reason = %reason,
443                        "auth.broker.stalled: refreshes keep failing; retrying on each sweep"
444                    );
445                }
446                Event::RunFreshnessCheck { .. }
447                | Event::RunRefresh { .. }
448                | Event::AlreadyInFlight { .. }
449                | Event::Unregistered { .. } => {}
450            }
451        }
452    }
453}
454
455#[cfg(test)]
456mod tests {
457    use super::*;
458    use std::sync::atomic::{AtomicUsize, Ordering};
459
460    #[tokio::test]
461    async fn concurrent_callers_collapse_onto_one_refresh() {
462        let scheduler = Arc::new(RefreshScheduler::new());
463        let refresh_calls = Arc::new(AtomicUsize::new(0));
464        let fresh_after_refresh = Arc::new(std::sync::atomic::AtomicBool::new(false));
465
466        let calls = refresh_calls.clone();
467        let fresh_flag = fresh_after_refresh.clone();
468        let fresh_flag_check = fresh_after_refresh.clone();
469        scheduler
470            .register(
471                "test:cred",
472                move || {
473                    let fresh = fresh_flag_check.load(Ordering::SeqCst);
474                    Box::pin(async move { fresh })
475                },
476                move || {
477                    let calls = calls.clone();
478                    let fresh_flag = fresh_flag.clone();
479                    Box::pin(async move {
480                        // Simulate real refresh latency so concurrent callers
481                        // actually overlap instead of serializing trivially.
482                        tokio::time::sleep(Duration::from_millis(50)).await;
483                        calls.fetch_add(1, Ordering::SeqCst);
484                        fresh_flag.store(true, Ordering::SeqCst);
485                        Ok(())
486                    })
487                },
488            )
489            .await;
490
491        let mut handles = Vec::new();
492        for _ in 0..10 {
493            let scheduler = scheduler.clone();
494            handles.push(tokio::spawn(async move {
495                scheduler.ensure_fresh("test:cred").await
496            }));
497        }
498        for h in handles {
499            h.await.unwrap().unwrap();
500        }
501
502        assert_eq!(
503            refresh_calls.load(Ordering::SeqCst),
504            1,
505            "10 concurrent callers for the same credential must collapse onto exactly one refresh"
506        );
507        assert_eq!(scheduler.state("test:cred"), Some(CredentialState::Fresh));
508    }
509
510    #[tokio::test]
511    async fn already_fresh_never_calls_refresh() {
512        let scheduler = RefreshScheduler::new();
513        let refresh_calls = Arc::new(AtomicUsize::new(0));
514        let calls = refresh_calls.clone();
515        scheduler
516            .register(
517                "test:cred",
518                || Box::pin(async { true }),
519                move || {
520                    let calls = calls.clone();
521                    Box::pin(async move {
522                        calls.fetch_add(1, Ordering::SeqCst);
523                        Ok(())
524                    })
525                },
526            )
527            .await;
528
529        scheduler.ensure_fresh("test:cred").await.unwrap();
530        scheduler.ensure_fresh("test:cred").await.unwrap();
531        assert_eq!(refresh_calls.load(Ordering::SeqCst), 0);
532    }
533
534    #[tokio::test]
535    async fn a_failed_refresh_does_not_mark_the_credential_fresh() {
536        let scheduler = RefreshScheduler::new();
537        scheduler
538            .register(
539                "test:cred",
540                || Box::pin(async { false }), // never becomes fresh in this test — refresh always fails
541                || {
542                    Box::pin(async {
543                        Err(RefreshErrorKind::Transient(
544                            "simulated refresh failure".to_string(),
545                        ))
546                    })
547                },
548            )
549            .await;
550
551        let result = scheduler.ensure_fresh("test:cred").await;
552        assert!(result.is_err());
553        // A second call must attempt the refresh again (not treat the
554        // failed attempt as having succeeded).
555        let result2 = scheduler.ensure_fresh("test:cred").await;
556        assert!(result2.is_err());
557        assert!(matches!(
558            scheduler.state("test:cred"),
559            Some(CredentialState::Failed { consecutive_failures: 2, .. })
560        ));
561    }
562
563    #[tokio::test]
564    async fn unregistered_credential_errors_without_panicking() {
565        let scheduler = RefreshScheduler::new();
566        let result = scheduler.ensure_fresh("nope").await;
567        assert!(result.is_err());
568    }
569
570    #[tokio::test]
571    async fn permanent_auth_failure_stops_the_sweep_loop_retrying_but_ensure_fresh_still_rechecks() {
572        let scheduler = Arc::new(RefreshScheduler::new());
573        let refresh_calls = Arc::new(AtomicUsize::new(0));
574        let calls = refresh_calls.clone();
575        scheduler
576            .register(
577                "test:cred",
578                || Box::pin(async { false }),
579                move || {
580                    let calls = calls.clone();
581                    Box::pin(async move {
582                        calls.fetch_add(1, Ordering::SeqCst);
583                        Err(RefreshErrorKind::PermanentAuthFailure("invalid_grant".into()))
584                    })
585                },
586            )
587            .await;
588
589        assert!(scheduler.ensure_fresh("test:cred").await.is_err());
590        assert!(matches!(
591            scheduler.state("test:cred"),
592            Some(CredentialState::NeedsReauth { .. })
593        ));
594
595        // An on-demand ensure_fresh call still re-attempts (a human may
596        // have logged in again out-of-band) — this is call #2.
597        assert!(scheduler.ensure_fresh("test:cred").await.is_err());
598        assert_eq!(refresh_calls.load(Ordering::SeqCst), 2);
599    }
600
601    #[tokio::test]
602    async fn re_registering_a_credential_mid_refresh_does_not_orphan_a_waiting_second_caller() {
603        // Pre-refactor latent race: register() on an already-registered id
604        // replaced the Entry (including its per-id lock), so a SECOND
605        // caller already blocked waiting on the OLD entry's lock waited
606        // forever — the replacement entry's lock was a different object
607        // nothing would ever signal for that waiter. Here, single-flight is
608        // reducer-state-driven and waiting goes through a per-id Notify
609        // that `register()` never replaces (only ensures exists), so a
610        // second caller that observed AlreadyInFlight is woken regardless
611        // of a concurrent re-register.
612        let scheduler = Arc::new(RefreshScheduler::new());
613        let gate = Arc::new(tokio::sync::Notify::new());
614        let gate_wait = gate.clone();
615        scheduler
616            .register(
617                "test:cred",
618                || Box::pin(async { false }),
619                move || {
620                    let gate_wait = gate_wait.clone();
621                    Box::pin(async move {
622                        gate_wait.notified().await;
623                        Ok(())
624                    })
625                },
626            )
627            .await;
628
629        let s1 = scheduler.clone();
630        let first = tokio::spawn(async move { s1.ensure_fresh("test:cred").await });
631        // Give the first call time to reach the gated refresh closure and
632        // land the credential in `Refreshing`.
633        tokio::time::sleep(Duration::from_millis(20)).await;
634        assert_eq!(
635            scheduler.state("test:cred"),
636            Some(CredentialState::Refreshing { prior_failures: 0, prior_reauth: None, offline: false })
637        );
638
639        // A second caller now dispatches while still Refreshing — gets
640        // AlreadyInFlight and waits on the id's Notify.
641        let s2 = scheduler.clone();
642        let second = tokio::spawn(async move { s2.ensure_fresh("test:cred").await });
643        tokio::time::sleep(Duration::from_millis(20)).await;
644        assert!(!second.is_finished(), "second caller must be waiting, not returned yet");
645
646        // Re-register while BOTH the first call is gated inside `refresh`
647        // AND the second call is waiting on AlreadyInFlight.
648        scheduler
649            .register("test:cred", || Box::pin(async { true }), || Box::pin(async { Ok(()) }))
650            .await;
651
652        gate.notify_waiters();
653        let first_result = tokio::time::timeout(Duration::from_secs(2), first)
654            .await
655            .expect("first caller must not hang after a concurrent re-register")
656            .unwrap();
657        assert!(first_result.is_ok());
658        let second_result = tokio::time::timeout(Duration::from_secs(2), second)
659            .await
660            .expect("second (waiting) caller must not be orphaned by a concurrent re-register")
661            .unwrap();
662        assert!(second_result.is_ok());
663    }
664
665    #[tokio::test]
666    async fn unregistering_a_credential_mid_refresh_wakes_a_waiting_second_caller() {
667        // reagent re-review on #2275: unregister() dispatched
668        // Command::Unregister without ever calling wake(), so a second
669        // caller already parked on AlreadyInFlight's notified().await for
670        // this id would hang forever once the entry was gone — nothing else
671        // was ever going to notify it.
672        let scheduler = Arc::new(RefreshScheduler::new());
673        let gate = Arc::new(tokio::sync::Notify::new());
674        let gate_wait = gate.clone();
675        scheduler
676            .register(
677                "test:cred",
678                || Box::pin(async { false }),
679                move || {
680                    let gate_wait = gate_wait.clone();
681                    Box::pin(async move {
682                        gate_wait.notified().await;
683                        Ok(())
684                    })
685                },
686            )
687            .await;
688
689        let s1 = scheduler.clone();
690        let first = tokio::spawn(async move { s1.ensure_fresh("test:cred").await });
691        tokio::time::sleep(Duration::from_millis(20)).await;
692        assert_eq!(
693            scheduler.state("test:cred"),
694            Some(CredentialState::Refreshing { prior_failures: 0, prior_reauth: None, offline: false })
695        );
696
697        let s2 = scheduler.clone();
698        let second = tokio::spawn(async move { s2.ensure_fresh("test:cred").await });
699        tokio::time::sleep(Duration::from_millis(20)).await;
700        assert!(!second.is_finished(), "second caller must be waiting, not returned yet");
701
702        // Unregister while BOTH the first call is gated inside `refresh` AND
703        // the second call is waiting on AlreadyInFlight.
704        scheduler.unregister("test:cred").await;
705
706        let second_result = tokio::time::timeout(Duration::from_secs(2), second)
707            .await
708            .expect("second (waiting) caller must not hang after a concurrent unregister")
709            .unwrap();
710        assert!(
711            second_result.is_err(),
712            "credential is gone — the woken caller should see it as unregistered"
713        );
714
715        // Release the gate so the orphaned first call's own refresh
716        // resolves and its spawned task doesn't leak past the test.
717        gate.notify_waiters();
718        let _ = tokio::time::timeout(Duration::from_secs(2), first).await;
719    }
720}
721
722#[cfg(test)]
723mod recovery_tests {
724    use super::*;
725    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
726
727    /// A credential whose refresh behaves as `script` says, one entry per call
728    /// (the last repeats): `hang` never returns, `fail` reports no answer, `ok` refreshes.
729    async fn scripted(limits: Limits, script: &'static [&'static str]) -> (Arc<RefreshScheduler>, Arc<AtomicUsize>, Arc<AtomicBool>) {
730        let scheduler = Arc::new(RefreshScheduler::with_limits(limits));
731        let calls = Arc::new(AtomicUsize::new(0));
732        let fresh = Arc::new(AtomicBool::new(false));
733        let (c, f, f2) = (calls.clone(), fresh.clone(), fresh.clone());
734        scheduler
735            .register(
736                "test:cred",
737                move || {
738                    let fresh = f2.load(Ordering::SeqCst);
739                    Box::pin(async move { fresh })
740                },
741                move || {
742                    let n = c.fetch_add(1, Ordering::SeqCst);
743                    let step = script[n.min(script.len() - 1)];
744                    let fresh = f.clone();
745                    Box::pin(async move {
746                        match step {
747                            "hang" => std::future::pending::<()>().await,
748                            "fail" => return Err(RefreshErrorKind::Unreachable("error sending request".into())),
749                            _ => fresh.store(true, Ordering::SeqCst),
750                        }
751                        Ok(())
752                    })
753                },
754            )
755            .await;
756        (scheduler, calls, fresh)
757    }
758
759    const FAST: Limits = Limits {
760        check: Duration::from_secs(5),
761        refresh: Duration::from_millis(200),
762        wait: Duration::from_secs(5),
763    };
764
765    async fn spawn_caller(scheduler: &Arc<RefreshScheduler>) -> tokio::task::JoinHandle<Result<(), String>> {
766        let s = scheduler.clone();
767        tokio::spawn(async move { s.ensure_fresh("test:cred").await })
768    }
769
770    async fn until_refreshing(calls: &AtomicUsize) {
771        while calls.load(Ordering::SeqCst) == 0 {
772            tokio::time::sleep(Duration::from_millis(10)).await;
773        }
774    }
775
776    #[tokio::test(flavor = "multi_thread")]
777    async fn a_refresh_that_never_answers_fails_in_its_time_and_the_next_caller_refreshes() {
778        let (scheduler, calls, _) = scripted(FAST, &["hang", "ok"]).await;
779        let first = tokio::time::timeout(Duration::from_secs(3), scheduler.ensure_fresh("test:cred")).await.expect("bounded");
780        assert!(first.unwrap_err().contains("took longer"), "the hung refresh is reported as a failure");
781        assert!(matches!(scheduler.state("test:cred"), Some(CredentialState::Failed { offline: true, .. })), "offline, not stuck refreshing");
782        tokio::time::timeout(Duration::from_secs(3), scheduler.ensure_fresh("test:cred")).await.expect("bounded").unwrap();
783        assert_eq!(calls.load(Ordering::SeqCst), 2);
784        assert_eq!(scheduler.state("test:cred"), Some(CredentialState::Fresh));
785    }
786
787    #[tokio::test(flavor = "multi_thread")]
788    async fn callers_parked_behind_a_hung_refresh_are_freed_when_it_fails() {
789        let (scheduler, calls, _) = scripted(FAST, &["hang", "ok"]).await;
790        let leader = spawn_caller(&scheduler).await;
791        until_refreshing(&calls).await;
792        let waiter = spawn_caller(&scheduler).await;
793        assert!(leader.await.unwrap().is_err());
794        // The waiter woke, took over as the refresher, and its refresh succeeded.
795        tokio::time::timeout(Duration::from_secs(3), waiter).await.expect("freed").unwrap().unwrap();
796        assert_eq!(scheduler.state("test:cred"), Some(CredentialState::Fresh));
797    }
798
799    #[tokio::test(flavor = "multi_thread")]
800    async fn a_dropped_refresher_does_not_leave_the_state_refreshing() {
801        let limits = Limits { refresh: Duration::from_secs(60), ..FAST };
802        let (scheduler, calls, _) = scripted(limits, &["hang", "ok"]).await;
803        let leader = spawn_caller(&scheduler).await;
804        until_refreshing(&calls).await;
805        let waiter = spawn_caller(&scheduler).await;
806        tokio::time::sleep(Duration::from_millis(50)).await;
807        // The caller goes away mid-refresh (an HTTP handler whose client left).
808        leader.abort();
809        let _ = leader.await;
810        tokio::time::timeout(Duration::from_secs(3), waiter).await.expect("freed").unwrap().unwrap();
811        assert_eq!(scheduler.state("test:cred"), Some(CredentialState::Fresh));
812    }
813
814    #[tokio::test(flavor = "multi_thread")]
815    async fn a_waiter_gives_up_instead_of_parking_for_good() {
816        let limits = Limits { refresh: Duration::from_secs(60), wait: Duration::from_millis(150), ..FAST };
817        let (scheduler, calls, _) = scripted(limits, &["hang"]).await;
818        let leader = spawn_caller(&scheduler).await;
819        until_refreshing(&calls).await;
820        let waited = tokio::time::timeout(Duration::from_secs(3), scheduler.ensure_fresh("test:cred")).await.expect("bounded");
821        assert!(waited.unwrap_err().contains("has not finished"));
822        leader.abort();
823    }
824
825    #[tokio::test(flavor = "multi_thread")]
826    async fn refreshes_that_fail_n_times_end_fresh_and_the_offline_flag_clears() {
827        let (scheduler, calls, _) = scripted(FAST, &["fail", "fail", "fail", "ok"]).await;
828        for _ in 0..3 {
829            assert!(scheduler.ensure_fresh("test:cred").await.is_err());
830            assert!(matches!(scheduler.state("test:cred"), Some(CredentialState::Failed { offline: true, .. })));
831        }
832        scheduler.ensure_fresh("test:cred").await.unwrap();
833        assert_eq!(calls.load(Ordering::SeqCst), 4);
834        assert_eq!(scheduler.state("test:cred"), Some(CredentialState::Fresh), "no longer offline");
835    }
836
837    #[tokio::test(flavor = "multi_thread")]
838    async fn registering_again_frees_callers_parked_behind_the_old_state() {
839        let limits = Limits { refresh: Duration::from_secs(60), ..FAST };
840        let (scheduler, calls, _) = scripted(limits, &["hang"]).await;
841        let leader = spawn_caller(&scheduler).await;
842        until_refreshing(&calls).await;
843        let waiter = spawn_caller(&scheduler).await;
844        tokio::time::sleep(Duration::from_millis(50)).await;
845        scheduler.register("test:cred", || Box::pin(async { true }), || Box::pin(async { Ok(()) })).await;
846        tokio::time::timeout(Duration::from_secs(3), waiter).await.expect("freed").unwrap().unwrap();
847        leader.abort();
848    }
849}