1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
//! The order in which calls take a session: each prompt, change, and rewind
//! waits for those the daemon read before it, on any connection, to take
//! their place in the session's queue, as the protocol promises ("Changes
//! and turns take the session one at a time, in the order the daemon took
//! their requests"). A connection runs each call in its own task, so
//! without this a prompt sent right after a model change could start its
//! turn on the old model.
//!
//! The connection lines each call up as it reads it
//! ([`SessionOrder::line_up`]). Once the call's turn is under the turn lock
//! it says so with [`took_place`], and the next call on the session starts;
//! a call that ends first, refused or failed, lets the next start as it
//! ends.
use std::{
cell::RefCell,
collections::{BTreeSet, HashMap},
sync::{Arc, Mutex, MutexGuard, PoisonError},
};
use rho_protocol::{self as wire, InTurnCall, SessionOrder};
use tokio::sync::watch;
use super::Sessions;
// NEXT_MAJOR(rho-protocol Service): take the place as a parameter of the prompt, configure and rewind methods, and remove this task-local.
tokio::task_local! {
/// The place of the call this task runs, until it took it.
static PLACE: RefCell<Option<Place>>;
}
/// Each session's line of calls the daemon read and has yet to start or
/// take their place.
#[derive(Default)]
pub(super) struct Lines {
lines: Arc<Mutex<HashMap<wire::SessionId, Line>>>,
}
/// One session's line. Places are numbered as they join it; a session
/// with no place in line has no entry.
struct Line {
/// The number the next place takes.
issued: u64,
/// The first place that has yet to leave the line; every place before it
/// has left.
head: watch::Sender<u64>,
/// Places after `head` that left, by ending before they started.
left: BTreeSet<u64>,
}
/// A call's place in its session's line: it starts once `head` reaches
/// it, and leaves when it took its place or drops.
struct Place {
lines: Arc<Mutex<HashMap<wire::SessionId, Line>>>,
session: wire::SessionId,
number: u64,
head: watch::Receiver<u64>,
}
impl Lines {
/// A new place at the end of `session`'s line.
fn join(&self, session: &wire::SessionId) -> Place {
let mut lines = lock(&self.lines);
let line = lines.entry(session.clone()).or_insert_with(|| Line {
issued: 0,
head: watch::Sender::new(0),
left: BTreeSet::new(),
});
let number = line.issued;
line.issued += 1;
Place {
lines: Arc::clone(&self.lines),
session: session.clone(),
number,
head: line.head.subscribe(),
}
}
/// How many calls wait in `session`'s line for the ones before them;
/// `None` once its line is gone, no call being in it.
#[cfg(test)]
pub(super) fn waiting(&self, session: &wire::SessionId) -> Option<u64> {
lock(&self.lines).get(session).map(|line| {
(line.issued - *line.head.borrow()).saturating_sub(1 + line.left.len() as u64)
})
}
}
impl Place {
/// Waits until every place before this one left.
async fn reached(&mut self) {
let number = self.number;
// The sender lives while this place is in line.
let _ = self.head.wait_for(|head| *head >= number).await;
}
}
impl Drop for Place {
fn drop(&mut self) {
let mut lines = lock(&self.lines);
let Some(line) = lines.get_mut(&self.session) else {
return;
};
line.left.insert(self.number);
let mut head = *line.head.borrow();
while line.left.remove(&head) {
head += 1;
}
line.head.send_replace(head);
if head == line.issued {
lines.remove(&self.session);
}
}
}
impl SessionOrder for Sessions {
fn line_up(&self, session: &wire::SessionId, call: InTurnCall) -> InTurnCall {
let mut place = self.lines.join(session);
Box::pin(async move {
place.reached().await;
PLACE.scope(RefCell::new(Some(place)), call).await;
})
}
}
/// Tells `session`'s line that the call this task runs took its place in
/// the session's queue, so the next call may start. Does nothing in a task
/// no line runs, such as a turn the daemon starts on its own, or for
/// another session than the call's.
pub(super) fn took_place(session: &wire::SessionId) {
let _ = PLACE.try_with(|place| {
let mut place = place.borrow_mut();
if place
.as_ref()
.is_some_and(|place| place.session == *session)
{
place.take();
}
});
}
fn lock(
lines: &Mutex<HashMap<wire::SessionId, Line>>,
) -> MutexGuard<'_, HashMap<wire::SessionId, Line>> {
lines.lock().unwrap_or_else(PoisonError::into_inner)
}
#[cfg(test)]
#[path = "line_tests.rs"]
mod tests;