Something went wrong. Try again.
A terminal UI for Libby libbui.vinnymac.dev
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170//! The account request gate.//!//! Every sentry request passes through one [`AccountGate`]: one request in//! flight at a time, and at least `gap` (plus up to `jitter`) between the end//! of one request and the start of the next. Libraries suspend cards that//! look automated, so this is a hard rule, not a tuning knob. Retries and//! refreshes go through the gate too.
use std::future::Future;use std::hash::BuildHasher;use std::sync::atomic::{AtomicU64, Ordering};use std::time::Duration;
use tokio::sync::{Mutex, MutexGuard};use tokio::time::{Instant, sleep_until};
/// Serializes and paces account requests.#[derive(Debug)]pub(crate) struct AccountGate { last_completion: Mutex<Option<Instant>>, gap: Duration, jitter: Duration,}
impl AccountGate { pub(crate) fn new(gap: Duration, jitter: Duration) -> Self { Self { last_completion: Mutex::new(None), gap, jitter, } }
/// Runs `work` once the gate is free and the gap since the previous /// request has elapsed. The completion time is recorded even when `work` /// is cancelled part-way, because the request may already have been sent. pub(crate) async fn run<F: Future>(&self, work: F) -> F::Output { let guard = self.last_completion.lock().await; if let Some(done) = *guard { sleep_until(done + self.gap + jitter(self.jitter)).await; } let _stamp = Stamp(guard); work.await }}
/// Records the completion time when the request finishes or is dropped.struct Stamp<'a>(MutexGuard<'a, Option<Instant>>);
impl Drop for Stamp<'_> { fn drop(&mut self) { *self.0 = Some(Instant::now()); }}
/// A uniformly-ish random duration in `0..=max`. Not cryptographic; it only/// needs to keep request spacing from being perfectly regular.fn jitter(max: Duration) -> Duration { static COUNTER: AtomicU64 = AtomicU64::new(0); let max_nanos = u64::try_from(max.as_nanos()).unwrap_or(u64::MAX); if max_nanos == 0 { return Duration::ZERO; } let random = std::collections::hash_map::RandomState::new() .hash_one(COUNTER.fetch_add(1, Ordering::Relaxed)); Duration::from_nanos(random % max_nanos.saturating_add(1))}
#[cfg(test)]mod tests { #![allow(clippy::unwrap_used)]
use std::sync::Arc; use std::sync::atomic::AtomicUsize;
use tokio::time::sleep;
use super::*;
const GAP: Duration = Duration::from_millis(750); const JITTER: Duration = Duration::from_millis(250); const WORK: Duration = Duration::from_millis(100);
#[tokio::test(start_paused = true)] async fn spaces_sequential_requests_by_gap_plus_jitter() { let gate = AccountGate::new(GAP, JITTER); let mut starts = Vec::new(); for _ in 0..20 { gate.run(async { starts.push(Instant::now()); sleep(WORK).await; }) .await; } for pair in starts.windows(2) { let between = pair[1] - pair[0]; assert!(between >= WORK + GAP, "{between:?}"); assert!(between <= WORK + GAP + JITTER, "{between:?}"); } }
#[tokio::test(start_paused = true)] async fn the_first_request_does_not_wait() { let gate = AccountGate::new(GAP, JITTER); let before = Instant::now(); let started = gate.run(async { Instant::now() }).await; assert_eq!(started, before); }
#[tokio::test(start_paused = true)] async fn exactly_the_gap_without_jitter() { let gate = AccountGate::new(GAP, Duration::ZERO); let first = gate.run(async { Instant::now() }).await; sleep(Duration::from_millis(100)).await; let second = gate.run(async { Instant::now() }).await; assert_eq!(second - first, GAP); // A caller that was already idle for longer than the gap goes at once. sleep(GAP * 2).await; let idle = Instant::now(); let third = gate.run(async { Instant::now() }).await; assert_eq!(third, idle); }
#[tokio::test(start_paused = true)] async fn one_request_in_flight_across_tasks() { let gate = Arc::new(AccountGate::new(GAP, JITTER)); let in_flight = Arc::new(AtomicUsize::new(0)); let peak = Arc::new(AtomicUsize::new(0)); let start = Instant::now(); let tasks: Vec<_> = (0..5) .map(|_| { let (gate, in_flight, peak) = (gate.clone(), in_flight.clone(), peak.clone()); tokio::spawn(async move { gate.run(async { let now = in_flight.fetch_add(1, Ordering::SeqCst) + 1; peak.fetch_max(now, Ordering::SeqCst); sleep(WORK).await; in_flight.fetch_sub(1, Ordering::SeqCst); }) .await; }) }) .collect(); for task in tasks { task.await.unwrap(); } assert_eq!(peak.load(Ordering::SeqCst), 1); assert!(start.elapsed() >= WORK * 5 + GAP * 4); }
#[tokio::test(start_paused = true)] async fn a_cancelled_request_still_counts() { let gate = AccountGate::new(GAP, Duration::ZERO); let cancelled = tokio::time::timeout(Duration::from_millis(10), gate.run(sleep(WORK))).await; assert!(cancelled.is_err()); let cancelled_at = Instant::now(); let next = gate.run(async { Instant::now() }).await; assert_eq!(next - cancelled_at, GAP); }
#[test] fn jitter_stays_in_range() { assert_eq!(jitter(Duration::ZERO), Duration::ZERO); for _ in 0..1000 { assert!(jitter(JITTER) <= JITTER); } }}