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    /// Hold this print's turn when no turn is running for it, without waiting.
47    ///
48    /// For a caller that may itself be answering the turn that holds it — a
49    /// read the agent made from inside its own turn — and so must never queue
50    /// behind that turn.
51    ///
52    /// # Panics
53    ///
54    /// When the turn locks are poisoned, which only a panic while they were
55    /// being read can leave them.
56    pub fn try_acquire(&self, print_id: PrintId) -> Option<TurnGuard<'_>> {
57        let mut queues = self.queues.lock().expect("the turn locks are not poisoned");
58        let queue = queues.entry(print_id).or_default();
59        if queue.held {
60            return None;
61        }
62        queue.held = true;
63        drop(queues);
64        Some(TurnGuard {
65            locks: self,
66            print_id,
67        })
68    }
69
70    /// Release one print's turn and wake whoever is queued behind it.
71    fn release(&self, print_id: PrintId) {
72        let woken = {
73            let mut queues = self.queues.lock().expect("the turn locks are not poisoned");
74            let queue = queues.entry(print_id).or_default();
75            queue.held = false;
76            core::mem::take(&mut queue.waiting)
77        };
78        for waker in woken {
79            waker.wake();
80        }
81    }
82}
83
84/// The future that waits for one print's turn.
85#[derive(Debug)]
86pub struct Acquire<'a> {
87    /// The locks being waited on.
88    locks: &'a TurnLocks,
89    /// The print whose turn is being waited for.
90    print_id: PrintId,
91}
92
93impl<'a> Future for Acquire<'a> {
94    type Output = TurnGuard<'a>;
95
96    fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
97        let mut queues = self
98            .locks
99            .queues
100            .lock()
101            .expect("the turn locks are not poisoned");
102        let queue = queues.entry(self.print_id).or_default();
103        if queue.held {
104            queue.waiting.push(context.waker().clone());
105            return Poll::Pending;
106        }
107        queue.held = true;
108        drop(queues);
109        Poll::Ready(TurnGuard {
110            locks: self.locks,
111            print_id: self.print_id,
112        })
113    }
114}
115
116/// The turn one print is running, released when this is dropped.
117#[derive(Debug)]
118pub struct TurnGuard<'a> {
119    /// The locks this guard came from.
120    locks: &'a TurnLocks,
121    /// The print whose turn is being held.
122    print_id: PrintId,
123}
124
125impl Drop for TurnGuard<'_> {
126    fn drop(&mut self) {
127        self.locks.release(self.print_id);
128    }
129}