asyncq_derive/lib.rs
1use darling::FromDeriveInput;
2use proc_macro::TokenStream;
3use quote::quote;
4use syn::{parse_macro_input, DeriveInput};
5
6/// Derive the `Job` trait for a struct, registering it as a background job type.
7///
8/// # Required attributes
9///
10/// At minimum, specify the queue name:
11///
12/// ```rust,ignore
13/// #[derive(Job, Serialize, Deserialize)]
14/// #[job(queue = "emails")]
15/// struct WelcomeEmail {
16/// email: String,
17/// }
18/// ```
19///
20/// # Optional attributes
21///
22/// | Attribute | Default | Description |
23/// |-----------|---------|-------------|
24/// | `queue = "name"` | **required** | Queue this job is enqueued to |
25/// | `retries = N` | `10` | Max delivery attempts before dead-lettering |
26/// | `timeout_secs = N` | none | Per-job execution timeout in seconds |
27/// | `kind = "Name"` | struct name | Override the job type identifier |
28///
29/// # Full example
30///
31/// ```rust,ignore
32/// #[derive(Job, Serialize, Deserialize)]
33/// #[job(queue = "payments", retries = 5, timeout_secs = 30)]
34/// struct ProcessPayment {
35/// order_id: Uuid,
36/// amount_cents: u64,
37/// }
38/// ```
39#[proc_macro_derive(Job, attributes(job))]
40pub fn derive_job(input: TokenStream) -> TokenStream {
41 let input = parse_macro_input!(input as DeriveInput);
42 match JobInput::from_derive_input(&input) {
43 Ok(parsed) => expand(parsed).into(),
44 Err(e) => e.write_errors().into(),
45 }
46}
47
48// ── Attribute parsing ─────────────────────────────────────────────────────────
49
50#[derive(Debug, FromDeriveInput)]
51#[darling(attributes(job), supports(struct_any))]
52struct JobInput {
53 ident: syn::Ident,
54 generics: syn::Generics,
55
56 /// Queue name — required.
57 queue: String,
58
59 /// Maximum retry attempts. Default: 10.
60 #[darling(default = "default_retries")]
61 retries: u32,
62
63 /// Optional execution timeout in seconds.
64 #[darling(default)]
65 timeout_secs: Option<u64>,
66
67 /// Override the job kind string. Defaults to the struct name.
68 #[darling(default)]
69 kind: Option<String>,
70}
71
72fn default_retries() -> u32 {
73 10
74}
75
76// ── Code generation ───────────────────────────────────────────────────────────
77
78fn expand(input: JobInput) -> proc_macro2::TokenStream {
79 let JobInput { ident, generics, queue, retries, timeout_secs, kind, .. } = input;
80 let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
81
82 let kind_str = kind.unwrap_or_else(|| ident.to_string());
83
84 let timeout_expr = match timeout_secs {
85 Some(secs) => quote! { ::core::option::Option::Some(#secs) },
86 None => quote! { ::core::option::Option::None },
87 };
88
89 quote! {
90 #[automatically_derived]
91 impl #impl_generics ::asyncq::Job for #ident #ty_generics #where_clause {
92 const KIND: &'static str = #kind_str;
93 const QUEUE: &'static str = #queue;
94 const MAX_RETRIES: u32 = #retries;
95 const TIMEOUT_SECS: ::core::option::Option<u64> = #timeout_expr;
96 }
97 }
98}