//! Optional queue deadline. Claim and expiration have one atomic winner. use crate::{adapters::SystemClock, ports::SharedClock, worker::GenerationCommand}; use std::sync::{ Arc, atomic::{AtomicU8, Ordering}, }; use std::time::Duration; use tokio::{ sync::{mpsc, oneshot}, time::{Instant, timeout_at}, }; const QUEUED: u8 = 0; const CLAIMED: u8 = 1; const EXPIRED: u8 = 2; pub struct Ticket { deadline: Instant, clock: SharedClock, state: Arc, started: oneshot::Sender<()>, } impl Ticket { pub(crate) fn claim(self) -> bool { if self .state .compare_exchange(QUEUED, CLAIMED, Ordering::AcqRel, Ordering::Acquire) .is_err() { return false; } // Check after the CAS: a thread may have been preempted across the // deadline before claiming. The requester waits for acknowledgment // after losing its expiry CAS, so a late claimant can still refuse. if self.clock.now() >= self.deadline { self.state.store(EXPIRED, Ordering::Release); return false; } // A requester that disappeared before acknowledgment must not start work. self.started.send(()).is_ok() } } #[derive(Debug, PartialEq, Eq)] pub enum Error { Expired, Closed, } /// [`enqueue_with`] on the system clock. pub async fn enqueue( sender: &mpsc::Sender, command: GenerationCommand, budget: Option, ) -> Result<(), Error> { enqueue_with(sender, command, budget, SystemClock::shared()).await } /// Queue a command; with a `budget` it must be claimed by the worker before `clock.now() + budget`. pub async fn enqueue_with( sender: &mpsc::Sender, mut command: GenerationCommand, budget: Option, clock: SharedClock, ) -> Result<(), Error> { let Some(budget) = budget else { return sender.send(command).await.map_err(|_| Error::Closed); }; let deadline = clock.now() + budget; let state = Arc::new(AtomicU8::new(QUEUED)); let (started, received) = oneshot::channel(); command.queue = Some(Ticket { deadline, clock, state: state.clone(), started, }); match timeout_at(deadline, sender.send(command)).await { Err(_) => return Err(Error::Expired), Ok(Err(_)) => return Err(Error::Closed), Ok(Ok(())) => (), } await_start(received, &state, deadline).await } /// Wait until the worker takes the request off the queue, or expire it at `deadline` if nobody has claimed it. async fn await_start( mut received: oneshot::Receiver<()>, state: &AtomicU8, deadline: Instant, ) -> Result<(), Error> { let acknowledged = tokio::select! { biased; result = &mut received => result, _ = tokio::time::sleep_until(deadline) => { if state.compare_exchange(QUEUED, EXPIRED, Ordering::AcqRel, Ordering::Acquire).is_ok() { return Err(Error::Expired); } // The worker won the claim race. Its synchronous acknowledgment or // channel closure resolves this wait; the queue clock no longer applies. received.await } }; acknowledged.map_err(|_| { if state.load(Ordering::Acquire) == EXPIRED { Error::Expired } else { Error::Closed } }) } #[cfg(test)] mod tests { use super::*; use crate::{wire::Generate, worker::GenerationResult}; fn command() -> ( GenerationCommand, oneshot::Receiver, String>>, ) { let (result, received) = oneshot::channel(); ( GenerationCommand { queue: None, activity: None, request: Generate { token_ids: vec![65], max_new: 1, ..Default::default() }, result: GenerationResult::Buffered(result), }, received, ) } #[tokio::test] async fn full_channel_and_unclaimed_jobs_expire_without_claim() { let (sender, mut pending) = mpsc::channel(1); let (first, _first_result) = command(); sender.send(first).await.unwrap(); let (second, _second_result) = command(); assert_eq!( enqueue(&sender, second, Some(Duration::from_millis(10))).await, Err(Error::Expired) ); drop(pending.recv().await.unwrap()); assert!( pending.try_recv().is_err(), "channel-timeout job was never queued" ); let (third, _third_result) = command(); assert_eq!( enqueue(&sender, third, Some(Duration::from_millis(10))).await, Err(Error::Expired) ); assert!(!pending.recv().await.unwrap().queue.unwrap().claim()); } #[tokio::test] async fn claim_removes_queue_deadline_and_closed_queue_is_distinct() { let (sender, mut pending) = mpsc::channel(1); let (job, _result) = command(); let submit = tokio::spawn(async move { enqueue(&sender, job, Some(Duration::from_secs(1))).await }); let mut job = pending.recv().await.unwrap(); assert!(job.queue.take().unwrap().claim()); assert_eq!(submit.await.unwrap(), Ok(())); // A claimed job has no remaining ticket/timer attached to execution. assert!(job.queue.is_none()); let (sender, pending) = mpsc::channel(1); drop(pending); let (job, _result) = command(); assert_eq!( enqueue(&sender, job, Some(Duration::from_secs(1))).await, Err(Error::Closed) ); } #[test] fn worker_claim_rejects_late_expired_and_abandoned_tickets() { for (deadline, initial, abandoned) in [ (Instant::now() - Duration::from_secs(1), QUEUED, false), (Instant::now() + Duration::from_secs(10), EXPIRED, false), (Instant::now() + Duration::from_secs(10), QUEUED, true), ] { let (started, received) = oneshot::channel(); let state = Arc::new(AtomicU8::new(initial)); if abandoned { drop(received); } assert!( !Ticket { deadline, clock: SystemClock::shared(), state, started } .claim() ); } } #[tokio::test] async fn queue_deadline_follows_the_injected_clock() { let clock = crate::ports::fakes::ManualClock::new(0); let (sender, mut pending) = mpsc::channel(1); let (job, _result) = command(); let submit_clock = clock.clone(); let submit = tokio::spawn(async move { enqueue_with(&sender, job, Some(Duration::from_secs(30)), submit_clock).await }); let ticket = pending.recv().await.unwrap().queue.unwrap(); // 31 s pass on the injected clock only; no real time does. clock.advance(Duration::from_secs(31)); assert!( !ticket.claim(), "a claim after the deadline of the injected clock must be refused" ); assert_eq!(submit.await.unwrap(), Err(Error::Expired)); } }