use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
use serde::Serialize;
use serde::de::DeserializeOwned;
use super::alarm::LONGEST_SLEEP;
use super::queue::Queue;
use super::read::{Job, State};
use super::state::QueueState;
use crate::Result;
pub(crate) type Hears = Arc<dyn Fn() + Send + Sync>;
#[derive(Default)]
pub(crate) struct Watchers {
subs: Mutex<HashMap<u64, Sub>>,
last: AtomicU64,
}
struct Sub {
key: String,
hears: Hears,
gone: Option<Gone>,
}
#[derive(Clone, Debug)]
enum Gone {
Cancelled,
Failed(String),
}
impl Watchers {
pub(crate) fn changed(&self) {
let hearing: Vec<Hears> = self.lock().values().map(|sub| Arc::clone(&sub.hears)).collect();
for hears in hearing {
hears();
}
}
pub(crate) fn cancelled(&self, key: &str, cancelled: bool) {
self.mark(key, cancelled.then_some(Gone::Cancelled));
}
pub(crate) fn failed(&self, key: &str, error: &str) {
self.mark(key, Some(Gone::Failed(error.to_owned())));
}
fn mark(&self, key: &str, gone: Option<Gone>) {
for sub in self.lock().values_mut().filter(|sub| sub.key == key) {
sub.gone = gone.clone();
}
}
fn lock(&self) -> MutexGuard<'_, HashMap<u64, Sub>> {
self.subs.lock().unwrap_or_else(PoisonError::into_inner)
}
}
impl std::fmt::Debug for Watchers {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Watchers({})", self.lock().len())
}
}
pub(crate) struct Subscription {
queue: Arc<QueueState>,
id: u64,
}
impl Subscription {
pub(crate) fn new(queue: &Arc<QueueState>, key: &str, hears: Hears) -> Subscription {
let id = queue.watchers.last.fetch_add(1, Ordering::Relaxed) + 1;
queue.watchers.lock().insert(id, Sub { key: key.to_owned(), hears, gone: None });
Subscription { queue: Arc::clone(queue), id }
}
fn gone(&self) -> Option<Gone> {
self.queue.watchers.lock().get(&self.id).and_then(|sub| sub.gone.clone())
}
}
impl Drop for Subscription {
fn drop(&mut self) {
self.queue.watchers.lock().remove(&self.id);
}
}
pub(crate) enum Report<V> {
Changed(Box<Job<V>>),
Same,
Over,
}
pub(crate) struct Seen<V> {
last: Option<Job<V>>,
over: bool,
}
impl<V> Default for Seen<V> {
fn default() -> Self {
Seen { last: None, over: false }
}
}
impl<V> Seen<V>
where
V: Serialize + DeserializeOwned + Clone + Send + 'static,
{
pub(crate) fn read(&mut self, queue: &Queue<V>, key: &str, sub: &Subscription) -> Result<Report<V>> {
if self.over {
return Ok(Report::Over);
}
let Some(job) = queue.get(key)? else {
self.over = true;
return Ok(self.last.take().map_or(Report::Over, |mut last| {
match sub.gone() {
None => last.state = State::Done,
Some(Gone::Cancelled) => last.state = State::Cancelled,
Some(Gone::Failed(error)) => (last.state, last.error) = (State::Failed, Some(error)),
}
last.ahead = 0;
Report::Changed(Box::new(last))
}));
};
if self.last.as_ref().is_some_and(|last| shows_the_same(last, &job)) {
return Ok(Report::Same);
}
self.over = matches!(job.state, State::Done | State::Failed);
self.last = Some(job.clone());
Ok(Report::Changed(Box::new(job)))
}
}
fn shows_the_same<V>(a: &Job<V>, b: &Job<V>) -> bool {
(a.state, a.ahead, a.attempt, a.at) == (b.state, b.ahead, b.attempt, b.at)
&& a.progress == b.progress
&& a.error == b.error
}
pub struct Watch<V> {
queue: Queue<V>,
key: String,
woken: Arc<Woken>,
sub: Subscription,
seen: Seen<V>,
}
#[derive(Default)]
struct Woken {
raised: Mutex<bool>,
changed: Condvar,
}
impl Woken {
fn raise(&self) {
*self.raised.lock().unwrap_or_else(PoisonError::into_inner) = true;
self.changed.notify_all();
}
fn wait(&self) {
let raised = self.raised.lock().unwrap_or_else(PoisonError::into_inner);
let (mut raised, _) = self
.changed
.wait_timeout_while(raised, LONGEST_SLEEP, |raised| !*raised)
.unwrap_or_else(PoisonError::into_inner);
*raised = false;
}
}
impl<V> Queue<V>
where
V: Serialize + DeserializeOwned + Clone + Send + 'static,
{
pub fn watch(&self, id: impl AsRef<str>) -> Watch<V> {
let woken = Arc::new(Woken::default());
let raising = Arc::clone(&woken);
let sub = Subscription::new(&self.state, id.as_ref(), Arc::new(move || raising.raise()));
Watch { queue: self.clone(), key: id.as_ref().to_owned(), woken, sub, seen: Seen::default() }
}
}
impl<V> Iterator for Watch<V>
where
V: Serialize + DeserializeOwned + Clone + Send + 'static,
{
type Item = Result<Job<V>>;
fn next(&mut self) -> Option<Result<Job<V>>> {
loop {
match self.seen.read(&self.queue, &self.key, &self.sub) {
Ok(Report::Changed(job)) => return Some(Ok(*job)),
Ok(Report::Over) => return None,
Ok(Report::Same) => self.woken.wait(),
Err(error) => {
self.seen.over = true;
return Some(Err(error));
}
}
}
}
}
impl<V> std::fmt::Debug for Watch<V> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Watch({}: id {:?})", self.queue.state.describe(), self.key)
}
}