autumn-macros 0.9.0

Proc macros for the Autumn web framework
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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
//! `#[throttle]` proc macro implementation.
//!
//! Generates a per-route rate-limit guard that runs as a `FromRequestParts`
//! gate — a hidden, handler-unique parameter inserted ahead of the handler's
//! own parameters — instead of a statement inside the handler body (issue
//! #1668). Axum resolves every `FromRequestParts` extractor, left to right,
//! *before* it ever reaches a `FromRequest` body extractor (`Json` / `Form` /
//! `Multipart`) and short-circuits on the first rejection, so an over-limit
//! request is rejected with `429` before the request body is parsed or
//! buffered, rather than after.
//!
//! ## Forms
//!
//! - `#[throttle(limit = 5, per = "1m")]` -- inline limit, default key strategy
//! - `#[throttle(limit = 5, per = "1m", key = "ip")]` -- inline with key override
//! - `#[throttle(limit = 5, per = "1m", key = "principal")]`
//! - `#[throttle(limit = 5, per = "1m", key = "token")]`
//! - `#[throttle("login")]` -- named limiter defined in
//!   `[security.rate_limit.named.login]`

use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::parse::Parser as _;
use syn::{Expr, Lit, LitInt, LitStr};

use crate::idempotency_guard::should_own_replay;

/// Parsed `#[throttle(...)]` attribute arguments.
enum ThrottleAttrs {
    /// `#[throttle("login")]`
    Named(String),
    /// `#[throttle(limit = 5, per = "1m", key = "ip")]`
    Inline {
        limit: u32,
        per_secs: u64,
        key: Option<String>,
    },
}

fn parse_key_str(s: &str) -> Result<&'static str, String> {
    match s {
        "ip" => Ok("ip"),
        "principal" => Ok("principal"),
        "token" => Ok("token"),
        other => Err(format!(
            "#[throttle] key must be \"ip\", \"principal\", or \"token\" (got \"{other}\")"
        )),
    }
}

/// Parse a duration string like `"1m"`, `"30s"`, `"1h"` at macro-expand time.
fn parse_per_str(s: &str) -> Result<u64, String> {
    let mut total_secs: u64 = 0;
    let mut current = String::new();
    for ch in s.chars() {
        if ch.is_ascii_digit() {
            current.push(ch);
        } else if ch.is_ascii_alphabetic() {
            let num: u64 = current
                .parse()
                .map_err(|_| format!("invalid per: '{s}' (expected e.g. \"1m\")"))?;
            current.clear();
            match ch {
                's' => total_secs = total_secs.checked_add(num).ok_or("overflow")?,
                'm' => {
                    total_secs = total_secs
                        .checked_add(num.checked_mul(60).ok_or("overflow")?)
                        .ok_or("overflow")?;
                }
                'h' => {
                    total_secs = total_secs
                        .checked_add(num.checked_mul(3600).ok_or("overflow")?)
                        .ok_or("overflow")?;
                }
                'd' => {
                    total_secs = total_secs
                        .checked_add(num.checked_mul(86400).ok_or("overflow")?)
                        .ok_or("overflow")?;
                }
                _ => return Err(format!("invalid per: '{s}' (unit must be s/m/h/d)")),
            }
        } else if ch == ' ' {
            // skip
        } else {
            return Err(format!("invalid per: '{s}'"));
        }
    }
    if !current.is_empty() {
        return Err(format!("invalid per: '{s}' (trailing number without unit)"));
    }
    if total_secs == 0 {
        return Err(format!("invalid per: '{s}' (must be > 0)"));
    }
    Ok(total_secs)
}

fn parse_throttle_args(attr: TokenStream) -> syn::Result<ThrottleAttrs> {
    use proc_macro2::TokenTree;

    if attr.is_empty() {
        return Err(syn::Error::new(
            proc_macro2::Span::call_site(),
            "#[throttle] requires either a named limiter (`#[throttle(\"name\")]`) or \
             `limit`/`per` arguments (`#[throttle(limit = 5, per = \"1m\")]`)",
        ));
    }

    // Peek for a leading bare string literal — the named form.
    let mut iter = attr.clone().into_iter().peekable();
    if let Some(TokenTree::Literal(lit)) = iter.peek() {
        let s: LitStr = syn::parse2(quote! { #lit })?;
        iter.next();
        // No more args allowed after the name.
        if iter.next().is_some() {
            return Err(syn::Error::new_spanned(
                &s,
                "#[throttle(\"name\")] takes no other arguments",
            ));
        }
        return Ok(ThrottleAttrs::Named(s.value()));
    }

    // Otherwise expect keyword form.
    let mut limit: Option<u32> = None;
    let mut per: Option<u64> = None;
    let mut key: Option<String> = None;

    syn::meta::parser(|meta| {
        if meta.path.is_ident("limit") {
            let expr: Expr = meta.value()?.parse()?;
            let n: u32 = match &expr {
                Expr::Lit(l) => match &l.lit {
                    Lit::Int(i) => i.base10_parse::<u32>()?,
                    _ => return Err(meta.error("`limit` must be a positive integer")),
                },
                _ => return Err(meta.error("`limit` must be a literal positive integer")),
            };
            if n == 0 {
                return Err(meta.error("`limit` must be greater than zero"));
            }
            limit = Some(n);
            Ok(())
        } else if meta.path.is_ident("per") {
            let s: LitStr = meta.value()?.parse()?;
            let secs = parse_per_str(&s.value()).map_err(|msg| syn::Error::new_spanned(&s, msg))?;
            per = Some(secs);
            Ok(())
        } else if meta.path.is_ident("key") {
            let s: LitStr = meta.value()?.parse()?;
            let name = parse_key_str(&s.value()).map_err(|msg| syn::Error::new_spanned(&s, msg))?;
            key = Some(name.to_owned());
            Ok(())
        } else {
            Err(meta.error("unsupported #[throttle] argument: expected `limit`, `per`, or `key`"))
        }
    })
    .parse2(attr)?;

    let limit = limit.ok_or_else(|| {
        syn::Error::new(
            proc_macro2::Span::call_site(),
            "#[throttle] requires a `limit = N` argument",
        )
    })?;
    let per_secs = per.ok_or_else(|| {
        syn::Error::new(
            proc_macro2::Span::call_site(),
            "#[throttle] requires a `per = \"1m\"` argument",
        )
    })?;

    Ok(ThrottleAttrs::Inline {
        limit,
        per_secs,
        key,
    })
}

fn build_spec_tokens(attrs: &ThrottleAttrs) -> TokenStream {
    match attrs {
        ThrottleAttrs::Named(name) => {
            let name_lit = LitStr::new(name, proc_macro2::Span::call_site());
            quote! {
                ::autumn_web::security::ThrottleSpec::Named(#name_lit)
            }
        }
        ThrottleAttrs::Inline {
            limit,
            per_secs,
            key,
        } => {
            let limit_lit = LitInt::new(&limit.to_string(), proc_macro2::Span::call_site());
            let per_lit = LitInt::new(&per_secs.to_string(), proc_macro2::Span::call_site());
            let key_tokens = match key.as_deref() {
                None => quote! { ::core::option::Option::None },
                Some("ip") => quote! {
                    ::core::option::Option::Some(::autumn_web::security::KeyStrategy::Ip)
                },
                Some("principal") => quote! {
                    ::core::option::Option::Some(
                        ::autumn_web::security::KeyStrategy::AuthenticatedPrincipal
                    )
                },
                Some("token") => quote! {
                    ::core::option::Option::Some(::autumn_web::security::KeyStrategy::ApiToken)
                },
                Some(_) => unreachable!("key strategies validated at parse time"),
            };
            quote! {
                ::autumn_web::security::ThrottleSpec::Inline {
                    limit: #limit_lit,
                    per_secs: #per_lit,
                    key: #key_tokens,
                }
            }
        }
    }
}

/// Expand the `#[throttle(...)]` attribute.
#[allow(clippy::too_many_lines)]
// `item` is only ever borrowed via
// `param_helpers::split_leading_items_and_reject_incompatible` now, but
// keeps the owned `TokenStream` signature every macro entry point in this
// crate shares (and the proc-macro boundary in `lib.rs` requires).
#[allow(clippy::needless_pass_by_value)]
pub fn throttle_macro(attr: TokenStream, item: TokenStream) -> TokenStream {
    let attrs = match parse_throttle_args(attr) {
        Ok(a) => a,
        Err(err) => return err.to_compile_error(),
    };

    let (leading_items, mut input_fn) =
        match crate::param_helpers::split_leading_items_and_reject_incompatible(&item, "throttle") {
            Ok(v) => v,
            Err(err) => return err,
        };

    // An attribute sharing #[authorize]'s argument grammar under a different
    // name is refused rather than guessed at — see
    // `authorize::reject_if_ambiguous_authorize_shape`'s doc comment.
    if let Some(err) = crate::authorize::reject_if_ambiguous_authorize_shape(&input_fn) {
        return err;
    }

    let fn_name = input_fn.sig.ident.clone();
    let fn_name_str = fn_name.to_string();
    let spec_tokens = build_spec_tokens(&attrs);
    let gate_ident = format_ident!("__AutumnThrottleGate_{}", fn_name);

    // Whether THIS gate should also serve a cached idempotency replay: see
    // `should_own_replay` for the full ordering rationale (issue #1668's
    // pre-body gates and `#[authorize]`'s in-body check must never both skip
    // replay-ownership, nor both claim it).
    let owns_replay = should_own_replay(&input_fn);
    let replay_check = if owns_replay {
        crate::idempotency_guard::owned_replay_check_tokens()
    } else {
        quote! {}
    };

    // The throttle check must run BEFORE the idempotency-replay lookup.
    // Returning a cached response ahead of `__check_throttle` would let repeat
    // requests reusing the same `Idempotency-Key` bypass the per-route bucket
    // forever. Running the throttle check first ensures replays still consume
    // the bucket and can 429 once the route limit is exhausted; only if the
    // throttle check passes do we replay any cached response.
    //
    // Both the check and the replay lookup run inside a `FromRequestParts`
    // gate — a hidden parameter inserted ahead of the handler's own
    // parameters — rather than as a statement inside the handler body. Axum
    // resolves every `FromRequestParts` extractor before it ever reaches a
    // `FromRequest` body extractor (`Json` / `Form` / `Multipart`) and
    // short-circuits on the first rejection, so an over-limit or replayed
    // request never causes the body to be parsed or buffered.
    // Stable per-handler bucket namespace. Two routes pointing at the same
    // named limiter share their bucket via the runtime registry — the
    // route_id here is only used for inline limiters and for uniqueness when
    // a named entry is missing from config.
    //
    // Emitted from one shared `TokenStream` (cheaply `Clone`) so it can be
    // declared TWICE — once inside the gate below for the actual runtime
    // check, and once (inert) into the handler body via `route_id_marker`
    // near the bottom of this function — mirroring `secured_macro`'s
    // `role_scope_consts`/`markers` split. `api_doc::infer_response_body`'s
    // guard recovery (`RESPONSE_REWRITING_GUARD_MARKERS`) requires this const
    // in the handler's OWN body to tell a real guard's `__autumn_inner`
    // wrapper apart from unrelated code with the same shape; since #1668
    // moved the throttle check itself into this gate, this is the only
    // reason a copy still needs to live in the body at all (issue #2516).
    let route_id_marker = quote! {
        #[allow(dead_code)]
        const __AUTUMN_THROTTLE_ROUTE_ID: &str =
            ::core::concat!(::core::module_path!(), "::", #fn_name_str);
    };

    let gate_item = crate::request_gate::wrap_gate(
        &gate_ident,
        &quote! {
            #route_id_marker
            // Borrowed, not cloned: `__check_throttle` takes `&HeaderMap`,
            // and this gate owns `parts` for the whole check.
            let __autumn_throttle_headers = &parts.headers;
            // Optional because `MatchedPath` is absent for some routes
            // (fallbacks, unnested handlers). When present, the
            // runtime matched route pattern isolates an INLINE
            // throttle's bucket per mounted path — a handler reused
            // under two `scoped` prefixes maps to the same
            // compile-time `route_id`, so folding the matched path in
            // gives each mount its own bucket. `__check_throttle`
            // consults it only for inline throttles.
            let __autumn_throttle_matched_path = parts
                .extensions
                .get::<::autumn_web::reexports::axum::extract::MatchedPath>()
                .cloned();
            let __autumn_throttle_peer = parts
                .extensions
                .get::<::autumn_web::reexports::axum::extract::ConnectInfo<::std::net::SocketAddr>>()
                .copied();
            let __autumn_throttle_principal = parts
                .extensions
                .get::<::autumn_web::security::RateLimitPrincipal>()
                .cloned();
            // Optional so throttled routes without session middleware
            // (or a per-route throttle that doesn't key on the
            // principal) still compile and run. `__check_throttle`
            // only consults it for `key = "principal"` when no
            // `RateLimitPrincipal` extension was installed, deriving
            // the principal from the same verified session
            // `populate_rate_limit_principal` reads. Read directly
            // from extensions (not the `Session` extractor) so a
            // route with no `SessionLayer` installed does not panic.
            let __autumn_throttle_session = parts
                .extensions
                .get::<::autumn_web::session::Session>()
                .cloned();
            let __autumn_throttle_exempt = parts
                .extensions
                .get::<::autumn_web::security::RateLimitExempt>()
                .is_some();
            if let ::core::result::Result::Err(__autumn_throttle_response) =
                ::autumn_web::security::__check_throttle(
                    state,
                    __AUTUMN_THROTTLE_ROUTE_ID,
                    __autumn_throttle_matched_path.as_ref().map(|__mp| __mp.as_str()),
                    #spec_tokens,
                    __autumn_throttle_headers,
                    __autumn_throttle_peer.map(|c| c.0),
                    __autumn_throttle_principal.as_ref(),
                    __autumn_throttle_session.as_ref(),
                    __autumn_throttle_exempt,
                ).await
            {
                return ::core::result::Result::Err(__autumn_throttle_response);
            }
            #replay_check
        },
    );

    // NOT `param_helpers::build_original_response` (which `secured`/
    // `step_up`/`authorize` share): this match has an extra
    // `should_stringify_primitive_output` arm below that the other three
    // don't need. Deliberate divergence, not an omission — see that arm's
    // comment.
    let original_body = input_fn.block.clone();
    let original_response = match &input_fn.sig.output {
        syn::ReturnType::Default => quote! {
            let __autumn_inner: () = (async move #original_body).await;
            ::autumn_web::reexports::axum::response::IntoResponse::into_response(__autumn_inner)
        },
        syn::ReturnType::Type(_, ty) if crate::param_helpers::type_contains_impl_trait(ty) => {
            quote! {
                ::autumn_web::reexports::axum::response::IntoResponse::into_response(
                    (async move #original_body).await
                )
            }
        }
        // A bare numeric/bool primitive does not implement `IntoResponse`;
        // Autumn's plain primitive-output wrapper serves it by stringifying. The
        // route macro suppresses that wrapper when `#[throttle]` is present (the
        // handler is rewritten to return `Response`), so mirror the stringify
        // here to keep primitive-returning throttled handlers compiling.
        syn::ReturnType::Type(_, ty)
            if crate::route::should_stringify_primitive_output(&input_fn.sig.output) =>
        {
            quote! {
                let __autumn_inner: #ty = (async move #original_body).await;
                ::autumn_web::reexports::axum::response::IntoResponse::into_response(
                    ::std::string::ToString::to_string(&__autumn_inner)
                )
            }
        }
        syn::ReturnType::Type(_, ty) => quote! {
            let __autumn_inner: #ty = (async move #original_body).await;
            ::autumn_web::reexports::axum::response::IntoResponse::into_response(__autumn_inner)
        },
    };

    // Insert the gate as the FIRST parameter. Axum evaluates `FromRequestParts`
    // extractors left to right, so this must sit ahead of every other
    // extractor — including any earlier-inserted guard gate, which then
    // correctly runs AFTER (see `should_own_replay`'s doc comment: whichever
    // guard is applied to a still-unguarded function owns replay, and
    // "unguarded" is judged at each macro's OWN expansion time, before later
    // macros insert their gates further left).
    crate::request_gate::insert_gate_param(&mut input_fn, &gate_ident);

    input_fn.block = syn::parse_quote! {
        {
            #route_id_marker
            #original_response
        }
    };

    quote! {
        #leading_items
        #gate_item
        #input_fn
    }
}

// ── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use quote::quote;

    use super::throttle_macro;
    use crate::static_route::static_get_macro;

    /// Characterization test (Echo refactor, clone class: the
    /// `FromRequestParts` gate skeleton shared with `secured`/`step_up`):
    /// pins `#[throttle(limit = 5, per = "1m", key = "principal")]`'s exact
    /// expansion — exercising the rate-limit check and (as the only guard on
    /// this handler) the replay lookup at once — so that factoring the
    /// gate's struct+impl skeleton into `request_gate::wrap_gate` cannot
    /// silently change a single token of it.
    #[test]
    fn throttle_macro_expansion_is_unchanged_by_the_gate_skeleton_refactor() {
        let generated = throttle_macro(
            quote! { limit = 5, per = "1m", key = "principal" },
            quote! {
                async fn handler() -> &'static str { "ok" }
            },
        )
        .to_string();
        assert_eq!(
            generated,
            include_str!("../testdata/throttle_golden.txt").trim_end()
        );
    }

    #[test]
    fn throttle_rejects_when_invoked_on_a_static_route_handler_via_an_alias() {
        // See `secured::tests::secured_rejects_when_invoked_on_a_static_route_handler_via_an_alias`
        // for the full rationale (Codex review on #2513, tenth finding).
        let accepted = static_get_macro(
            quote! { "/private" },
            quote! {
                #[auth]
                async fn private() -> &'static str { "private" }
            },
        );
        assert!(
            !accepted.to_string().contains("compile_error"),
            "static_get_macro cannot recognize an aliased guard attribute by name: {accepted}"
        );

        let accepted_fn = crate::param_helpers::extract_fn_item(accepted, "private");
        let generated =
            throttle_macro(quote! { limit = 5, per = "1m" }, quote! { #accepted_fn }).to_string();

        assert!(
            generated.contains("compile_error"),
            "throttle_macro must reject a handler already marked as a #[static_get] route, \
             regardless of what alias attribute name the source used to invoke it: {generated}"
        );
    }

    #[test]
    fn inline_form_generates_check_call() {
        let generated = throttle_macro(
            quote! { limit = 5, per = "1m" },
            quote! {
                async fn login() -> &'static str { "ok" }
            },
        )
        .to_string();
        assert!(
            generated.contains("__check_throttle"),
            "should emit runtime check call:\n{generated}"
        );
        assert!(
            generated.contains("ThrottleSpec :: Inline"),
            "should emit an inline spec:\n{generated}"
        );
        assert!(
            generated.contains("limit : 5") || generated.contains("limit: 5"),
            "should embed the limit value:\n{generated}"
        );
        assert!(
            generated.contains("60"),
            "1m should expand to 60 seconds:\n{generated}"
        );
    }

    #[test]
    fn named_form_generates_named_spec() {
        let generated = throttle_macro(
            quote! { "login" },
            quote! {
                async fn login() -> &'static str { "ok" }
            },
        )
        .to_string();
        assert!(
            generated.contains("ThrottleSpec :: Named"),
            "should emit a named spec:\n{generated}"
        );
        assert!(
            generated.contains("\"login\""),
            "should reference the limiter name:\n{generated}"
        );
    }

    #[test]
    fn key_principal_selects_authenticated_principal() {
        let generated = throttle_macro(
            quote! { limit = 3, per = "1s", key = "principal" },
            quote! {
                async fn handler() -> &'static str { "ok" }
            },
        )
        .to_string();
        assert!(
            generated.contains("AuthenticatedPrincipal"),
            "should map key = \"principal\" to AuthenticatedPrincipal:\n{generated}"
        );
    }

    #[test]
    fn key_token_selects_api_token() {
        let generated = throttle_macro(
            quote! { limit = 3, per = "1s", key = "token" },
            quote! {
                async fn handler() -> &'static str { "ok" }
            },
        )
        .to_string();
        assert!(
            generated.contains("ApiToken"),
            "should map key = \"token\" to ApiToken:\n{generated}"
        );
    }

    #[test]
    fn key_ip_selects_ip_strategy() {
        let generated = throttle_macro(
            quote! { limit = 3, per = "1s", key = "ip" },
            quote! {
                async fn handler() -> &'static str { "ok" }
            },
        )
        .to_string();
        assert!(
            generated.contains("KeyStrategy :: Ip"),
            "should map key = \"ip\" to KeyStrategy::Ip:\n{generated}"
        );
    }

    #[test]
    fn rejects_sync_functions() {
        let generated = throttle_macro(
            quote! { limit = 3, per = "1s" },
            quote! {
                fn sync_handler() -> &'static str { "ok" }
            },
        )
        .to_string();
        assert!(
            generated.contains("compile_error"),
            "should emit compile_error for non-async functions:\n{generated}"
        );
    }

    #[test]
    fn rejects_missing_arguments() {
        let generated = throttle_macro(
            quote! {},
            quote! {
                async fn handler() -> &'static str { "ok" }
            },
        )
        .to_string();
        assert!(
            generated.contains("compile_error"),
            "should emit compile_error when no arguments supplied:\n{generated}"
        );
    }

    #[test]
    fn rejects_unknown_key_strategy() {
        let generated = throttle_macro(
            quote! { limit = 3, per = "1s", key = "unknown" },
            quote! {
                async fn handler() -> &'static str { "ok" }
            },
        )
        .to_string();
        assert!(
            generated.contains("compile_error"),
            "should emit compile_error for unknown key strategy:\n{generated}"
        );
    }

    #[test]
    fn rejects_missing_per() {
        let generated = throttle_macro(
            quote! { limit = 5 },
            quote! {
                async fn handler() -> &'static str { "ok" }
            },
        )
        .to_string();
        assert!(
            generated.contains("compile_error"),
            "should emit compile_error when `per` is missing:\n{generated}"
        );
    }

    #[test]
    fn rejects_bad_per_syntax() {
        let generated = throttle_macro(
            quote! { limit = 5, per = "not-a-duration" },
            quote! {
                async fn handler() -> &'static str { "ok" }
            },
        )
        .to_string();
        assert!(
            generated.contains("compile_error"),
            "should emit compile_error for bad `per` string:\n{generated}"
        );
    }

    #[test]
    fn gate_reads_state_from_from_request_parts() {
        let generated = throttle_macro(
            quote! { limit = 5, per = "1m" },
            quote! {
                async fn handler() -> &'static str { "ok" }
            },
        )
        .to_string();
        assert!(
            generated.contains("FromRequestParts"),
            "check should run in a FromRequestParts gate, not a body statement:\n{generated}"
        );
        assert!(
            generated.contains("__check_throttle"),
            "should still emit the runtime check call:\n{generated}"
        );
        assert!(
            !generated.contains("__autumn_state"),
            "the old hidden State<AppState> handler parameter should be gone — the gate reads \
             state from its own `from_request_parts` argument instead:\n{generated}"
        );
    }

    #[test]
    fn injects_headers_and_connect_info() {
        let generated = throttle_macro(
            quote! { limit = 5, per = "1m" },
            quote! {
                async fn handler() -> &'static str { "ok" }
            },
        )
        .to_string();
        assert!(
            generated.contains("__autumn_throttle_headers"),
            "should read headers from request parts:\n{generated}"
        );
        assert!(
            generated.contains("__autumn_throttle_headers = & parts . headers"),
            "the gate must borrow request headers:\n{generated}"
        );
        assert!(
            !generated.contains("headers . clone ()"),
            "the gate must borrow request headers, not clone them:\n{generated}"
        );
        assert!(
            generated.contains("ConnectInfo"),
            "should read ConnectInfo from request parts:\n{generated}"
        );
    }

    #[test]
    fn injects_matched_path_extractor() {
        let generated = throttle_macro(
            quote! { limit = 5, per = "1m" },
            quote! {
                async fn handler() -> &'static str { "ok" }
            },
        )
        .to_string();
        assert!(
            generated.contains("__autumn_throttle_matched_path"),
            "should read MatchedPath from request parts:\n{generated}"
        );
        assert!(
            generated.contains("MatchedPath"),
            "should reference axum MatchedPath:\n{generated}"
        );
    }

    #[test]
    fn emits_gate_struct_and_impl_as_sibling_items() {
        let generated = throttle_macro(
            quote! { limit = 5, per = "1m" },
            quote! {
                async fn handler() -> &'static str { "ok" }
            },
        )
        .to_string();
        assert!(
            generated.contains("struct __AutumnThrottleGate_handler"),
            "should emit a handler-unique gate marker struct:\n{generated}"
        );
        assert!(
            generated
                .contains("impl :: autumn_web :: reexports :: axum :: extract :: FromRequestParts"),
            "gate must implement FromRequestParts so Axum resolves it before the body extractor:\n{generated}"
        );
    }

    #[test]
    fn inserts_gate_as_first_parameter() {
        let generated_fn = {
            let generated = throttle_macro(
                quote! { limit = 5, per = "1m" },
                quote! {
                    async fn handler(::autumn_web::reexports::axum::extract::Json(_body): ::autumn_web::reexports::axum::extract::Json<String>) -> &'static str { "ok" }
                },
            );
            let items: syn::File = syn::parse2(generated).expect("generated tokens must parse");
            items
                .items
                .into_iter()
                .find_map(|item| match item {
                    syn::Item::Fn(f) if f.sig.ident == "handler" => Some(f),
                    _ => None,
                })
                .expect("handler fn must be present in the expansion")
        };
        let first_param = generated_fn
            .sig
            .inputs
            .first()
            .expect("handler must have at least the gate parameter");
        let syn::FnArg::Typed(pat_type) = first_param else {
            panic!("first parameter must be a typed gate parameter");
        };
        let syn::Type::Path(type_path) = pat_type.ty.as_ref() else {
            panic!("gate parameter must be a named type");
        };
        assert_eq!(
            type_path.path.segments.last().unwrap().ident,
            "__AutumnThrottleGate_handler",
            "the gate must be the FIRST parameter — ahead of the body extractor — so Axum \
             resolves (and can reject on) it before ever reaching the body"
        );
    }

    #[test]
    fn handler_body_no_longer_contains_the_throttle_check() {
        // The whole point of issue #1668: the runtime check must live in the
        // gate's `FromRequestParts` impl, not in a statement inside the
        // handler body (which only runs after every extractor — including a
        // body extractor — has already succeeded).
        let generated_fn = {
            let generated = throttle_macro(
                quote! { limit = 5, per = "1m" },
                quote! {
                    async fn handler() -> &'static str { "ok" }
                },
            );
            let items: syn::File = syn::parse2(generated).expect("generated tokens must parse");
            items
                .items
                .into_iter()
                .find_map(|item| match item {
                    syn::Item::Fn(f) if f.sig.ident == "handler" => Some(f),
                    _ => None,
                })
                .expect("handler fn must be present in the expansion")
        };
        let body = quote! { #generated_fn }.to_string();
        assert!(
            !body.contains("__check_throttle"),
            "the handler body must not call the runtime check directly:\n{body}"
        );
    }

    #[test]
    fn owns_replay_when_unguarded() {
        let generated = throttle_macro(
            quote! { limit = 5, per = "1m" },
            quote! {
                async fn handler() -> &'static str { "ok" }
            },
        )
        .to_string();
        assert!(
            generated.contains("__replay_response"),
            "an otherwise-unguarded throttled handler's gate must own replay-serving:\n{generated}"
        );
    }

    #[test]
    fn defers_replay_to_an_earlier_gate_when_stacked() {
        // Simulate `#[secured]` having already expanded and inserted its own
        // gate parameter ahead of `#[throttle]`'s.
        let generated = throttle_macro(
            quote! { limit = 5, per = "1m" },
            quote! {
                async fn handler(_g: __AutumnSecuredGate_handler) -> &'static str { "ok" }
            },
        )
        .to_string();
        assert!(
            !generated.contains("__replay_response"),
            "must defer replay-ownership to the earlier-inserted gate:\n{generated}"
        );
    }

    #[test]
    fn defers_replay_when_authorize_still_pending() {
        // `#[authorize]` written below `#[throttle]` hasn't expanded yet, so
        // its in-body policy check will only run once the handler body is
        // invoked — strictly after this gate. If this gate served a cached
        // replay itself, `#[authorize]`'s check would never run for a replay.
        let generated = throttle_macro(
            quote! { limit = 5, per = "1m" },
            quote! {
                #[authorize("update", resource = Post)]
                async fn handler() -> &'static str { "ok" }
            },
        )
        .to_string();
        assert!(
            !generated.contains("__replay_response"),
            "must defer replay-ownership while #[authorize] is still pending:\n{generated}"
        );
    }

    #[test]
    fn per_hours_and_seconds_parse() {
        let generated_h = throttle_macro(
            quote! { limit = 1, per = "2h" },
            quote! {
                async fn handler() -> &'static str { "ok" }
            },
        )
        .to_string();
        assert!(
            generated_h.contains("7200"),
            "2h should expand to 7200 seconds:\n{generated_h}"
        );

        let generated_s = throttle_macro(
            quote! { limit = 1, per = "30s" },
            quote! {
                async fn handler() -> &'static str { "ok" }
            },
        )
        .to_string();
        assert!(
            generated_s.contains("30"),
            "30s should expand to 30 seconds:\n{generated_s}"
        );
    }

    /// Echo clone-class regression, `throttle`'s side of the pair covered by
    /// `step_up::tests::step_up_handles_nested_impl_trait_return_type` — see
    /// `secured::tests::secured_handles_nested_impl_trait_return_type` for
    /// why the recursive `type_contains_impl_trait` guard matters. Already
    /// green here (`throttle_macro` has the fix); kept alongside the other
    /// three copies so the four macros stay provably in lockstep on this
    /// rule.
    #[test]
    fn throttle_handles_nested_impl_trait_return_type() {
        let generated = throttle_macro(
            quote! { limit = 5, per = "1m" },
            quote! {
                async fn handler() -> Result<impl IntoResponse, String> {
                    Ok("ok")
                }
            },
        )
        .to_string();
        assert!(
            !generated.contains("__autumn_inner :"),
            "should not emit an explicit local annotation for nested impl Trait: {generated}"
        );
    }
}