laravel-rust-queue-macros 0.1.0

Laravel for Rust's procedural macros for jobs, events, notifications and workflows, re-exported by `laravel-rust`
Documentation
use proc_macro2::TokenStream;
use quote::{ToTokens, format_ident, quote};
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::{FnArg, ItemFn, ItemImpl, Meta, Token, Type};

use crate::queue::{self, Provided};
use crate::syntax::{self, FnOrImpl, is_dependency, is_reference_to};

#[derive(Default)]
pub(crate) struct Options {
    name: Option<syn::LitStr>,
    fail_when_missing_models: bool,
}

const OPTIONS: &str =
    "`callback` takes a name and `fail_when_missing_models`, such as `#[callback(name = \"imports.finished\")]`";

impl Parse for Options {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut options = Self::default();
        for option in Punctuated::<Meta, Token![,]>::parse_terminated(input)? {
            let given = match &option {
                Meta::NameValue(name) if name.path.is_ident("name") => {
                    options.name.replace(syntax::string(&name.value, "name")?).is_some()
                }
                Meta::Path(path) if path.is_ident("fail_when_missing_models") => {
                    std::mem::replace(&mut options.fail_when_missing_models, true)
                }
                option => return Err(syn::Error::new_spanned(option, OPTIONS)),
            };
            if given {
                return Err(syn::Error::new_spanned(
                    option.path(),
                    format!("`{}` is given twice", option.path().to_token_stream()),
                ));
            }
        }

        Ok(options)
    }
}

pub(crate) fn expand_item(options: Options, item: FnOrImpl) -> syn::Result<TokenStream> {
    match item {
        FnOrImpl::Impl(implementation) => expand(options, implementation),
        FnOrImpl::Fn(function) => expand_function(options, function),
    }
}

fn expand_function(options: Options, mut function: ItemFn) -> syn::Result<TokenStream> {
    let signature = &function.sig;
    syntax::require_async(
        signature,
        "a callback must be a safe async function without generic parameters",
    )?;

    let mut captures = Vec::new();
    let mut fields = Vec::new();
    let mut runtime = Vec::new();
    let mut arguments = Vec::new();
    let mut batch = false;
    let mut error = false;
    for (index, input) in signature.inputs.iter().enumerate() {
        let FnArg::Typed(argument) = input else {
            return Err(syn::Error::new_spanned(input, "a callback function can't take `self`"));
        };
        let ty = &argument.ty;
        let binding = format_ident!("__laravel_argument_{index}");
        if is_reference_to(ty, "Batch") {
            if std::mem::replace(&mut batch, true) {
                return Err(syn::Error::new_spanned(
                    argument,
                    "a callback takes at most one `&Batch`",
                ));
            }
            runtime.push(quote!(#binding: #ty));
        } else if is_reference_to(ty, "Error") {
            if std::mem::replace(&mut error, true) {
                return Err(syn::Error::new_spanned(
                    argument,
                    "a callback takes at most one `&Error`",
                ));
            }
            runtime.push(quote!(#binding: #ty));
        } else if is_dependency(ty) {
            runtime.push(quote!(#binding: #ty));
        } else {
            if contains_reference(ty) {
                return Err(syn::Error::new_spanned(
                    ty,
                    "callback captures must be owned and serializable: use `String` instead of `&str`, or an owned value instead of a reference",
                ));
            }
            captures.push(quote!(#ty));
            fields.push(binding.clone());
        }
        arguments.push(quote!(#binding));
    }

    let (visibility, documentation) = syntax::take_visibility_and_docs(&mut function);
    let name = function.sig.ident.clone();
    let output = function.sig.output.to_token_stream();
    let definition = quote! {
        #(#documentation)*
        #[expect(non_camel_case_types, reason = "callback constructors use their function's name")]
        #[derive(::laravel::queue::Queueable)]
        #visibility struct #name(#(#visibility #captures),*);
    };
    function.sig.ident = format_ident!("__laravel_call", span = name.span());

    let methods: Vec<_> = if error { vec!["catch"] } else { vec!["then", "finally"] }
        .into_iter()
        .map(|method| {
            let method = format_ident!("{method}");
            quote! {
                async fn #method(self, #(#runtime),*) #output {
                    let Self(#(#fields),*) = self;
                    Self::__laravel_call(#(#arguments),*).await
                }
            }
        })
        .collect();
    let implementation = syn::parse2(quote! {
        impl #name {
            #[doc(hidden)]
            #function
            #(#methods)*
        }
    })?;
    let expanded = expand(options, implementation)?;

    Ok(quote! {
        #definition
        #expanded
    })
}

fn contains_reference(ty: &Type) -> bool {
    match ty {
        Type::Reference(_) => true,
        Type::Array(array) => contains_reference(&array.elem),
        Type::Slice(slice) => contains_reference(&slice.elem),
        Type::Tuple(tuple) => tuple.elems.iter().any(contains_reference),
        Type::Paren(paren) => contains_reference(&paren.elem),
        Type::Group(group) => contains_reference(&group.elem),
        Type::Path(path) => path.path.segments.iter().any(|segment| match &segment.arguments {
            syn::PathArguments::AngleBracketed(arguments) => arguments
                .args
                .iter()
                .any(|argument| matches!(argument, syn::GenericArgument::Type(ty) if contains_reference(ty))),
            _ => false,
        }),
        _ => false,
    }
}

pub(crate) fn expand(options: Options, implementation: ItemImpl) -> syn::Result<TokenStream> {
    let ident = syntax::inherent_impl(&implementation, "callback")?;
    let ty = &implementation.self_ty;

    let then = syntax::consuming_method(&implementation, "then")?;
    let catch = syntax::consuming_method(&implementation, "catch")?;
    let finally = syntax::consuming_method(&implementation, "finally")?;
    let owner = quote!(<Self as ::laravel::queue::Callback>::NAME);
    if then.is_none() && catch.is_none() && finally.is_none() {
        return Err(syn::Error::new_spanned(
            &implementation.self_ty,
            "a callback requires an async `then`, `catch` or `finally` method",
        ));
    }

    let mut impls = Vec::new();
    let mut registrations = Vec::new();
    if let Some(then) = then {
        let call = queue::call(
            quote!(<#ty>::then),
            quote!(self),
            &then.sig,
            &[Provided::Batch],
            owner.clone(),
            "`then` takes a `&Batch`, `Inject<T>` services and `Section<T>` config sections: a callback's data belongs in its fields",
        )?;
        impls.push(quote! {
            impl ::laravel::queue::Then for #ty {
                async fn then(self, __laravel_batch: &::laravel::queue::Batch) -> ::laravel::Result<()> {
                    #call
                }
            }
        });
        registrations.push(quote!(.then::<#ty>()));
    }
    if let Some(catch) = catch {
        let call = queue::call(
            quote!(<#ty>::catch),
            quote!(self),
            &catch.sig,
            &[Provided::Batch, Provided::Error],
            owner.clone(),
            "`catch` takes an `&laravel::Error`, a `&Batch`, `Inject<T>` services and `Section<T>` config sections",
        )?;
        let takes_batch = catch
            .sig
            .inputs
            .iter()
            .any(|argument| matches!(argument, FnArg::Typed(argument) if is_reference_to(&argument.ty, "Batch")));
        let batch = takes_batch.then(|| {
            quote! {
                let ::std::option::Option::Some(__laravel_batch) = __laravel_batch else {
                    return ::std::result::Result::Err(::laravel::abort_with(
                        500,
                        ::std::format!(
                            "the callback `{}` takes a `&Batch`, so only a batch can call its `catch`",
                            <Self as ::laravel::queue::Callback>::NAME,
                        ),
                    ));
                };
            }
        });
        let chain = (!takes_batch).then(|| {
            quote! {
                impl ::laravel::queue::ChainCatch for #ty {}
            }
        });
        impls.push(quote! {
            impl ::laravel::queue::Catch for #ty {
                async fn catch(
                    self,
                    __laravel_batch: ::std::option::Option<&::laravel::queue::Batch>,
                    __laravel_error: &::laravel::Error,
                ) -> ::laravel::Result<()> {
                    #batch
                    #call
                }
            }

            #chain
        });
        registrations.push(quote!(.catch::<#ty>()));
    }
    if let Some(finally) = finally {
        let call = queue::call(
            quote!(<#ty>::finally),
            quote!(self),
            &finally.sig,
            &[Provided::Batch],
            owner,
            "`finally` takes a `&Batch`, `Inject<T>` services and `Section<T>` config sections: a callback's data belongs in its fields",
        )?;
        impls.push(quote! {
            impl ::laravel::queue::Finally for #ty {
                async fn finally(self, __laravel_batch: &::laravel::queue::Batch) -> ::laravel::Result<()> {
                    #call
                }
            }
        });
        registrations.push(quote!(.finally::<#ty>()));
    }

    let name = syntax::registered_name(options.name.as_ref(), ident);
    let fail_when_missing_models = options.fail_when_missing_models;

    Ok(quote! {
        #implementation

        impl ::laravel::queue::Callback for #ty {
            const NAME: &'static str = #name;
            const FAIL_WHEN_MISSING_MODELS: bool = #fail_when_missing_models;
        }

        #(#impls)*

        ::laravel::__inventory::submit! {
            ::laravel::queue::__CallbackRegistration::new::<#ty>() #(#registrations)*
        }
    })
}

#[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_callbacks_have_actionable_errors() {
        for (options, input, expected) in [
            ("", "impl Example {}", "`then`, `catch` or `finally`"),
            ("", "impl Example { fn then(self) {} }", "safe async method"),
            ("", "impl Example { async fn finally(&self) {} }", "consume `self`"),
            (
                "",
                "impl Example { async fn then(self, id: i64) {} }",
                "belongs in its fields",
            ),
            (
                "",
                "impl Example { async fn then(self, error: &Error) {} }",
                "belongs in its fields",
            ),
            (
                "",
                "impl Example { async fn catch(self, a: &Error, b: &Error) {} }",
                "at most one `&laravel::Error`",
            ),
            (
                "",
                "impl Example { async fn then(self, a: &Batch, b: &Batch) {} }",
                "at most one `&Batch`",
            ),
            (
                "",
                "impl<T> Example<T> { async fn then(self) {} }",
                "without generic parameters",
            ),
            (
                "queue = \"x\"",
                "impl Example { async fn then(self) {} }",
                "takes a name and `fail_when_missing_models`",
            ),
            (
                "fail_when_missing_models, fail_when_missing_models",
                "impl Example { async fn then(self) {} }",
                "`fail_when_missing_models` is given twice",
            ),
        ] {
            let error = error(options, input);
            assert!(error.contains(expected), "{options} {input}: {error}");
        }
    }

    #[test]
    fn only_catch_methods_without_a_batch_are_chain_callbacks() {
        let expand = |input: &str| {
            expand(Options::default(), syn::parse_str(input).unwrap())
                .unwrap()
                .to_string()
        };

        assert!(expand("impl Example { async fn catch(self, error: &Error) {} }").contains("ChainCatch"));
        assert!(!expand("impl Example { async fn catch(self, batch: &Batch) {} }").contains("ChainCatch"));
    }

    #[test]
    fn invalid_callback_functions_have_actionable_errors() {
        for (input, expected) in [
            ("fn finished() {}", "safe async function"),
            ("async unsafe fn finished() {}", "safe async function"),
            ("async fn finished<T>(value: T) {}", "without generic parameters"),
            (
                "async fn finished() where String: Send {}",
                "without generic parameters",
            ),
            ("async fn finished(value: &str) {}", "captures must be owned"),
            ("async fn finished(value: Vec<&str>) {}", "captures must be owned"),
            ("async fn finished(value: (i64, &str)) {}", "captures must be owned"),
            ("async fn finished(value: &mut Batch) {}", "captures must be owned"),
            ("async fn finished(a: &Batch, b: &Batch) {}", "at most one `&Batch`"),
            ("async fn finished(a: &Error, b: &Error) {}", "at most one `&Error`"),
        ] {
            let error = expand_item(Options::default(), syn::parse_str(input).unwrap()).unwrap_err();
            assert!(error.to_string().contains(expected), "{input}: {error}");
        }
    }
}