g3_cache_macros/lib.rs
1//! Proc macro support for [g3-cache](https://docs.rs/g3-cache). Use it
2//! through `g3_cache::cache_shared`.
3
4use proc_macro::TokenStream;
5use proc_macro2::TokenStream as TokenStream2;
6
7mod cache;
8
9/// Caches a server function whose answer is the same for every visitor: at
10/// the CDN, on the server, or both.
11///
12/// Place it **above** the route attribute:
13///
14/// ```ignore
15/// #[g3_cache::cache_shared(cdn = 300, server = "5m")]
16/// #[get("/api/trending?media_type", db: Db)]
17/// pub async fn get_trending(media_type: Option<MediaType>) -> Result<Vec<Media>> { .. }
18/// ```
19///
20/// # Arguments
21///
22/// - `cdn = <seconds>`: CDN caching. Successful responses are marked
23/// `public, max-age=60, s-maxage=<seconds>` (see `g3_cache::cdn`).
24/// - `server = "<duration>"`: server caching, e.g. `"30s"`, `"5m"`, `"1h"`,
25/// `"1d"`. The whole function's `Ok` answer is kept per set of arguments;
26/// concurrent misses share one call and errors are not kept.
27/// - `capacity = <entries>`: the most answers the server cache keeps.
28/// Default 10 000.
29/// - `trust_extractors`: skips the extractor check below, for an extractor
30/// whose name looks per-visitor but isn't.
31///
32/// At least one of `cdn` and `server` is required.
33///
34/// # Checked at compile time
35///
36/// - The function uses `#[get]`: a CDN never caches other methods, and
37/// shared data is read, not written.
38/// - No extractor in the route attribute is named like per-visitor state
39/// (`session`, `auth`, `user`, `cookie`, `token`, `claims`, `header`...),
40/// and the body doesn't call `FullstackContext`. Either would make the
41/// answer depend on who asks, and sharing it would show one visitor's
42/// data to everyone.
43/// - The function is `async` and returns a `Result`.
44///
45/// # Not checked
46///
47/// A function can depend on the visitor in ways no macro can see: a query
48/// that uses the database session's user, a global, a value from an
49/// extractor with a neutral name. Only share functions whose answer comes
50/// entirely from their arguments and public data.
51#[proc_macro_attribute]
52pub fn cache_shared(attr: TokenStream, item: TokenStream) -> TokenStream {
53 report(cache::expand(attr.into(), item.clone().into()), item)
54}
55
56/// The expansion, or the item unchanged plus the error, so one mistake
57/// doesn't also bury the function under "cannot find" errors.
58fn report(result: syn::Result<TokenStream2>, item: TokenStream) -> TokenStream {
59 match result {
60 Ok(tokens) => tokens.into(),
61 Err(err) => {
62 let mut item: TokenStream2 = item.into();
63 item.extend(err.to_compile_error());
64 item.into()
65 }
66 }
67}