use std::future::Future;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::Duration;
use tokio::time::Instant;
const NO_PENDING: u64 = u64::MAX;
tokio::task_local! {
static CONTACT: Arc<ContactLedger>;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ResponseSeen {
Yes,
No,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Contact {
pub(crate) response: ResponseSeen,
pub(crate) stall: Option<Duration>,
}
impl Contact {
#[cfg(test)]
pub(crate) const UNTOUCHED: Self = Self {
response: ResponseSeen::No,
stall: None,
};
}
#[derive(Debug)]
pub(crate) struct ContactLedger {
origin: Instant,
responded: AtomicBool,
pending_since: AtomicU64,
}
impl ContactLedger {
pub(crate) fn new() -> Arc<Self> {
Arc::new(Self {
origin: Instant::now(),
responded: AtomicBool::new(false),
pending_since: AtomicU64::new(NO_PENDING),
})
}
pub(crate) async fn scope<F: Future>(self: &Arc<Self>, fetch: F) -> F::Output {
CONTACT.scope(Arc::clone(self), fetch).await
}
fn nanos_since_origin(&self, now: Instant) -> u64 {
let nanos = now.saturating_duration_since(self.origin).as_nanos();
u64::try_from(nanos).map_or(NO_PENDING - 1, |n| n.min(NO_PENDING - 1))
}
fn request(&self, now: Instant) {
let _ = self.pending_since.compare_exchange(
NO_PENDING,
self.nanos_since_origin(now),
Ordering::AcqRel,
Ordering::Acquire,
);
}
fn response(&self) {
self.responded.store(true, Ordering::Release);
self.pending_since.store(NO_PENDING, Ordering::Release);
}
pub(crate) fn snapshot(&self, now: Instant) -> Contact {
let response = if self.responded.load(Ordering::Acquire) {
ResponseSeen::Yes
} else {
ResponseSeen::No
};
let pending = self.pending_since.load(Ordering::Acquire);
let stall = (pending != NO_PENDING).then(|| {
now.saturating_duration_since(self.origin)
.saturating_sub(Duration::from_nanos(pending))
});
Contact { response, stall }
}
}
pub(crate) fn note_request() {
let _ = CONTACT.try_with(|ledger| ledger.request(Instant::now()));
}
pub(crate) fn note_response() {
let _ = CONTACT.try_with(|ledger| ledger.response());
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test(start_paused = true)]
async fn hooks_outside_a_scope_do_nothing() {
note_request();
note_response();
}
#[tokio::test(start_paused = true)]
async fn a_fresh_ledger_is_untouched() {
let ledger = ContactLedger::new();
assert_eq!(ledger.snapshot(Instant::now()), Contact::UNTOUCHED);
}
#[tokio::test(start_paused = true)]
async fn a_pending_request_stalls_until_answered() {
let ledger = ContactLedger::new();
ledger
.scope(async {
note_request();
tokio::time::sleep(Duration::from_secs(4)).await;
let stalled = ledger.snapshot(Instant::now());
assert_eq!(stalled.response, ResponseSeen::No);
assert_eq!(stalled.stall, Some(Duration::from_secs(4)));
note_response();
let answered = ledger.snapshot(Instant::now());
assert_eq!(answered.response, ResponseSeen::Yes);
assert_eq!(answered.stall, None);
})
.await;
}
#[tokio::test(start_paused = true)]
async fn the_stall_restarts_at_the_next_request_after_a_response() {
let ledger = ContactLedger::new();
ledger
.scope(async {
note_request();
tokio::time::sleep(Duration::from_millis(100)).await;
note_response();
tokio::time::sleep(Duration::from_secs(3)).await;
note_request();
tokio::time::sleep(Duration::from_secs(2)).await;
let contact = ledger.snapshot(Instant::now());
assert_eq!(contact.response, ResponseSeen::Yes);
assert_eq!(contact.stall, Some(Duration::from_secs(2)));
})
.await;
}
#[tokio::test(start_paused = true)]
async fn a_second_request_keeps_the_oldest_pending_time() {
let ledger = ContactLedger::new();
ledger
.scope(async {
note_request();
tokio::time::sleep(Duration::from_secs(2)).await;
note_request();
tokio::time::sleep(Duration::from_secs(1)).await;
let contact = ledger.snapshot(Instant::now());
assert_eq!(contact.stall, Some(Duration::from_secs(3)));
})
.await;
}
}