Skip to main content

printobserver_core/
turn_lock.rs

1//! One supervision turn per print at a time.
2//!
3//! An event arriving while a turn for the same print is still running is queued
4//! behind it rather than opening a second concurrent conversation: two turns
5//! talking to one session at once is two agents disagreeing about one machine.
6//!
7//! The queue is per print rather than global, because two prints are two
8//! conversations and nothing is served by serializing them against each other.
9//! It is an asynchronous lock rather than a `std` one because a guard is held
10//! across an await and has to be sendable; the wakers are what make a queued
11//! caller resume the moment the turn ahead of it returns rather than on a poll.
12
13use core::future::Future;
14use core::pin::Pin;
15use core::task::{Context, Poll, Waker};
16use std::collections::BTreeMap;
17use std::sync::Mutex;
18
19use printobserver_types::PrintId;
20
21/// One print's queue: whether a turn holds it, and who is waiting.
22#[derive(Debug, Default)]
23struct Queue {
24    /// Whether a turn is running for this print.
25    held: bool,
26    /// The callers waiting for it, in the order they arrived.
27    waiting: Vec<Waker>,
28}
29
30/// The per-print turn locks.
31#[derive(Debug, Default)]
32pub struct TurnLocks {
33    /// One queue per print that has ever taken a turn.
34    queues: Mutex<BTreeMap<PrintId, Queue>>,
35}
36
37impl TurnLocks {
38    /// Wait until no turn is running for this print, then hold it.
39    pub const fn acquire(&self, print_id: PrintId) -> Acquire<'_> {
40        Acquire {
41            locks: self,
42            print_id,
43        }
44    }
45
46    /// Release one print's turn and wake whoever is queued behind it.
47    fn release(&self, print_id: PrintId) {
48        let woken = {
49            let mut queues = self.queues.lock().expect("the turn locks are not poisoned");
50            let queue = queues.entry(print_id).or_default();
51            queue.held = false;
52            core::mem::take(&mut queue.waiting)
53        };
54        for waker in woken {
55            waker.wake();
56        }
57    }
58}
59
60/// The future that waits for one print's turn.
61#[derive(Debug)]
62pub struct Acquire<'a> {
63    /// The locks being waited on.
64    locks: &'a TurnLocks,
65    /// The print whose turn is being waited for.
66    print_id: PrintId,
67}
68
69impl<'a> Future for Acquire<'a> {
70    type Output = TurnGuard<'a>;
71
72    fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
73        let mut queues = self
74            .locks
75            .queues
76            .lock()
77            .expect("the turn locks are not poisoned");
78        let queue = queues.entry(self.print_id).or_default();
79        if queue.held {
80            queue.waiting.push(context.waker().clone());
81            return Poll::Pending;
82        }
83        queue.held = true;
84        drop(queues);
85        Poll::Ready(TurnGuard {
86            locks: self.locks,
87            print_id: self.print_id,
88        })
89    }
90}
91
92/// The turn one print is running, released when this is dropped.
93#[derive(Debug)]
94pub struct TurnGuard<'a> {
95    /// The locks this guard came from.
96    locks: &'a TurnLocks,
97    /// The print whose turn is being held.
98    print_id: PrintId,
99}
100
101impl Drop for TurnGuard<'_> {
102    fn drop(&mut self) {
103        self.locks.release(self.print_id);
104    }
105}