use std::fmt;
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime};
use serde::Serialize;
use serde::de::DeserializeOwned;
use super::claim::{How, Lease};
use super::engine::Jobs;
use super::state::QueueState;
use super::steps;
use crate::clock::{from_unix_millis, millis};
use crate::limits::PROGRESS_BYTES;
use crate::{Error, Result, unix_millis};
const MAX_PROGRESS: usize = PROGRESS_BYTES.bound as usize;
pub struct Run {
pub(crate) lease: Arc<Lease>,
pub(crate) queue: Arc<QueueState>,
pub(crate) jobs: Arc<Jobs>,
deadline: Instant,
}
impl Run {
pub(crate) fn new(lease: Arc<Lease>, queue: Arc<QueueState>, jobs: Arc<Jobs>) -> Run {
let deadline = Instant::now() + queue.policy.timeout;
Run { lease, queue, jobs, deadline }
}
pub fn id(&self) -> Option<&str> {
self.lease.key.as_deref()
}
pub fn at(&self) -> SystemTime {
from_unix_millis(self.lease.at)
}
pub fn attempt(&self) -> u32 {
u32::try_from(self.lease.attempt).unwrap_or(u32::MAX)
}
pub fn group(&self) -> Option<&str> {
self.lease.group.as_deref()
}
pub fn stopped(&self) -> bool {
self.lease.cancelled() || Instant::now() >= self.deadline
}
pub fn set_progress(&self, progress: &impl Serialize) -> Result<()> {
let value = serde_json::to_value(progress)
.map_err(|error| Error::invalid("a progress JSON cannot write").with_source(error))?;
let size = serde_json::to_vec(&value).map_or(0, |bytes| bytes.len());
if size > MAX_PROGRESS {
let refused =
PROGRESS_BYTES.refuse(size as u64, format!("a progress of {size} bytes, past {MAX_PROGRESS}"));
return Err(refused.within(self.describe()));
}
self.lease.set_progress(value);
self.queue.watchers.changed();
Ok(())
}
pub fn step<T, E>(&self, name: &str, work: impl FnOnce() -> Result<T, E>) -> Result<T, E>
where
T: Serialize + DeserializeOwned,
E: From<Error>,
{
steps::run(self, name, work)
}
#[must_use = "an answer does nothing unless the handler returns it"]
pub fn done(&self) -> Outcome {
Outcome(Answer::Done)
}
#[must_use = "an answer does nothing unless the handler returns it"]
pub fn retry(&self, when: impl Into<When>) -> Outcome {
Outcome(Answer::Retry(when.into()))
}
#[must_use = "an answer does nothing unless the handler returns it"]
pub fn snooze(&self, when: impl Into<When>) -> Outcome {
Outcome(Answer::Snooze(when.into()))
}
#[must_use = "an answer does nothing unless the handler returns it"]
pub fn fail(&self, reason: impl fmt::Display) -> Outcome {
Outcome(Answer::Fail(reason.to_string()))
}
pub(crate) fn describe(&self) -> String {
described(&self.queue, &self.lease)
}
}
pub(crate) fn described(queue: &QueueState, lease: &Lease) -> String {
match &lease.key {
Some(key) => format!("{}: id {key:?}", queue.describe()),
None => queue.describe(),
}
}
impl fmt::Debug for Run {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Run")
.field("queue", &self.queue.name)
.field("id", &self.lease.key)
.field("attempt", &self.lease.attempt)
.finish()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum When {
After(Duration),
At(SystemTime),
}
impl From<Duration> for When {
fn from(span: Duration) -> When {
When::After(span)
}
}
impl From<SystemTime> for When {
fn from(time: SystemTime) -> When {
When::At(time)
}
}
impl When {
fn at(self, now: i64) -> i64 {
match self {
When::After(span) => now.saturating_add(millis(span)),
When::At(time) => unix_millis(time),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Outcome(Answer);
#[derive(Clone, Debug, PartialEq, Eq)]
enum Answer {
Done,
Retry(When),
Snooze(When),
Fail(String),
}
impl From<()> for Outcome {
fn from((): ()) -> Outcome {
Outcome(Answer::Done)
}
}
impl Outcome {
pub(crate) fn fail_with(cause: String) -> Outcome {
Outcome(Answer::Fail(cause))
}
pub(crate) fn how(self, now: i64) -> How {
let how = match self.0 {
Answer::Done => How::Done,
Answer::Retry(when) => {
How::Retry { at: Some(when.at(now)), cause: "the handler asked to retry".to_owned() }
}
Answer::Snooze(when) => How::Snooze { at: when.at(now) },
Answer::Fail(cause) => How::Fail { cause },
};
match how.outside_years() {
Some(at) => {
let cause = format!("the handler answered a time outside the years 1 to 9999, {at} in unix ms");
How::Retry { at: None, cause }
}
None => how,
}
}
}