canic-macros 0.7.8

Canic — a canister orchestration and management toolkit for the Internet Computer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
//! Canic proc macros.
//!
//! Thin, opinionated wrappers around IC CDK endpoint attributes
//! (`#[query]`, `#[update]`), routed through `canic::cdk::*`.
//!
//! Pipeline enforced by generated wrappers:
//!   guard → auth → env → rule → dispatch

use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use syn::{Expr, ItemFn, Meta, Token, parse::Parser, parse_macro_input, punctuated::Punctuated};

//
// ============================================================================
// Public entry points
// ============================================================================
//

#[proc_macro_attribute]
pub fn canic_query(attr: TokenStream, item: TokenStream) -> TokenStream {
    expand_entry(EndpointKind::Query, attr, item)
}

#[proc_macro_attribute]
pub fn canic_update(attr: TokenStream, item: TokenStream) -> TokenStream {
    expand_entry(EndpointKind::Update, attr, item)
}

//
// ============================================================================
// Shared internal types
// ============================================================================
//

#[derive(Clone, Copy)]
enum EndpointKind {
    Query,
    Update,
}

//
// ============================================================================
// parse — attribute grammar only
// ============================================================================
//

mod parse {
    use super::*;

    #[derive(Clone, Debug)]
    pub enum AuthSpec {
        Any(Vec<Expr>),
        All(Vec<Expr>),
    }

    #[derive(Debug)]
    pub struct ParsedArgs {
        pub forwarded: Vec<TokenStream2>,
        pub app_guard: bool,
        pub user_guard: bool,
        pub auth: Option<AuthSpec>,
        pub env: Vec<Expr>,
        pub rules: Vec<Expr>,
    }

    pub fn parse_args(attr: TokenStream2) -> syn::Result<ParsedArgs> {
        let Ok(metas) = Punctuated::<Meta, Token![,]>::parse_terminated.parse2(attr.clone()) else {
            // If the attr doesn't parse as Meta list, fall back to forwarding raw tokens to the CDK.
            // This preserves compatibility with CDK syntax we don't model.
            if attr.is_empty() {
                return Ok(empty());
            }

            return Ok(ParsedArgs {
                forwarded: vec![attr],
                ..empty()
            });
        };

        let mut forwarded = Vec::new();
        let mut app_guard = false;
        let mut user_guard = false;
        let mut auth = None::<AuthSpec>;
        let mut env = Vec::<Expr>::new();
        let mut rules = Vec::<Expr>::new();

        for meta in metas {
            match meta {
                // guard(...)
                //
                // Canic-specific guard stage. Top-level `app` is no longer accepted.
                Meta::List(list) if list.path.is_ident("guard") => {
                    let inner = Punctuated::<Meta, Token![,]>::parse_terminated
                        .parse2(list.tokens.clone())?
                        .into_iter()
                        .collect::<Vec<_>>();

                    if inner.is_empty() {
                        return Err(syn::Error::new_spanned(
                            list,
                            "`guard(...)` expects at least one argument (e.g., `guard(app)`)",
                        ));
                    }

                    // Only guard(app) is supported.
                    for item in inner {
                        match item {
                            Meta::Path(p) if p.is_ident("app") => {
                                app_guard = true;
                            }
                            other => {
                                return Err(syn::Error::new_spanned(
                                    other,
                                    "only `guard(app)` is supported",
                                ));
                            }
                        }
                    }
                }

                // auth_any(...)
                Meta::List(list) if list.path.is_ident("auth_any") => {
                    if auth.is_some() {
                        return Err(conflicting_auth(&list));
                    }
                    let rules = parse_rules(&list)?;
                    auth = Some(AuthSpec::Any(rules));
                }

                // auth_all(...)
                Meta::List(list) if list.path.is_ident("auth_all") => {
                    if auth.is_some() {
                        return Err(conflicting_auth(&list));
                    }
                    let rules = parse_rules(&list)?;
                    auth = Some(AuthSpec::All(rules));
                }

                // rule(...)
                //
                // Parse as Expr so you can do rule(local_only()), rule(max_rounds(rounds, 10_000)), etc.
                Meta::List(list) if list.path.is_ident("rule") => {
                    let parsed = Punctuated::<Expr, Token![,]>::parse_terminated
                        .parse2(list.tokens.clone())?
                        .into_iter()
                        .collect::<Vec<_>>();

                    if parsed.is_empty() {
                        return Err(syn::Error::new_spanned(
                            list,
                            "`rule(...)` expects at least one rule expression",
                        ));
                    }

                    rules.extend(parsed);
                }

                // env(...)
                //
                // Parse as Expr so you can do env(is_prime_subnet), env(is_root), etc.
                Meta::List(list) if list.path.is_ident("env") => {
                    let parsed = Punctuated::<Expr, Token![,]>::parse_terminated
                        .parse2(list.tokens.clone())?
                        .into_iter()
                        .collect::<Vec<_>>();

                    if parsed.is_empty() {
                        return Err(syn::Error::new_spanned(
                            list,
                            "`env(...)` expects at least one expression",
                        ));
                    }

                    env.extend(parsed);
                }

                // explicit CDK guard = ...
                //
                // We still forward it, but track that it exists so validation can ban combinations.
                Meta::NameValue(nv) if nv.path.is_ident("guard") => {
                    user_guard = true;
                    forwarded.push(quote!(#nv));
                }

                // Everything else is forwarded to the CDK attribute unchanged.
                _ => forwarded.push(quote!(#meta)),
            }
        }

        Ok(ParsedArgs {
            forwarded,
            app_guard,
            user_guard,
            auth,
            env,
            rules,
        })
    }
    const fn empty() -> ParsedArgs {
        ParsedArgs {
            forwarded: Vec::new(),
            app_guard: false,
            user_guard: false,
            auth: None,
            env: Vec::new(),
            rules: Vec::new(),
        }
    }

    fn parse_rules(list: &syn::MetaList) -> syn::Result<Vec<Expr>> {
        let rules = Punctuated::<Expr, Token![,]>::parse_terminated
            .parse2(list.tokens.clone())?
            .into_iter()
            .collect::<Vec<_>>();

        if rules.is_empty() {
            return Err(syn::Error::new_spanned(
                list,
                "authorization requires at least one rule",
            ));
        }

        Ok(rules)
    }

    fn conflicting_auth(list: &syn::MetaList) -> syn::Error {
        syn::Error::new_spanned(list, "conflicting authorization composition")
    }
}

//
// ============================================================================
// validate — semantic constraints
// ============================================================================
//

mod validate {
    use super::*;
    use parse::{AuthSpec, ParsedArgs};

    pub struct ValidatedArgs {
        pub forwarded: Vec<TokenStream2>,
        pub app_guard: bool,
        pub auth: Option<AuthSpec>,
        pub env: Vec<Expr>,
        pub rules: Vec<Expr>,
    }

    pub fn validate(
        parsed: ParsedArgs,
        sig: &syn::Signature,
        asyncness: bool,
    ) -> syn::Result<ValidatedArgs> {
        if parsed.app_guard && parsed.user_guard {
            return Err(syn::Error::new_spanned(
                &sig.ident,
                "`app` cannot be combined with `guard = ...`",
            ));
        }

        if parsed.auth.is_some() && parsed.user_guard {
            return Err(syn::Error::new_spanned(
                &sig.ident,
                "authorization cannot be combined with `guard = ...`",
            ));
        }

        if parsed.auth.is_some() {
            if !asyncness {
                return Err(syn::Error::new_spanned(
                    &sig.ident,
                    "authorization requires `async fn`",
                ));
            }
            if !returns_result(sig) {
                return Err(syn::Error::new_spanned(
                    &sig.output,
                    "authorized endpoints must return `Result<_, From<canic::PublicError>>`",
                ));
            }
        }

        if parsed.app_guard && !returns_result(sig) {
            return Err(syn::Error::new_spanned(
                &sig.output,
                "`app` guard requires `Result<_, From<canic::PublicError>>`",
            ));
        }

        if !parsed.rules.is_empty() && !returns_result(sig) {
            return Err(syn::Error::new_spanned(
                &sig.output,
                "`rule(...)` requires `Result<_, From<canic::PublicError>>`",
            ));
        }

        if !parsed.env.is_empty() && !returns_result(sig) {
            return Err(syn::Error::new_spanned(
                &sig.output,
                "`env(...)` requires `Result<_, From<canic::PublicError>>`",
            ));
        }

        Ok(ValidatedArgs {
            forwarded: parsed.forwarded,
            app_guard: parsed.app_guard,
            auth: parsed.auth,
            rules: parsed.rules,
            env: parsed.env,
        })
    }

    fn returns_result(sig: &syn::Signature) -> bool {
        let syn::ReturnType::Type(_, ty) = &sig.output else {
            return false;
        };
        let syn::Type::Path(ty) = &**ty else {
            return false;
        };

        ty.path
            .segments
            .last()
            .is_some_and(|seg| seg.ident == "Result")
    }
}

//
// ============================================================================
// expand — code generation only
// ============================================================================
//

mod expand {
    use super::*;
    use parse::AuthSpec;
    use validate::ValidatedArgs;

    pub fn expand(kind: EndpointKind, args: ValidatedArgs, mut func: ItemFn) -> TokenStream {
        let attrs = func.attrs.clone();
        let orig_sig = func.sig.clone();
        let orig_name = orig_sig.ident.clone();
        let vis = func.vis.clone();
        let inputs = orig_sig.inputs.clone();
        let output = orig_sig.output.clone();
        let asyncness = orig_sig.asyncness.is_some();
        let returns_result = returns_result(&orig_sig);

        let impl_name = format_ident!("__canic_impl_{}", orig_name);
        func.sig.ident = impl_name.clone();

        let cdk_attr = cdk_attr(kind, &args.forwarded);

        let dispatch = dispatch(kind, asyncness);

        let wrapper_sig = syn::Signature {
            ident: orig_name.clone(),
            inputs,
            output,
            ..orig_sig.clone()
        };

        let call_ident = format_ident!("__canic_call");
        let call_decl = call_decl(kind, &call_ident, &orig_name);

        let attempted = attempted(&call_ident);
        let guard = guard(kind, args.app_guard, &call_ident);
        let auth = auth(args.auth.as_ref(), &call_ident);
        let env = env(&args.env, &call_ident);
        let rule = rule(&args.rules, &call_ident);

        let call_args = match extract_args(&orig_sig) {
            Ok(v) => v,
            Err(e) => return e.to_compile_error().into(),
        };

        let dispatch_call = dispatch_call(asyncness, dispatch, &call_ident, impl_name, &call_args);
        let completion = completion(&call_ident, returns_result, dispatch_call);

        quote! {
           #(#attrs)*
           #cdk_attr
            #vis #wrapper_sig {
                #call_decl
                #attempted
                #guard
                #auth
                #env
                #rule
                #completion
            }

            #func
        }
        .into()
    }

    fn returns_result(sig: &syn::Signature) -> bool {
        let syn::ReturnType::Type(_, ty) = &sig.output else {
            return false;
        };
        let syn::Type::Path(ty) = &**ty else {
            return false;
        };
        ty.path
            .segments
            .last()
            .is_some_and(|seg| seg.ident == "Result")
    }

    fn dispatch(kind: EndpointKind, asyncness: bool) -> TokenStream2 {
        match (kind, asyncness) {
            (EndpointKind::Query, false) => quote!(::canic::core::dispatch::dispatch_query),
            (EndpointKind::Query, true) => quote!(::canic::core::dispatch::dispatch_query_async),
            (EndpointKind::Update, false) => quote!(::canic::core::dispatch::dispatch_update),
            (EndpointKind::Update, true) => quote!(::canic::core::dispatch::dispatch_update_async),
        }
    }

    fn call_decl(
        kind: EndpointKind,
        call_ident: &syn::Ident,
        orig_name: &syn::Ident,
    ) -> TokenStream2 {
        let call_kind = match kind {
            EndpointKind::Query => quote!(::canic::core::api::EndpointCallKind::Query),
            EndpointKind::Update => quote!(::canic::core::api::EndpointCallKind::Update),
        };

        quote! {
            let #call_ident = ::canic::core::api::EndpointCall {
                endpoint: ::canic::core::api::EndpointId::new(stringify!(#orig_name)),
                kind: #call_kind,
            };
        }
    }

    fn record_access_denied(call: &syn::Ident, kind: TokenStream2) -> TokenStream2 {
        quote! {
            ::canic::core::api::instrumentation::AccessMetrics::increment(#call, #kind);
        }
    }

    fn attempted(call: &syn::Ident) -> TokenStream2 {
        quote! {
            ::canic::core::api::instrumentation::EndpointAttemptMetrics::increment_attempted(#call);
        }
    }

    fn guard(kind: EndpointKind, enabled: bool, call: &syn::Ident) -> TokenStream2 {
        if !enabled {
            return quote!();
        }

        let metric = record_access_denied(
            call,
            quote!(::canic::core::dto::metrics::AccessMetricKind::Guard),
        );

        match kind {
            EndpointKind::Query => quote! {
                if let Err(err) = ::canic::core::api::access::guard_app_query() {
                    #metric
                    return Err(err.into());
                }
            },
            EndpointKind::Update => quote! {
                if let Err(err) = ::canic::core::api::access::guard_app_update() {
                    #metric
                    return Err(err.into());
                }
            },
        }
    }

    fn auth(auth: Option<&AuthSpec>, call: &syn::Ident) -> TokenStream2 {
        let metric = record_access_denied(
            call,
            quote!(::canic::core::dto::metrics::AccessMetricKind::Auth),
        );

        match auth {
            Some(AuthSpec::Any(rules)) => quote! {
                if let Err(err) = ::canic::core::auth_require_any!(#(#rules),*) {
                    #metric
                    return Err(err.into());
                }
            },
            Some(AuthSpec::All(rules)) => quote! {
                if let Err(err) = ::canic::core::auth_require_all!(#(#rules),*) {
                    #metric
                    return Err(err.into());
                }
            },
            None => quote!(),
        }
    }

    fn rule(rules: &[Expr], call: &syn::Ident) -> TokenStream2 {
        if rules.is_empty() {
            return quote!();
        }

        let metric = record_access_denied(
            call,
            quote!(::canic::core::dto::metrics::AccessMetricKind::Rule),
        );

        let checks = rules.iter().map(|expr| {
            quote! {
                if let Err(err) = #expr().await {
                    #metric
                    return Err(err.into());
                }
            }
        });
        quote!(#(#checks)*)
    }

    fn env(envs: &[Expr], call: &syn::Ident) -> TokenStream2 {
        if envs.is_empty() {
            return quote!();
        }

        let metric = record_access_denied(
            call,
            quote!(::canic::core::dto::metrics::AccessMetricKind::Rule),
        );

        let checks = envs.iter().map(|expr| {
            quote! {
                if let Err(err) = #expr().await {
                    #metric
                    return Err(err.into());
                }
            }
        });
        quote!(#(#checks)*)
    }

    fn dispatch_call(
        asyncness: bool,
        dispatch: TokenStream2,
        call: &syn::Ident,
        impl_name: syn::Ident,
        call_args: &[TokenStream2],
    ) -> TokenStream2 {
        if asyncness {
            quote! {
                #dispatch(#call, || async move {
                    #impl_name(#(#call_args),*).await
                }).await
            }
        } else {
            quote! {
                #dispatch(#call, || {
                    #impl_name(#(#call_args),*)
                })
            }
        }
    }

    fn completion(
        call: &syn::Ident,
        returns_result: bool,
        dispatch_call: TokenStream2,
    ) -> TokenStream2 {
        let result_metrics = if returns_result {
            quote! {
                if out.is_ok() {
                    ::canic::core::api::instrumentation::EndpointResultMetrics::increment_ok(#call);
                } else {
                    ::canic::core::api::instrumentation::EndpointResultMetrics::increment_err(#call);
                }
            }
        } else {
            quote!()
        };

        quote! {
            {
                let out = #dispatch_call;
                ::canic::core::api::instrumentation::EndpointAttemptMetrics::increment_completed(#call);
                #result_metrics
                out
            }
        }
    }

    fn extract_args(sig: &syn::Signature) -> syn::Result<Vec<TokenStream2>> {
        let mut out = Vec::new();
        for input in &sig.inputs {
            match input {
                syn::FnArg::Typed(pat) => match &*pat.pat {
                    syn::Pat::Ident(id) => out.push(quote!(#id)),
                    _ => {
                        return Err(syn::Error::new_spanned(
                            &pat.pat,
                            "destructuring parameters not supported",
                        ));
                    }
                },
                syn::FnArg::Receiver(r) => {
                    return Err(syn::Error::new_spanned(
                        r,
                        "`self` not supported in canic endpoints",
                    ));
                }
            }
        }
        Ok(out)
    }
}

fn cdk_attr(kind: EndpointKind, forwarded: &[TokenStream2]) -> TokenStream2 {
    match kind {
        EndpointKind::Query => {
            if forwarded.is_empty() {
                quote!(#[::canic::cdk::query])
            } else {
                quote!(#[::canic::cdk::query(#(#forwarded),*)])
            }
        }
        EndpointKind::Update => {
            if forwarded.is_empty() {
                quote!(#[::canic::cdk::update])
            } else {
                quote!(#[::canic::cdk::update(#(#forwarded),*)])
            }
        }
    }
}

//
// ============================================================================
// Entry dispatcher
// ============================================================================
//

fn expand_entry(kind: EndpointKind, attr: TokenStream, item: TokenStream) -> TokenStream {
    let func = parse_macro_input!(item as ItemFn);
    let sig = func.sig.clone();
    let asyncness = sig.asyncness.is_some();

    let parsed = match parse::parse_args(attr.into()) {
        Ok(v) => v,
        Err(e) => return e.to_compile_error().into(),
    };

    let validated = match validate::validate(parsed, &sig, asyncness) {
        Ok(v) => v,
        Err(e) => return e.to_compile_error().into(),
    };

    expand::expand(kind, validated, func)
}