Skip to main content

riverqueue_macros/
lib.rs

1#![doc = include_str!("../README.md")]
2#![forbid(unsafe_code)]
3
4use proc_macro::TokenStream;
5use proc_macro2::Span;
6use quote::{quote, quote_spanned};
7use syn::{
8    Data, DeriveInput, Fields, Ident, Lit, LitBool, LitInt, LitStr, Meta, Token,
9    ext::IdentExt as _, meta::ParseNestedMeta, parenthesized, parse_macro_input,
10    punctuated::Punctuated, spanned::Spanned as _, token,
11};
12
13/// Derives `riverqueue::JobArgs`.
14///
15/// The type must declare `#[river(kind = "...")]`. Other type-level options:
16///
17/// * `aliases("old_kind", ...)`: former kinds handled by the same worker.
18/// * `queue = "..."`, `max_attempts = N`, `priority = N`, `pending = true`,
19///   and `tags("a", "b")`: default insertion options.
20/// * `unique(...)`: makes the job unique by default. Options are `by_args`,
21///   `by_args("nested.path", ...)`, `by_period = "1h"` (a duration of at least
22///   one second, such as `"90s"` or `"1h30m"`), `by_queue`, `by_state(available, running, ...)`, and
23///   `exclude_kind`.
24/// * `insert_opts = path::to_fn`: a `fn() -> InsertOpts` whose options are
25///   overlaid on the attribute defaults.
26/// * `crate = "path"`: the path to `riverqueue` when it is renamed or
27///   re-exported.
28///
29/// Fields marked `#[river(unique)]` are the arguments hashed by `unique(by_args)`,
30/// together with any `by_args` paths; without either, every argument is
31/// hashed. Marking a field requires `unique(by_args)` on the type. Field
32/// names follow Serde's serialization-side `rename` and `rename_all`. A
33/// unique field may be conditionally omitted with `skip_serializing_if`, but
34/// cannot be flattened or unconditionally skipped.
35/// `by_args` paths separate nested names with `.`; escape a literal dot or
36/// backslash with a backslash (for example, `"user\\.id"` selects the single
37/// JSON name `user.id`). Tagged fields use their whole serialized name as one
38/// component, even when that name contains a dot.
39#[proc_macro_derive(JobArgs, attributes(river))]
40pub fn derive_job_args(input: TokenStream) -> TokenStream {
41    let input = parse_macro_input!(input as DeriveInput);
42    expand_job_args(&input)
43        .unwrap_or_else(syn::Error::into_compile_error)
44        .into()
45}
46
47#[derive(Default)]
48struct TypeAttributes {
49    aliases: Vec<LitStr>,
50    krate: Option<syn::Path>,
51    insert_opts: Option<syn::Path>,
52    kind: Option<LitStr>,
53    max_attempts: Option<LitInt>,
54    pending: Option<LitBool>,
55    priority: Option<LitInt>,
56    queue: Option<LitStr>,
57    tags: Vec<LitStr>,
58    unique: Option<UniqueAttribute>,
59}
60
61struct UniqueAttribute {
62    by_args: bool,
63    by_args_paths: Vec<LitStr>,
64    by_period: Option<(u64, u32)>,
65    by_queue: bool,
66    by_state: Option<Vec<Ident>>,
67    exclude_kind: bool,
68}
69
70const JOB_STATES: [(&str, &str); 8] = [
71    ("available", "Available"),
72    ("cancelled", "Cancelled"),
73    ("completed", "Completed"),
74    ("discarded", "Discarded"),
75    ("pending", "Pending"),
76    ("retryable", "Retryable"),
77    ("running", "Running"),
78    ("scheduled", "Scheduled"),
79];
80
81const UNIQUE_REQUIRES_OPTION: &str =
82    "unique(...) requires at least one of by_args, by_period, by_queue, by_state, or exclude_kind";
83
84const JOB_STATES_REQUIRED_FOR_UNIQUE: [&str; 4] = ["available", "pending", "running", "scheduled"];
85
86fn parse_type_attributes(input: &DeriveInput) -> syn::Result<TypeAttributes> {
87    let mut parsed = TypeAttributes::default();
88    for attribute in &input.attrs {
89        if !attribute.path().is_ident("river") {
90            continue;
91        }
92        attribute.parse_nested_meta(|meta| {
93            if meta.path.is_ident("aliases") {
94                parsed.aliases = parse_string_list(&meta)?;
95            } else if meta.path.is_ident("crate") {
96                parsed.krate = Some(meta.value()?.parse::<LitStr>()?.parse()?);
97            } else if meta.path.is_ident("insert_opts") {
98                parsed.insert_opts = Some(meta.value()?.parse()?);
99            } else if meta.path.is_ident("kind") {
100                parsed.kind = Some(meta.value()?.parse()?);
101            } else if meta.path.is_ident("max_attempts") {
102                parsed.max_attempts = Some(meta.value()?.parse()?);
103            } else if meta.path.is_ident("pending") {
104                parsed.pending = Some(meta.value()?.parse()?);
105            } else if meta.path.is_ident("priority") {
106                parsed.priority = Some(meta.value()?.parse()?);
107            } else if meta.path.is_ident("queue") {
108                parsed.queue = Some(meta.value()?.parse()?);
109            } else if meta.path.is_ident("tags") {
110                parsed.tags = parse_string_list(&meta)?;
111            } else if meta.path.is_ident("unique") {
112                parsed.unique = Some(parse_unique(&meta)?);
113            } else {
114                return Err(meta.error("unsupported river type attribute"));
115            }
116            Ok(())
117        })?;
118    }
119    Ok(parsed)
120}
121
122fn parse_string_list(meta: &ParseNestedMeta<'_>) -> syn::Result<Vec<LitStr>> {
123    let content;
124    parenthesized!(content in meta.input);
125    Ok(Punctuated::<LitStr, Token![,]>::parse_terminated(&content)?
126        .into_iter()
127        .collect())
128}
129
130fn parse_unique(meta: &ParseNestedMeta<'_>) -> syn::Result<UniqueAttribute> {
131    let span = meta
132        .path
133        .get_ident()
134        .map_or_else(Span::call_site, Ident::span);
135    {
136        let lookahead = meta.input.fork();
137        let content;
138        parenthesized!(content in lookahead);
139        if content.peek(LitStr) {
140            return Err(content
141                .error("declare unique argument paths with `unique(by_args(\"path\", ...))`"));
142        }
143        if content.is_empty() {
144            return Err(syn::Error::new(span, UNIQUE_REQUIRES_OPTION));
145        }
146    }
147    let mut unique = UniqueAttribute {
148        by_args: false,
149        by_args_paths: Vec::new(),
150        by_period: None,
151        by_queue: false,
152        by_state: None,
153        exclude_kind: false,
154    };
155    meta.parse_nested_meta(|option| {
156        if option.path.is_ident("by_args") {
157            unique.by_args = true;
158            if option.input.peek(token::Paren) {
159                unique.by_args_paths = parse_string_list(&option)?;
160            }
161        } else if option.path.is_ident("by_period") {
162            let period = option.value()?.parse::<LitStr>()?;
163            let nanos = parse_go_duration(&period.value())
164                .map_err(|message| syn::Error::new_spanned(&period, message))?;
165            if nanos < 1_000_000_000 {
166                return Err(syn::Error::new_spanned(
167                    &period,
168                    "by_period must be at least one second",
169                ));
170            }
171            let seconds = u64::try_from(nanos / 1_000_000_000)
172                .map_err(|_| syn::Error::new_spanned(&period, "by_period is too large"))?;
173            let nanos = u32::try_from(nanos % 1_000_000_000).unwrap_or_default();
174            unique.by_period = Some((seconds, nanos));
175        } else if option.path.is_ident("by_queue") {
176            unique.by_queue = true;
177        } else if option.path.is_ident("by_state") {
178            let content;
179            parenthesized!(content in option.input);
180            let states = Punctuated::<Ident, Token![,]>::parse_terminated(&content)?
181                .into_iter()
182                .collect::<Vec<_>>();
183            validate_unique_states(&states, &option)?;
184            unique.by_state = Some(states);
185        } else if option.path.is_ident("exclude_kind") {
186            unique.exclude_kind = true;
187        } else {
188            return Err(option.error(
189                "unsupported unique option; expected by_args, by_period, by_queue, by_state, or exclude_kind",
190            ));
191        }
192        Ok(())
193    })?;
194    Ok(unique)
195}
196
197fn validate_unique_states(states: &[Ident], option: &ParseNestedMeta<'_>) -> syn::Result<()> {
198    let mut seen = Vec::new();
199    for state in states {
200        let name = state.to_string();
201        if !JOB_STATES.iter().any(|(known, _)| *known == name) {
202            return Err(syn::Error::new_spanned(
203                state,
204                format!(
205                    "unknown job state `{name}`; expected one of {}",
206                    JOB_STATES
207                        .iter()
208                        .map(|(known, _)| *known)
209                        .collect::<Vec<_>>()
210                        .join(", ")
211                ),
212            ));
213        }
214        if seen.contains(&name) {
215            return Err(syn::Error::new_spanned(
216                state,
217                format!("duplicate job state `{name}`"),
218            ));
219        }
220        seen.push(name);
221    }
222    let missing = JOB_STATES_REQUIRED_FOR_UNIQUE
223        .iter()
224        .filter(|required| !seen.iter().any(|state| state == *required))
225        .copied()
226        .collect::<Vec<_>>();
227    if !missing.is_empty() {
228        return Err(option.error(format!(
229            "by_state must include available, pending, running, and scheduled; missing {}",
230            missing.join(", ")
231        )));
232    }
233    Ok(())
234}
235
236/// Parses a Go `time.ParseDuration` string without a sign, such as `1h30m`
237/// or `1.5h`, into nanoseconds.
238fn parse_go_duration(text: &str) -> Result<u128, String> {
239    let invalid = || format!("invalid duration {text:?}; expected a duration such as \"1h\"");
240    if text.is_empty() {
241        return Err(invalid());
242    }
243    let mut rest = text;
244    let mut total = 0_u128;
245    while !rest.is_empty() {
246        let number_end = rest
247            .find(|character: char| !(character.is_ascii_digit() || character == '.'))
248            .unwrap_or(rest.len());
249        let (number, after_number) = rest.split_at(number_end);
250        let unit_end = after_number
251            .find(|character: char| character.is_ascii_digit() || character == '.')
252            .unwrap_or(after_number.len());
253        let (unit, after_unit) = after_number.split_at(unit_end);
254        rest = after_unit;
255
256        let unit_nanos: u128 = match unit {
257            "ns" => 1,
258            "us" | "\u{b5}s" | "\u{3bc}s" => 1_000,
259            "ms" => 1_000_000,
260            "s" => 1_000_000_000,
261            "m" => 60_000_000_000,
262            "h" => 3_600_000_000_000,
263            _ => return Err(invalid()),
264        };
265        let (whole, fraction) = number.split_once('.').unwrap_or((number, ""));
266        if whole.is_empty() && fraction.is_empty() {
267            return Err(invalid());
268        }
269        let whole = if whole.is_empty() {
270            0
271        } else {
272            whole.parse::<u128>().map_err(|_| invalid())?
273        };
274        let mut value = whole.checked_mul(unit_nanos).ok_or_else(invalid)?;
275        if !fraction.is_empty() {
276            let scale = 10_u128
277                .checked_pow(u32::try_from(fraction.len()).map_err(|_| invalid())?)
278                .ok_or_else(invalid)?;
279            let fraction = fraction.parse::<u128>().map_err(|_| invalid())?;
280            value = value
281                .checked_add(fraction.checked_mul(unit_nanos).ok_or_else(invalid)? / scale)
282                .ok_or_else(invalid)?;
283        }
284        total = total.checked_add(value).ok_or_else(invalid)?;
285    }
286    Ok(total)
287}
288
289#[expect(
290    clippy::too_many_lines,
291    reason = "the derive's validation and generated items read the same parsed attributes"
292)]
293fn expand_job_args(input: &DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
294    let attributes = parse_type_attributes(input)?;
295    let kind = attributes.kind.clone().ok_or_else(|| {
296        syn::Error::new_spanned(&input.ident, "JobArgs requires #[river(kind = \"...\")]")
297    })?;
298    validate_kind(&kind)?;
299    for alias in &attributes.aliases {
300        validate_kind(alias)?;
301        if alias.value() == kind.value() {
302            return Err(syn::Error::new_spanned(
303                alias,
304                "a kind alias cannot equal the primary kind",
305            ));
306        }
307    }
308    let mut alias_values = attributes
309        .aliases
310        .iter()
311        .map(LitStr::value)
312        .collect::<Vec<_>>();
313    alias_values.sort_unstable();
314    if alias_values.windows(2).any(|pair| pair[0] == pair[1]) {
315        return Err(syn::Error::new_spanned(
316            &input.ident,
317            "kind aliases must be unique",
318        ));
319    }
320    if let Some(max_attempts) = &attributes.max_attempts
321        && !(1..=i32::MAX as u64).contains(&max_attempts.base10_parse::<u64>()?)
322    {
323        return Err(syn::Error::new_spanned(
324            max_attempts,
325            "max_attempts must be between 1 and 2147483647",
326        ));
327    }
328    if let Some(priority) = &attributes.priority
329        && !(1..=4).contains(&priority.base10_parse::<u8>()?)
330    {
331        return Err(syn::Error::new_spanned(
332            priority,
333            "priority must be between 1 and 4",
334        ));
335    }
336    if let Some(queue) = &attributes.queue {
337        validate_queue(queue)?;
338    }
339    for tag in &attributes.tags {
340        validate_tag(tag)?;
341    }
342
343    let fields = match &input.data {
344        Data::Struct(data) => match &data.fields {
345            Fields::Named(fields) => &fields.named,
346            _ => {
347                return Err(syn::Error::new_spanned(
348                    &input.ident,
349                    "JobArgs can only be derived for a struct with named fields",
350                ));
351            }
352        },
353        _ => {
354            return Err(syn::Error::new_spanned(
355                &input.ident,
356                "JobArgs can only be derived for structs",
357            ));
358        }
359    };
360
361    let rename_all = serde_serialize_rename_all(&input.attrs)?;
362    let mut available_json_fields = Vec::new();
363    let mut unique_fields = Vec::new();
364    for field in fields {
365        let mut unique = false;
366        for attribute in &field.attrs {
367            if attribute.path().is_ident("river") {
368                attribute.parse_nested_meta(|meta| {
369                    if meta.path.is_ident("unique") {
370                        unique = true;
371                        return Ok(());
372                    }
373                    Err(meta.error("unsupported river field attribute"))
374                })?;
375            }
376        }
377        let serde = serde_field_attributes(&field.attrs)?;
378        if unique && (serde.flatten || serde.skip || serde.skip_serializing) {
379            return Err(syn::Error::new_spanned(
380                field,
381                "#[river(unique)] cannot be combined with #[serde(flatten)], #[serde(skip)], or #[serde(skip_serializing)]",
382            ));
383        }
384        let field_ident = field.ident.as_ref().expect("named fields have identifiers");
385        let rust_name = field_ident.unraw().to_string();
386        let mut json_name = rename_all.as_ref().map_or_else(
387            || Ok(rust_name.clone()),
388            |rule| rename_field(&rust_name, rule),
389        )?;
390        if let Some(rename) = serde.rename {
391            json_name = rename.value();
392        }
393        if !serde.flatten && !serde.skip && !serde.skip_serializing {
394            available_json_fields.push(json_name.clone());
395        }
396        if unique {
397            if !attributes
398                .unique
399                .as_ref()
400                .is_some_and(|unique| unique.by_args)
401            {
402                return Err(syn::Error::new_spanned(
403                    field_ident,
404                    "#[river(unique)] fields are only hashed with `unique(by_args)`; add it to the type's #[river(...)] attribute",
405                ));
406            }
407            unique_fields.push(vec![LitStr::new(&json_name, field_ident.span())]);
408        }
409    }
410    if let Some(unique) = &attributes.unique {
411        for path in &unique.by_args_paths {
412            let components = parse_unique_path(path)?;
413            let first = &components[0];
414            if !available_json_fields.iter().any(|field| field == first) {
415                return Err(syn::Error::new_spanned(
416                    path,
417                    "unique JSON path must start with a serialized field name",
418                ));
419            }
420            unique_fields.push(
421                components
422                    .into_iter()
423                    .map(|component| LitStr::new(&component, path.span()))
424                    .collect(),
425            );
426        }
427    }
428    validate_unique_paths(&unique_fields)?;
429    let unique_fields = unique_fields.iter().map(|path| quote!(&[#(#path),*]));
430
431    let krate = attributes
432        .krate
433        .clone()
434        .unwrap_or_else(|| syn::parse_quote!(::riverqueue));
435    let name = &input.ident;
436    let aliases = &attributes.aliases;
437    let (impl_generics, type_generics, where_clause) = input.generics.split_for_impl();
438    let set_max_attempts = attributes
439        .max_attempts
440        .as_ref()
441        .map(|value| quote!(.with_max_attempts(#value)));
442    let set_pending = attributes
443        .pending
444        .as_ref()
445        .map(|value| quote!(.with_pending(#value)));
446    let set_priority = attributes
447        .priority
448        .as_ref()
449        .map(|value| quote!(.with_priority(#value)));
450    let set_queue = attributes
451        .queue
452        .as_ref()
453        .map(|value| quote!(.with_queue(#value)));
454    let set_tags = (!attributes.tags.is_empty()).then(|| {
455        let tags = &attributes.tags;
456        quote!(.with_tags([#(#tags),*]))
457    });
458    let set_unique = attributes
459        .unique
460        .as_ref()
461        .map(|unique| expand_unique_opts(&krate, unique));
462    // Bind the function's result with the expected type so a mismatched
463    // function is reported at its path.
464    let overlay = attributes.insert_opts.as_ref().map(|function| {
465        let call = quote_spanned!(function.span()=> #function());
466        quote! {
467            .overlay({
468                let overrides: #krate::InsertOpts = #call;
469                overrides
470            })
471        }
472    });
473    Ok(quote! {
474        impl #impl_generics #krate::JobArgs for #name #type_generics #where_clause {
475            const KIND: &'static str = #kind;
476
477            fn kind_aliases() -> &'static [&'static str] {
478                &[#(#aliases),*]
479            }
480
481            fn default_insert_opts() -> #krate::InsertOpts {
482                #krate::InsertOpts::default()
483                    #set_max_attempts
484                    #set_pending
485                    #set_priority
486                    #set_queue
487                    #set_tags
488                    #set_unique
489                    #overlay
490            }
491
492            fn unique_fields() -> &'static [&'static [&'static str]] {
493                &[#(#unique_fields),*]
494            }
495        }
496    })
497}
498
499fn expand_unique_opts(krate: &syn::Path, unique: &UniqueAttribute) -> proc_macro2::TokenStream {
500    let by_args = unique.by_args.then(|| quote!(.with_by_args(true)));
501    let by_period = unique.by_period.map(
502        |(seconds, nanos)| quote!(.with_by_period(::core::time::Duration::new(#seconds, #nanos))),
503    );
504    let by_queue = unique.by_queue.then(|| quote!(.with_by_queue(true)));
505    let by_state = unique.by_state.as_ref().map(|states| {
506        let variants = states.iter().map(|state| {
507            let variant = JOB_STATES
508                .iter()
509                .find(|(name, _)| state == name)
510                .map_or("Available", |(_, variant)| variant);
511            let variant = Ident::new(variant, state.span());
512            quote!(#krate::JobState::#variant)
513        });
514        quote!(.with_by_state([#(#variants),*]))
515    });
516    let exclude_kind = unique
517        .exclude_kind
518        .then(|| quote!(.with_exclude_kind(true)));
519    quote! {
520        .with_unique(
521            #krate::UniqueOpts::new()
522                #by_args
523                #by_period
524                #by_queue
525                #by_state
526                #exclude_kind
527        )
528    }
529}
530
531/// Decode the convenience dotted syntax into literal JSON field names.
532fn parse_unique_path(path: &LitStr) -> syn::Result<Vec<String>> {
533    let mut parts = Vec::new();
534    let mut current = String::new();
535    let mut escaped = false;
536    for character in path.value().chars() {
537        if escaped {
538            current.push(character);
539            escaped = false;
540        } else if character == '\\' {
541            escaped = true;
542        } else if character == '.' {
543            parts.push(std::mem::take(&mut current));
544        } else {
545            current.push(character);
546        }
547    }
548    if escaped {
549        return Err(syn::Error::new_spanned(
550            path,
551            "unique JSON path ends in an escape",
552        ));
553    }
554    parts.push(current);
555    if parts.iter().any(String::is_empty) {
556        return Err(syn::Error::new_spanned(
557            path,
558            "unique JSON path segments cannot be empty",
559        ));
560    }
561    Ok(parts)
562}
563
564fn validate_unique_paths(paths: &[Vec<LitStr>]) -> syn::Result<()> {
565    for path in paths {
566        if path.iter().any(|segment| segment.value().is_empty()) {
567            return Err(syn::Error::new_spanned(
568                &path[0],
569                "unique JSON path segments cannot be empty",
570            ));
571        }
572        if let Some(segment) = path.iter().find(|segment| {
573            let value = segment.value();
574            value.bytes().all(|byte| byte.is_ascii_digit()) || value == "-1"
575        }) {
576            return Err(syn::Error::new_spanned(
577                segment,
578                "numeric unique JSON path segments require array semantics that are not yet supported",
579            ));
580        }
581    }
582    for path in paths {
583        let value = path.iter().map(LitStr::value).collect::<Vec<_>>();
584        if let Some(other) = paths.iter().find(|other| {
585            other.len() > path.len()
586                && other
587                    .iter()
588                    .zip(&value)
589                    .all(|(segment, value)| segment.value() == *value)
590        }) {
591            return Err(syn::Error::new_spanned(
592                &other[0],
593                format!(
594                    "unique JSON path {:?} is inside another unique path {value:?}",
595                    other.iter().map(LitStr::value).collect::<Vec<_>>()
596                ),
597            ));
598        }
599    }
600    Ok(())
601}
602
603#[derive(Default)]
604struct SerdeFieldAttributes {
605    flatten: bool,
606    rename: Option<LitStr>,
607    skip: bool,
608    skip_serializing: bool,
609}
610
611fn serde_field_attributes(attributes: &[syn::Attribute]) -> syn::Result<SerdeFieldAttributes> {
612    let mut parsed = SerdeFieldAttributes::default();
613    for attribute in attributes {
614        if !attribute.path().is_ident("serde") {
615            continue;
616        }
617        for meta in serde_metas(attribute)? {
618            match meta {
619                Meta::Path(path) if path.is_ident("flatten") => parsed.flatten = true,
620                Meta::Path(path) if path.is_ident("skip") => parsed.skip = true,
621                Meta::Path(path) if path.is_ident("skip_serializing") => {
622                    parsed.skip_serializing = true;
623                }
624                Meta::NameValue(meta) if meta.path.is_ident("rename") => {
625                    parsed.rename = Some(meta_lit_str(&meta)?);
626                }
627                Meta::List(meta) if meta.path.is_ident("rename") => {
628                    if let Some(rename) = serialize_name_from_list(&meta)? {
629                        parsed.rename = Some(rename);
630                    }
631                }
632                _ => {}
633            }
634        }
635    }
636    Ok(parsed)
637}
638
639fn serde_serialize_rename_all(attributes: &[syn::Attribute]) -> syn::Result<Option<LitStr>> {
640    let mut rename_all = None;
641    for attribute in attributes {
642        if !attribute.path().is_ident("serde") {
643            continue;
644        }
645        for meta in serde_metas(attribute)? {
646            match meta {
647                Meta::NameValue(meta) if meta.path.is_ident("rename_all") => {
648                    rename_all = Some(meta_lit_str(&meta)?);
649                }
650                Meta::List(meta) if meta.path.is_ident("rename_all") => {
651                    if let Some(rename) = serialize_name_from_list(&meta)? {
652                        rename_all = Some(rename);
653                    }
654                }
655                _ => {}
656            }
657        }
658    }
659    Ok(rename_all)
660}
661
662fn serde_metas(attribute: &syn::Attribute) -> syn::Result<Punctuated<Meta, Token![,]>> {
663    attribute.parse_args_with(Punctuated::<Meta, Token![,]>::parse_terminated)
664}
665
666fn serialize_name_from_list(meta: &syn::MetaList) -> syn::Result<Option<LitStr>> {
667    let nested = meta.parse_args_with(Punctuated::<Meta, Token![,]>::parse_terminated)?;
668    nested
669        .iter()
670        .find_map(|meta| match meta {
671            Meta::NameValue(meta) if meta.path.is_ident("serialize") => Some(meta_lit_str(meta)),
672            _ => None,
673        })
674        .transpose()
675}
676
677fn meta_lit_str(meta: &syn::MetaNameValue) -> syn::Result<LitStr> {
678    match &meta.value {
679        syn::Expr::Lit(expression) => match &expression.lit {
680            Lit::Str(value) => Ok(value.clone()),
681            _ => Err(syn::Error::new_spanned(
682                &meta.value,
683                "expected string literal",
684            )),
685        },
686        _ => Err(syn::Error::new_spanned(
687            &meta.value,
688            "expected string literal",
689        )),
690    }
691}
692
693fn rename_field(field: &str, rule: &LitStr) -> syn::Result<String> {
694    let renamed = match rule.value().as_str() {
695        "lowercase" | "snake_case" => field.to_owned(),
696        "UPPERCASE" | "SCREAMING_SNAKE_CASE" => field.to_ascii_uppercase(),
697        "PascalCase" => rename_field_pascal_case(field),
698        "camelCase" => {
699            let pascal = rename_field_pascal_case(field);
700            let mut characters = pascal.chars();
701            characters.next().map_or_else(String::new, |first| {
702                first.to_ascii_lowercase().to_string() + characters.as_str()
703            })
704        }
705        "kebab-case" => field.replace('_', "-"),
706        "SCREAMING-KEBAB-CASE" => field.to_ascii_uppercase().replace('_', "-"),
707        unsupported => {
708            return Err(syn::Error::new_spanned(
709                rule,
710                format!("unsupported serde rename rule {unsupported:?}"),
711            ));
712        }
713    };
714    Ok(renamed)
715}
716
717fn rename_field_pascal_case(field: &str) -> String {
718    let mut renamed = String::new();
719    let mut capitalize = true;
720    for character in field.chars() {
721        if character == '_' {
722            capitalize = true;
723        } else if capitalize {
724            renamed.push(character.to_ascii_uppercase());
725            capitalize = false;
726        } else {
727            renamed.push(character);
728        }
729    }
730    renamed
731}
732
733fn validate_kind(kind: &LitStr) -> syn::Result<()> {
734    let value = kind.value();
735    let mut characters = value.chars();
736    if value.len() < 2
737        || value.len() >= 128
738        || !characters
739            .next()
740            .is_some_and(|character| character == '_' || character.is_ascii_alphanumeric())
741        || !characters.all(|character| {
742            character.is_ascii_alphanumeric()
743                || matches!(
744                    character,
745                    '_' | '-' | '[' | ']' | '<' | '>' | '/' | '.' | 'ยท' | ':' | '+'
746                )
747        })
748    {
749        return Err(syn::Error::new_spanned(kind, "invalid River job kind"));
750    }
751    Ok(())
752}
753
754fn validate_queue(queue: &LitStr) -> syn::Result<()> {
755    let value = queue.value();
756    let mut characters = value.chars();
757    let valid = value.len() <= 64
758        && characters
759            .next()
760            .is_some_and(|character| character.is_ascii_lowercase() || character.is_ascii_digit())
761        && value.chars().all(|character| {
762            character.is_ascii_lowercase()
763                || character.is_ascii_digit()
764                || matches!(character, '_' | '-')
765        })
766        && !value.contains("__")
767        && !value.contains("--")
768        && !value.contains("_-")
769        && !value.contains("-_")
770        && value
771            .chars()
772            .next_back()
773            .is_some_and(|character| character.is_ascii_lowercase() || character.is_ascii_digit());
774    if !valid {
775        return Err(syn::Error::new_spanned(queue, "invalid River queue name"));
776    }
777    Ok(())
778}
779
780/// Validates a tag with River's rules: 3 to 255 bytes of ASCII word
781/// characters and `-`, starting and ending with a word character.
782fn validate_tag(tag: &LitStr) -> syn::Result<()> {
783    let value = tag.value();
784    let is_word = |character: char| character == '_' || character.is_ascii_alphanumeric();
785    let valid = (3..=255).contains(&value.len())
786        && value.chars().next().is_some_and(is_word)
787        && value.chars().next_back().is_some_and(is_word)
788        && value
789            .chars()
790            .all(|character| is_word(character) || character == '-');
791    if !valid {
792        return Err(syn::Error::new_spanned(
793            tag,
794            "invalid River tag; tags contain 3 to 255 ASCII letters, digits, `_`, or `-`, and start and end with a letter, digit, or `_`",
795        ));
796    }
797    Ok(())
798}
799
800#[cfg(test)]
801mod tests {
802    use super::*;
803
804    fn derive(source: &str) -> syn::Result<proc_macro2::TokenStream> {
805        expand_job_args(&syn::parse_str(source).expect("valid Rust syntax"))
806    }
807
808    fn compact(tokens: &proc_macro2::TokenStream) -> String {
809        tokens.to_string().replace(' ', "")
810    }
811
812    #[test]
813    fn accepts_complete_job_args_configuration() {
814        let expanded = derive(
815            r#"
816            #[derive(serde::Serialize)]
817            #[serde(rename_all = "camelCase")]
818            #[river(
819                kind = "email.send",
820                aliases("email_send_v1"),
821                max_attempts = 8,
822                pending = true,
823                priority = 2,
824                queue = "email-critical",
825                tags("email", "outbound-mail"),
826                unique(
827                    by_args("account.id"),
828                    by_period = "1h30m",
829                    by_queue,
830                    by_state(available, pending, running, scheduled, retryable),
831                    exclude_kind
832                ),
833                insert_opts = email_insert_opts
834            )]
835            struct EmailArgs {
836                account: Account,
837                #[river(unique)]
838                message_id: String,
839            }
840            "#,
841        )
842        .unwrap();
843        let expanded = compact(&expanded);
844
845        assert!(expanded.contains("\"email.send\""));
846        assert!(expanded.contains("\"email_send_v1\""));
847        assert!(expanded.contains(".with_tags([\"email\",\"outbound-mail\"])"));
848        assert!(expanded.contains(".with_by_args(true)"));
849        assert!(expanded.contains(".with_by_period(::core::time::Duration::new(5400u64,0u32))"));
850        assert!(expanded.contains(".with_by_queue(true)"));
851        assert!(expanded.contains("::riverqueue::JobState::Retryable"));
852        assert!(expanded.contains(".with_exclude_kind(true)"));
853        assert!(expanded.contains(
854            ".overlay({letoverrides:::riverqueue::InsertOpts=email_insert_opts();overrides})"
855        ));
856        assert!(expanded.contains("&[&[\"messageId\"],&[\"account\",\"id\"]]"));
857    }
858
859    #[test]
860    fn follows_serde_serialization_names() {
861        let expanded = derive(
862            r#"
863            #[serde(rename_all(serialize = "SCREAMING-KEBAB-CASE", deserialize = "camelCase"))]
864            #[river(kind = "serde_names", unique(by_args))]
865            struct SerdeNames {
866                #[river(unique)]
867                first_value: String,
868                #[river(unique)]
869                #[serde(rename(serialize = "wire-name", deserialize = "inputName"))]
870                second_value: String,
871                #[river(unique)]
872                r#type: String,
873            }
874            "#,
875        )
876        .unwrap()
877        .to_string();
878
879        assert!(expanded.contains("FIRST-VALUE"));
880        assert!(expanded.contains("wire-name"));
881        assert!(expanded.contains("TYPE"));
882        assert!(!expanded.contains("inputName"));
883    }
884
885    #[test]
886    fn parses_go_durations() {
887        for (text, nanos) in [
888            ("1s", 1_000_000_000),
889            ("1h", 3_600_000_000_000),
890            ("1h30m", 5_400_000_000_000),
891            ("1.5h", 5_400_000_000_000),
892            ("90m", 5_400_000_000_000),
893            ("1500ms", 1_500_000_000),
894            ("2s500ms", 2_500_000_000),
895            ("1\u{b5}s", 1_000),
896            ("7ns", 7),
897        ] {
898            assert_eq!(parse_go_duration(text), Ok(nanos), "{text}");
899        }
900        for text in ["", "1", "h", "1x", "-1h", "1.h.", "."] {
901            assert!(parse_go_duration(text).is_err(), "{text}");
902        }
903    }
904
905    #[test]
906    fn permits_conditionally_omitted_unique_fields() {
907        let expanded = derive(
908            r#"
909            #[river(kind = "optional_unique", unique(by_args))]
910            struct OptionalUnique {
911                #[river(unique)]
912                #[serde(skip_serializing_if = "Option::is_none")]
913                optional: Option<String>,
914            }
915            "#,
916        )
917        .unwrap()
918        .to_string();
919
920        assert!(expanded.contains("optional"));
921    }
922
923    #[test]
924    fn rejects_serde_attributes_that_hide_unique_fields() {
925        for serde_attribute in ["flatten", "skip", "skip_serializing"] {
926            let source = format!(
927                r#"
928                #[river(kind = "invalid_serde", unique(by_args))]
929                struct InvalidSerde {{
930                    #[river(unique)]
931                    #[serde({serde_attribute})]
932                    value: String,
933                }}
934                "#,
935            );
936            let error = derive(&source).expect_err("attribute combination should be rejected");
937
938            assert!(
939                error
940                    .to_string()
941                    .contains("#[river(unique)] cannot be combined"),
942                "unexpected error for {serde_attribute}: {error}"
943            );
944        }
945
946        for serde_attribute in ["flatten", "skip", "skip_serializing"] {
947            let source = format!(
948                r#"
949                #[river(kind = "invalid_serde_path", unique(by_args("value")))]
950                struct InvalidSerdePath {{
951                    #[serde({serde_attribute})]
952                    value: String,
953                }}
954                "#,
955            );
956            let error = derive(&source).expect_err("hidden unique path should be rejected");
957
958            assert!(
959                error
960                    .to_string()
961                    .contains("unique JSON path must start with a serialized field name"),
962                "unexpected path error for {serde_attribute}: {error}"
963            );
964        }
965    }
966
967    #[test]
968    fn rejects_unsupported_serde_rename_rule() {
969        let error = derive(
970            r#"
971            #[serde(rename_all(serialize = "Title Case"))]
972            #[river(kind = "invalid_rename")]
973            struct InvalidRename { value: String }
974            "#,
975        )
976        .expect_err("rename rule should be rejected");
977
978        assert!(
979            error
980                .to_string()
981                .contains("unsupported serde rename rule \"Title Case\"")
982        );
983    }
984
985    #[test]
986    fn rejects_invalid_job_args_configuration() {
987        let cases = [
988            (
989                "struct MissingKind { value: String }",
990                "JobArgs requires #[river(kind = \"...\")]",
991            ),
992            (
993                r#"#[river(kind = "x")] struct InvalidKind { value: String }"#,
994                "invalid River job kind",
995            ),
996            (
997                r#"#[river(kind = "valid", aliases("valid"))] struct DuplicateKind { value: String }"#,
998                "a kind alias cannot equal the primary kind",
999            ),
1000            (
1001                r#"#[river(kind = "valid", priority = 5)] struct InvalidPriority { value: String }"#,
1002                "priority must be between 1 and 4",
1003            ),
1004            (
1005                r#"#[river(kind = "valid", queue = "Invalid")] struct InvalidQueue { value: String }"#,
1006                "invalid River queue name",
1007            ),
1008            (
1009                r#"#[river(kind = "valid", tags("x"))] struct InvalidTag { value: String }"#,
1010                "invalid River tag",
1011            ),
1012            (
1013                r#"#[river(kind = "valid", unique(by_args("missing.id")))] struct InvalidPath { value: String }"#,
1014                "unique JSON path must start with a serialized field name",
1015            ),
1016            (
1017                r#"#[river(kind = "valid", unique("value"))] struct OldPathSyntax { value: String }"#,
1018                "declare unique argument paths with `unique(by_args(",
1019            ),
1020            (
1021                r#"#[river(kind = "valid", unique())] struct EmptyUnique { value: String }"#,
1022                "unique(...) requires at least one of",
1023            ),
1024            (
1025                r#"#[river(kind = "valid", unique(by_arg))] struct UnknownUnique { value: String }"#,
1026                "unsupported unique option",
1027            ),
1028            (
1029                r#"#[river(kind = "valid", unique(by_period = "500ms"))] struct ShortPeriod { value: String }"#,
1030                "by_period must be at least one second",
1031            ),
1032            (
1033                r#"#[river(kind = "valid", unique(by_period = "1 hour"))] struct BadPeriod { value: String }"#,
1034                "invalid duration",
1035            ),
1036            (
1037                r#"#[river(kind = "valid", unique(by_state(available, running)))] struct MissingStates { value: String }"#,
1038                "missing pending, scheduled",
1039            ),
1040            (
1041                r#"#[river(kind = "valid", unique(by_state(available, pending, running, scheduled, done)))] struct UnknownState { value: String }"#,
1042                "unknown job state `done`",
1043            ),
1044            (
1045                r#"#[river(kind = "valid", unique(by_state(available, available, pending, running, scheduled)))] struct DuplicateState { value: String }"#,
1046                "duplicate job state `available`",
1047            ),
1048            (
1049                r#"#[river(kind = "valid", unique(by_queue))] struct UniqueFieldWithoutArgs { #[river(unique)] value: String }"#,
1050                "#[river(unique)] fields are only hashed with `unique(by_args)`",
1051            ),
1052            (
1053                r#"#[river(kind = "valid")] struct UniqueFieldWithoutUnique { #[river(unique)] value: String }"#,
1054                "#[river(unique)] fields are only hashed with `unique(by_args)`",
1055            ),
1056            (
1057                r#"#[river(kind = "valid", unique(by_args("value.0")))] struct IndexPath { value: String }"#,
1058                "require array semantics",
1059            ),
1060            (
1061                r#"#[river(kind = "valid", unique(by_args("value", "value.id")))] struct NestedPath { value: String }"#,
1062                "is inside another unique path",
1063            ),
1064        ];
1065
1066        for (source, message) in cases {
1067            let error = derive(source).expect_err("configuration should be rejected");
1068            assert!(
1069                error.to_string().contains(message),
1070                "unexpected error for {source}: {error}"
1071            );
1072        }
1073    }
1074
1075    #[test]
1076    fn uses_configured_crate_path() {
1077        let expanded = derive(
1078            r#"
1079            #[river(kind = "renamed", crate = "::my_app::river", unique(by_state(available, pending, running, scheduled)))]
1080            struct Renamed { value: String }
1081            "#,
1082        )
1083        .unwrap();
1084        let expanded = compact(&expanded);
1085
1086        assert!(expanded.contains("impl::my_app::river::JobArgsforRenamed"));
1087        assert!(expanded.contains("::my_app::river::JobState::Available"));
1088        assert!(!expanded.contains("::riverqueue::"));
1089    }
1090}