use std::time::Duration;
use super::super::doubt::{ASKED_AGAIN, in_doubt};
use super::{Invocation, MailCell, Mailbox, Slots, lock_mail};
pub(super) const HOLD_WAITS: u32 = 240;
pub(super) const HOLD_TICK: Duration = Duration::from_millis(125);
pub(super) const HAND_OFFS: u32 = 3;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Taken {
Work(Vec<Invocation>),
Superseded,
}
impl Taken {
pub fn work(self) -> Vec<Invocation> {
match self {
Self::Work(work) => work,
Self::Superseded => Vec::new(),
}
}
}
impl Mailbox {
pub fn take(&self, client: &str) -> Result<Taken, String> {
let reading = self.reading(client)?;
let mut ack = true;
for _ in 0..self.waits {
match self.drain(&reading, ack) {
None => return Ok(Taken::Superseded),
Some(taken) if !taken.is_empty() => return Ok(Taken::Work(taken)),
Some(_) => {}
}
ack = false;
std::thread::sleep(self.tick);
}
Ok(self
.drain(&reading, ack)
.map_or(Taken::Superseded, Taken::Work))
}
pub(crate) fn reading(&self, client: &str) -> Result<Reading, String> {
let mut slots = lock_mail(&self.cell);
if slots.reading.contains_key(client) {
return Err(format!(
"invocations: {client:?} is already holding this server's follow-class \
read — one machine's queue has one reader, and a read never takes it \
from the read that holds it: an activation that is entitled to the \
queue advertises first, which ends that read and tells it so. \
Something else is presenting this certificate: stop it, or stop this"
));
}
slots.reads += 1;
let token = slots.reads;
slots.reading.insert(client.to_owned(), token);
Ok(Reading {
cell: self.cell.clone(),
name: client.to_owned(),
token,
})
}
pub fn supersede(&self, client: &str) {
lock_mail(&self.cell).reading.remove(client);
}
pub fn serving(&self, client: &str) -> bool {
lock_mail(&self.cell).reading.contains_key(client)
}
fn drain(&self, reading: &Reading, ack: bool) -> Option<Vec<Invocation>> {
let client = reading.name.as_str();
let mut slots = lock_mail(&self.cell);
if !reading.holds(&slots) {
return None;
}
let mut out = Vec::new();
for slot in slots.live.values_mut() {
if slot.client != client || slot.run.over() {
continue;
}
if slot.run.acknowledged() {
slot.doubt(ASKED_AGAIN);
} else if slot.handed >= HAND_OFFS {
slot.run.doubt(&in_doubt(client, slot.handed));
} else if ack || slot.handed == 0 {
slot.handed += 1;
out.push(slot.invocation.clone());
}
}
Some(out)
}
}
pub(crate) struct Reading {
cell: MailCell,
name: String,
token: u64,
}
impl Reading {
fn holds(&self, slots: &Slots) -> bool {
slots.reading.get(&self.name) == Some(&self.token)
}
}
impl Drop for Reading {
fn drop(&mut self) {
let mut slots = lock_mail(&self.cell);
if self.holds(&slots) {
slots.reading.remove(&self.name);
}
}
}