use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Waker, ready};
use futures_core::Stream;
use serde::Serialize;
use serde::de::DeserializeOwned;
use super::queue::Queue;
use crate::Result;
use crate::jobs::{Job, Report, Seen, State, Subscription};
use crate::sync::lock;
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 { state: Mutex::new((true, None)) });
Watch {
queue: self.clone(),
key: id.as_ref().to_owned(),
woken,
sub: None,
seen: Some(Seen::default()),
reading: None,
over: false,
}
}
}
pub struct Watch<V> {
queue: Queue<V>,
key: String,
woken: Arc<Woken>,
sub: Option<Arc<Subscription>>,
seen: Option<Seen<V>>,
reading: Option<Reading<V>>,
over: bool,
}
type Reading<V> = Pin<Box<dyn Future<Output = Result<(Seen<V>, Result<Report<V>>)>> + Send>>;
struct Woken {
state: Mutex<(bool, Option<Waker>)>,
}
impl Woken {
fn raise(&self) {
let waker = {
let mut state = lock(&self.state);
state.0 = true;
state.1.take()
};
if let Some(waker) = waker {
waker.wake();
}
}
fn lower_or_wait(&self, waker: &Waker) -> bool {
let mut state = lock(&self.state);
if std::mem::replace(&mut state.0, false) {
return true;
}
state.1 = Some(waker.clone());
false
}
}
impl<V> Unpin for Watch<V> {}
impl<V> Stream for Watch<V>
where
V: Serialize + DeserializeOwned + Clone + Send + 'static,
{
type Item = Result<Job<V>>;
fn poll_next(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let watch = self.get_mut();
loop {
if watch.over {
return Poll::Ready(None);
}
if let Some(reading) = &mut watch.reading {
let read = ready!(reading.as_mut().poll(context));
watch.reading = None;
if let Some(report) = watch.reported(read) {
return Poll::Ready(report);
}
}
if !watch.woken.lower_or_wait(context.waker()) {
return Poll::Pending;
}
watch.reading = Some(watch.read());
}
}
}
impl<V> Watch<V>
where
V: Serialize + DeserializeOwned + Clone + Send + 'static,
{
fn read(&mut self) -> Reading<V> {
let sub = match &self.sub {
Some(sub) => Arc::clone(sub),
None => {
let woken = Arc::clone(&self.woken);
let sub =
Arc::new(Subscription::new(&self.queue.queue.state, &self.key, Arc::new(move || woken.raise())));
Arc::clone(self.sub.insert(sub))
}
};
let (queue, key, mut seen) = (self.queue.queue.clone(), self.key.clone(), self.seen.take().unwrap_or_default());
let what = format!("{queue:?}: id {key:?}: a watch");
Box::pin(crate::aio::run::read(&self.queue.pool, what, move || {
let report = seen.read(&queue, &key, &sub);
Ok((seen, report))
}))
}
fn reported(&mut self, read: Result<(Seen<V>, Result<Report<V>>)>) -> Option<Option<Result<Job<V>>>> {
let report = read.and_then(|(seen, report)| {
self.seen = Some(seen);
report
});
match report {
Ok(Report::Same) => None,
Ok(Report::Changed(job)) => {
self.over = matches!(job.state, State::Done | State::Failed | State::Cancelled);
Some(Some(Ok(job)))
}
Ok(Report::Over) => {
self.over = true;
Some(None)
}
Err(error) => {
self.over = true;
Some(Some(Err(error)))
}
}
}
}
impl<V> fmt::Debug for Watch<V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Watch({:?}: id {:?})", self.queue, self.key)
}
}