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, FnArg, GenericArgument, Ident, ImplItemFn, ItemFn, ItemImpl, Meta, PathArguments, Signature, Token, Type,
};
use crate::job;
use crate::queue::{self, Provided};
use crate::syntax::{self, FnOrImpl};
const OPTIONS: &str = "`at_dispatch`, or `queued` with `connection`, `delay`, `name`, `queue`, `tries`, \
`max_errors`, `backoff`, `timeout`, `retry_for`, `debounce_for`, `max_wait` or `fail_when_missing_models`";
pub(crate) enum Args {
AfterCommit,
AtDispatch,
Queued(Box<Queued>),
}
pub(crate) struct Queued {
job: job::Options,
connection: Option<syn::LitStr>,
delay: Option<Expr>,
}
impl Parse for Args {
fn parse(input: ParseStream) -> syn::Result<Self> {
let mut at_dispatch = None;
let mut queued = None;
let mut connection = None;
let mut delay = None;
let mut job_options = Vec::new();
for option in Punctuated::<Meta, Token![,]>::parse_terminated(input)? {
let key = option.path().get_ident().map(ToString::to_string).unwrap_or_default();
let span = option.path().span();
let given = match option {
Meta::Path(_) if key == "at_dispatch" => at_dispatch.replace(span).is_some(),
Meta::Path(_) if key == "queued" => queued.replace(span).is_some(),
Meta::NameValue(option) if key == "connection" => connection
.replace(syntax::string(&option.value, "connection")?)
.is_some(),
Meta::NameValue(option) if key == "delay" => delay.replace(option.value).is_some(),
Meta::Path(_) if key == "fail_when_missing_models" => {
job_options.push(option);
false
}
Meta::NameValue(_) if job::NAMES.contains(&key.as_str()) => {
job_options.push(option);
false
}
option => {
return Err(syn::Error::new_spanned(
option,
format!("unknown listener option: expected {OPTIONS}"),
));
}
};
if given {
return Err(syn::Error::new(span, format!("`{key}` is given twice")));
}
}
if queued.is_none() {
let queue_option = job_options
.first()
.map(|option| option.path().span())
.or_else(|| connection.as_ref().map(syn::LitStr::span))
.or_else(|| delay.as_ref().map(Spanned::span));
if let Some(span) = queue_option {
return Err(syn::Error::new(
span,
"queue options apply to queued listeners: add `queued`, as in `#[listener(queued, tries = 3)]`",
));
}
return Ok(if at_dispatch.is_some() {
Self::AtDispatch
} else {
Self::AfterCommit
});
}
if let Some(at_dispatch) = at_dispatch {
return Err(syn::Error::new(
at_dispatch,
"queued listeners run on the queue after the database transaction commits: remove `at_dispatch`",
));
}
let job = syn::parse2(quote!(#(#job_options),*))?;
Ok(Self::Queued(Box::new(Queued { job, connection, delay })))
}
}
pub(crate) fn expand(args: Args, item: FnOrImpl) -> syn::Result<TokenStream> {
match (args, item) {
(Args::Queued(queued), FnOrImpl::Fn(function)) => expand_queued_function(*queued, function),
(Args::Queued(queued), FnOrImpl::Impl(implementation)) => expand_queued_impl(*queued, implementation),
(Args::AfterCommit, FnOrImpl::Fn(function)) => expand_function(quote!(listen), function),
(Args::AtDispatch, FnOrImpl::Fn(function)) => expand_function(quote!(listen_at_dispatch), function),
(_, FnOrImpl::Impl(implementation)) => Err(syn::Error::new_spanned(
implementation.impl_token,
"a listener impl runs on the queue: add `queued`, as in `#[listener(queued)]`",
)),
}
}
fn expand_function(listen: TokenStream, function: ItemFn) -> syn::Result<TokenStream> {
let signature = &function.sig;
check_function(signature)?;
if signature.inputs.is_empty() {
return Err(syn::Error::new_spanned(
signature,
"a listener requires an `Event<T>` as its first argument",
));
}
let name = &signature.ident;
Ok(quote! {
#function
::laravel::__inventory::submit! {
::laravel::event::__Registration {
crate_name: ::core::env!("CARGO_CRATE_NAME"),
name: || ::std::any::type_name_of_val(&#name),
register: |__laravel_events| { __laravel_events.#listen(#name); },
}
}
})
}
fn expand_queued_function(queued: Queued, mut function: ItemFn) -> syn::Result<TokenStream> {
let (visibility, documentation) = syntax::take_visibility_and_docs(&mut function);
check_function(&function.sig)?;
let event = event_type(&function.sig)?;
let name = function.sig.ident.clone();
let call = queue::call(
quote!(#name),
quote!(__laravel_event),
&function.sig,
&[Provided::Attempt],
quote!(<Self as ::laravel::event::QueuedListener>::NAME),
"after the event, a queued listener takes `Inject<T>` services, `Section<T>` config sections and an `&Attempt`",
)?;
let ty: Type = syn::parse_quote!(#name);
let listener = listener_impl(
&queued,
&ty,
&name,
event,
"e! {
async fn handle(
__laravel_event: ::laravel::event::Event<Self::Event>,
__laravel_attempt: &::laravel::queue::Attempt,
) -> ::laravel::Result<()> {
#function
#call
}
},
);
let registration = registration(&ty);
Ok(quote! {
#(#documentation)*
#[expect(non_camel_case_types, reason = "queued listeners keep their function's name")]
#[derive(Debug, Clone, Copy, Default)]
#visibility struct #name;
#listener
#registration
})
}
fn expand_queued_impl(queued: Queued, implementation: ItemImpl) -> syn::Result<TokenStream> {
let ident = syntax::inherent_impl(&implementation, "listener")?;
let ty = &*implementation.self_ty;
let handle = function(&implementation, "handle", true)?.ok_or_else(|| {
syn::Error::new_spanned(
ty,
"a queued listener requires an async `handle` function taking the `Event<T>`",
)
})?;
let event = event_type(&handle.sig)?;
let call = queue::call(
quote!(<#ty>::handle),
quote!(__laravel_event),
&handle.sig,
&[Provided::Attempt],
quote!(<Self as ::laravel::event::QueuedListener>::NAME),
"after the event, a queued listener takes `Inject<T>` services, `Section<T>` config sections and an `&Attempt`",
)?;
let mut methods = vec![quote! {
async fn handle(
__laravel_event: ::laravel::event::Event<Self::Event>,
__laravel_attempt: &::laravel::queue::Attempt,
) -> ::laravel::Result<()> {
#call
}
}];
if let Some(failed) = function(&implementation, "failed", true)? {
if failed.sig.inputs.is_empty() {
return Err(syn::Error::new_spanned(
&failed.sig,
"`failed` takes the `Event<T>` as its first argument",
));
}
let call = queue::call(
quote!(<#ty>::failed),
quote!(__laravel_event),
&failed.sig,
&[Provided::Attempt, Provided::Error],
quote!(<Self as ::laravel::event::QueuedListener>::NAME),
"after the event, `failed` takes an `&laravel::Error`, `Inject<T>` services, `Section<T>` config sections and an `&Attempt`",
)?;
methods.push(quote! {
async fn failed(
__laravel_event: ::laravel::event::Event<Self::Event>,
__laravel_error: &::laravel::Error,
__laravel_attempt: &::laravel::queue::Attempt,
) -> ::laravel::Result<()> {
#call
}
});
}
if function(&implementation, "should_queue", false)?.is_some() {
methods.push(quote! {
fn should_queue(__laravel_event: &Self::Event) -> bool {
<#ty>::should_queue(__laravel_event)
}
});
}
if let Some(middleware) = function(&implementation, "middleware", false)? {
let group = quote_spanned! {syntax::output_span(&middleware.sig)=>
::laravel::queue::IntoMiddleware::into_group(__laravel_middleware)
};
methods.push(quote! {
fn middleware(__laravel_event: &Self::Event) -> ::laravel::queue::MiddlewareGroup {
let __laravel_middleware = <#ty>::middleware(__laravel_event);
#group
}
});
}
let debounce_id = function(&implementation, "debounce_id", false)?;
if let Some(debounce_id) = debounce_id.filter(|_| !queued.job.debounce_for) {
return Err(syn::Error::new_spanned(
&debounce_id.sig.ident,
"`debounce_id` tells a debounced listener's jobs apart: add `debounce_for` to `#[listener(..)]`",
));
}
if let Some(debounce_id) = debounce_id {
let id =
quote_spanned! {syntax::output_span(&debounce_id.sig)=> ::std::string::ToString::to_string(&__laravel_id)};
methods.push(quote! {
fn debounce_id(__laravel_event: &Self::Event) -> ::std::string::String {
let __laravel_id = <#ty>::debounce_id(__laravel_event);
#id
}
});
}
let listener = listener_impl(&queued, ty, ident, event, "e!(#(#methods)*));
let registration = registration(ty);
Ok(quote! {
#implementation
#listener
#registration
})
}
fn listener_impl(queued: &Queued, ty: &Type, ident: &Ident, event: &Type, methods: &TokenStream) -> TokenStream {
let items = queued.job.items(ident);
let connection = queued.connection.as_ref().map(|connection| {
quote! {
fn connection() -> ::std::option::Option<&'static str> {
::std::option::Option::Some(#connection)
}
}
});
let delay = queued.delay.as_ref().map(|delay| {
let delay = quote_spanned! {delay.span()=> ::std::convert::Into::<::laravel::time::Moment>::into(#delay)};
quote! {
fn delay() -> ::std::option::Option<::laravel::time::Moment> {
#[allow(unused_imports)]
use ::laravel::time::ToSpan as _;
::std::option::Option::Some(#delay)
}
}
});
quote! {
impl ::laravel::event::QueuedListener for #ty {
type Event = #event;
#items
#connection
#delay
#methods
}
}
}
fn registration(ty: &Type) -> TokenStream {
quote! {
::laravel::__inventory::submit! {
::laravel::queue::__Registration::new::<::laravel::event::Queued<#ty>>()
}
::laravel::__inventory::submit! {
::laravel::event::__Registration {
crate_name: ::core::env!("CARGO_CRATE_NAME"),
name: ::std::any::type_name::<#ty>,
register: |__laravel_events| { __laravel_events.__listen_queued::<#ty>(); },
}
}
}
}
fn check_function(signature: &Signature) -> syn::Result<()> {
syntax::require_async(
signature,
"`listener` requires a safe async function without generic parameters",
)?;
Ok(())
}
fn function<'a>(implementation: &'a ItemImpl, name: &str, asynchronous: bool) -> syn::Result<Option<&'a ImplItemFn>> {
let Some(function) = syntax::method(implementation, name) else {
return Ok(None);
};
let signature = &function.sig;
if signature.asyncness.is_some() != asynchronous || !syntax::is_plain(signature) {
let kind = if asynchronous { "an async" } else { "a non-async" };
return Err(syn::Error::new_spanned(
signature,
format!("`{name}` must be {kind} function without generic parameters"),
));
}
if let Some(FnArg::Receiver(receiver)) = signature.inputs.first() {
return Err(syn::Error::new_spanned(
receiver,
format!("`{name}` takes the event instead of `self`: a queued listener's data is its event"),
));
}
if !asynchronous && signature.inputs.len() != 1 {
return Err(syn::Error::new_spanned(
&signature.inputs,
format!("`{name}` takes only a reference to the event, such as `event: &OrderPlaced`"),
));
}
Ok(Some(function))
}
fn event_type(signature: &Signature) -> syn::Result<&Type> {
let error = || {
syn::Error::new_spanned(
&signature.inputs,
"a queued listener takes an `Event<T>` as its first argument, for a serializable event `T`",
)
};
let Some(FnArg::Typed(argument)) = signature.inputs.first() else {
return Err(error());
};
let Type::Path(path) = &*argument.ty else {
return Err(error());
};
let segment = path.path.segments.last().ok_or_else(error)?;
match &segment.arguments {
PathArguments::AngleBracketed(arguments) if segment.ident == "Event" && arguments.args.len() == 1 => {
match arguments.args.first() {
Some(GenericArgument::Type(event)) => Ok(event),
_ => Err(error()),
}
}
_ => Err(error()),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn error(args: &str, input: &str) -> String {
let args = match syn::parse_str::<Args>(args) {
Ok(args) => args,
Err(error) => return error.to_string(),
};
expand(args, syn::parse_str(input).unwrap()).unwrap_err().to_string()
}
#[test]
fn invalid_signatures_have_actionable_errors() {
for (args, input, message) in [
("", "fn example() {}", "safe async function"),
("", "async unsafe fn example(e: Event<E>) {}", "safe async function"),
("", "async fn example<T>(e: Event<T>) {}", "without generic parameters"),
("", "async fn example() {}", "first argument"),
("queued", "async fn example() {}", "`Event<T>` as its first argument"),
(
"queued",
"async fn example(e: E) {}",
"`Event<T>` as its first argument",
),
(
"queued",
"async fn example(e: Event<E>, id: i64) {}",
"takes `Inject<T>` services",
),
(
"queued",
"async fn example(e: Event<E>, a: &Attempt, b: &Attempt) {}",
"at most one `&Attempt`",
),
(
"queued",
"async fn example(e: Event<E>, error: &Error) {}",
"takes `Inject<T>`",
),
("", "impl Example {}", "add `queued`"),
("queued", "impl Example {}", "requires an async `handle`"),
(
"queued",
"impl Example { fn handle(e: Event<E>) {} }",
"must be an async function",
),
(
"queued",
"impl Example { async fn handle(self) {} }",
"instead of `self`",
),
(
"queued",
"impl<T> Example<T> { async fn handle(e: Event<E>) {} }",
"without generic parameters",
),
(
"queued",
"impl Example { async fn handle(e: Event<E>) {} async fn should_queue(e: &E) -> bool { true } }",
"must be a non-async function",
),
(
"queued",
"impl Example { async fn handle(e: Event<E>) {} fn middleware(e: &E, f: &F) {} }",
"takes only a reference to the event",
),
(
"queued",
"impl Example { async fn handle(e: Event<E>) {} async fn failed(e: Event<E>, a: &Error, b: &Error) {} }",
"at most one `&laravel::Error`",
),
(
"queued",
"impl Example { async fn handle(e: Event<E>) {} fn debounce_id(e: &E) -> i64 { 1 } }",
"add `debounce_for`",
),
(
"queued, max_wait = 2.minutes()",
"async fn example(e: Event<E>) {}",
"add `debounce_for`",
),
] {
let error = error(args, input);
assert!(error.contains(message), "{args} {input}: {error}");
}
}
#[test]
fn options_are_checked_against_queued() {
for (args, message) in [
("tries = 3", "add `queued`"),
("connection = \"redis\"", "add `queued`"),
("queued, at_dispatch", "remove `at_dispatch`"),
("queued, queued", "given twice"),
("queued, delay = 1, delay = 2", "given twice"),
("queued, retries = 3", "unknown listener option"),
("after", "unknown listener option"),
("at_dispatch = true", "unknown listener option"),
("queued, connection = redis", "is a string"),
("queued, tries = 0", "at least 1"),
] {
let error = syn::parse_str::<Args>(args).err().unwrap();
assert!(error.to_string().contains(message), "{args}: {error}");
}
}
#[test]
fn listener_impls_are_named_after_their_type_not_its_path() {
let args: Args = syn::parse_str("queued").unwrap();
let expanded = expand(
args,
syn::parse_str("impl listeners::RewardGiftCard { async fn handle(e: Event<E>) {} }").unwrap(),
)
.unwrap()
.to_string();
assert!(expanded.contains("stringify ! (RewardGiftCard)"), "{expanded}");
}
}