Skip to main content

g3_kit_macros/
lib.rs

1//! Proc macros for [g3-kit](https://docs.rs/g3-kit). Use them through
2//! `g3_kit::cache_shared` and `g3_kit::public`.
3
4use proc_macro::TokenStream;
5use proc_macro2::TokenStream as TokenStream2;
6
7mod cache;
8mod public;
9mod routes;
10
11/// Caches a server function whose answer is the same for every visitor: at
12/// the CDN, on the server, or both.
13///
14/// Place it **above** the route attribute:
15///
16/// ```ignore
17/// #[g3_kit::cache_shared(cdn = 300, server = "5m")]
18/// #[get("/api/trending?media_type", db: Db)]
19/// pub async fn get_trending(media_type: Option<MediaType>) -> Result<Vec<Media>> { .. }
20/// ```
21///
22/// # Arguments
23///
24/// - `cdn = <seconds>`: CDN caching. Successful responses are marked
25///   `public, max-age=60, s-maxage=<seconds>` (see `g3_kit::cache::cdn`).
26/// - `server = "<duration>"`: server caching, e.g. `"30s"`, `"5m"`, `"1h"`,
27///   `"1d"`. The whole function's `Ok` answer is kept per set of arguments;
28///   concurrent misses share one call and errors are not kept.
29/// - `capacity = <entries>`: the most answers the server cache keeps.
30///   Default 10 000.
31/// - `trust_extractors`: skips the extractor check below, for an extractor
32///   whose name looks per-visitor but isn't.
33///
34/// At least one of `cdn` and `server` is required.
35///
36/// # Checked at compile time
37///
38/// - The function uses `#[get]`: a CDN never caches other methods, and
39///   shared data is read, not written.
40/// - No extractor in the route attribute is named like per-visitor state
41///   (`session`, `auth`, `user`, `cookie`, `token`, `claims`, `header`...),
42///   and the body doesn't call `FullstackContext`. Either would make the
43///   answer depend on who asks, and sharing it would show one visitor's
44///   data to everyone.
45/// - The function is `async` and returns a `Result`.
46///
47/// # Not checked
48///
49/// A function can depend on the visitor in ways no macro can see: a query
50/// that uses the database session's user, a global, a value from an
51/// extractor with a neutral name. Only share functions whose answer comes
52/// entirely from their arguments and public data.
53#[proc_macro_attribute]
54pub fn cache_shared(attr: TokenStream, item: TokenStream) -> TokenStream {
55    report(cache::expand(attr.into(), item.clone().into()), item)
56}
57
58/// Marks a server function as reachable without a session.
59///
60/// g3-kit's auth guard denies every request that has no signed-in user,
61/// unless its path is a static asset, a public page the app names, or a
62/// server function marked with this attribute. Place it **above** the route
63/// attribute:
64///
65/// ```ignore
66/// #[g3_kit::public]
67/// #[get("/api/v1/is_signed_in", ctx: SessionContext)]
68/// pub async fn is_signed_in() -> Result<bool> { .. }
69/// ```
70///
71/// Forgetting it is the safe mistake: the endpoint answers a signed-out
72/// caller with `401`. Adding it is a deliberate, reviewable line next to the
73/// function it opens up, so say why in a comment.
74///
75/// # Checked at compile time
76///
77/// - It sits above a `#[get]`, `#[post]`, `#[put]`, `#[patch]` or `#[delete]`
78///   with an explicit path. Below it, the route attribute has already
79///   expanded; `#[server]` derives its path at build time.
80/// - The path starts with `/`. A `?query` suffix is ignored, and `{param}`
81///   segments match any one segment.
82///
83/// In a build without `g3-kit/server` it registers nothing, so client
84/// builds compile the same code.
85#[proc_macro_attribute]
86pub fn public(attr: TokenStream, item: TokenStream) -> TokenStream {
87    report(public::expand(attr.into(), item.clone().into()), item)
88}
89
90/// The expansion, or the item unchanged plus the error, so one mistake
91/// doesn't also bury the function under "cannot find" errors.
92fn report(result: syn::Result<TokenStream2>, item: TokenStream) -> TokenStream {
93    match result {
94        Ok(tokens) => tokens.into(),
95        Err(err) => {
96            let mut item: TokenStream2 = item.into();
97            item.extend(err.to_compile_error());
98            item.into()
99        }
100    }
101}
102
103/// Marks pages of a `Routable` enum as reachable without a session.
104///
105/// Derive it next to `Routable` and put `#[public]` on each page a signed-out
106/// visitor may load: the splash, sign-in, legal pages, share links.
107///
108/// ```ignore
109/// #[derive(Clone, Routable, PartialEq, PublicRoutes)]
110/// enum Route {
111///     #[redirect("/:..segments", |segments: Vec<String>| Route::Splash {})]
112///     #[public]
113///     #[route("/")]
114///     Splash {},
115///     #[nest("/games/:game_id")]
116///         #[public]
117///         #[route("/join")]
118///         JoinGame { game_id: String },
119///     #[end_nest]
120///     #[route("/home")]
121///     Home {},
122/// }
123///
124/// let guard = AuthGuard::for_routes(Route::Splash {});
125/// ```
126///
127/// It implements `g3_kit::auth::PublicRoutes` from the variants' own
128/// `#[route]` and enclosing `#[nest]` paths, and matches a request path
129/// against those directly. It never parses the path into the enum: a
130/// catch-all `#[redirect]` would turn every unknown path, and every `/api/`
131/// path, into its target, and a check on the parsed value would open them
132/// all. Redirects are never public.
133///
134/// # Checked at compile time
135///
136/// - `#[public]` takes no arguments and sits on a variant with `#[route]`.
137/// - Not on a `#[child]` variant, whose paths live in another enum.
138/// - `#[nest]` and `#[end_nest]` pair up.
139#[proc_macro_derive(PublicRoutes, attributes(public))]
140pub fn derive_public_routes(item: TokenStream) -> TokenStream {
141    match routes::expand(item.into()) {
142        Ok(tokens) => tokens.into(),
143        Err(err) => err.to_compile_error().into(),
144    }
145}