use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::time::Instant;
tokio::task_local! {
static TURN_OWNER_WAIT: OwnerWaitClock;
}
#[derive(Clone, Default)]
pub struct OwnerWaitClock(Arc<Mutex<OwnerWaitState>>, Option<Box<OwnerWaitClock>>);
#[derive(Default)]
struct OwnerWaitState {
open: usize,
since: Option<Instant>,
waited: Duration,
first_step: Option<chrono::DateTime<chrono::Utc>>,
last_step_end: Option<chrono::DateTime<chrono::Utc>>,
}
pub struct StepRunning {
clock: OwnerWaitClock,
_parent: Option<Box<StepRunning>>,
}
pub struct OwnerWaiting {
clock: OwnerWaitClock,
_parent: Option<Box<OwnerWaiting>>,
}
impl OwnerWaitClock {
pub fn waited(&self) -> Duration {
let state = self.0.lock().unwrap_or_else(|e| e.into_inner());
state.waited + state.since.map_or(Duration::ZERO, |since| since.elapsed())
}
pub fn current() -> Option<Self> {
TURN_OWNER_WAIT.try_with(Clone::clone).ok()
}
pub async fn within<F: std::future::Future>(clock: Option<Self>, future: F) -> F::Output {
match clock {
Some(clock) => TURN_OWNER_WAIT.scope(clock, future).await,
None => future.await,
}
}
pub fn nested(&self) -> Self {
Self(Arc::default(), Some(Box::new(self.clone())))
}
pub fn steps(&self) -> Option<(chrono::DateTime<chrono::Utc>, chrono::DateTime<chrono::Utc>)> {
let state = self.0.lock().unwrap_or_else(|e| e.into_inner());
Some((state.first_step?, state.last_step_end?))
}
pub fn begin_step() -> Option<StepRunning> {
Some(Self::current()?.step())
}
fn step(&self) -> StepRunning {
{
let mut state = self.0.lock().unwrap_or_else(|e| e.into_inner());
state.first_step.get_or_insert_with(chrono::Utc::now);
}
StepRunning {
clock: self.clone(),
_parent: self.1.as_ref().map(|parent| Box::new(parent.step())),
}
}
pub fn begin_waiting() -> Option<OwnerWaiting> {
Some(Self::current()?.open_wait())
}
fn open_wait(&self) -> OwnerWaiting {
{
let mut state = self.0.lock().unwrap_or_else(|e| e.into_inner());
state.open += 1;
if state.open == 1 {
state.since = Some(Instant::now());
}
}
OwnerWaiting {
clock: self.clone(),
_parent: self.1.as_ref().map(|parent| Box::new(parent.open_wait())),
}
}
}
#[derive(Clone)]
pub struct WorkDeadline {
started: tokio::time::Instant,
limit: std::time::Duration,
owner_wait: OwnerWaitClock,
waited_at_start: std::time::Duration,
}
impl WorkDeadline {
pub fn starting_now(limit: std::time::Duration, owner_wait: OwnerWaitClock) -> Self {
Self {
started: tokio::time::Instant::now(),
limit,
waited_at_start: owner_wait.waited(),
owner_wait,
}
}
pub fn limit(&self) -> std::time::Duration {
self.limit
}
pub fn remaining(&self) -> std::time::Duration {
let waited_since_start = self
.owner_wait
.waited()
.saturating_sub(self.waited_at_start);
let worked = self.started.elapsed().saturating_sub(waited_since_start);
self.limit.saturating_sub(worked)
}
pub async fn reached(&self, check: std::time::Duration) {
loop {
let left = self.remaining();
if left.is_zero() {
return;
}
tokio::time::sleep(left.min(check)).await;
}
}
}
#[derive(Clone)]
pub struct ProgressClock(Arc<Mutex<ProgressState>>, OwnerWaitClock);
struct ProgressState {
last: Instant,
waited_at_last: Duration,
in_flight: usize,
}
pub struct InFlight(ProgressClock);
impl ProgressClock {
pub fn starting_now(owner_wait: OwnerWaitClock) -> Self {
Self(
Arc::new(Mutex::new(ProgressState {
last: Instant::now(),
waited_at_last: owner_wait.waited(),
in_flight: 0,
})),
owner_wait,
)
}
pub fn touch(&self) {
let waited = self.1.waited();
let mut state = self.0.lock().unwrap_or_else(|e| e.into_inner());
state.last = Instant::now();
state.waited_at_last = waited;
}
pub fn begin(&self) -> InFlight {
self.touch();
self.0.lock().unwrap_or_else(|e| e.into_inner()).in_flight += 1;
InFlight(self.clone())
}
pub fn idle(&self) -> Duration {
let waited = self.1.waited();
let state = self.0.lock().unwrap_or_else(|e| e.into_inner());
if state.in_flight > 0 {
return Duration::ZERO;
}
state
.last
.elapsed()
.saturating_sub(waited.saturating_sub(state.waited_at_last))
}
pub async fn idle_for(&self, limit: Duration, check: Duration) {
loop {
let idle = self.idle();
if idle >= limit {
return;
}
tokio::time::sleep((limit - idle).min(check)).await;
}
}
}
impl Drop for InFlight {
fn drop(&mut self) {
{
let mut state = self.0.0.lock().unwrap_or_else(|e| e.into_inner());
state.in_flight = state.in_flight.saturating_sub(1);
}
self.0.touch();
}
}
impl Drop for StepRunning {
fn drop(&mut self) {
let now = chrono::Utc::now();
let mut state = self.clock.0.lock().unwrap_or_else(|e| e.into_inner());
if state.last_step_end.is_none_or(|end| end < now) {
state.last_step_end = Some(now);
}
}
}
impl Drop for OwnerWaiting {
fn drop(&mut self) {
let mut state = self.clock.0.lock().unwrap_or_else(|e| e.into_inner());
state.open = state.open.saturating_sub(1);
if state.open == 0
&& let Some(since) = state.since.take()
{
state.waited += since.elapsed();
}
}
}
#[cfg(test)]
mod progress_tests {
use super::*;
const STEP: Duration = Duration::from_millis(60);
#[tokio::test]
async fn a_call_in_flight_is_never_idle_and_its_end_restarts_the_clock() {
let clock = ProgressClock::starting_now(OwnerWaitClock::default());
tokio::time::sleep(STEP).await;
assert!(clock.idle() >= STEP);
let call = clock.begin();
tokio::time::sleep(STEP * 3).await;
assert_eq!(clock.idle(), Duration::ZERO, "a long call is progress");
drop(call);
assert!(clock.idle() < STEP);
tokio::time::sleep(STEP).await;
assert!(clock.idle() >= STEP);
clock.touch();
assert!(clock.idle() < STEP);
}
#[tokio::test]
async fn a_nested_clock_measures_its_own_waits_and_counts_for_the_turn() {
let turn = OwnerWaitClock::default();
let helper = turn.nested();
let sibling = turn.nested();
OwnerWaitClock::within(Some(helper.clone()), async {
let card = OwnerWaitClock::begin_waiting();
tokio::time::sleep(STEP * 2).await;
drop(card);
})
.await;
assert!(helper.waited() >= STEP * 2, "{:?}", helper.waited());
assert!(turn.waited() >= STEP * 2, "{:?}", turn.waited());
assert_eq!(sibling.waited(), Duration::ZERO);
}
#[tokio::test]
async fn a_nested_clock_times_its_own_steps() {
let turn = OwnerWaitClock::default();
let helper = turn.nested();
assert!(helper.steps().is_none());
let before = chrono::Utc::now();
OwnerWaitClock::within(Some(helper.clone()), async {
tokio::time::sleep(STEP).await; let first = OwnerWaitClock::begin_step();
tokio::time::sleep(STEP).await;
drop(first);
let second = OwnerWaitClock::begin_step();
tokio::time::sleep(STEP).await;
drop(second);
tokio::time::sleep(STEP).await; })
.await;
let (first, last) = helper.steps().expect("timed steps");
let ran = (last - first).to_std().unwrap();
assert!(ran >= STEP * 2 && ran < STEP * 4, "{ran:?}");
assert!(first - before >= chrono::Duration::from_std(STEP).unwrap());
assert!(turn.steps().is_some());
}
#[tokio::test]
async fn waiting_on_the_owner_is_not_idle() {
let owner = OwnerWaitClock::default();
let clock = ProgressClock::starting_now(owner.clone());
OwnerWaitClock::within(Some(owner), async {
let card = OwnerWaitClock::begin_waiting();
tokio::time::sleep(STEP * 4).await;
drop(card);
})
.await;
assert!(clock.idle() < STEP * 2, "{:?}", clock.idle());
}
}
fn open_approvals() -> &'static std::sync::Mutex<std::collections::HashMap<String, usize>> {
static OPEN: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, usize>>> =
std::sync::OnceLock::new();
OPEN.get_or_init(Default::default)
}
pub struct ApprovalOpen(String);
impl ApprovalOpen {
pub fn begin(session_id: &str) -> Self {
if let Ok(mut open) = open_approvals().lock() {
*open.entry(session_id.to_owned()).or_default() += 1;
}
Self(session_id.to_owned())
}
}
impl Drop for ApprovalOpen {
fn drop(&mut self) {
if let Ok(mut open) = open_approvals().lock()
&& let Some(n) = open.get_mut(&self.0)
{
*n = n.saturating_sub(1);
if *n == 0 {
open.remove(&self.0);
}
}
}
}
pub fn approval_open(session_id: &str) -> bool {
open_approvals()
.lock()
.is_ok_and(|open| open.get(session_id).is_some_and(|n| *n > 0))
}
#[cfg(test)]
mod approval_open_tests {
use super::{ApprovalOpen, approval_open};
#[test]
fn a_card_is_open_until_dropped() {
let session = "telegram:synthetic-approval-open";
assert!(!approval_open(session));
let first = ApprovalOpen::begin(session);
let second = ApprovalOpen::begin(session);
drop(first);
assert!(approval_open(session));
drop(second);
assert!(!approval_open(session));
}
}