Skip to main content

cachekit_macros/
lib.rs

1use proc_macro::TokenStream;
2use proc_macro2::TokenStream as TokenStream2;
3use quote::{quote, quote_spanned};
4use syn::{
5    parse::{Parse, ParseStream},
6    parse_macro_input,
7    spanned::Spanned,
8    Ident, ItemFn, LitInt, LitStr, ReturnType, Token, Type,
9};
10
11// ── Attribute argument parsing ───────────────────────────────────────────────
12
13struct MacroArgs {
14    client: Ident,
15    ttl: u64,
16    interop: String,
17    namespace: String,
18    secure: bool,
19}
20
21/// Compile-time mirror of the interop/v1 segment grammar
22/// (`^[a-z0-9][a-z0-9._-]{0,63}$` — see `cachekit::interop`'s
23/// `validate_segment`, the canonical implementation). Duplicated because a
24/// proc-macro crate cannot depend on the runtime crate; `interop_key`
25/// re-validates at runtime, so drift fails loudly, never silently. The `..`
26/// ban and the reserved-namespace check are mirrored in `parse_segment`.
27fn segment_is_valid(segment: &str) -> bool {
28    let bytes = segment.as_bytes();
29    matches!(bytes.first(), Some(b) if b.is_ascii_lowercase() || b.is_ascii_digit())
30        && bytes.len() <= 64
31        && bytes[1..].iter().all(|b| {
32            b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'.' | b'_' | b'-')
33        })
34}
35
36/// Extract and validate an interop segment from a string literal, spanning
37/// the error to the literal.
38///
39/// Mirrors `validate_segment`'s `..` ban (either segment; the CachekitIO
40/// server rejects `..` anywhere in a key) and its namespace reservation: a
41/// `namespace` of exactly `ns` or `nsapi` is rejected (the server parses a key
42/// starting `ns:` / `nsapi:` as namespace-prefixed); both stay valid as
43/// `interop`.
44fn parse_segment(kind: &str, lit: &LitStr) -> syn::Result<String> {
45    let value = lit.value();
46    if !segment_is_valid(&value) {
47        return Err(syn::Error::new(
48            lit.span(),
49            format!(
50                "`{kind}` {value:?} is not a valid interop/v1 key segment: must match \
51                 ^[a-z0-9][a-z0-9._-]{{0,63}}$ (lowercase ASCII letters, digits, '.', '_', \
52                 '-'; 1-64 chars)"
53            ),
54        ));
55    }
56    if value.contains("..") {
57        return Err(syn::Error::new(
58            lit.span(),
59            format!(
60                "`{kind}` {value:?} must not contain \"..\": the CachekitIO server rejects \
61                 \"..\" anywhere in a key"
62            ),
63        ));
64    }
65    if kind == "namespace" && matches!(value.as_str(), "ns" | "nsapi") {
66        return Err(syn::Error::new(
67            lit.span(),
68            format!(
69                "`namespace` {value:?} is reserved: the CachekitIO server parses a key \
70                 starting \"{value}:\" as namespace-prefixed"
71            ),
72        ));
73    }
74    Ok(value)
75}
76
77impl Parse for MacroArgs {
78    fn parse(input: ParseStream) -> syn::Result<Self> {
79        let mut client: Option<Ident> = None;
80        let mut ttl: Option<u64> = None;
81        let mut interop: Option<String> = None;
82        let mut namespace: Option<String> = None;
83        let mut secure = false;
84
85        while !input.is_empty() {
86            let key: Ident = input.parse()?;
87            match key.to_string().as_str() {
88                "client" => {
89                    input.parse::<Token![=]>()?;
90                    client = Some(input.parse()?);
91                }
92                "ttl" => {
93                    input.parse::<Token![=]>()?;
94                    let lit: LitInt = input.parse()?;
95                    ttl = Some(lit.base10_parse()?);
96                }
97                "interop" => {
98                    input.parse::<Token![=]>()?;
99                    let lit: LitStr = input.parse()?;
100                    interop = Some(parse_segment("interop", &lit)?);
101                }
102                "namespace" => {
103                    input.parse::<Token![=]>()?;
104                    let lit: LitStr = input.parse()?;
105                    namespace = Some(parse_segment("namespace", &lit)?);
106                }
107                "secure" => {
108                    secure = true;
109                }
110                other => {
111                    return Err(syn::Error::new(
112                        key.span(),
113                        format!("unknown attribute `{other}`"),
114                    ));
115                }
116            }
117
118            // Consume trailing comma if present
119            if !input.is_empty() {
120                input.parse::<Token![,]>()?;
121            }
122        }
123
124        let client = client
125            .ok_or_else(|| input.error("`client` is required: #[cachekit(client = name, ...)]"))?;
126        let ttl = ttl.ok_or_else(|| {
127            input.error("`ttl` is required: #[cachekit(client = name, ttl = 60)]")
128        })?;
129        let interop = interop.ok_or_else(|| {
130            input.error(
131                "`interop` is required: #[cachekit(client = name, ttl = 60, interop = \
132                 \"get_user\", namespace = \"users\")] — it names the operation segment of the \
133                 interop/v1 cache key `{namespace}:{operation}:{args_hash}`, and the spec \
134                 requires it to be explicit (protocol spec/interop-mode.md, SDK requirement 1)",
135            )
136        })?;
137        let namespace = namespace.ok_or_else(|| {
138            input.error(
139                "`namespace` is required: #[cachekit(client = name, ttl = 60, interop = \
140                 \"get_user\", namespace = \"users\")] — cache keys are interop/v1 \
141                 `{namespace}:{operation}:{args_hash}` and the namespace segment cannot be empty",
142            )
143        })?;
144
145        Ok(MacroArgs {
146            client,
147            ttl,
148            interop,
149            namespace,
150            secure,
151        })
152    }
153}
154
155// ── Return-type extraction ───────────────────────────────────────────────────
156
157/// Extract `T` from `Result<T, E>` in a function's return type.
158fn extract_ok_type(ret: &ReturnType) -> syn::Result<Type> {
159    let ty = match ret {
160        ReturnType::Type(_, ty) => ty.as_ref(),
161        ReturnType::Default => {
162            return Err(syn::Error::new_spanned(
163                ret,
164                "#[cachekit] function must return Result<T, CachekitError>",
165            ));
166        }
167    };
168
169    // Walk through the type to find Result<T, E> and extract T.
170    if let Type::Path(type_path) = ty {
171        if let Some(seg) = type_path.path.segments.last() {
172            if seg.ident != "Result" {
173                return Err(syn::Error::new_spanned(
174                    ty,
175                    "#[cachekit] function must return Result<T, CachekitError>",
176                ));
177            }
178            if let syn::PathArguments::AngleBracketed(args) = &seg.arguments {
179                if let Some(syn::GenericArgument::Type(first)) = args.args.first() {
180                    return Ok(first.clone());
181                }
182            }
183        }
184    }
185
186    Err(syn::Error::new_spanned(
187        ty,
188        "#[cachekit] function must return Result<T, CachekitError>",
189    ))
190}
191
192// ── Proc-macro entry point ──────────────────────────────────────────────────
193
194/// Cache the result of an async function under an interop/v1 cache key.
195///
196/// Keys are `{namespace}:{operation}:{args_hash}` per the protocol's
197/// interop-mode spec, so the same entry is addressable from the Python and
198/// TypeScript SDKs — Python's `@cache(interop="get_user",
199/// namespace="users")` computes the identical key for the same arguments.
200///
201/// # Attributes
202///
203/// - `client = <ident>` (required): Name of the `&CacheKit` parameter.
204/// - `ttl = <integer>` (required): TTL in seconds.
205/// - `interop = "<string>"` (required): explicit, language-neutral operation
206///   segment (`^[a-z0-9][a-z0-9._-]{0,63}$`) — same meaning as Python's
207///   `interop=` / TypeScript's `interop:`.
208/// - `namespace = "<string>"` (required): interop/v1 namespace segment,
209///   same grammar. `ns` and `nsapi` are reserved as namespaces (a compile
210///   error — the CachekitIO server parses those key prefixes); operations are
211///   unaffected. Neither segment may contain `..` (a compile error — the
212///   server rejects `..` anywhere in a key); a lone `.` is fine.
213/// - `secure` (optional flag): require encryption — every call fails with
214///   `CachekitError::Config` on a client without it — and fail closed on
215///   every backend error (see *Reliability behaviour*). The flag is not what
216///   encrypts: on a client with encryption configured, a function without it
217///   stores and reads ciphertext too, because the client's value methods
218///   encrypt.
219///
220/// # Requirements
221///
222/// - Every non-client argument must be a plain identifier (no destructuring
223///   patterns, no `self`) and must convert into
224///   `cachekit::interop::InteropValue` via `From` (`bool`, `i32`/`i64`/
225///   `u32`/`u64`/`i128`, `f64`, `&str`/`String`, `Uuid`). Unsupported
226///   argument types fail at compile time.
227/// - In-model *values* outside the interop ranges fail at CALL time with
228///   `CachekitError::Serialization` before the body runs: non-finite floats
229///   (`NAN`, `±INFINITY`) and `i128` outside `[-2^63, 2^64-1]`. This
230///   fail-loud contract matches the Python and TypeScript SDKs — silently
231///   running uncached would mask cross-SDK key divergence.
232/// - The client must be built **without** `.namespace()` — interop keys
233///   carry their own namespace segment, and reads fail closed on a
234///   namespaced client.
235/// - A stored entry that cannot be decoded as the return type
236///   (`CachekitError::Serialization`) is treated as a miss and overwritten
237///   (self-healing). On a client with encryption configured, `secure` or
238///   not, this covers only post-decrypt decode failures: an entry that fails
239///   AES-GCM authentication raises `CachekitError::Encryption`, which
240///   propagates (fail-closed). The failed read drops the key's L1 copy and
241///   leaves the backend entry in place, so the next call reads the backend
242///   again: it fails while that entry remains, succeeds once any process
243///   replaces it with ciphertext this client can decrypt, and is a miss once
244///   it expires or is deleted.
245///
246/// # Requirements (continued)
247///
248/// - The function must be `async` — the generated body awaits the cache
249///   read, the cold-miss single-flight, and SWR refresh scheduling. A sync
250///   function is a clear compile-time error, never a silent no-op.
251///
252/// # Reliability behaviour
253///
254/// - **Stale-while-revalidate** (client SWR enabled — the default with the
255///   `l1` feature on native targets): an L1 hit past the client's freshness
256///   threshold (`swr_threshold_ratio` × entry TTL, ±10% jitter) but before
257///   hard expiry is returned **immediately** — the caller never blocks on a
258///   merely-stale entry — while one background task re-executes the function.
259///   Its version-checked commit rewrites both layers only if no newer set or
260///   delete replaced the stale entry; a successful commit renews the L1 hard
261///   expiry with the full write-path TTL. Refresh dedup rides
262///   `CacheKit::single_flight`: N concurrent stale readers trigger exactly
263///   one re-execution per process (and, on lock-capable backends, per
264///   fleet). Hard-expired entries always take the normal blocking miss path.
265///   The refresh task needs a tokio runtime (skipped otherwise — the stale
266///   value was already served) and captures arguments by owned copy
267///   (`Clone`/`ToOwned` — already required for key derivation); the future
268///   must be `Send`. Refresh failures are absorbed: the stale value keeps
269///   serving until hard expiry, where the blocking path surfaces errors.
270/// - **Graceful degradation**: on an outage-class backend failure —
271///   transient, timeout, an open circuit breaker, or a backpressure shed —
272///   the plain path fails *open*: the function executes uncached and its
273///   result is returned.
274///   Permanent and authentication errors propagate even on the plain path
275///   (a wrong API key must fail loudly, not silently disable caching
276///   forever). With `secure`, *every* backend and decryption error fails
277///   *closed* and propagates: an encrypted workload never silently
278///   degrades. Without the flag, a client with encryption configured still
279///   propagates decryption errors and still encrypts what it writes; only
280///   the outage-class backend errors above fail open.
281/// - **Cold-miss single-flight**: concurrent calls that miss on the same
282///   key are collapsed to one execution per process (and per fleet, when
283///   the backend supports distributed fill locks — CachekitIO and Redis do,
284///   with the `reliability` feature). Waiters re-read the filled entry
285///   instead of recomputing. See `cachekit::flight`.
286///
287/// # Example
288///
289/// ```ignore
290/// #[cachekit(client = cache, ttl = 60, interop = "get_user", namespace = "users")]
291/// async fn get_user(cache: &CacheKit, id: u64) -> Result<User, CachekitError> {
292///     Ok(User { name: format!("User {id}") })
293/// }
294/// ```
295#[proc_macro_attribute]
296pub fn cachekit(attr: TokenStream, item: TokenStream) -> TokenStream {
297    let args = parse_macro_input!(attr as MacroArgs);
298    let input_fn = parse_macro_input!(item as ItemFn);
299
300    match expand(&args, input_fn) {
301        Ok(tokens) => tokens.into(),
302        Err(e) => e.to_compile_error().into(),
303    }
304}
305
306fn expand(args: &MacroArgs, mut func: ItemFn) -> syn::Result<TokenStream2> {
307    let client_ident = &args.client;
308    let ttl_secs = args.ttl;
309    let namespace = args.namespace.as_str();
310    let operation = args.interop.as_str();
311
312    // The generated body awaits (cache reads, single-flight, SWR refresh
313    // scheduling); a sync function cannot drive any of it. Fail with a clear
314    // decoration-time error instead of a cascade of "await is only allowed
315    // inside async functions" — no silent no-op (the sibling SDK posture).
316    if func.sig.asyncness.is_none() {
317        return Err(syn::Error::new_spanned(
318            func.sig.fn_token,
319            "#[cachekit] requires an `async fn`: the cache read, cold-miss single-flight, \
320             and stale-while-revalidate background refresh all await — annotate the \
321             function `async` (a sync function cannot be cached by this macro)",
322        ));
323    }
324
325    // Extract the Ok type from Result<T, E>
326    let ok_type = extract_ok_type(&func.sig.output)?;
327
328    // Collect non-client parameters (ident + type) for cache key derivation
329    // and SWR refresh capture. Every parameter MUST contribute to the key — a
330    // silently skipped parameter means two different calls share one cache
331    // entry (wrong-data collision), so anything we can't name is a compile
332    // error, never a skip.
333    let mut non_client_params: Vec<(&Ident, &Type)> = Vec::new();
334    for arg in &func.sig.inputs {
335        match arg {
336            syn::FnArg::Receiver(recv) => {
337                return Err(syn::Error::new_spanned(
338                    recv,
339                    "#[cachekit] does not support methods: a `self` receiver cannot \
340                     contribute to the interop/v1 cache key — wrap a free function instead",
341                ));
342            }
343            syn::FnArg::Typed(pat) => match pat.pat.as_ref() {
344                syn::Pat::Ident(pi) => {
345                    if pi.ident != *client_ident {
346                        non_client_params.push((&pi.ident, pat.ty.as_ref()));
347                    }
348                }
349                other => {
350                    return Err(syn::Error::new_spanned(
351                        other,
352                        "#[cachekit] parameters must be plain identifiers: destructuring \
353                         patterns cannot contribute to the cache key, and skipping them \
354                         would make different calls share one cache entry",
355                    ));
356                }
357            },
358        }
359    }
360    let non_client_idents: Vec<&Ident> = non_client_params.iter().map(|(id, _)| *id).collect();
361
362    // Convert each non-client argument to an InteropValue. `.clone()` keeps
363    // the original binding usable by the function body; for Copy types it
364    // compiles to a copy. Types outside the interop data model fail here at
365    // COMPILE time with a missing `From<T> for InteropValue` — that is the
366    // contract, not a bug: interop/v1 keys only hash modelable values.
367    // quote_spanned pins that error to the offending parameter, not the
368    // attribute.
369    let interop_args = non_client_idents.iter().map(|id| {
370        quote_spanned! {id.span()=> cachekit::interop::InteropValue::from(#id.clone()) }
371    });
372
373    // Generate cache get/set calls depending on `secure` flag.
374    let (get_expr, get_swr_expr, set_expr, complete_refresh_expr) = if args.secure {
375        (
376            quote! {
377                {
378                    let __ck_sec = #client_ident.secure_cache()?;
379                    __ck_sec.interop_get::<#ok_type>(&__ck_key).await
380                }
381            },
382            quote! {
383                {
384                    let __ck_sec = #client_ident.secure_cache()?;
385                    __ck_sec.interop_get_swr::<#ok_type>(&__ck_key).await
386                }
387            },
388            quote! {
389                let __ck_sec = #client_ident.secure_cache()?;
390                let _ = __ck_sec.set_with_ttl(&__ck_key, __ck_val, std::time::Duration::from_secs(#ttl_secs)).await;
391            },
392            quote! {
393                let __ck_sec = #client_ident.secure_cache()?;
394                let _ = __ck_sec.__complete_swr_refresh(
395                    &__ck_key,
396                    __ck_val,
397                    std::time::Duration::from_secs(#ttl_secs),
398                    __ck_swr_token,
399                ).await;
400            },
401        )
402    } else {
403        (
404            quote! { #client_ident.interop_get::<#ok_type>(&__ck_key).await },
405            quote! { #client_ident.interop_get_swr::<#ok_type>(&__ck_key).await },
406            quote! {
407                let _ = #client_ident.set_with_ttl(&__ck_key, __ck_val, std::time::Duration::from_secs(#ttl_secs)).await;
408            },
409            quote! {
410                let _ = #client_ident.__complete_swr_refresh(
411                    &__ck_key,
412                    __ck_val,
413                    std::time::Duration::from_secs(#ttl_secs),
414                    __ck_swr_token,
415                ).await;
416            },
417        )
418    };
419
420    // SWR refresh capture: the background task is `'static`, so every
421    // argument is re-materialised as an owned value before the spawn and
422    // rebound under its original name (and, for references, its original
423    // shape) inside the task — the function body runs unchanged:
424    //   - `&str`     → captured as `String`, rebound via `.as_str()` (exact)
425    //   - other `&T` → captured as `T` via `ToOwned`, rebound as `&owned`
426    //   - owned `T`  → captured via `Clone`, rebound by value
427    let mut swr_captures = TokenStream2::new();
428    let mut swr_rebinds = TokenStream2::new();
429    for (i, (id, ty)) in non_client_params.iter().enumerate() {
430        let holder = quote::format_ident!("__ck_swr_arg_{i}");
431        match ty {
432            Type::Reference(r) => {
433                // The refresh task re-executes the body from an owned
434                // snapshot rebound as an immutable borrow — mutation through
435                // a `&mut` argument cannot be preserved, so reject it up
436                // front instead of surfacing a confusing downstream error.
437                if r.mutability.is_some() {
438                    return Err(syn::Error::new_spanned(
439                        ty,
440                        "#[cachekit] does not support `&mut` parameters: the SWR background \
441                         refresh re-executes the function from an owned snapshot, so mutation \
442                         through the reference cannot be preserved — take the argument by \
443                         owned value instead",
444                    ));
445                }
446                swr_captures.extend(quote_spanned! {id.span()=>
447                    let #holder = ::std::borrow::ToOwned::to_owned(#id);
448                });
449                let is_str = matches!(r.elem.as_ref(),
450                    Type::Path(p) if p.path.is_ident("str"));
451                if is_str {
452                    swr_rebinds.extend(quote! { let #id = #holder.as_str(); });
453                } else {
454                    swr_rebinds.extend(quote! { let #id = &#holder; });
455                }
456            }
457            _ => {
458                swr_captures.extend(quote_spanned! {id.span()=>
459                    #[allow(clippy::clone_on_copy)]
460                    let #holder = #id.clone();
461                });
462                swr_rebinds.extend(quote! { let #id = #holder; });
463            }
464        }
465    }
466
467    // Graceful degradation: on an OUTAGE-class backend failure —
468    // retryable (transient/timeout), a fast-failing open circuit breaker,
469    // or a backpressure shed — the plain path fails OPEN: the
470    // wrapped function runs uncached, so a cache outage costs performance,
471    // not availability. A shed is the same class as CircuitOpen (the call
472    // never reached the backend), and failing open adds no work a cold-miss
473    // storm doesn't already create: the limiter bounds backend cache ops,
474    // not origin executions, and single-flight still dedupes those.
475    // Permanent and authentication errors PROPAGATE even on the plain path:
476    // a wrong API key that silently fell open would run uncached forever
477    // with zero signal while looking healthy. The
478    // `secure` path stays fail-CLOSED on everything: backend and decryption
479    // errors reach the caller, so an encrypted workload never silently
480    // degrades.
481    let fail_open_arm = if args.secure {
482        quote! {}
483    } else {
484        quote! {
485            Err(cachekit::error::CachekitError::Backend(__ck_be))
486                if __ck_be.kind.is_retryable()
487                    || matches!(
488                        __ck_be.kind,
489                        cachekit::error::BackendErrorKind::CircuitOpen
490                            | cachekit::error::BackendErrorKind::Backpressure
491                    ) => {}
492        }
493    };
494
495    // Capture the original function body.
496    let original_body = &func.block;
497
498    // Extract the raw return type (without `->` arrow) for type annotation.
499    let ret_ty = match &func.sig.output {
500        ReturnType::Type(_, ty) => ty.as_ref(),
501        ReturnType::Default => {
502            return Err(syn::Error::new_spanned(
503                &func.sig,
504                "#[cachekit] function must return Result<T, CachekitError>",
505            ));
506        }
507    };
508
509    // Build the new function body.
510    let new_body: syn::Block = syn::parse_quote! {
511        {
512            // interop/v1 key: {namespace}:{operation}:{args_hash} — the same
513            // key is computable from any SDK (protocol spec/interop-mode.md).
514            // The generated `.clone()` per argument keeps the binding usable
515            // by the body; for Copy types it is a copy and for `&str` it is
516            // a deliberate reference copy — hence the allows.
517            #[allow(clippy::clone_on_copy, noop_method_call)]
518            let __ck_key = cachekit::interop::interop_key(
519                #namespace,
520                #operation,
521                &[#(#interop_args),*],
522            )?;
523
524            // Try cache hit, classified against the stale-while-revalidate
525            // freshness window. A Serialization error means the stored entry
526            // cannot be decoded as #ok_type (poisoned, foreign-shaped, or a
527            // Python-internal CK frame) — treat it as a miss so the fresh
528            // result OVERWRITES it, instead of hard-failing every call until
529            // TTL expiry. Backend errors fail open on the plain path (run
530            // the function uncached) and fail closed on the secure path.
531            // Other errors (namespaced-client Config, decryption) propagate.
532            match #get_swr_expr {
533                Ok(cachekit::SwrRead::Fresh(__ck_cached)) => return Ok(__ck_cached),
534                // Stale (past the freshness threshold, before hard expiry):
535                // serve the cached value immediately and schedule ONE
536                // background refresh. Dedup rides the same single-flight as
537                // the cold-miss path: the first refresh task leads and
538                // re-executes the function; concurrent tasks queue, see the
539                // (still-present) entry, and exit without computing. Refresh
540                // failures are deliberately absorbed — the stale value keeps
541                // being served, a later stale read retries, and hard expiry
542                // falls through to the blocking path where errors surface.
543                // Completion is version-checked, so a newer explicit set or
544                // delete always wins over this older origin computation.
545                Ok(cachekit::SwrRead::Stale(__ck_cached, __ck_swr_token)) => {
546                    let __ck_swr_client = ::std::clone::Clone::clone(#client_ident);
547                    let __ck_swr_key = __ck_key.clone();
548                    #swr_captures
549                    cachekit::__swr_spawn(async move {
550                        let #client_ident = &__ck_swr_client;
551                        let __ck_key = __ck_swr_key;
552                        #swr_rebinds
553                        let _: ::std::result::Result<(), cachekit::error::CachekitError> = async {
554                            let mut __ck_flight = #client_ident.single_flight(&__ck_key).await;
555                            while __ck_flight.wait_for_fill().await {
556                                if matches!(#get_expr, Ok(Some(_))) {
557                                    // Another worker is already on it (the
558                                    // stale entry is still present, or the
559                                    // leader has refreshed) — stand down.
560                                    __ck_flight.release().await;
561                                    return Ok(());
562                                }
563                            }
564                            let __ck_result: #ret_ty = (async #original_body).await;
565                            if let Ok(ref __ck_val) = __ck_result {
566                                // Commit only if no newer set/delete replaced
567                                // the stale entry while the origin ran.
568                                #complete_refresh_expr
569                            }
570                            __ck_flight.release().await;
571                            __ck_result.map(|_| ())
572                        }
573                        .await;
574                    });
575                    return Ok(__ck_cached);
576                }
577                Ok(cachekit::SwrRead::Miss) => {}
578                Err(cachekit::error::CachekitError::Serialization(_)) => {}
579                #fail_open_arm
580                Err(__ck_err) => return Err(__ck_err.into()),
581            }
582
583            // Cold-miss single-flight: collapse concurrent fills of this key
584            // to one execution (misses are billable). While another worker is
585            // filling, re-check the cache instead of recomputing.
586            let mut __ck_flight = #client_ident.single_flight(&__ck_key).await;
587            while __ck_flight.wait_for_fill().await {
588                match #get_expr {
589                    Ok(Some(__ck_cached)) => {
590                        __ck_flight.release().await;
591                        return Ok(__ck_cached);
592                    }
593                    Ok(None) => {}
594                    Err(cachekit::error::CachekitError::Serialization(_)) => {}
595                    #fail_open_arm
596                    Err(__ck_err) => {
597                        __ck_flight.release().await;
598                        return Err(__ck_err.into());
599                    }
600                }
601            }
602
603            // Execute original function body
604            let __ck_result: #ret_ty = (async #original_body).await;
605
606            // Cache on success
607            if let Ok(ref __ck_val) = __ck_result {
608                #set_expr
609            }
610
611            __ck_flight.release().await;
612            __ck_result
613        }
614    };
615
616    *func.block = new_body;
617    Ok(quote! { #func })
618}
619
620#[cfg(test)]
621mod tests {
622    use super::{expand, segment_is_valid, MacroArgs};
623
624    /// A sync fn must fail at decoration time with a clear, actionable error
625    /// — never a cascade of "await is only allowed inside async" diagnostics,
626    /// and never a silent no-op.
627    #[test]
628    fn sync_fn_is_a_clear_decoration_time_error() {
629        let args: MacroArgs = syn::parse_quote!(
630            client = cache,
631            ttl = 60,
632            interop = "get_user",
633            namespace = "users"
634        );
635        let func: syn::ItemFn = syn::parse_quote! {
636            fn get_user(cache: &CacheKit, id: u64) -> Result<String, CachekitError> {
637                Ok(format!("User {id}"))
638            }
639        };
640        let err = expand(&args, func).expect_err("sync fn must be rejected");
641        let msg = err.to_string();
642        assert!(
643            msg.contains("requires an `async fn`"),
644            "error must name the fix, got: {msg}"
645        );
646    }
647
648    /// `&mut` parameters are rejected at decoration time: the SWR refresh
649    /// task rebinds references as immutable borrows of an owned snapshot,
650    /// so mutation through the argument cannot be modelled.
651    #[test]
652    fn mut_ref_param_is_a_clear_decoration_time_error() {
653        let args: MacroArgs = syn::parse_quote!(
654            client = cache,
655            ttl = 60,
656            interop = "get_user",
657            namespace = "users"
658        );
659        let func: syn::ItemFn = syn::parse_quote! {
660            async fn get_user(cache: &CacheKit, id: &mut u64) -> Result<String, CachekitError> {
661                Ok(format!("User {id}"))
662            }
663        };
664        let err = expand(&args, func).expect_err("&mut param must be rejected");
665        assert!(
666            err.to_string().contains("`&mut` parameters"),
667            "error must name the constraint, got: {err}"
668        );
669    }
670
671    /// The same function with `async` added expands cleanly — proving the
672    /// rejection above is precisely about asyncness.
673    #[test]
674    fn async_fn_expands() {
675        let args: MacroArgs = syn::parse_quote!(
676            client = cache,
677            ttl = 60,
678            interop = "get_user",
679            namespace = "users"
680        );
681        let func: syn::ItemFn = syn::parse_quote! {
682            async fn get_user(cache: &CacheKit, id: u64) -> Result<String, CachekitError> {
683                Ok(format!("User {id}"))
684            }
685        };
686        expand(&args, func).expect("async fn must expand");
687    }
688
689    /// Mirror of interop.rs's validate_segment acceptance table — the two
690    /// implementations must not drift (see the NOTE on validate_segment).
691    #[test]
692    fn segment_grammar_table() {
693        for ok in [
694            "a",
695            "0",
696            "users",
697            "users.fetch_by_id",
698            "a-b_c.d",
699            &"a".repeat(64),
700        ] {
701            assert!(segment_is_valid(ok), "{ok:?} should be accepted");
702        }
703        for bad in [
704            "",
705            ".users",
706            "-users",
707            "_users",
708            "Users",
709            "users\n",
710            "users:x",
711            "users/x",
712            "usérs",
713            &"a".repeat(65),
714        ] {
715            assert!(!segment_is_valid(bad), "{bad:?} should be rejected");
716        }
717    }
718
719    /// Mirror of interop.rs's namespace reservation: `ns` / `nsapi` are a
720    /// compile error as `namespace`, but stay valid as the operation.
721    #[test]
722    fn reserved_namespace_is_a_compile_error() {
723        let attr = |interop: &str, namespace: &str| {
724            syn::parse_str::<MacroArgs>(&format!(
725                "client = cache, ttl = 60, interop = {interop:?}, namespace = {namespace:?}"
726            ))
727        };
728        for reserved in ["ns", "nsapi"] {
729            let Err(err) = attr("get_user", reserved) else {
730                panic!("namespace {reserved:?} must be rejected");
731            };
732            assert!(
733                err.to_string().contains("reserved"),
734                "error must name the reservation, got: {err}"
735            );
736            assert!(
737                attr(reserved, "users").is_ok(),
738                "operation {reserved:?} must be accepted"
739            );
740        }
741        assert!(attr("get_user", "nsx").is_ok());
742        assert!(attr("get_user", "nsapi2").is_ok());
743    }
744
745    /// Mirror of interop.rs's `..` ban: a compile error in either segment,
746    /// while lone dots, including a trailing one, stay valid.
747    #[test]
748    fn double_dot_segment_is_a_compile_error() {
749        let attr = |interop: &str, namespace: &str| {
750            syn::parse_str::<MacroArgs>(&format!(
751                "client = cache, ttl = 60, interop = {interop:?}, namespace = {namespace:?}"
752            ))
753        };
754        for (interop, namespace) in [("get_user", "a..b"), ("x..y", "users"), ("x..", "users")] {
755            let Err(err) = attr(interop, namespace) else {
756                panic!("{interop:?}/{namespace:?} must be rejected");
757            };
758            assert!(
759                err.to_string().contains("must not contain"),
760                "error must name the '..' ban, got: {err}"
761            );
762        }
763        assert!(attr("users.fetch.by_id", "app.").is_ok());
764    }
765}