use std::collections::HashMap;
use std::fmt;
use std::future::Future;
use std::str::FromStr;
use std::sync::{Arc, LazyLock};
use std::time::Duration;
use futures_util::future::BoxFuture;
use jiff::ZonedDateTimeArithmetic;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use super::{Attempt, MiddlewareGroup, Queueable};
use crate::time::ExactDuration;
use crate::{Error, Result};
pub trait Job: Queueable {
const NAME: &'static str;
#[must_use]
fn options() -> JobOptions {
JobOptions::new()
}
#[must_use]
fn middleware(&self) -> MiddlewareGroup {
MiddlewareGroup::new()
}
#[must_use]
fn debounce_id(&self) -> String {
String::new()
}
fn handle(self, attempt: &Attempt) -> impl Future<Output = Result<()>> + Send;
fn failed(self, error: &Error, attempt: &Attempt) -> impl Future<Output = Result<()>> + Send {
let _ = (error, attempt);
async { Ok(()) }
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct JobOptions {
pub queue: Option<&'static str>,
pub tries: Option<u32>,
pub max_errors: Option<u32>,
pub backoff: Vec<ExactDuration>,
pub timeout: Option<ExactDuration>,
pub retry_for: Option<ExactDuration>,
pub debounce_for: Option<ExactDuration>,
pub max_wait: Option<ExactDuration>,
pub fail_when_missing_models: bool,
}
impl JobOptions {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub const fn queue(mut self, queue: &'static str) -> Self {
self.queue = Some(queue);
self
}
#[must_use]
pub fn tries(mut self, tries: u32) -> Self {
self.tries = Some(tries.max(1));
self
}
#[must_use]
pub fn max_errors(mut self, errors: u32) -> Self {
self.max_errors = Some(errors.max(1));
self
}
#[must_use]
pub fn backoff(mut self, delays: impl IntoIterator<Item = impl Into<ZonedDateTimeArithmetic>>) -> Self {
self.backoff = delays
.into_iter()
.map(|delay| crate::clock::exact_duration(delay).into())
.collect();
self
}
#[must_use]
pub fn timeout(mut self, timeout: impl Into<ZonedDateTimeArithmetic>) -> Self {
self.timeout = Some(crate::clock::exact_duration(timeout).into());
self
}
#[must_use]
pub fn retry_for(mut self, lifetime: impl Into<ZonedDateTimeArithmetic>) -> Self {
self.retry_for = Some(crate::clock::exact_duration(lifetime).into());
self
}
#[must_use]
pub fn debounce_for(mut self, delay: impl Into<ZonedDateTimeArithmetic>) -> Self {
self.debounce_for = Some(crate::clock::exact_duration(delay).into());
self
}
#[must_use]
pub fn max_wait(mut self, wait: impl Into<ZonedDateTimeArithmetic>) -> Self {
self.max_wait = Some(crate::clock::exact_duration(wait).into());
self
}
#[must_use]
pub const fn fail_when_missing_models(mut self) -> Self {
self.fail_when_missing_models = true;
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct JobId(uuid::Uuid);
impl JobId {
pub(crate) fn generate() -> Self {
Self(crate::str::uuid7())
}
pub(crate) const fn into_uuid(self) -> uuid::Uuid {
self.0
}
}
impl fmt::Display for JobId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.hyphenated().fmt(f)
}
}
impl FromStr for JobId {
type Err = ParseIdError;
fn from_str(id: &str) -> Result<Self, Self::Err> {
id.parse().map(Self).map_err(ParseIdError)
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("the ID isn't a UUID")]
pub struct ParseIdError(
#[source]
#[doc(hidden)]
pub uuid::Error,
);
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub struct JobTimedOut {
after: Duration,
}
impl JobTimedOut {
pub(crate) const fn new(after: Duration) -> Self {
Self { after }
}
#[must_use]
pub fn after(&self) -> ExactDuration {
self.after.into()
}
}
impl fmt::Display for JobTimedOut {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "the job ran longer than its timeout of {}", self.after())
}
}
#[diagnostic::on_unimplemented(
message = "`{Self}` isn't a job or callback method's return type",
label = "return `()` or `laravel::Result<()>`",
note = "`?` converts other errors into a `laravel::Error`, and the method ends with `Ok(())`"
)]
pub trait JobResult: sealed::Result {
#[doc(hidden)]
fn into_result(self) -> Result<()>;
}
impl JobResult for () {
fn into_result(self) -> Result<()> {
Ok(())
}
}
impl JobResult for Result<()> {
fn into_result(self) -> Result<()> {
self
}
}
mod sealed {
pub trait Result {}
impl Result for () {}
impl Result for crate::Result<()> {}
}
type Run = fn(Value, Arc<Attempt>) -> BoxFuture<'static, Result<BoxFuture<'static, Result<()>>>>;
type Failed = for<'a> fn(Value, &'a Error, &'a Attempt) -> BoxFuture<'a, Result<BoxFuture<'a, Result<()>>>>;
#[doc(hidden)]
#[derive(Debug)]
pub struct __Registration {
name: &'static str,
pub(crate) type_name: fn() -> &'static str,
options: fn() -> JobOptions,
run: Run,
failed: Failed,
}
impl __Registration {
#[must_use]
pub const fn new<J: Job>() -> Self {
Self {
name: J::NAME,
type_name: std::any::type_name::<J>,
options: J::options,
run: run::<J>,
failed: failed::<J>,
}
}
}
impl __Registration {
pub(crate) fn find(name: &str) -> Result<&'static Self> {
registry().get(name).copied().ok_or_else(|| {
crate::error::fail(format!(
"no job named `{name}` is registered: was it renamed, or removed, after it was dispatched?"
))
})
}
pub(crate) const fn name(&self) -> &'static str {
self.name
}
pub(crate) fn options(&self) -> JobOptions {
(self.options)()
}
pub(crate) fn run(
&self,
data: Value,
attempt: Arc<Attempt>,
) -> BoxFuture<'static, Result<BoxFuture<'static, Result<()>>>> {
(self.run)(data, attempt)
}
pub(crate) fn failed<'a>(
&self,
data: Value,
error: &'a Error,
attempt: &'a Attempt,
) -> BoxFuture<'a, Result<BoxFuture<'a, Result<()>>>> {
(self.failed)(data, error, attempt)
}
}
inventory::collect!(__Registration);
fn run<J: Job>(data: Value, attempt: Arc<Attempt>) -> BoxFuture<'static, Result<BoxFuture<'static, Result<()>>>> {
Box::pin(async move {
let job = restore::<J>(data).await?;
Ok(Box::pin(async move {
let middleware = job.middleware();
let handle = {
let attempt = Arc::clone(&attempt);
Box::pin(async move {
if let Some(id) = attempt.debounce_id() {
super::debounce::running(J::NAME, id).await;
}
job.handle(&attempt).await
})
};
middleware.run(attempt, handle).await
}) as BoxFuture<'static, Result<()>>)
})
}
fn failed<'a, J: Job>(
data: Value,
error: &'a Error,
attempt: &'a Attempt,
) -> BoxFuture<'a, Result<BoxFuture<'a, Result<()>>>> {
Box::pin(async move {
let job = restore::<J>(data).await?;
Ok(Box::pin(job.failed(error, attempt)) as BoxFuture<'a, Result<()>>)
})
}
pub(crate) async fn restore<J: Job>(data: Value) -> Result<J> {
J::__restore(data)
.await
.map_err(|error| super::queueable::restore_error("job", J::NAME, error))
}
fn registry() -> &'static HashMap<&'static str, &'static __Registration> {
static REGISTRY: LazyLock<HashMap<&'static str, &'static __Registration>> = LazyLock::new(|| {
inventory::iter::<__Registration>
.into_iter()
.map(|registration| (registration.name, registration))
.collect()
});
®ISTRY
}
pub(crate) fn check_names() -> Result<(), String> {
duplicate_names(
"jobs",
"#[job(name = \"..\")]",
inventory::iter::<__Registration>
.into_iter()
.map(|registration| (registration.name, (registration.type_name)())),
)
}
pub fn duplicate_names<'a>(
kind: &str,
rename: &str,
types: impl Iterator<Item = (&'a str, &'a str)>,
) -> Result<(), String> {
let mut named: HashMap<&str, Vec<&str>> = HashMap::new();
for (name, ty) in types {
named.entry(name).or_default().push(ty);
}
let mut duplicates: Vec<_> = named.into_iter().filter(|(_, types)| types.len() > 1).collect();
duplicates.sort_unstable();
match duplicates.first() {
None => Ok(()),
Some((name, types)) => Err(format!(
"the {kind} {} are all named `{name}`: give each its own `{rename}`",
types
.iter()
.map(|ty| format!("`{ty}`"))
.collect::<Vec<_>>()
.join(" and "),
)),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn names_shared_by_several_jobs_are_rejected() {
let rename = "#[job(name = \"..\")]";
assert_eq!(
duplicate_names("jobs", rename, [("a", "app::A"), ("b", "app::B")].into_iter()),
Ok(())
);
let error = duplicate_names(
"jobs",
rename,
[("send", "app::Send"), ("ship", "app::Ship"), ("send", "billing::Send")].into_iter(),
)
.unwrap_err();
assert_eq!(
error,
"the jobs `app::Send` and `billing::Send` are all named `send`: give each its own `#[job(name = \"..\")]`"
);
}
}