use proc_macro2::TokenStream;
use quote::{quote, quote_spanned};
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::{Expr, ExprLit, FnArg, ImplItemFn, ItemImpl, Lit, Meta, Token, Type};
use crate::queue::{self, Provided};
use crate::syntax;
#[derive(Default)]
pub(crate) struct Options {
name: Option<syn::LitStr>,
setters: Vec<TokenStream>,
pub(crate) debounce_for: bool,
}
pub(crate) const NAMES: [&str; 9] = [
"name",
"queue",
"tries",
"max_errors",
"backoff",
"timeout",
"retry_for",
"debounce_for",
"max_wait",
];
const OPTIONS: &str = "`name`, `queue`, `tries`, `max_errors`, `backoff`, `timeout`, `retry_for`, `debounce_for`, \
`max_wait` or `fail_when_missing_models`";
impl Parse for Options {
fn parse(input: ParseStream) -> syn::Result<Self> {
let mut options = Self::default();
let mut seen = Vec::new();
let mut max_wait = None;
for option in Punctuated::<Meta, Token![,]>::parse_terminated(input)? {
if let Meta::Path(path) = &option
&& path.is_ident("fail_when_missing_models")
{
if seen.iter().any(|key| key == "fail_when_missing_models") {
return Err(syn::Error::new_spanned(
path,
"`fail_when_missing_models` is given twice",
));
}
options.setters.push(quote!(.fail_when_missing_models()));
seen.push("fail_when_missing_models".to_owned());
continue;
}
let Meta::NameValue(option) = option else {
return Err(syn::Error::new_spanned(
option,
format!("expected an option such as `tries = 3`: {OPTIONS}"),
));
};
let key = option.path.get_ident().map(ToString::to_string).unwrap_or_default();
if seen.contains(&key) {
return Err(syn::Error::new_spanned(&option.path, format!("`{key}` is given twice")));
}
let value = &option.value;
match key.as_str() {
"name" => options.name = Some(syntax::string(value, "name")?),
"queue" => {
let queue = syntax::string(value, "queue")?;
options.setters.push(quote!(.queue(#queue)));
}
"tries" => {
let tries = count(value, "tries = 3")?;
options.setters.push(quote!(.tries(#tries)));
}
"max_errors" => {
let errors = count(value, "max_errors = 3")?;
options.setters.push(quote!(.max_errors(#errors)));
}
"backoff" => {
let delays = match value {
Expr::Array(array) => array.elems.iter().collect(),
delay => vec![delay],
};
options
.setters
.push(quote_spanned!(value.span()=> .backoff([#(#delays),*])));
}
"timeout" => options.setters.push(quote_spanned!(value.span()=> .timeout(#value))),
"retry_for" => options.setters.push(quote_spanned!(value.span()=> .retry_for(#value))),
"debounce_for" => {
options.debounce_for = true;
options
.setters
.push(quote_spanned!(value.span()=> .debounce_for(#value)));
}
"max_wait" => {
max_wait = Some(option.path.span());
options.setters.push(quote_spanned!(value.span()=> .max_wait(#value)));
}
_ => {
return Err(syn::Error::new_spanned(
&option.path,
format!("unknown job option: expected {OPTIONS}"),
));
}
}
seen.push(key);
}
if let Some(max_wait) = max_wait.filter(|_| !options.debounce_for) {
return Err(syn::Error::new(
max_wait,
"`max_wait` limits how long a debounced dispatch waits: add `debounce_for`",
));
}
Ok(options)
}
}
impl Options {
pub(crate) const fn name(&self) -> Option<&syn::LitStr> {
self.name.as_ref()
}
pub(crate) fn items(&self, ident: &syn::Ident) -> TokenStream {
let name = syntax::registered_name(self.name(), ident);
let setters = &self.setters;
quote! {
const NAME: &'static str = #name;
fn options() -> ::laravel::queue::JobOptions {
#[allow(unused_imports)]
use ::laravel::time::ToSpan as _;
::laravel::queue::JobOptions::new() #(#setters)*
}
}
}
}
fn count<'a>(value: &'a Expr, example: &str) -> syn::Result<&'a syn::LitInt> {
match value {
Expr::Lit(ExprLit {
lit: Lit::Int(count), ..
}) if count.base10_parse::<u32>()? > 0 => Ok(count),
_ => {
let option = example.split(' ').next().unwrap_or_default();
Err(syn::Error::new_spanned(
value,
format!("`{option}` is a whole number of at least 1, such as `{example}`"),
))
}
}
}
pub(crate) fn expand(options: Options, implementation: ItemImpl) -> syn::Result<TokenStream> {
let ident = syntax::inherent_impl(&implementation, "job")?;
let ty = &implementation.self_ty;
let owner = quote!(<Self as ::laravel::queue::Job>::NAME);
let handler = syntax::consuming_method(&implementation, "handle")?
.ok_or_else(|| syn::Error::new_spanned(&implementation.self_ty, "a job requires an async `handle` method"))?;
let handle = queue::call(
quote!(<#ty>::handle),
quote!(self),
&handler.sig,
&[Provided::Attempt],
owner.clone(),
"`handle` takes `Inject<T>` services, `Section<T>` config sections and an `&Attempt`: a job's data belongs in its fields",
)?;
let failed = syntax::consuming_method(&implementation, "failed")?
.map(|failed| {
let call = queue::call(
quote!(<#ty>::failed),
quote!(self),
&failed.sig,
&[Provided::Attempt, Provided::Error],
owner,
"`failed` takes an `&laravel::Error`, `Inject<T>` services, `Section<T>` config sections and an `&Attempt`",
)?;
Ok::<_, syn::Error>(quote! {
async fn failed(
self,
__laravel_error: &::laravel::Error,
__laravel_attempt: &::laravel::queue::Attempt,
) -> ::laravel::Result<()> {
#call
}
})
})
.transpose()?;
let middleware = middleware(ty, &implementation)?;
let debounce_id = debounce_id(ty, &implementation, &options)?;
let items = options.items(ident);
Ok(quote! {
#implementation
impl ::laravel::queue::Job for #ty {
#items
#middleware
#debounce_id
async fn handle(self, __laravel_attempt: &::laravel::queue::Attempt) -> ::laravel::Result<()> {
#handle
}
#failed
}
impl #ty {
#[track_caller]
pub fn dispatch(self) -> ::laravel::queue::PendingDispatch<Self> {
::laravel::queue::dispatch(self)
}
#[track_caller]
pub fn dispatch_sync(self) -> impl ::std::future::Future<Output = ::laravel::Result<()>> + ::std::marker::Send {
::laravel::queue::dispatch_sync(self)
}
}
::laravel::__inventory::submit! {
::laravel::queue::__Registration::new::<#ty>()
}
})
}
fn middleware(ty: &Type, implementation: &ItemImpl) -> syn::Result<Option<TokenStream>> {
let Some(method) = borrowing_method(implementation, "middleware")? else {
return Ok(None);
};
let output = syntax::output_span(&method.sig);
let group = quote_spanned! {output=> ::laravel::queue::IntoMiddleware::into_group(__laravel_middleware)};
Ok(Some(quote! {
fn middleware(&self) -> ::laravel::queue::MiddlewareGroup {
let __laravel_middleware = <#ty>::middleware(self);
#group
}
}))
}
fn debounce_id(ty: &Type, implementation: &ItemImpl, options: &Options) -> syn::Result<Option<TokenStream>> {
let method = borrowing_method(implementation, "debounce_id")?;
if let Some(method) = method.filter(|_| !options.debounce_for) {
return Err(syn::Error::new_spanned(
&method.sig.ident,
"`debounce_id` tells a debounced job's dispatches apart: add `debounce_for` to `#[job(..)]`",
));
}
let Some(method) = method else {
return Ok(None);
};
let output = syntax::output_span(&method.sig);
let id = quote_spanned! {output=> ::std::string::ToString::to_string(&__laravel_id)};
Ok(Some(quote! {
fn debounce_id(&self) -> ::std::string::String {
let __laravel_id = <#ty>::debounce_id(self);
#id
}
}))
}
fn borrowing_method<'a>(implementation: &'a ItemImpl, name: &str) -> syn::Result<Option<&'a ImplItemFn>> {
let Some(method) = syntax::method(implementation, name) else {
return Ok(None);
};
let signature = &method.sig;
let takes_only_self = matches!(
signature.inputs.first(),
Some(FnArg::Receiver(receiver)) if receiver.reference.is_some() && receiver.mutability.is_none() && receiver.colon_token.is_none()
) && signature.inputs.len() == 1;
if signature.asyncness.is_some() || !syntax::is_plain(signature) || !takes_only_self {
return Err(syn::Error::new_spanned(
signature,
format!("`{name}` must be a safe, non-async method without generic parameters, taking only `&self`"),
));
}
Ok(Some(method))
}
#[cfg(test)]
mod tests {
use super::*;
fn error(options: &str, input: &str) -> String {
let options = match syn::parse_str::<Options>(options) {
Ok(options) => options,
Err(error) => return error.to_string(),
};
expand(options, syn::parse_str(input).unwrap()).unwrap_err().to_string()
}
#[test]
fn invalid_jobs_have_actionable_errors() {
for (options, input, expected) in [
("", "impl Example {}", "requires an async `handle`"),
("", "impl Example { fn handle(self) {} }", "safe async method"),
("", "impl Example { async fn handle(&self) {} }", "consume `self`"),
(
"",
"impl<T> Example<T> { async fn handle(self) {} }",
"without generic parameters",
),
("", "impl Job for Example { async fn handle(self) {} }", "inherent impl"),
(
"",
"impl Example { async fn handle(self, id: i64) {} }",
"belongs in its fields",
),
(
"",
"impl Example { async fn handle(self, a: &Attempt, b: &Attempt) {} }",
"at most one `&Attempt`",
),
(
"",
"impl Example { async fn handle(self) {} async fn failed(self, a: &Error, b: &Error) {} }",
"at most one `&laravel::Error`",
),
(
"",
"impl Example { async fn handle(self, error: &Error) {} }",
"belongs in its fields",
),
("tries = 0", "impl Example { async fn handle(self) {} }", "at least 1"),
(
"max_errors = 0",
"impl Example { async fn handle(self) {} }",
"`max_errors` is a whole number of at least 1",
),
(
"tries = \"3\"",
"impl Example { async fn handle(self) {} }",
"at least 1",
),
(
"queue = podcasts",
"impl Example { async fn handle(self) {} }",
"is a string",
),
(
"name = \"\"",
"impl Example { async fn handle(self) {} }",
"is a string",
),
(
"retries = 3",
"impl Example { async fn handle(self) {} }",
"unknown job option",
),
(
"tries = 1, tries = 2",
"impl Example { async fn handle(self) {} }",
"given twice",
),
(
"",
"impl Example { async fn handle(self) {} async fn middleware(&self) -> Throttle { Throttle } }",
"non-async method",
),
(
"",
"impl Example { async fn handle(self) {} fn middleware(self) -> Throttle { Throttle } }",
"taking only `&self`",
),
(
"",
"impl Example { async fn handle(self) {} fn middleware(&self, key: &str) -> Throttle { Throttle } }",
"taking only `&self`",
),
(
"after_commit",
"impl Example { async fn handle(self) {} }",
"expected an option",
),
(
"max_wait = 2.minutes()",
"impl Example { async fn handle(self) {} }",
"add `debounce_for`",
),
(
"",
"impl Example { async fn handle(self) {} fn debounce_id(&self) -> i64 { 1 } }",
"add `debounce_for`",
),
(
"debounce_for = 30.seconds()",
"impl Example { async fn handle(self) {} fn debounce_id(self) -> i64 { 1 } }",
"`debounce_id` must be a safe, non-async method",
),
] {
let error = error(options, input);
assert!(error.contains(expected), "{options} {input}: {error}");
}
}
}