celery-codegen 0.1.1

Macros for rusty-celery
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
// Adapted from https://github.com/kureuil/batch-rs/blob/master/batch-codegen/src/job.rs.

use proc_macro2::{Span, TokenStream};
use quote::{quote, ToTokens};
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::token::Comma;
use syn::visit_mut::VisitMut;
use syn::{parse, FnArg, Token};

use crate::error::Error;

#[derive(Clone)]
struct TaskAttrs {
    attrs: Vec<TaskAttr>,
}

#[derive(Clone)]
enum TaskAttr {
    Name(syn::LitStr),
    Wrapper(syn::Ident),
    Timeout(syn::LitInt),
    MaxRetries(syn::LitInt),
    MinRetryDelay(syn::LitInt),
    MaxRetryDelay(syn::LitInt),
    AcksLate(syn::LitBool),
}

#[derive(Clone)]
struct Task {
    errors: Vec<Error>,
    visibility: syn::Visibility,
    name: String,
    wrapper: Option<syn::Ident>,
    timeout: Option<syn::LitInt>,
    max_retries: Option<syn::LitInt>,
    min_retry_delay: Option<syn::LitInt>,
    max_retry_delay: Option<syn::LitInt>,
    acks_late: Option<syn::LitBool>,
    original_args: Vec<syn::FnArg>,
    inputs: Option<Punctuated<FnArg, Comma>>,
    inner_block: Option<syn::Block>,
    ret: Option<syn::Type>,
}

impl TaskAttrs {
    fn name(&self) -> Option<String> {
        self.attrs
            .iter()
            .filter_map(|a| match a {
                TaskAttr::Name(s) => Some(s.value()),
                _ => None,
            })
            .next()
    }

    fn wrapper(&self) -> Option<syn::Ident> {
        self.attrs
            .iter()
            .filter_map(|a| match a {
                TaskAttr::Wrapper(i) => Some(i.clone()),
                _ => None,
            })
            .next()
    }

    fn timeout(&self) -> Option<syn::LitInt> {
        self.attrs
            .iter()
            .filter_map(|a| match a {
                TaskAttr::Timeout(r) => Some(r.clone()),
                _ => None,
            })
            .next()
    }

    fn max_retries(&self) -> Option<syn::LitInt> {
        self.attrs
            .iter()
            .filter_map(|a| match a {
                TaskAttr::MaxRetries(r) => Some(r.clone()),
                _ => None,
            })
            .next()
    }

    fn min_retry_delay(&self) -> Option<syn::LitInt> {
        self.attrs
            .iter()
            .filter_map(|a| match a {
                TaskAttr::MinRetryDelay(r) => Some(r.clone()),
                _ => None,
            })
            .next()
    }

    fn max_retry_delay(&self) -> Option<syn::LitInt> {
        self.attrs
            .iter()
            .filter_map(|a| match a {
                TaskAttr::MaxRetryDelay(r) => Some(r.clone()),
                _ => None,
            })
            .next()
    }

    fn acks_late(&self) -> Option<syn::LitBool> {
        self.attrs
            .iter()
            .filter_map(|a| match a {
                TaskAttr::AcksLate(r) => Some(r.clone()),
                _ => None,
            })
            .next()
    }
}

impl parse::Parse for TaskAttrs {
    fn parse(input: parse::ParseStream) -> parse::Result<Self> {
        let attrs: Punctuated<_, Token![,]> = input.parse_terminated(TaskAttr::parse)?;
        Ok(TaskAttrs {
            attrs: attrs.into_iter().collect(),
        })
    }
}

mod kw {
    syn::custom_keyword!(name);
    syn::custom_keyword!(wrapper);
    syn::custom_keyword!(timeout);
    syn::custom_keyword!(max_retries);
    syn::custom_keyword!(min_retry_delay);
    syn::custom_keyword!(max_retry_delay);
    syn::custom_keyword!(acks_late);
}

impl parse::Parse for TaskAttr {
    fn parse(input: parse::ParseStream) -> parse::Result<Self> {
        let lookahead = input.lookahead1();
        if lookahead.peek(kw::name) {
            input.parse::<kw::name>()?;
            input.parse::<Token![=]>()?;
            Ok(TaskAttr::Name(input.parse()?))
        } else if lookahead.peek(kw::wrapper) {
            input.parse::<kw::wrapper>()?;
            input.parse::<Token![=]>()?;
            Ok(TaskAttr::Wrapper(input.parse()?))
        } else if lookahead.peek(kw::timeout) {
            input.parse::<kw::timeout>()?;
            input.parse::<Token![=]>()?;
            Ok(TaskAttr::Timeout(input.parse()?))
        } else if lookahead.peek(kw::max_retries) {
            input.parse::<kw::max_retries>()?;
            input.parse::<Token![=]>()?;
            Ok(TaskAttr::MaxRetries(input.parse()?))
        } else if lookahead.peek(kw::min_retry_delay) {
            input.parse::<kw::min_retry_delay>()?;
            input.parse::<Token![=]>()?;
            Ok(TaskAttr::MinRetryDelay(input.parse()?))
        } else if lookahead.peek(kw::max_retry_delay) {
            input.parse::<kw::max_retry_delay>()?;
            input.parse::<Token![=]>()?;
            Ok(TaskAttr::MaxRetryDelay(input.parse()?))
        } else if lookahead.peek(kw::acks_late) {
            input.parse::<kw::acks_late>()?;
            input.parse::<Token![=]>()?;
            Ok(TaskAttr::AcksLate(input.parse()?))
        } else {
            Err(lookahead.error())
        }
    }
}

impl Task {
    fn new(attrs: TaskAttrs) -> Result<Self, Error> {
        let errors = Vec::new();
        let visibility = syn::Visibility::Inherited;
        let name = match attrs.name() {
            Some(name) => name,
            None => String::from(""),
        };
        let wrapper = attrs.wrapper();
        let timeout = attrs.timeout();
        let max_retries = attrs.max_retries();
        let min_retry_delay = attrs.min_retry_delay();
        let max_retry_delay = attrs.max_retry_delay();
        let acks_late = attrs.acks_late();
        let original_args = Vec::new();
        let inputs = None;
        let inner_block = None;
        let ret = None;
        Ok(Task {
            errors,
            visibility,
            name,
            wrapper,
            timeout,
            max_retries,
            min_retry_delay,
            max_retry_delay,
            acks_late,
            original_args,
            inputs,
            inner_block,
            ret,
        })
    }
}

impl VisitMut for Task {
    fn visit_item_fn_mut(&mut self, node: &mut syn::ItemFn) {
        const ERR_ABI: &str = "functions with non-Rust ABI are not supported";
        let ident = node.ident.clone();

        self.visibility = node.vis.clone();
        if let Some(ref mut it) = node.abi {
            self.errors.push(Error::spanned(ERR_ABI, it.span()));
        };
        if self.name.is_empty() {
            self.name = ident.to_string()
        }
        if self.wrapper.is_none() {
            self.wrapper = Some(ident);
        }
        self.visit_fn_decl_mut(&mut *node.decl);
        self.inner_block = Some((*node.block).clone());
    }

    fn visit_fn_decl_mut(&mut self, node: &mut syn::FnDecl) {
        const ERR_GENERICS: &str = "functions with generic arguments are not supported";
        const ERR_VARIADIC: &str = "functions with variadic arguments are not supported";

        if !node.generics.params.is_empty() {
            self.errors
                .push(Error::spanned(ERR_GENERICS, node.generics.span()));
        }
        self.original_args = node.inputs.clone().into_iter().collect();
        self.inputs = Some(node.inputs.clone());
        if let Some(ref mut it) = node.variadic {
            self.errors.push(Error::spanned(ERR_VARIADIC, it.span()));
        }
        if let syn::ReturnType::Type(_arr, ref ty) = node.output {
            self.ret = Some((**ty).clone());
        }
    }
}

fn args2fields<'a>(args: impl IntoIterator<Item = &'a syn::FnArg>) -> TokenStream {
    args.into_iter()
        .fold(TokenStream::new(), |acc, arg| match arg {
            syn::FnArg::Captured(cap) => {
                let ident = match cap.pat {
                    syn::Pat::Ident(ref pat) => &pat.ident,
                    _ => return acc,
                };
                let ty = &cap.ty;
                quote! {
                    #acc
                    #ident: #ty,
                }
            }
            _ => acc,
        })
}

impl ToTokens for Task {
    fn to_tokens(&self, dst: &mut TokenStream) {
        let krate = quote!(::celery);
        let export = quote!(#krate::export);
        let vis = &self.visibility;
        let wrapper = self.wrapper.as_ref().unwrap();
        let timeout = self.timeout.as_ref().map(|r| {
            quote! {
                fn timeout(&self) -> Option<u32> {
                    Some(#r)
                }
            }
        });
        let max_retries = self.max_retries.as_ref().map(|r| {
            quote! {
                fn max_retries(&self) -> Option<u32> {
                    Some(#r)
                }
            }
        });
        let min_retry_delay = self.min_retry_delay.as_ref().map(|r| {
            quote! {
                fn min_retry_delay(&self) -> Option<u32> {
                    Some(#r)
                }
            }
        });
        let max_retry_delay = self.max_retry_delay.as_ref().map(|r| {
            quote! {
                fn max_retry_delay(&self) -> Option<u32> {
                    Some(#r)
                }
            }
        });
        let acks_late = self.acks_late.as_ref().map(|r| {
            quote! {
                fn acks_late(&self) -> Option<bool> {
                    Some(#r)
                }
            }
        });
        let task_name = &self.name;
        let arg_names = self
            .original_args
            .iter()
            .fold(TokenStream::new(), |acc, arg| match arg {
                syn::FnArg::Captured(cap) => match cap.pat {
                    syn::Pat::Ident(ref pat) => {
                        let name = &pat.ident.to_string();
                        quote! {
                            #acc
                            #name,
                        }
                    }
                    _ => acc,
                },
                _ => acc,
            });
        let serialized_fields = args2fields(&self.original_args);
        let deserialized_bindings =
            self.original_args
                .iter()
                .fold(TokenStream::new(), |acc, arg| match arg {
                    syn::FnArg::Captured(cap) => match cap.pat {
                        syn::Pat::Ident(ref pat) => {
                            let ident = &pat.ident;
                            quote! {
                                #acc
                                let #ident = self.#ident;
                            }
                        }
                        _ => acc,
                    },
                    _ => acc,
                });
        let inner_block = {
            let block = &self.inner_block;
            quote!(#block)
        };

        let ret_ty = self
            .ret
            .as_ref()
            .map(|ty| quote!(#ty))
            .unwrap_or_else(|| quote!(()));

        let dummy_const = syn::Ident::new(
            &format!("__IMPL_BATCH_JOB_FOR_{}", wrapper.to_string()),
            Span::call_site(),
        );

        let original_args = self.inputs.clone();
        let wrapper_fields =
            self.original_args
                .iter()
                .fold(TokenStream::new(), |acc, arg| match arg {
                    syn::FnArg::Captured(cap) => match cap.pat {
                        syn::Pat::Ident(ref pat) => {
                            let ident = &pat.ident;
                            quote! {
                                #acc
                                #ident,
                            }
                        }
                        _ => acc,
                    },
                    _ => acc,
                });
        let wrapper_struct = quote! {
            #[allow(non_camel_case_types)]
            #[derive(#export::Deserialize, #export::Serialize)]
            #vis struct #wrapper {
                #serialized_fields
            }

            impl #wrapper {
                #vis fn new(#original_args) -> Self {
                    #wrapper {
                        #wrapper_fields
                    }
                }
            }
        };

        let output = quote! {
            #wrapper_struct

            const #dummy_const: () = {
                use #export::async_trait;

                #[async_trait]
                impl #krate::Task for #wrapper {
                    const NAME: &'static str = #task_name;
                    const ARGS: &'static [&'static str] = &[#arg_names];

                    type Returns = #ret_ty;

                    async fn run(mut self) -> Result<Self::Returns, #krate::Error> {
                        #deserialized_bindings
                        Ok(#inner_block)
                    }

                    #timeout

                    #max_retries

                    #min_retry_delay

                    #max_retry_delay

                    #acks_late
                }
            };
        };
        dst.extend(output);
    }
}

pub(crate) fn impl_macro(
    args: proc_macro::TokenStream,
    input: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
    let attrs = syn::parse_macro_input!(args as TaskAttrs);
    let mut item = syn::parse_macro_input!(input as syn::ItemFn);
    let mut task = match Task::new(attrs) {
        Ok(task) => task,
        Err(e) => return quote!(#e).into(),
    };
    task.visit_item_fn_mut(&mut item);
    if !task.errors.is_empty() {
        task.errors
            .iter()
            .fold(TokenStream::new(), |mut acc, err| {
                err.to_tokens(&mut acc);
                acc
            })
            .into()
    } else {
        let output = quote! {
            #task
        };
        output.into()
    }
}