Skip to main content

wordval_cache_macros/
lib.rs

1//! Wordval cache proc macros: `#[cached]`, `#[cache_evict]`, `#[cache_evict_pattern]`.
2//!
3//! ## `#[cached(key = "...", ttl = 300, prefix = "...", unless = "...", empty_ttl = 60)]`
4//!
5//! Wraps an async handler with cache-aside pattern. The function must return `ResResult<T>`.
6//! `key` is a template with `{param}` placeholders matching function parameter names.
7//!
8//! ```ignore
9//! #[cached(key = "product:{id}", ttl = 600)]
10//! async fn get_product(id: u64) -> ResResult<Product> { ... }
11//!
12//! #[cached(key = "products:{cat}", prefix = "store", unless = "__data.is_empty()")]
13//! async fn get_products(cat: u64) -> ResResult<Vec<Product>> { ... }
14//!
15//! #[cached(key = "user:{uid}", ttl = 3600, empty_ttl = 120)]
16//! async fn get_user(uid: u64) -> ResResult<User> { ... }
17//! ```
18//!
19//! ## `#[cache_evict(key = "...", delay_ms = 500)]`
20//!
21//! Deletes a single cache entry on success, then deletes it again after
22//! `delay_ms` milliseconds (delayed double-delete) to clear stale values
23//! refilled by concurrent readers during the delete window.
24//! `delay_ms = 0` disables the second delete.
25//!
26//! ```ignore
27//! #[cache_evict(key = "product:{id}")]               // default delay 500ms
28//! async fn update_product(id: u64, data: UpdateReq) -> ResResult<()> { ... }
29//!
30//! #[cache_evict(key = "user:{uid}", delay_ms = 800)]
31//! async fn update_user(uid: u64, data: UpdateReq) -> ResResult<()> { ... }
32//! ```
33//!
34//! ## `#[cache_evict_pattern(pattern = "...", delay_ms = 500)]`
35//!
36//! Deletes all cache entries matching a glob pattern on success, with the
37//! same delayed second delete as `#[cache_evict]`.
38//!
39//! ```ignore
40//! #[cache_evict_pattern(pattern = "sys_dict:*")]
41//! async fn refresh_all_dicts() -> ResResult<()> { ... }
42//!
43//! #[cache_evict_pattern(pattern = "sys_dict:{dict_type}:*", delay_ms = 1000)]
44//! async fn refresh_dict(dict_type: &str) -> ResResult<()> { ... }
45//! ```
46
47use proc_macro::TokenStream;
48use quote::{format_ident, quote};
49use syn::{
50    parse_macro_input, FnArg, GenericArgument, ItemFn, Pat, PathArguments, ReturnType, Type,
51};
52
53// ──── Attribute Parsing ────────────────────────────────────────
54
55/// Parsed arguments from `#[cached(..)]` / `#[cache_evict(..)]`
56struct CacheAttr {
57    key: String,
58    ttl: u64,
59    prefix: Option<String>,
60    unless: Option<String>,
61    empty_ttl: Option<u64>,
62    pattern: Option<String>,
63    delay_ms: u64,
64}
65
66/// Split attribute string on commas, respecting quote boundaries.
67fn split_attr_parts(input: &str) -> Vec<String> {
68    let mut parts = Vec::new();
69    let mut current = String::new();
70    let mut in_quote = false;
71    for c in input.chars() {
72        match c {
73            '"' => {
74                in_quote = !in_quote;
75                current.push(c);
76            }
77            ',' if !in_quote => {
78                parts.push(current.trim().to_string());
79                current = String::new();
80            }
81            _ => current.push(c),
82        }
83    }
84    let last = current.trim().to_string();
85    if !last.is_empty() {
86        parts.push(last);
87    }
88    parts
89}
90
91/// Parse key="...", ttl=<num>, prefix="...", unless="...", empty_ttl=<num>, pattern="...", delay_ms=<num>
92fn parse_attr(attr: &str) -> Result<CacheAttr, String> {
93    let mut key = String::new();
94    let mut ttl = 300u64;
95    let mut prefix = None;
96    let mut unless = None;
97    let mut empty_ttl = None;
98    let mut pattern = None;
99    let mut delay_ms = 500u64; // 默认开启延迟双删(第二次删除),0 关闭
100
101    for part in split_attr_parts(attr) {
102        let part = part.trim();
103        if let Some(k) = part.strip_prefix("key = \"") {
104            key = k.trim_end_matches('"').to_string();
105        } else if let Some(v) = part.strip_prefix("ttl = ") {
106            ttl = v
107                .trim()
108                .parse()
109                .map_err(|_| format!("invalid ttl value `{}`", v.trim()))?;
110        } else if let Some(p) = part.strip_prefix("prefix = \"") {
111            prefix = Some(p.trim_end_matches('"').to_string());
112        } else if let Some(u) = part.strip_prefix("unless = \"") {
113            unless = Some(u.trim_end_matches('"').to_string());
114        } else if let Some(e) = part.strip_prefix("empty_ttl = ") {
115            empty_ttl = Some(
116                e.trim()
117                    .parse()
118                    .map_err(|_| format!("invalid empty_ttl value `{}`", e.trim()))?,
119            );
120        } else if let Some(p) = part.strip_prefix("pattern = \"") {
121            pattern = Some(p.trim_end_matches('"').to_string());
122        } else if let Some(v) = part.strip_prefix("delay_ms = ") {
123            delay_ms = v
124                .trim()
125                .parse()
126                .map_err(|_| format!("invalid delay_ms value `{}`", v.trim()))?;
127        } else {
128            return Err(format!("unknown attribute `{}`", part));
129        }
130    }
131    Ok(CacheAttr {
132        key,
133        ttl,
134        prefix,
135        unless,
136        empty_ttl,
137        pattern,
138        delay_ms,
139    })
140}
141
142/// Parse an expression string into a TokenStream (for `unless`).
143fn parse_expr(expr_str: &str) -> Result<proc_macro2::TokenStream, String> {
144    expr_str
145        .parse()
146        .map_err(|e| format!("invalid `unless` expression `{expr_str}`: {e}"))
147}
148
149// ──── Key Template Processing ────────────────────────────────
150
151struct FnParam {
152    name: String,
153}
154
155fn get_fn_params(inputs: &[&FnArg]) -> Vec<FnParam> {
156    inputs
157        .iter()
158        .copied()
159        .filter_map(|arg| match arg {
160            FnArg::Typed(pat_type) => match pat_type.pat.as_ref() {
161                Pat::Ident(pat_ident) => Some(FnParam {
162                    name: pat_ident.ident.to_string(),
163                }),
164                _ => None,
165            },
166            FnArg::Receiver(_) => None,
167        })
168        .collect()
169}
170
171struct KeyTemplate {
172    format_string: String,
173    params: Vec<proc_macro2::Ident>,
174}
175
176/// Process a key template like `"product:{id}"` → `("product:{}", [__id])`.
177fn process_key_template(key: &str, fn_params: &[FnParam]) -> KeyTemplate {
178    let mut format_string = String::new();
179    let mut params = Vec::new();
180    let mut rest = key;
181
182    while let Some(start) = rest.find('{') {
183        format_string.push_str(&rest[..start]);
184        rest = &rest[start + 1..];
185
186        if let Some(end) = rest.find('}') {
187            let param_name = &rest[..end];
188            rest = &rest[end + 1..];
189
190            match fn_params.iter().find(|p| p.name == param_name) {
191                Some(found) => {
192                    format_string.push_str("{}");
193                    params.push(format_ident!("__{}", found.name));
194                }
195                None => {
196                    let valid: Vec<&str> = fn_params.iter().map(|p| p.name.as_str()).collect();
197                    panic!(
198                        "unknown parameter `{param_name}` in cache key, expected one of: {}",
199                        valid.join(", ")
200                    );
201                }
202            }
203        } else {
204            format_string.push('{');
205            format_string.push_str(rest);
206            rest = "";
207        }
208    }
209    format_string.push_str(rest);
210    KeyTemplate {
211        format_string,
212        params,
213    }
214}
215
216/// Build `format!(...)` or `"...".to_string()` for key generation.
217fn build_key_expr(template: &KeyTemplate) -> proc_macro2::TokenStream {
218    let s = &template.format_string;
219    let p = &template.params;
220    if p.is_empty() {
221        quote! { #s.to_string() }
222    } else {
223        quote! { format!(#s, #(#p),*) }
224    }
225}
226
227/// Build key expression with optional prefix: `"{prefix}:{key_template}"`.
228fn build_prefixed_key_expr(
229    prefix: Option<&str>,
230    template: &KeyTemplate,
231) -> proc_macro2::TokenStream {
232    match prefix {
233        Some(pre) => {
234            let full = format!("{}:{}", pre, template.format_string);
235            let p = &template.params;
236            if p.is_empty() {
237                quote! { #full.to_string() }
238            } else {
239                quote! { format!(#full, #(#p),*) }
240            }
241        }
242        None => build_key_expr(template),
243    }
244}
245
246// ──── Return Type Extraction ──────────────────────────────────
247
248fn extract_inner_type(return_type: &ReturnType) -> Option<Type> {
249    if let ReturnType::Type(_, ty) = return_type {
250        if let Type::Path(type_path) = ty.as_ref() {
251            let last_seg = type_path.path.segments.last()?;
252            if last_seg.ident == "ResResult" {
253                if let PathArguments::AngleBracketed(args) = &last_seg.arguments {
254                    if let Some(GenericArgument::Type(inner)) = args.args.first() {
255                        return Some(inner.clone());
256                    }
257                }
258            }
259        }
260    }
261    None
262}
263
264// ──── Shared Code Generation Helpers ─────────────────────────
265
266/// Generate `let __name = &name;` for all function parameters.
267fn gen_param_bindings(fn_params: &[FnParam]) -> Vec<proc_macro2::TokenStream> {
268    fn_params
269        .iter()
270        .map(|p| {
271            let orig = format_ident!("{}", p.name);
272            let pref = format_ident!("__{}", p.name);
273            quote! { let #pref = &#orig; }
274        })
275        .collect()
276}
277
278/// 将缓存写入语句包裹进 `unless` 守卫:条件为真时跳过缓存(`if !(cond) { write }`)。
279///
280/// 守卫必须置于 `if let Some(ref __data) = __res.data` 绑定**之内**,
281/// `unless = "__data.is_empty()"` 等引用返回数据的条件才能解析;
282/// 历史实现把守卫放在绑定之外,引用 `__data` 必然 E0425。
283fn wrap_unless(
284    write: proc_macro2::TokenStream,
285    cond: &Option<proc_macro2::TokenStream>,
286) -> proc_macro2::TokenStream {
287    match cond {
288        Some(c) => quote! { if !(#c) { #write } },
289        None => write,
290    }
291}
292
293// ──── Macro: #[cached] ────────────────────────────────────────
294
295#[proc_macro_attribute]
296pub fn cached(attr: TokenStream, item: TokenStream) -> TokenStream {
297    let attr = match parse_attr(&attr.to_string()) {
298        Ok(a) => a,
299        Err(e) => {
300            return syn::Error::new(proc_macro2::Span::call_site(), e)
301                .to_compile_error()
302                .into()
303        }
304    };
305    let item_fn = parse_macro_input!(item as ItemFn);
306
307    let vis = &item_fn.vis;
308    let sig = &item_fn.sig;
309    let body = &item_fn.block;
310    let attrs = &item_fn.attrs;
311    let inputs: Vec<&FnArg> = sig.inputs.iter().collect();
312    let fn_params = get_fn_params(&inputs);
313
314    let inner_type = match extract_inner_type(&sig.output) {
315        Some(t) => t,
316        None => {
317            return syn::Error::new_spanned(
318                &sig.output,
319                "#[cached] requires return type `ResResult<T>`",
320            )
321            .to_compile_error()
322            .into();
323        }
324    };
325
326    let template = process_key_template(&attr.key, &fn_params);
327    let key_expr = build_prefixed_key_expr(attr.prefix.as_deref(), &template);
328    let param_bindings = gen_param_bindings(&fn_params);
329    let ttl = attr.ttl;
330
331    // ── unless 条件:在 __data 绑定内求值(见 wrap_unless)──
332    let unless_cond = match &attr.unless {
333        Some(expr) => match parse_expr(expr) {
334            Ok(ts) => Some(ts),
335            Err(e) => {
336                return syn::Error::new(proc_macro2::Span::call_site(), e)
337                    .to_compile_error()
338                    .into()
339            }
340        },
341        None => None,
342    };
343
344    // ── empty_ttl: if set, use serde_json::Value as intermediary ──
345    //    When data is None, cache serde_json::Value::Null with empty_ttl.
346    //    On retrieval, deserialize from Value.
347    let (read_cache, write_cache) = match attr.empty_ttl {
348        Some(et) => {
349            // Read: use serde_json::Value
350            let read = quote! {
351                if let Ok(Some(__cached_json)) = ::wordval::cache()
352                    .get::<::wordval::serde_json::Value>(&__cache_key)
353                    .await
354                {
355                    if __cached_json.is_null() {
356                        return Ok(Res { code: 200, msg: "ok".into(), data: None });
357                    }
358                    if let Ok(__data) = ::wordval::serde_json::from_value::<#inner_type>(__cached_json) {
359                        return Ok(Res::ok(__data));
360                    }
361                }
362            };
363            // Write: differentiate Some vs None;unless 仅守卫数据写入(Some 分支),
364            // None 分支的空值标记(防穿透)不受 unless 影响
365            let some_write = wrap_unless(
366                quote! {
367                    if let Ok(__json) = ::wordval::serde_json::to_value(__data) {
368                        let _ = ::wordval::cache()
369                            .set_ex(&__cache_key, &__json, #ttl)
370                            .await;
371                    }
372                },
373                &unless_cond,
374            );
375            let write = quote! {
376                if let Some(ref __data) = __res.data {
377                    #some_write
378                } else {
379                    let _ = ::wordval::cache()
380                        .set_ex(&__cache_key, &::wordval::serde_json::Value::Null, #et)
381                        .await;
382                }
383            };
384            (read, write)
385        }
386        None => {
387            // Standard: typed T directly
388            let read = quote! {
389                if let Ok(Some(__cached)) = ::wordval::cache()
390                    .get::<#inner_type>(&__cache_key)
391                    .await
392                {
393                    return Ok(Res::ok(__cached));
394                }
395            };
396            let some_write = wrap_unless(
397                quote! {
398                    let _ = ::wordval::cache()
399                        .set_ex(&__cache_key, __data, #ttl)
400                        .await;
401                },
402                &unless_cond,
403            );
404            let write = quote! {
405                if let Some(ref __data) = __res.data {
406                    #some_write
407                }
408            };
409            (read, write)
410        }
411    };
412
413    let expanded = quote! {
414        #(#attrs)*
415        #vis #sig {
416            #(#param_bindings)*
417            #[allow(unused_imports)]
418            use ::wordval::Cache as _;
419            let __cache_key = #key_expr;
420            #read_cache
421            let __result = { #body };
422            if let Ok(ref __res) = __result {
423                if __res.code == 200 {
424                    #write_cache
425                }
426            }
427            __result
428        }
429    };
430
431    expanded.into()
432}
433
434// ──── Macro: #[cache_evict] ──────────────────────────────────
435
436#[proc_macro_attribute]
437pub fn cache_evict(attr: TokenStream, item: TokenStream) -> TokenStream {
438    let attr = match parse_attr(&attr.to_string()) {
439        Ok(a) => a,
440        Err(e) => {
441            return syn::Error::new(proc_macro2::Span::call_site(), e)
442                .to_compile_error()
443                .into()
444        }
445    };
446    let item_fn = parse_macro_input!(item as ItemFn);
447
448    let vis = &item_fn.vis;
449    let sig = &item_fn.sig;
450    let body = &item_fn.block;
451    let attrs = &item_fn.attrs;
452    let inputs: Vec<&FnArg> = sig.inputs.iter().collect();
453    let fn_params = get_fn_params(&inputs);
454
455    let template = process_key_template(&attr.key, &fn_params);
456    let key_expr = build_prefixed_key_expr(attr.prefix.as_deref(), &template);
457    let param_bindings = gen_param_bindings(&fn_params);
458    let delay_ms = attr.delay_ms;
459
460    // 延迟双删第二次删除:默认延迟后再次删除;delay_ms = 0 时跳过
461    let delayed_evict = if delay_ms > 0 {
462        quote! {
463            let _ = ::wordval::delete_after(
464                ::wordval::cache().clone(),
465                __cache_key,
466                std::time::Duration::from_millis(#delay_ms),
467            );
468        }
469    } else {
470        quote! {}
471    };
472
473    let expanded = quote! {
474        #(#attrs)*
475        #vis #sig {
476            #(#param_bindings)*
477            #[allow(unused_imports)]
478            use ::wordval::Cache as _;
479            let __result = { #body };
480            if __result.is_ok() {
481                let __cache_key = #key_expr;
482                let _ = ::wordval::cache()
483                    .del(&__cache_key)
484                    .await;
485                #delayed_evict
486            }
487            __result
488        }
489    };
490
491    expanded.into()
492}
493
494// ──── Macro: #[cache_evict_pattern] ──────────────────────────
495
496/// Evict all cache entries matching a glob pattern after a successful write,
497/// with a delayed second delete (delayed double-delete, default 500ms;
498/// `delay_ms = 0` disables it).
499///
500/// `pattern` — template with `{param}` placeholders, e.g. `"sys_dict:{type}:*"`.
501///
502/// ```ignore
503/// #[cache_evict_pattern(pattern = "sys_dict:*")]
504/// async fn refresh_all_dicts() -> ResResult<()> { ... }
505///
506/// #[cache_evict_pattern(pattern = "sys_dict:{dict_type}:*", delay_ms = 1000)]
507/// async fn refresh_dict(dict_type: &str) -> ResResult<()> { ... }
508/// ```
509#[proc_macro_attribute]
510pub fn cache_evict_pattern(attr: TokenStream, item: TokenStream) -> TokenStream {
511    let attr = match parse_attr(&attr.to_string()) {
512        Ok(a) => a,
513        Err(e) => {
514            return syn::Error::new(proc_macro2::Span::call_site(), e)
515                .to_compile_error()
516                .into()
517        }
518    };
519    let item_fn = parse_macro_input!(item as ItemFn);
520
521    let vis = &item_fn.vis;
522    let sig = &item_fn.sig;
523    let body = &item_fn.block;
524    let attrs = &item_fn.attrs;
525    let inputs: Vec<&FnArg> = sig.inputs.iter().collect();
526    let fn_params = get_fn_params(&inputs);
527
528    // Pattern supports {param} interpolation too
529    let template = process_key_template(attr.pattern.as_deref().unwrap_or(""), &fn_params);
530    let pattern_expr = build_key_expr(&template);
531    let param_bindings = gen_param_bindings(&fn_params);
532    let delay_ms = attr.delay_ms;
533
534    // 延迟双删第二次删除(模式):默认延迟后再次删除;delay_ms = 0 时跳过
535    let delayed_evict = if delay_ms > 0 {
536        quote! {
537            let _ = ::wordval::delete_pattern_after(
538                ::wordval::cache().clone(),
539                __cache_pattern,
540                std::time::Duration::from_millis(#delay_ms),
541            );
542        }
543    } else {
544        quote! {}
545    };
546
547    let expanded = quote! {
548        #(#attrs)*
549        #vis #sig {
550            #(#param_bindings)*
551            #[allow(unused_imports)]
552            use ::wordval::Cache as _;
553            let __result = { #body };
554            if __result.is_ok() {
555                let __cache_pattern = #pattern_expr;
556                let _ = ::wordval::cache()
557                    .delete_pattern(&__cache_pattern)
558                    .await;
559                #delayed_evict
560            }
561            __result
562        }
563    };
564
565    expanded.into()
566}