use darling::FromDeriveInput;
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};
#[proc_macro_derive(Job, attributes(job))]
pub fn derive_job(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
match JobInput::from_derive_input(&input) {
Ok(parsed) => expand(parsed).into(),
Err(e) => e.write_errors().into(),
}
}
#[derive(Debug, FromDeriveInput)]
#[darling(attributes(job), supports(struct_any))]
struct JobInput {
ident: syn::Ident,
generics: syn::Generics,
queue: String,
#[darling(default = "default_retries")]
retries: u32,
#[darling(default)]
timeout_secs: Option<u64>,
#[darling(default)]
kind: Option<String>,
}
fn default_retries() -> u32 {
10
}
fn expand(input: JobInput) -> proc_macro2::TokenStream {
let JobInput { ident, generics, queue, retries, timeout_secs, kind, .. } = input;
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
let kind_str = kind.unwrap_or_else(|| ident.to_string());
let timeout_expr = match timeout_secs {
Some(secs) => quote! { ::core::option::Option::Some(#secs) },
None => quote! { ::core::option::Option::None },
};
quote! {
#[automatically_derived]
impl #impl_generics ::asyncq::Job for #ident #ty_generics #where_clause {
const KIND: &'static str = #kind_str;
const QUEUE: &'static str = #queue;
const MAX_RETRIES: u32 = #retries;
const TIMEOUT_SECS: ::core::option::Option<u64> = #timeout_expr;
}
}
}