use std::fmt;
use std::time::{Duration, SystemTime};
use serde::Serialize;
use serde::de::DeserializeOwned;
#[cfg(any(feature = "wire", feature = "sql", feature = "async"))]
use super::queue::Change;
use super::queue::Queue;
use super::repeat::Asked as Repeat;
use super::values::{self, Kept};
use super::write::Prepared;
use crate::clock::millis;
use crate::{Error, Result, Transaction, unix_millis};
const MAX_ID: usize = 1024;
const EARLIEST: i64 = -62_135_596_800_000;
const LATEST: i64 = 253_402_300_799_999;
pub(crate) fn in_years(at: i64) -> bool {
(EARLIEST..=LATEST).contains(&at)
}
pub(crate) const LONGEST_SPAN: i64 = LATEST - EARLIEST;
#[must_use = "a job's call runs at its last step: add, set or update"]
pub struct JobCall<'a, V> {
queue: &'a Queue<V>,
tx: Option<&'a Transaction<'a>>,
asked: Asked,
}
#[derive(Debug, Default)]
pub(crate) struct Asked {
id: Option<String>,
when: Option<When>,
group: Option<String>,
repeat: Option<Repeat>,
refused: Option<String>,
}
#[derive(Clone, Copy, Debug)]
enum When {
At(SystemTime),
After(Duration),
}
impl<'a, V> JobCall<'a, V>
where
V: Serialize + DeserializeOwned + Send + 'static,
{
pub(crate) fn new(queue: &'a Queue<V>, tx: Option<&'a Transaction<'a>>) -> Self {
JobCall { queue, tx, asked: Asked::default() }
}
pub fn id(mut self, id: impl AsRef<str>) -> Self {
self.asked.id = Some(id.as_ref().to_owned());
self
}
pub fn at(self, time: SystemTime) -> Self {
self.when(When::At(time))
}
pub fn delay(self, span: Duration) -> Self {
self.when(When::After(span))
}
pub fn group(mut self, group: impl AsRef<str>) -> Self {
self.asked.group = Some(group.as_ref().to_owned());
self
}
pub fn every(mut self, span: Duration) -> Self {
self.asked.repeat = Some(Repeat::Every(span));
self
}
pub fn cron(mut self, expr: &str, zone: &str) -> Self {
self.asked.repeat = Some(Repeat::Cron { expr: expr.to_owned(), zone: zone.to_owned() });
self
}
#[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) -> Result<bool> {
self.queue.add_asked(self.asked, value, self.tx)
}
pub fn set(self, value: &V) -> Result<()> {
self.queue.set_asked(self.asked, value, self.tx)
}
pub fn update(self, value: &V) -> Result<bool> {
self.queue.update_asked(self.asked, value, self.tx)
}
#[cfg(feature = "wire")]
pub(crate) fn write_then(self, change: Change, value: &V, done: impl FnOnce(Result<bool>) + Send + 'static) {
self.queue.write_then(change, self.asked, value, done);
}
#[cfg(feature = "async")]
pub(crate) fn writing(self, change: Change, value: &V) -> super::queue::Writing {
debug_assert!(self.tx.is_none(), "an awaited job's call is made outside a transaction");
self.queue.writing(change, self.asked, value)
}
#[cfg(feature = "sql")]
pub(crate) fn lent(self, change: Change, value: &V) -> Result<crate::engine::LentWrite> {
if self.tx.is_some() {
return Err(Error::invalid("a job's call made through a transaction runs in it, not in a batch"));
}
self.queue.lent(change, self.asked, value)
}
fn when(mut self, when: When) -> Self {
if self.asked.when.is_some() {
self.asked.refused = Some("a time given twice: at or delay, not both".to_owned());
}
self.asked.when = Some(when);
self
}
}
impl<V> fmt::Debug for JobCall<'_, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("JobCall").field("asked", &self.asked).finish()
}
}
impl Asked {
#[cfg(feature = "replication")]
pub(crate) fn write(&self, out: &mut crate::replication::Out) {
out.maybe_text(self.id.as_deref()).maybe_text(self.group.as_deref()).maybe_text(self.refused.as_deref());
match self.when {
None => out.byte(0),
Some(When::At(time)) => out.byte(1).long(unix_millis(time) as u64),
Some(When::After(span)) => out.byte(2).span(span),
};
match &self.repeat {
None => out.byte(0),
Some(repeat) => repeat.write(out),
};
}
#[cfg(feature = "replication")]
pub(crate) fn read(at: &mut crate::replication::In<'_>) -> Result<Asked> {
let (id, group, refused) = (at.maybe_text()?, at.maybe_text()?, at.maybe_text()?);
let when = match at.byte()? {
0 => None,
1 => Some(When::At(crate::clock::from_unix_millis(at.long()? as i64))),
2 => Some(When::After(at.span()?)),
_ => return Err(super::forward::corrupt("a job's time")),
};
let repeat = match at.byte()? {
0 => None,
tag => Some(Repeat::read(tag, at)?),
};
Ok(Asked { id, when, group, repeat, refused })
}
pub(crate) fn with_id(id: &str) -> Asked {
Asked { id: Some(id.to_owned()), ..Asked::default() }
}
pub(crate) fn id(&self) -> Option<&str> {
self.id.as_deref()
}
pub(crate) fn prepare<V: Serialize>(self, value: &V, now: i64) -> Result<Prepared> {
if let Some(refused) = self.refused {
return Err(Error::invalid(refused));
}
for (what, text) in [("an id", &self.id), ("a group", &self.group)] {
if let Some(text) = text
&& (text.is_empty() || text.len() > MAX_ID)
{
return Err(Error::invalid(format!("{what} of {} bytes, not 1 to {MAX_ID}", text.len())));
}
}
let repeat = match (&self.repeat, &self.id) {
(Some(_), None) => return Err(Error::invalid("a repeat without an id, which alone could stop it")),
(Some(repeat), Some(id)) => Some(repeat.of(id)?),
(None, _) => None,
};
let at = match self.when {
Some(When::At(time)) => unix_millis(time),
Some(When::After(span)) => now.saturating_add(millis(span)),
None => repeat.as_ref().and_then(|repeat| repeat.next(now)).unwrap_or(now),
};
if !in_years(at) {
return Err(Error::invalid("a time outside the years 1 to 9999"));
}
Ok(Prepared {
key: self.id,
at,
timed: self.when.is_some(),
repeat: repeat.map(|repeat| repeat.text()),
group: self.group,
value: Kept::of(values::encode(value)?),
now,
})
}
}