use std::collections::VecDeque;
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll, ready};
use std::time::{Duration, SystemTime};
use futures_core::Stream;
use serde::Serialize;
use serde::de::DeserializeOwned;
use super::run::Run;
use crate::jobs::{self, Change, Concurrency, Counts, Filter, Job, JobRef, Lease, Outcome, Page, Took};
use crate::pool::Pool;
use crate::{ErrorKind, Result, Transaction, TxHandle};
#[must_use = "a queue opens with open()"]
pub struct QueueBuilder<V> {
builder: jobs::QueueBuilder<V>,
pool: Arc<Pool>,
}
impl<V> fmt::Debug for QueueBuilder<V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.builder, f)
}
}
impl<V> QueueBuilder<V>
where
V: Serialize + DeserializeOwned + Send + 'static,
{
pub(crate) fn new(builder: jobs::QueueBuilder<V>, pool: Arc<Pool>) -> Self {
QueueBuilder { builder, pool }
}
fn with(self, option: impl FnOnce(jobs::QueueBuilder<V>) -> jobs::QueueBuilder<V>) -> Self {
QueueBuilder { builder: option(self.builder), pool: self.pool }
}
pub fn attempts(self, attempts: u32) -> Self {
self.with(|builder| builder.attempts(attempts))
}
pub fn backoff(self, initial: Duration, max: Duration) -> Self {
self.with(|builder| builder.backoff(initial, max))
}
pub fn timeout(self, timeout: Duration) -> Self {
self.with(|builder| builder.timeout(timeout))
}
pub fn concurrency(self, concurrency: impl Into<Concurrency>) -> Self {
let concurrency = concurrency.into();
self.with(|builder| builder.concurrency(concurrency))
}
pub fn rate(self, count: u32, per: Duration) -> Self {
self.with(|builder| builder.rate(count, per))
}
pub fn dedupe(self, span: Duration) -> Self {
self.with(|builder| builder.dedupe(span))
}
pub fn keep(self, span: Duration) -> Self {
self.with(|builder| builder.keep(span))
}
pub fn max_waiting(self, jobs: u64) -> Self {
self.with(|builder| builder.max_waiting(jobs))
}
pub fn open(self) -> Result<Queue<V>> {
Ok(Queue { queue: self.builder.open()?, pool: self.pool })
}
}
pub struct Queue<V> {
pub(super) queue: jobs::Queue<V>,
pub(super) pool: Arc<Pool>,
}
impl<V> Clone for Queue<V> {
fn clone(&self) -> Self {
Queue { queue: self.queue.clone(), pool: Arc::clone(&self.pool) }
}
}
impl<V> fmt::Debug for Queue<V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.queue, f)
}
}
impl<V> From<jobs::Queue<V>> for Queue<V> {
fn from(queue: jobs::Queue<V>) -> Queue<V> {
let pool = super::pool_of(&queue);
Queue { queue, pool }
}
}
impl<V> Queue<V> {
pub fn blocking(&self) -> &jobs::Queue<V> {
&self.queue
}
}
impl<V> Queue<V>
where
V: Serialize + DeserializeOwned + Send + 'static,
{
pub fn add(&self, value: &V) -> impl Future<Output = Result<bool>> + Send + 'static {
self.call().add(value)
}
pub fn set(&self, id: impl AsRef<str>, value: &V) -> impl Future<Output = Result<()>> + Send + 'static {
self.id(id).set(value)
}
pub fn update(&self, id: impl AsRef<str>, value: &V) -> impl Future<Output = Result<bool>> + Send + 'static {
self.id(id).update(value)
}
pub fn cancel(&self, job: impl JobRef) -> impl Future<Output = Result<bool>> + Send + 'static {
let (queue, which) = (self.queue.clone(), job.which());
let what = match &which {
Some(which) => format!("{queue:?}: {}: a cancel", which.describe()),
None => format!("{queue:?}: a cancel"),
};
crate::aio::run::write(&self.pool, what, move |answer| match which {
Some(which) => queue.cancel_then(which, move |found| answer.send(found)),
None => answer.send(Ok(false)),
})
}
pub fn counts(&self) -> impl Future<Output = Result<Counts>> + Send + 'static {
let queue = self.queue.clone();
crate::aio::run::read(&self.pool, format!("{queue:?}: a count"), move || queue.counts())
}
pub fn get(&self, id: impl AsRef<str>) -> impl Future<Output = Result<Option<Job<V>>>> + Send + 'static {
let (queue, id) = (self.queue.clone(), id.as_ref().to_owned());
crate::aio::run::read(&self.pool, format!("{queue:?}: id {id:?}: a get"), move || queue.get(&id))
}
pub fn list(&self, filter: &Filter) -> impl Future<Output = Result<Page<V>>> + Send + 'static {
let (queue, filter) = (self.queue.clone(), filter.clone());
crate::aio::run::read(&self.pool, format!("{queue:?}: a list"), move || queue.list(&filter))
}
fn walked(&self, filter: &Filter) -> Reading<V> {
let (queue, filter) = (self.queue.clone(), filter.clone());
let page = move || queue.read_page(&filter).map(|page| (page.jobs, page.next));
Box::pin(crate::aio::run::read(&self.pool, format!("{:?}: a list", self.queue), page))
}
pub fn all(&self, filter: Filter) -> All<V> {
All { queue: self.clone(), filter: Some(filter), page: VecDeque::new(), reading: None }
}
pub fn id(&self, id: impl AsRef<str>) -> JobCall<'_, V> {
JobCall { call: self.queue.id(id), queue: self }
}
pub fn at(&self, time: SystemTime) -> JobCall<'_, V> {
JobCall { call: self.queue.at(time), queue: self }
}
pub fn delay(&self, span: Duration) -> JobCall<'_, V> {
JobCall { call: self.queue.delay(span), queue: self }
}
pub fn group(&self, group: impl AsRef<str>) -> JobCall<'_, V> {
JobCall { call: self.queue.group(group), queue: self }
}
fn call(&self) -> JobCall<'_, V> {
JobCall { call: jobs::JobCall::new(&self.queue, None), queue: self }
}
pub fn claim(&self) -> impl Future<Output = Result<Option<Claimed<V>>>> + Send + 'static {
let queue = self.clone();
async move {
loop {
let (run, unhanded) = match queue.claim_one().await? {
Taken::Job(run, unhanded) => (run, unhanded),
Taken::More => continue,
Taken::Nothing => return Ok(None),
};
let value = run.value::<V>().await;
unhanded.handed();
let value = match value {
Ok(value) => value,
Err(error) if error.kind() == ErrorKind::Invalid => {
Claimed { value: (), run }.settle(Outcome::fail_with(error.to_string())).await?;
continue;
}
Err(error) => return Err(queue.queue.fail(run.id(), error)),
};
if run.begin() {
return Ok(Some(Claimed { value, run }));
}
}
}
}
fn claim_one(&self) -> impl Future<Output = Result<Taken>> + Send + 'static + use<V> {
let (claiming, giving, what) = (self.queue.clone(), self.clone(), format!("{:?}: a claim", self.queue));
crate::aio::run::write(&self.pool, what, move |answer| {
claiming.claim_then(move |took| answer.send(took.map(|took| Taken::of(&giving, took))));
})
}
}
enum Taken {
Job(Run, Unhanded),
More,
Nothing,
}
impl Taken {
fn of<V>(queue: &Queue<V>, took: Took) -> Taken {
match took {
Took::Job(lease) => {
let run = Run::of(queue, lease);
let unhanded = Unhanded::of(&run);
Taken::Job(run, unhanded)
}
Took::More => Taken::More,
Took::Nothing => Taken::Nothing,
}
}
}
struct Unhanded(Option<(Arc<Lease>, jobs::Settling, Arc<Pool>)>);
impl Unhanded {
fn of(run: &Run) -> Unhanded {
let back = jobs::Settling::given_back(&run.run);
Unhanded(Some((Arc::clone(&run.run.lease), back, Arc::clone(&run.pool))))
}
fn handed(mut self) {
self.0 = None;
}
}
impl Drop for Unhanded {
fn drop(&mut self) {
let Some((lease, back, pool)) = self.0.take() else { return };
if !lease.cancelled() {
crate::polled::leading_on(&crate::aio::run::lead_on(&pool), || back.submit(drop));
}
}
}
impl<V> crate::transaction::sealed::Sealed for Queue<V> {}
impl<V> TxHandle for Queue<V>
where
V: Serialize + DeserializeOwned + Send + 'static,
{
type InTx<'t>
= jobs::TxQueue<'t, V>
where
Self: 't;
fn in_tx<'t>(&'t self, tx: &'t Transaction<'t>) -> jobs::TxQueue<'t, V> {
self.queue.in_tx(tx)
}
}
#[must_use = "a job's call runs at its last step: add, set or update"]
pub struct JobCall<'a, V> {
call: jobs::JobCall<'a, V>,
queue: &'a Queue<V>,
}
impl<V> fmt::Debug for JobCall<'_, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.call, f)
}
}
impl<'a, V> JobCall<'a, V>
where
V: Serialize + DeserializeOwned + Send + 'static,
{
fn with(self, step: impl FnOnce(jobs::JobCall<'a, V>) -> jobs::JobCall<'a, V>) -> Self {
JobCall { call: step(self.call), queue: self.queue }
}
pub fn id(self, id: impl AsRef<str>) -> Self {
self.with(|call| call.id(id))
}
pub fn at(self, time: SystemTime) -> Self {
self.with(|call| call.at(time))
}
pub fn delay(self, span: Duration) -> Self {
self.with(|call| call.delay(span))
}
pub fn group(self, group: impl AsRef<str>) -> Self {
self.with(|call| call.group(group))
}
pub fn every(self, span: Duration) -> Self {
self.with(|call| call.every(span))
}
pub fn cron(self, expr: &str, zone: &str) -> Self {
self.with(|call| call.cron(expr, zone))
}
#[expect(clippy::should_implement_trait, reason = "a queue's add puts a job in it, as BullMQ's does: no sum")]
pub fn add(self, value: &V) -> impl Future<Output = Result<bool>> + Send + 'static {
self.write(Change::Add, "an add", value)
}
pub fn set(self, value: &V) -> impl Future<Output = Result<()>> + Send + 'static {
let written = self.write(Change::Set, "a set", value);
async move { written.await.map(drop) }
}
pub fn update(self, value: &V) -> impl Future<Output = Result<bool>> + Send + 'static {
self.write(Change::Update, "an update", value)
}
#[cfg(feature = "sql")]
pub(crate) fn into_blocking(self) -> jobs::JobCall<'a, V> {
self.call
}
fn write(self, change: Change, what: &str, value: &V) -> impl Future<Output = Result<bool>> + Send + 'static {
let what = format!("{:?}: {what}", self.queue.queue);
let writing = self.call.writing(change, value);
crate::aio::run::write(&self.queue.pool, what, move |answer| {
writing.submit(move |written| answer.send(written))
})
}
}
pub struct Claimed<V> {
pub value: V,
run: Run,
}
impl<V> Claimed<V> {
pub fn run(&self) -> &Run {
&self.run
}
pub fn settle(self, outcome: impl Into<Outcome>) -> impl Future<Output = Result<()>> + Send + 'static {
let settling = jobs::Settling::of(&self.run.run, outcome.into());
let (pool, what) = (Arc::clone(&self.run.pool), format!("{}: a settlement", self.run.run.describe()));
async move {
crate::aio::run::write(&pool, what, move |answer| settling.submit(move |settled| answer.send(settled)))
.await
}
}
}
impl<V: fmt::Debug> fmt::Debug for Claimed<V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Claimed").field("value", &self.value).field("run", &self.run).finish()
}
}
pub struct All<V> {
queue: Queue<V>,
filter: Option<Filter>,
page: VecDeque<Result<Job<V>>>,
reading: Option<(Filter, Reading<V>)>,
}
type Reading<V> = Pin<Box<dyn Future<Output = Result<(Vec<Result<Job<V>>>, Option<String>)>> + Send>>;
impl<V> Unpin for All<V> {}
impl<V> Stream for All<V>
where
V: Serialize + DeserializeOwned + Send + 'static,
{
type Item = Result<Job<V>>;
fn poll_next(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let all = self.get_mut();
loop {
if let Some(job) = all.page.pop_front() {
return Poll::Ready(Some(job));
}
let (filter, reading) = match &mut all.reading {
Some(reading) => reading,
None => {
let Some(filter) = all.filter.take() else {
return Poll::Ready(None);
};
let reading = all.queue.walked(&filter);
all.reading.insert((filter, reading))
}
};
let page = ready!(reading.as_mut().poll(context));
let filter = filter.clone();
all.reading = None;
match page {
Ok((jobs, next)) => {
all.filter = next.map(|next| filter.after(next));
all.page.extend(jobs);
}
Err(error) => return Poll::Ready(Some(Err(error))),
}
}
}
}
impl<V> fmt::Debug for All<V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("All").field("queue", &self.queue).finish()
}
}
#[cfg(test)]
#[path = "queue_tests.rs"]
mod tests;