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
//! `#[feature_flag("key")]` proc macro implementation.
//!
//! Gates the entire route on a feature flag. If the flag is disabled for the
//! current actor the handler responds with 404 Not Found (default) or
//! delegates to a custom fallback handler specified with
//! `#[feature_flag("key", fallback = my_fallback_handler)]`.
//!
//! The flag check runs inside a dedicated `FromRequestParts` extractor so
//! Axum can short-circuit **before** body extractors (`Json`, `Form`) are
//! consumed and before other resources (DB connections, etc.) are acquired.
//!
//! ## Usage
//!
//! ```ignore
//! use autumn_web::prelude::*;
//!
//! #[get("/beta")]
//! #[feature_flag("beta_dashboard")]
//! async fn beta_dashboard() -> Markup {
//! html! { h1 { "Beta!" } }
//! }
//! ```
//!
//! With a custom fallback:
//!
//! ```ignore
//! #[get("/experimental")]
//! #[feature_flag("experimental_feature", fallback = feature_disabled)]
//! async fn experimental() -> Markup { html! { "Experimental" } }
//!
//! async fn feature_disabled() -> impl IntoResponse {
//! (StatusCode::NOT_FOUND, "Feature not available yet")
//! }
//! ```
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::{Expr, ItemFn, LitStr, Token, parse::ParseStream, parse_quote};
struct FeatureFlagArgs {
flag_key: String,
fallback: Option<Expr>,
}
impl syn::parse::Parse for FeatureFlagArgs {
fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
let flag_key: LitStr = input.parse()?;
let fallback = if input.peek(Token![,]) {
let _: Token![,] = input.parse()?;
let ident: syn::Ident = input.parse()?;
if ident != "fallback" {
return Err(syn::Error::new_spanned(
ident,
"expected `fallback = <handler_fn>`",
));
}
let _: Token![=] = input.parse()?;
Some(input.parse()?)
} else {
None
};
Ok(Self {
flag_key: flag_key.value(),
fallback,
})
}
}
pub fn feature_flag_macro(attr: TokenStream, item: TokenStream) -> TokenStream {
let args: FeatureFlagArgs = match syn::parse2(attr) {
Ok(a) => a,
Err(err) => return err.to_compile_error(),
};
let mut input_fn: ItemFn = match syn::parse2(item) {
Ok(f) => f,
Err(err) => return err.to_compile_error(),
};
if input_fn.sig.asyncness.is_none() {
return syn::Error::new_spanned(
input_fn.sig.fn_token,
"#[feature_flag] can only be applied to async functions",
)
.to_compile_error();
}
let flag_key = &args.flag_key;
let fn_name = &input_fn.sig.ident;
// One gate struct per handler keeps names unique within the module.
let gate_ident = format_ident!("__AutumnFlagGate_{}", fn_name);
// The gate's rejection: either the default 404 or a custom fallback.
let disabled_rejection = args.fallback.as_ref().map_or_else(
|| {
quote! {
::std::result::Result::Err(
::autumn_web::reexports::axum::response::IntoResponse::into_response(
::autumn_web::reexports::http::StatusCode::NOT_FOUND,
)
)
}
},
|fallback_fn| {
quote! {
::std::result::Result::Err(
::autumn_web::reexports::axum::response::IntoResponse::into_response(
#fallback_fn().await,
)
)
}
},
);
// Generate the gate struct and its FromRequestParts impl.
//
// Axum extracts all FromRequestParts items (including this gate) before
// it extracts the body extractor (Json, Form, etc.). If the flag is
// disabled, from_request_parts returns Err(Response) and Axum returns that
// response directly — the handler body and body extractors never run.
let gate_impl = quote! {
#[doc(hidden)]
#[allow(non_camel_case_types)]
struct #gate_ident;
#[automatically_derived]
impl ::autumn_web::reexports::axum::extract::FromRequestParts<::autumn_web::AppState>
for #gate_ident
{
type Rejection = ::autumn_web::reexports::axum::response::Response;
async fn from_request_parts(
parts: &mut ::autumn_web::reexports::http::request::Parts,
state: &::autumn_web::AppState,
) -> ::std::result::Result<Self, Self::Rejection> {
let flags = <::autumn_web::feature_flags::Flags
as ::autumn_web::reexports::axum::extract::FromRequestParts<
::autumn_web::AppState,
>>::from_request_parts(parts, state)
.await
.map_err(|e| {
::autumn_web::reexports::axum::response::IntoResponse::into_response(e)
})?;
if flags.enabled(#flag_key) {
if let ::core::option::Option::Some(replay) = parts.extensions.get::<::autumn_web::idempotency::IdempotencyReplayResponse>() {
let opt_ext = ::core::option::Option::Some(::autumn_web::reexports::axum::extract::Extension(replay.clone()));
if let ::core::option::Option::Some(resp) = ::autumn_web::idempotency::__replay_response(&opt_ext) {
return ::std::result::Result::Err(resp);
}
}
::std::result::Result::Ok(#gate_ident)
} else {
#disabled_rejection
}
}
}
};
// Inject the gate as the first handler parameter. The value is unused
// in the handler body — its sole purpose is to trigger the extraction.
let gate_param: syn::FnArg = parse_quote! { _: #gate_ident };
input_fn.sig.inputs.insert(0, gate_param);
input_fn
.attrs
.push(parse_quote!(#[allow(clippy::too_many_arguments)]));
// The return type and body are left unchanged — the gate extractor handles
// the disabled case before the handler is called, so no body injection or
// return-type change is needed.
quote! {
#gate_impl
#input_fn
}
}
#[cfg(test)]
mod tests {
use quote::quote;
use super::feature_flag_macro;
#[test]
fn feature_flag_generates_valid_code_for_simple_flag() {
let result = feature_flag_macro(
quote! { "my_flag" },
quote! {
async fn my_handler() -> &'static str {
"hello"
}
},
);
let code = result.to_string();
// Must contain the flag key lookup
assert!(
code.contains("my_flag"),
"flag key must appear in generated code: {code}"
);
// Must emit a gate type
assert!(
code.contains("__AutumnFlagGate_my_handler"),
"must emit a gate struct: {code}"
);
// Must handle the disabled case
assert!(
code.contains("NOT_FOUND") || code.contains("404"),
"must have 404 fallback: {code}"
);
// Must NOT emit typed local binding
assert!(
!code.contains("let __autumn_inner"),
"must not emit typed local binding: {code}"
);
}
#[test]
fn feature_flag_with_custom_fallback_uses_fallback_fn() {
let result = feature_flag_macro(
quote! { "my_flag", fallback = custom_fallback },
quote! {
async fn my_handler() -> &'static str {
"hello"
}
},
);
let code = result.to_string();
assert!(
code.contains("custom_fallback"),
"custom fallback fn must appear in generated code: {code}"
);
assert!(
!code.contains("NOT_FOUND"),
"must NOT have default 404 when custom fallback provided: {code}"
);
}
#[test]
fn feature_flag_on_non_async_fn_is_compile_error() {
let result = feature_flag_macro(
quote! { "my_flag" },
quote! {
fn my_sync_handler() -> &'static str {
"hello"
}
},
);
let code = result.to_string();
assert!(
code.contains("compile_error"),
"non-async fn must produce compile_error: {code}"
);
}
#[test]
fn feature_flag_impl_trait_return_does_not_emit_typed_binding() {
// The gate approach never emits a typed local binding at all —
// the handler body is unchanged and the return type is preserved.
let result = feature_flag_macro(
quote! { "my_flag" },
quote! {
async fn my_handler() -> Result<impl IntoResponse, String> {
Ok("hello")
}
},
);
let code = result.to_string();
assert!(
!code.contains("let __autumn_inner"),
"must not emit typed local binding: {code}"
);
}
#[test]
fn feature_flag_with_invalid_arg_is_compile_error() {
let result = feature_flag_macro(
quote! { "my_flag", unknown_arg = something },
quote! {
async fn my_handler() -> &'static str {
"hello"
}
},
);
let code = result.to_string();
assert!(
code.contains("compile_error"),
"unknown arg must produce compile_error: {code}"
);
}
#[test]
fn feature_flag_gate_runs_before_body_extractors() {
// The gate extractor is injected as the first parameter (a
// FromRequestParts impl), so Axum evaluates it before consuming the
// request body (Json, Form, etc.). Verify the generated code does NOT
// contain the old body-wrapping pattern.
let result = feature_flag_macro(
quote! { "my_flag" },
quote! {
async fn my_handler(body: String) -> String {
body
}
},
);
let code = result.to_string();
assert!(
code.contains("FromRequestParts"),
"must generate a FromRequestParts impl: {code}"
);
assert!(
!code.contains("async move"),
"must not wrap body in async move block: {code}"
);
}
}