use std::collections::{HashMap, HashSet};
use rho_protocol::SessionId;
use super::{
store::{DeliveryRecord, DeliveryResult, Snapshot, WatchFile, WatchRecord},
watcher::{End, News, Record, Watching},
};
use crate::app::session_control::{Holder, WaitResult};
pub(super) type Key = (String, SessionId);
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[error("session watches budget for {holder}: limit {limit}, asked {asked}")]
pub(crate) struct OverBudget {
pub(crate) holder: Holder,
pub(crate) limit: u32,
pub(crate) asked: u32,
}
#[derive(Debug, PartialEq, Eq)]
pub(super) struct Slot {
token: String,
session: Option<SessionId>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct Start {
pub(super) key: Key,
pub(super) generation: u64,
pub(super) watching: Watching,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Revision(Option<u64>);
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum Watched {
Unchanged { watching: bool },
Removed,
Started(Start),
}
#[derive(Debug)]
pub(super) struct WatchBook {
file: WatchFile,
max_watches: u32,
running: HashMap<Key, u64>,
generations: u64,
revisions: HashMap<Key, u64>,
pending: HashMap<Key, u32>,
pending_new: HashMap<String, u32>,
snapshots: u64,
}
impl WatchBook {
pub(super) fn resume(mut file: WatchFile, max_watches: u32) -> (Self, Vec<Start>) {
for watch in &mut file.watches {
watch.error = None;
}
file.max_watches = Some(max_watches);
let rows = file.watches.clone();
let mut book = Self {
file,
max_watches,
running: HashMap::new(),
generations: 0,
revisions: HashMap::new(),
pending: HashMap::new(),
pending_new: HashMap::new(),
snapshots: 0,
};
let starts = rows.into_iter().map(|row| book.run(row)).collect();
(book, starts)
}
pub(super) fn reserve(
&mut self,
token: &str,
session: Option<&SessionId>,
) -> Result<Slot, OverBudget> {
self.admit(token, session)?;
match session {
Some(session) => {
*self
.pending
.entry((token.to_owned(), session.clone()))
.or_default() += 1;
}
None => *self.pending_new.entry(token.to_owned()).or_default() += 1,
}
Ok(Slot {
token: token.to_owned(),
session: session.cloned(),
})
}
pub(super) fn release(&mut self, slot: Slot) {
match slot.session {
Some(session) => decrement(&mut self.pending, (slot.token, session)),
None => decrement(&mut self.pending_new, slot.token),
}
}
pub(super) fn revision(&self, key: &Key) -> Revision {
Revision(self.revisions.get(key).copied())
}
pub(super) fn watch(
&mut self,
token: &str,
webhook: String,
now: &WaitResult,
read: Revision,
) -> Result<Watched, OverBudget> {
let key = (token.to_owned(), now.session.clone());
if self.revision(&key) != read {
return Ok(Watched::Unchanged {
watching: self.running.contains_key(&key),
});
}
let reported = match News::of(now) {
News::Settled(_) if self.remove(&key) => return Ok(Watched::Removed),
News::Settled(_) => return Ok(Watched::Unchanged { watching: false }),
News::Asks(about) => Some(about),
News::Nothing => None,
};
self.admit(token, Some(&now.session))?;
Ok(Watched::Started(self.upsert(WatchRecord {
session: key.1,
token: key.0,
webhook,
reported,
error: None,
})))
}
pub(super) fn notify(&mut self, slot: Slot, session: SessionId, webhook: String) -> Start {
let token = slot.token.clone();
self.release(slot);
self.upsert(WatchRecord {
session,
token,
webhook,
reported: None,
error: None,
})
}
pub(super) fn remove(&mut self, key: &Key) -> bool {
self.running.remove(key);
self.revisions.remove(key);
let before = self.file.watches.len();
self.file
.watches
.retain(|watch| (&watch.token, &watch.session) != (&key.0, &key.1));
self.file.watches.len() != before
}
pub(super) fn apply_end(&mut self, key: &Key, generation: u64, end: &End) -> bool {
if !self.runs(key, generation) {
return false;
}
self.running.remove(key);
match end {
End::Delivered | End::Dropped(_) => {
self.remove(key);
}
End::Stalled(error) => {
if let Some(watch) = self.row_mut(key) {
watch.error = Some(error.clone());
}
}
}
true
}
pub(super) fn apply_record(
&mut self,
key: &Key,
generation: u64,
record: Record<'_>,
at: u64,
) -> bool {
if !self.runs(key, generation) {
return false;
}
let Some(watch) = self.row_mut(key) else {
return false;
};
let result = match record {
Record::Delivered { reported, status } => {
watch.reported = Some(reported.clone());
DeliveryResult::Delivered(status)
}
Record::Failed { error } => DeliveryResult::Failed(error.to_owned()),
};
let webhook = watch.webhook.clone();
self.file.deliveries.insert(
webhook,
DeliveryRecord {
at,
session: key.1.clone(),
result,
},
);
true
}
pub(super) fn snapshot(&mut self) -> Snapshot {
self.snapshots += 1;
Snapshot {
seq: self.snapshots,
file: self.file.clone(),
}
}
fn admit(&self, token: &str, session: Option<&SessionId>) -> Result<(), OverBudget> {
let sessions = self.sessions_of(token);
if session.is_some_and(|session| sessions.contains(session)) {
return Ok(());
}
let held = u32::try_from(sessions.len())
.unwrap_or(u32::MAX)
.saturating_add(self.pending_new.get(token).copied().unwrap_or(0));
let asked = held.saturating_add(1);
if asked > self.max_watches {
return Err(OverBudget {
holder: Holder::Token(token.to_owned()),
limit: self.max_watches,
asked,
});
}
Ok(())
}
fn upsert(&mut self, row: WatchRecord) -> Start {
match self.row_mut(&(row.token.clone(), row.session.clone())) {
Some(watch) => *watch = row.clone(),
None => self.file.watches.push(row.clone()),
}
self.run(row)
}
fn run(&mut self, row: WatchRecord) -> Start {
self.generations += 1;
let key = (row.token, row.session.clone());
self.running.insert(key.clone(), self.generations);
self.revisions.insert(key.clone(), self.generations);
Start {
key,
generation: self.generations,
watching: Watching {
session: row.session,
webhook: row.webhook,
reported: row.reported,
},
}
}
fn runs(&self, key: &Key, generation: u64) -> bool {
self.running.get(key) == Some(&generation)
}
fn row_mut(&mut self, key: &Key) -> Option<&mut WatchRecord> {
self.file
.watches
.iter_mut()
.find(|watch| (&watch.token, &watch.session) == (&key.0, &key.1))
}
fn sessions_of(&self, token: &str) -> HashSet<&SessionId> {
let watched = self
.file
.watches
.iter()
.filter(|watch| watch.token == token)
.map(|watch| &watch.session);
let pending = self
.pending
.keys()
.filter(|(holder, _)| holder == token)
.map(|(_, session)| session);
watched.chain(pending).collect()
}
}
fn decrement<K: Eq + std::hash::Hash>(counts: &mut HashMap<K, u32>, key: K) {
if let Some(count) = counts.get_mut(&key) {
*count = count.saturating_sub(1);
if *count == 0 {
counts.remove(&key);
}
}
}
#[cfg(test)]
#[path = "book_tests.rs"]
mod tests;