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