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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
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,
        &quote! {
            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, &quote!(#(#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}");
    }
}