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
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,
}

/// The options a job and a queued listener share.
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 {
    /// The name `name = ".."` gives, if any.
    pub(crate) const fn name(&self) -> Option<&syn::LitStr> {
        self.name.as_ref()
    }

    /// The `NAME` and `options` items of a job, or of a queued listener's job.
    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 {
            /// Dispatch this job to its queue.
            ///
            /// Await the returned dispatch to push the job. To learn more, see
            /// [`laravel::queue::dispatch`](::laravel::queue::dispatch).
            #[track_caller]
            pub fn dispatch(self) -> ::laravel::queue::PendingDispatch<Self> {
                ::laravel::queue::dispatch(self)
            }

            /// Run this job right away in this process and return its error, if any.
            ///
            /// To learn more, see [`laravel::queue::dispatch_sync`](::laravel::queue::dispatch_sync).
            #[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}");
        }
    }
}