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
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
//! # Autumn Macros
//!
//! Proc macros for the Autumn web framework.
//!
//! This crate provides:
//! - Route annotation macros (`#[get]`, `#[post]`, etc.)
//! - The `routes![]` collection macro
//! - The `#[autumn_web::main]` entry point macro (S-008)
//! - The `#[model]` attribute macro (S-018)
//!
//! Users should not depend on this crate directly — use `autumn-web` instead,
//! which re-exports everything.
use TokenStream;
/// Annotate an async function as a GET route handler.
///
/// Generates a companion `__autumn_route_info_{name}()` function that
/// returns a `Route` pairing the path with an Axum
/// handler. In debug builds, `#[axum::debug_handler]` is automatically
/// applied for improved error messages. This has zero cost in release
/// builds.
///
/// # Example
///
/// ```ignore
/// use autumn_web::get;
///
/// #[get("/hello")]
/// async fn hello() -> &'static str {
/// "Hello, Autumn!"
/// }
/// ```
///
/// # Route-level SEO defaults
///
/// A `seo(...)` argument declares per-page meta tag values once on the route
/// instead of rebuilding them in every handler. Take a `SeoMeta` parameter and
/// it arrives pre-populated; the builder is consuming, so the handler refines
/// the defaults with per-request data:
///
/// ```ignore
/// use autumn_web::get;
/// use autumn_web::seo::SeoMeta;
///
/// #[get("/about", seo(title = "About • My Blog", description = "Learn about us"))]
/// async fn about(seo: SeoMeta) -> Markup {
/// html! { head { (seo.render()) } }
/// }
///
/// #[get("/posts/{slug}", seo(og_type = "article"))]
/// async fn show(slug: Path<String>, seo: SeoMeta) -> Markup {
/// let seo = seo.title(format!("{} • Blog", *slug));
/// html! { head { (seo.render()) } }
/// }
/// ```
///
/// Accepted keys mirror the `SeoMeta` builder: `title`, `description`,
/// `canonical`, `og_title`, `og_description`, `og_image`, `og_type`, `og_url`,
/// `twitter_card`, `twitter_title`, `twitter_description`, `twitter_image`,
/// and `robots`. Values must be string literals; an unknown, repeated, or
/// empty `seo(...)` is a compile error. Every HTTP route macro accepts the
/// argument, as does [`macro@static_get`]; [`macro@ws`] does not, since a
/// WebSocket upgrade serves no crawlable document.
///
/// The argument supplies *values*, not markup: a handler that never takes a
/// `SeoMeta` parameter renders nothing regardless of what the attribute
/// declares.
/// Annotate an async function as a POST route handler.
///
/// Generates a companion `__autumn_route_info_{name}()` function that
/// returns a `Route` pairing the path with an Axum
/// handler. In debug builds, `#[axum::debug_handler]` is automatically
/// applied for improved error messages. This has zero cost in release
/// builds.
///
/// # Example
///
/// ```ignore
/// use autumn_web::post;
///
/// #[post("/items")]
/// async fn create_item() -> &'static str {
/// "created"
/// }
/// ```
/// Annotate an async function as a PUT route handler.
///
/// Generates a companion `__autumn_route_info_{name}()` function that
/// returns a `Route` pairing the path with an Axum
/// handler. In debug builds, `#[axum::debug_handler]` is automatically
/// applied for improved error messages. This has zero cost in release
/// builds.
///
/// # Example
///
/// ```ignore
/// use autumn_web::put;
///
/// #[put("/items/{id}")]
/// async fn update_item() -> &'static str {
/// "updated"
/// }
/// ```
/// Annotate an async function as a PATCH route handler.
///
/// Generates a companion `__autumn_route_info_{name}()` function and a typed
/// `__autumn_path_{name}(…) -> String` path helper.
///
/// # Example
///
/// ```ignore
/// use autumn_web::patch;
///
/// #[patch("/items/{id}")]
/// async fn patch_item() -> &'static str {
/// "patched"
/// }
/// ```
/// Annotate an async function as a DELETE route handler.
///
/// Generates a companion `__autumn_route_info_{name}()` function that
/// returns a `Route` pairing the path with an Axum
/// handler. In debug builds, `#[axum::debug_handler]` is automatically
/// applied for improved error messages. This has zero cost in release
/// builds.
///
/// # Example
///
/// ```ignore
/// use autumn_web::delete;
///
/// #[delete("/items/{id}")]
/// async fn remove_item() -> &'static str {
/// "removed"
/// }
/// ```
/// Annotate an OAuth2/OIDC callback handler.
///
/// This is a convenience alias for `#[get(\"...\")]`, intended for OAuth
/// callback endpoints such as `/auth/github/callback`.
/// Collect annotated route handlers into a `Vec<Route>`.
///
/// Each handler must have been annotated with a route macro (`#[get]`,
/// `#[post]`, etc.) which generates a companion
/// `__autumn_route_info_{name}()` function.
///
/// # Example
///
/// ```ignore
/// use autumn_web::{get, post, routes};
///
/// #[get("/hello")]
/// async fn hello() -> &'static str { "hello" }
///
/// #[post("/create")]
/// async fn create() -> &'static str { "created" }
///
/// let all_routes = routes![hello, create];
/// ```
/// Emit a `pub mod paths { … }` that re-exports each handler's typed path helper.
///
/// Takes the same comma-separated handler list as [`routes!`]. Each entry
/// exposes its `__autumn_path_{name}` companion under the short name:
///
/// ```ignore
/// autumn_web::paths![show_post, create_post, posts::index];
/// // expands to:
/// pub mod paths {
/// pub use super::__autumn_path_show_post as show_post;
/// pub use super::__autumn_path_create_post as create_post;
/// pub use super::posts::__autumn_path_index as index;
/// }
/// ```
///
/// Call this once at the top of the module where your handlers live (or a
/// sibling module) so consumers can write `use crate::routes::paths;` and
/// then `paths::show_post(id)`.
/// Set up the async runtime for an Autumn application.
///
/// This is a thin wrapper around `#[tokio::main]`. The real
/// framework setup happens in `autumn_web::app().run()`.
///
/// # Example
///
/// ```ignore
/// #[autumn_web::main]
/// async fn main() {
/// autumn_web::app()
/// .routes(routes![hello])
/// .run()
/// .await;
/// }
/// ```
/// Annotate an async function as a deterministic simulation test (S-1797, W1).
///
/// Expands into a synchronous `#[test]` function that reads a seed from the
/// `AUTUMN_SIM_SEED` environment variable (hex `0x..` or decimal, default `0`),
/// builds a paused current-thread tokio runtime, constructs a
/// `autumn_web::sim::Sim` from the seed, runs the async body, and prints a
/// copy-pasteable replay line on panic before re-propagating the failure.
///
/// The annotated function must be `async` and take exactly one argument — the
/// [`Sim`](../autumn_web/sim/struct.Sim.html) handle.
///
/// # Example
///
/// ```ignore
/// use autumn_web::sim::Sim;
/// use autumn_web::sim_test;
///
/// #[sim_test]
/// async fn deterministic(mut sim: Sim) {
/// assert_eq!(sim.seed, 0);
/// }
/// ```
/// Annotate an async inbound mail handler function.
///
/// Generates a companion `{name}_handler_info()` function that returns an
/// `InboundMailHandlerInfo` ready to be passed to `InboundMailRouter::handler`.
///
/// # Attributes
///
/// - `to = "address@example.com"` — exact recipient match.
/// - `to = "replies+{token}@app.example"` — plus-address routing; the captured
/// token is available via `InboundEmail::plus_token()`.
/// - `to = "prefix+*"` — local-part prefix match.
/// - `processing = "sync"` | `"background"` (default: `"background"`).
///
/// # Example
///
/// ```rust,ignore
/// #[inbound_mail(to = "support@company.com")]
/// async fn handle_support(email: InboundEmail) -> AutumnResult<()> {
/// tracing::info!(from = %email.from, "support email received");
/// Ok(())
/// }
///
/// // Registration:
/// InboundMailRouter::new()
/// .handler(handle_support_handler_info())
/// ```
/// Generate `send_*` and `deliver_later_*` helpers for a mailer impl block.
/// Register zero-argument mail preview methods for the dev mail preview UI.
/// Collect `#[mailer_preview]` impl blocks into runtime preview registrations.
/// Define a widget story for the `/_stories` gallery:
/// `story!{ "Group", "Name", { ... } }`.
///
/// The brace-delimited block is **both** executed for the live render and
/// captured byte-for-byte (comments and formatting included) as the displayed
/// source snippet, so the shown code is provably the code that rendered. The
/// block must be a self-contained expression evaluating to `maud::Markup`:
/// it is coerced to a plain `fn() -> Markup`, so capturing anything from the
/// surrounding environment is a compile error.
/// Attribute macro for Autumn database models.
///
/// Applies Diesel (`Queryable`, `Selectable`, `Insertable`) and Serde
/// (`Serialize`, `Deserialize`) derives, plus a `#[diesel(table_name)]`
/// attribute. The table name can be specified explicitly or inferred
/// from the struct name by converting `PascalCase` to `snake_case`
/// and appending `s`.
///
/// # Examples
///
/// Explicit table name:
///
/// ```ignore
/// use autumn_web::model;
///
/// #[model(table = "users")]
/// pub struct User {
/// pub id: i64,
/// pub name: String,
/// }
/// ```
///
/// Inferred table name (`BlogPost` -> `blog_posts`):
///
/// ```ignore
/// use autumn_web::model;
///
/// #[model]
/// pub struct BlogPost {
/// pub id: i64,
/// pub title: String,
/// }
/// ```
///
/// # Associations
///
/// Declare `#[belongs_to]`, `#[has_many]`, and `#[has_one]` on the struct to
/// get batched eager preloading for free — no hand-written join queries, no
/// N+1. Foreign keys and accessor names are inferred from the target's type
/// name, with `fk = ...` / `name = ...` overrides:
///
/// ```ignore
/// #[model]
/// #[belongs_to(User, fk = author_id)] // fk on THIS model
/// #[has_many(Comment)] // fk (post_id) on the TARGET
/// pub struct Post {
/// #[id]
/// pub id: i64,
/// pub author_id: i64,
/// pub title: String,
/// }
/// ```
///
/// Preload associations through a repository (`Model::preload()` builds the
/// spec; `_with` nests into the related model's own associations):
///
/// ```ignore
/// let posts = repo.find_all().await?;
/// let posts = repo.preload(posts, Post::preload().author().comments()).await?;
/// for post in &posts {
/// let author = post.author()?; // Result<Option<&Preloaded<User>>, NotLoaded>
/// let comments = post.comments()?; // Result<&[Preloaded<Comment>], NotLoaded>
/// }
/// ```
///
/// An association that was not preloaded returns `NotLoaded` from its
/// accessor rather than issuing SQL — autumn never lazy-loads.
///
/// ## Many-to-many (`through =`)
///
/// Add `through = <join_table>` to `#[has_many]` to declare a many-to-many
/// association backed by a join table, with the same batched preload
/// semantics as `belongs_to`/`has_many`/`has_one`:
///
/// ```ignore
/// #[model]
/// #[has_many(Tag, through = post_tags)] // join columns default to post_id / tag_id
/// pub struct Post {
/// #[id]
/// pub id: i64,
/// pub title: String,
/// }
/// ```
///
/// Join columns default to `{source}_id` / `{target}_id` and can be
/// overridden with `fk = ...` and `target_fk = ...`; the join table itself
/// needs no hand-written `diesel::table!` — the macro emits one and requires
/// a composite primary key on `(fk, target_fk)`:
///
/// ```sql
/// CREATE TABLE post_tags (
/// post_id BIGINT NOT NULL REFERENCES posts(id),
/// tag_id BIGINT NOT NULL REFERENCES tags(id),
/// PRIMARY KEY (post_id, tag_id)
/// );
/// ```
///
/// `Post::preload().tags()` issues one batched `INNER JOIN` query (plus one
/// more per level of `_with` nesting) — a fixed number of queries regardless
/// of how many tags each post has. The generated `tags()` accessor returns
/// `&[Arc<Preloaded<Tag>>]` (rather than `has_many`'s plain
/// `&[Preloaded<Tag>]`): the same tag can legitimately be linked to more than
/// one currently-loaded post, so it's shared via `Arc` instead of being
/// duplicated per parent.
///
/// The association also generates three mutation helpers on the model's
/// `#[repository]` — `add_{singular}`, `remove_{singular}`, and
/// `set_{plural}` (replace-all) — each idempotent and requiring no
/// hand-written SQL:
///
/// ```ignore
/// repo.add_tag(post_id, tag_id).await?; // idempotent: ON CONFLICT DO NOTHING
/// repo.remove_tag(post_id, tag_id).await?; // idempotent: no-op if unlinked
/// repo.set_tags(post_id, &tag_ids).await?; // replace-all, one transaction
/// ```
///
/// The `add_`/`remove_` singular is derived from the target *type* name, so a
/// model may declare at most one m2m association per target type by default —
/// a second one to the same target would generate colliding helpers (a compile
/// error). To declare two m2m associations to the same target (e.g. a
/// self-referential `followers`/`following` pair through one `Friendship` join
/// table), give each a distinct explicit `helper = "..."` override, which sets
/// the singular used for its `add_`/`remove_` helpers:
///
/// ```ignore
/// #[model]
/// #[has_many(User, through = friendships, name = followers,
/// fk = followed_id, target_fk = follower_id, helper = "follower")]
/// #[has_many(User, through = friendships, name = following,
/// fk = follower_id, target_fk = followed_id, helper = "following")]
/// pub struct User { /* ... */ }
/// // -> add_follower/remove_follower and add_following/remove_following
/// ```
///
/// # Votable (reactions)
///
/// `#[votable(by = <Reactor>)]` declares a reaction association (#1362): a
/// `(reactor, target)`-unique edge table plus an aggregate column maintained on
/// this model. It replaces the hand-written toggle/flip/upsert SQL and the
/// score recompute that every voting, liking or bookmarking feature otherwise
/// grows.
///
/// ```ignore
/// #[model]
/// #[votable(by = User, aggregate = sum)] // signed up/down votes
/// pub struct Post {
/// #[id]
/// pub id: i64,
/// pub title: String,
/// pub score: i64, // the aggregate column
/// }
/// ```
///
/// Two modes: `aggregate = sum` (the default — signed values, `score =
/// SUM(value)`) and `aggregate = count` (unary likes — no value column,
/// `{name}_count = COUNT(*)`). Every name is inferred and every inference has
/// an override:
///
/// | Key | Default | Meaning |
/// |---|---|---|
/// | `by` | **required** | the reactor model, e.g. `User` |
/// | `aggregate` | `sum` | `sum` \| `count` |
/// | `name` | `vote` | reaction name; drives `table` and the count column |
/// | `table` | `pluralize(name)` → `votes` | the edge table |
/// | `reactor_fk` | `{snake(by)}_id` → `user_id` | edge column → reactor |
/// | `target_fk` | `{snake(Model)}_id` → `post_id` | edge column → this model |
/// | `value_column` | `value` (sum only) | the edge's signed value |
/// | `column` | `score` (sum) / `{name}_count` (count) | aggregate column |
///
/// A likes feature is therefore `#[votable(by = User, aggregate = count, name
/// = like)]` → table `likes`, column `like_count`. At most one `#[votable]` per
/// model.
///
/// `by` may name a hand-written struct — it is name-resolved at compile time
/// but carries no trait bound, so the reactor's `i64` primary key is
/// documented contract, not a compile check (the edge table binds the reactor
/// FK as `BIGINT`; a UUID-keyed reactor fails on first use with a database
/// type error). The **target** model's `#[id]` and aggregate column *are*
/// compile-checked as `i64`.
///
/// **Write `#[votable]` *below* `#[model]`.** It is consumed by `#[model]`, not
/// registered as an attribute in its own right, so an attribute macro written
/// above it never sees it — an error reading `cannot find attribute `votable`
/// in this scope` means the two lines are the wrong way round.
///
/// ## Required migration
///
/// The edge table is the user's to create, and its **composite `UNIQUE
/// (reactor_fk, target_fk)` is load-bearing**: it is the `ON CONFLICT` arbiter
/// the generated upsert names, and it is what makes "at most one edge per
/// (reactor, target)" a database guarantee. The value column is `SMALLINT`, the
/// aggregate column `BIGINT NOT NULL DEFAULT 0`, and the model's own primary key
/// must be `BIGINT`/`i64` (both edge foreign keys are bound as `i64`; a
/// UUID-keyed model is a compile error).
///
/// `NOT NULL` on both foreign keys is strongly recommended: `NULL`s are
/// distinct in a unique constraint, so a nullable column is not covered by the
/// arbiter. A nullable *target* FK is nevertheless tolerated when every row this
/// association writes is non-`NULL` — the shape an XOR edge table has (reddit-
/// clone's `votes` points at either a post or a comment), where the unique
/// constraint still fully covers the non-`NULL` rows `react()` creates.
///
/// The `CHECK` on `value` is load-bearing in sum mode: **`react()` does not
/// validate `value`** — it writes what it is given, and the sum is only
/// meaningful because the database refuses anything outside the legal set.
/// Never bind `value` straight from a request; map the request to `1` / `-1`
/// yourself. A violating value surfaces as a database error (a 500), not a
/// validation failure.
///
/// ```sql
/// CREATE TABLE votes (
/// id BIGSERIAL PRIMARY KEY,
/// user_id BIGINT NOT NULL REFERENCES users(id),
/// post_id BIGINT NOT NULL REFERENCES posts(id) ON DELETE CASCADE,
/// value SMALLINT NOT NULL CHECK (value IN (-1, 1)),
/// UNIQUE (user_id, post_id) -- the ON CONFLICT arbiter
/// );
/// ALTER TABLE posts ADD COLUMN score BIGINT NOT NULL DEFAULT 0;
/// -- aggregate = count: drop the `value` column entirely.
/// ```
///
/// ## Generated helpers
///
/// A `{Model}Reactions` trait, blanket-implemented for the model's
/// `#[repository]`:
///
/// ```ignore
/// use autumn_web::repository::{Reaction, ReactionOutcome};
///
/// // sum mode. (count mode: `react(reactor_id, target_id)` — no value.)
/// let r: Reaction = posts.react(user_id, post_id, 1).await?;
/// r.value; // Option<i16>: the reactor's reaction AFTER the call
/// r.aggregate; // i64: the newly persisted score, ground truth at commit
/// r.outcome; // Inserted | Flipped | Removed
///
/// let mine: Option<i16> = posts.reaction_of(user_id, post_id).await?;
/// ```
///
/// `react()` is race-safe: the same value again toggles the edge off, a
/// different value flips it in place, a new one inserts it — and the aggregate
/// is recomputed from ground truth (`SUM`/`COUNT`) and persisted in the **same
/// transaction**, so a reader never observes edge/aggregate disagreement. The
/// target row is locked (`SELECT ... FOR NO KEY UPDATE` on Postgres — it does
/// not conflict with the `FOR KEY SHARE` locks foreign-key checks take, so
/// concurrent inserts referencing the target do not queue behind votes;
/// `BEGIN IMMEDIATE` on `SQLite`) for the whole read-decide-write-recompute
/// window, so concurrent reactions on one target converge to at most one edge
/// per `(reactor, target)` and the persisted aggregate is exact even across
/// *different* reactors.
///
/// It is **not idempotent** — it is a toggle. Retrying a call that timed out can
/// invert the outcome, because the first attempt may have committed; callers
/// that need retry safety dedupe above this layer (an idempotency key on the
/// HTTP request). `reaction_of()` is a plain read: it follows the repository's
/// read route (so a replica may serve it) and does not pin read-your-writes, so
/// render from the `Reaction` that `react()` returned rather than re-reading.
///
/// When the model has a `deleted_at` field, reacting to a soft-deleted target
/// is `NotFound` and leaves its aggregate untouched.
///
/// Tenant-isolated on the same terms: when the model has a `tenant_id` field
/// **and** the repository is `#[repository(..., tenant_scoped)]`, both the
/// target lock and the aggregate `UPDATE` carry `tenant_id = <current
/// tenant>`, so another tenant's `target_id` is `NotFound` before any write and
/// `reaction_of()` reports `None` for it. No tenant context is an error (as for
/// any derived query) and `across_tenants()` opts out. A model without the
/// column emits none of this. The m2m `add_*` / `remove_*` helpers are not
/// covered — they remain id-scoped.
///
/// `react()` acquires its **own** pooled connection and does not join an
/// enclosing `Db::tx` — do not hold a `Db` extractor across the call on a small
/// connection pool.
/// Derive a field-accurate `OpenApiSchema` impl for a plain struct with named
/// fields (issue #1972).
///
/// Use it on a handler-arg struct — a `Query<T>` param struct or a
/// non-`#[model]` `Json<T>` request body — so its `OpenAPI` component schema and
/// MCP tool `inputSchema` describe the real fields instead of degrading to a
/// generic `{"type":"object"}` placeholder, without a hand-written impl or an
/// `OpenApiConfig::register_schema` call.
///
/// Each field becomes a JSON-schema property (nullable `Option<T>`, `Vec<T>`
/// arrays, inline primitives, `$ref`s for other named types) and every
/// non-`Option` field is `required` — mirroring the schema `#[model]` already
/// generates. The derive also registers the schema in the compile-time
/// inventory the spec/MCP back-fill consults, so the referencing route resolves
/// it automatically.
///
/// # Examples
///
/// ```ignore
/// use autumn_web::openapi::OpenApiSchema;
///
/// #[derive(serde::Deserialize, OpenApiSchema)]
/// struct SearchParams {
/// q: String,
/// limit: Option<i32>,
/// }
/// ```
/// Derive a repository with CRUD operations and derived queries.
///
/// Generates a `PgXxxRepository` struct implementing the annotated trait,
/// with auto-generated CRUD methods and query-by-name derived methods.
///
/// # Read replica routing
///
/// When `database.replica_url` is configured, generated read-only methods
/// (`find_by_id`, `find_all`, `count`, `paginate`, `cursor_page`, derived
/// `find_by_*`, search reads) acquire their connection from the replica
/// pool; mutating methods always use the primary. Add `primary_reads` to
/// pin a read-after-write-sensitive repository's reads to the primary, or
/// call the generated `on_primary()` method to pin a single call chain
/// (read-your-writes).
///
/// # Examples
///
/// ```ignore
/// use autumn_web::repository;
///
/// #[repository(Post)]
/// trait PostRepository {
/// fn find_by_published(published: bool) -> Vec<Post>;
/// }
///
/// // Reads pinned to the primary even when a replica is configured.
/// #[repository(LedgerEntry, primary_reads)]
/// trait LedgerEntryRepository {}
/// ```
/// Declare a scheduled background task.
///
/// # Examples
///
/// ```ignore
/// #[scheduled(every = "5m", name = "cleanup")]
/// async fn cleanup(state: AppState) -> AutumnResult<()> { Ok(()) }
///
/// #[scheduled(cron = "0 0 0 * * *", name = "nightly")]
/// async fn nightly(state: AppState) -> AutumnResult<()> { Ok(()) }
/// ```
/// Declare an on-demand background job.
///
/// Route latency-sensitive work to a named queue with `queue = "..."`. Workers
/// drain queues in the priority order configured under `[jobs] queues` in
/// `autumn.toml`, so a flood of low-priority jobs can't delay a critical one.
/// Jobs with no `queue` land on the `"default"` queue.
///
/// ```ignore
/// #[job(queue = "critical", max_attempts = 5)]
/// async fn send_password_reset(state: AppState, args: ResetArgs) -> AutumnResult<()> {
/// Ok(())
/// }
///
/// // autumn.toml — strict priority (or weighted: { critical = 4, default = 1 }):
/// // [jobs]
/// // queues = ["critical", "default", "low"]
/// SendPasswordResetJob::enqueue(ResetArgs { user_id: 1 }).await?;
/// ```
///
/// Accept an optional third `JobContext` argument to report progress and
/// record a terminal result/error for jobs enqueued with `enqueue_tracked`
/// (the companion struct gains `enqueue_tracked` / `enqueue_tracked_for`
/// alongside `enqueue`):
///
/// ```ignore
/// #[job(name = "export_orders")]
/// async fn export_orders(state: AppState, args: ExportArgs, ctx: JobContext) -> AutumnResult<()> {
/// ctx.set_progress(50, Some("Rows 1200/5000")).await?;
/// ctx.set_result(serde_json::json!({ "download_url": "/blob/abc.csv" }));
/// Ok(())
/// }
///
/// let handle = ExportOrdersJob::enqueue_tracked(ExportArgs { account_id: 1 }).await?;
/// println!("poll at {}", handle.status_path());
/// ```
/// Declare a typed domain event.
///
/// Applies the serde + `Clone`/`Debug` derives the event bus needs and
/// implements `autumn_web::events::Event` with a stable `NAME` (the struct
/// name by default, or `#[event(name = "...")]`).
///
/// ```ignore
/// #[event]
/// struct UserSignedUp { user_id: i64 }
/// ```
/// Declare an event listener that reacts to a typed `#[event]`.
///
/// Runs **synchronously** (in-request) by default, or **durably** (enqueued on
/// the `#[job]` queue, surviving restarts with retry + DLQ) with `durable`.
///
/// ```ignore
/// #[listener(UserSignedUp, durable, max_attempts = 5)]
/// async fn send_welcome_email(state: AppState, event: UserSignedUp) -> AutumnResult<()> { Ok(()) }
/// ```
/// Collect `#[listener]` handlers into a `Vec<ListenerInfo>`.
/// Declare a one-off operational task runnable with `autumn task <name>`.
/// Annotate an async function as a statically pre-rendered GET route.
///
/// Like `#[get]`, this generates a route companion function. Additionally,
/// it generates a `__autumn_static_meta_{name}()` companion that registers
/// the route for static HTML generation at build time.
///
/// Phase 1: path parameters are **not** supported. Use `#[get]` for
/// parameterized routes.
///
/// # Example
///
/// ```ignore
/// use autumn_web::static_get;
///
/// #[static_get("/about")]
/// async fn about() -> &'static str {
/// "About us"
/// }
/// ```
///
/// # Route-level SEO defaults
///
/// Accepts the same `seo(...)` argument as [`macro@get`], so pre-rendered
/// pages carry the declared meta tags. Static generation drives the same
/// router as the live server, so the values reach the handler identically in
/// both modes:
///
/// ```ignore
/// #[static_get("/about", seo(title = "About • My Blog", og_type = "website"))]
/// async fn about(seo: SeoMeta) -> Markup {
/// html! { head { (seo.render()) } }
/// }
/// ```
/// Collect `#[scheduled]` task handlers into a `Vec<TaskInfo>`.
///
/// ```ignore
/// let all_tasks = tasks![cleanup, nightly];
/// ```
/// Collect `#[job]` handlers into a `Vec<JobInfo>`.
/// Collect `#[task]` handlers into a `Vec<OneOffTaskInfo>`.
/// Secure a route handler with authentication and optional role checks.
///
/// Applied before a route macro (`#[get]`, `#[post]`, etc.), this macro
/// injects an authentication guard at the top of the handler. The guard
/// checks the session for the configured auth key (default: `"user_id"`)
/// and, when roles are specified, verifies the user's role matches.
///
/// Returns `401 Unauthorized` if not authenticated, or `403 Forbidden`
/// if the user lacks the required role.
///
/// # Forms
///
/// - `#[secured]` -- require authentication only
/// - `#[secured("admin")]` -- require a specific role
/// - `#[secured("admin", "editor")]` -- require any of the listed roles
///
/// # Example
///
/// ```ignore
/// use autumn_web::prelude::*;
///
/// #[get("/admin")]
/// #[secured("admin")]
/// async fn admin_panel() -> AutumnResult<&'static str> {
/// Ok("welcome, admin")
/// }
/// ```
/// Declare a route handler as deliberately public (unauthenticated).
///
/// `#[public]` injects no runtime guard — it is a compile-time *marker* that
/// records intent. The route macros surface it as `ApiDoc::public`, which the
/// build-time security classifier (`autumn routes audit`) uses to distinguish
/// a route that is *meant* to be open from one whose auth posture was simply
/// never declared. Applying it makes an otherwise-unclassified route pass the
/// audit gate, exactly like adding a [`#[secured]`](macro@secured) guard does.
///
/// # Example
///
/// ```ignore
/// use autumn_web::prelude::*;
///
/// #[get("/health")]
/// #[public]
/// async fn health() -> &'static str { "ok" }
/// ```
/// Declare a read-path route as eligible to run in the edge capsule (#1790).
///
/// `#[edge]` injects no runtime guard and does not rewrite the handler
/// signature — it is a compile-time *marker*, like
/// [`#[public]`](macro@public). The route macro reads it back and emits an
/// extra `__autumn_edge_route_{name}()` companion returning an
/// `autumn_edge::EdgeRoute`, while gating the native (`autumn_web`) companions
/// behind `#[cfg(not(target_arch = "wasm32"))]` so the same handler source
/// compiles for both the origin binary and the `wasm32-wasip1` capsule.
/// Marking a handler makes it *eligible*; listing it in
/// [`edge_routes!`](macro@edge_routes) is what puts it in the capsule.
///
/// # Forms
///
/// - `#[edge]` — the handler needs no platform seam
/// - `#[edge(needs(kv))]` — the handler reads the edge key-value cache
/// (`autumn_edge::EdgeCache`), which the host must provide; a request
/// arriving at an edge without that capability falls through to the origin
///
/// # Restrictions
///
/// The edge lane is read-path only and carries no session, auth, or database
/// state, so these are compile errors:
///
/// - a method other than `#[get]`;
/// - combining with `#[secured]`, `#[authorize]`, `#[step_up]`, or
/// `#[throttle]` (in either attribute order);
/// - `#[static_get]` (already pre-rendered), `#[ws]`, or `#[oauth2_callback]`.
///
/// # Example
///
/// ```ignore
/// use autumn_edge::prelude::{EdgeCache, Path};
/// use autumn_web::{edge, get};
///
/// #[get("/greet/{name}")]
/// #[edge]
/// async fn greet(Path(name): Path<String>) -> String {
/// format!("Hello, {name}!")
/// }
///
/// #[get("/note/{id}")]
/// #[edge(needs(kv))]
/// async fn note(Path(id): Path<String>, cache: EdgeCache) -> String {
/// cache.get_string(&id).unwrap_or_else(|| "not cached".to_owned())
/// }
/// ```
/// Collect `#[edge]` handlers into a `Vec<EdgeRoute>` (#1790).
///
/// The edge-lane counterpart of [`routes!`](macro@routes): each entry resolves
/// to the handler's `__autumn_edge_route_{name}()` companion, so a handler that
/// was never marked `#[edge]` fails to resolve rather than silently vanishing
/// from the capsule.
///
/// ```ignore
/// use autumn_web::{edge, edge_routes, get};
///
/// #[get("/greet")]
/// #[edge]
/// async fn greet() -> &'static str { "hi" }
///
/// pub fn edge_routes() -> Vec<autumn_edge::EdgeRoute> {
/// edge_routes![greet]
/// }
/// ```
/// Require fresh ("step-up") authentication before a route handler runs.
///
/// The handler is guarded by a freshness check on the session's
/// `last_strong_auth_at` claim. When the claim is missing or older than
/// `max_age` the request is handled as follows:
///
/// - **Browser clients** (no `application/json` in `Accept`): redirect to
/// `/reauth?return_to=<current-path>`.
/// - **API / JSON clients** (`Accept: application/json`): `401 Unauthorized`
/// with an RFC 7807 problem-details body (`type` =
/// `"https://autumn.rs/probs/step-up-required"`) and a
/// `WWW-Authenticate: StepUp max-age=N` hint header.
///
/// # Forms
///
/// - `#[step_up]` — default max-age (5 minutes, or the global `[auth.step_up]`
/// config override)
/// - `#[step_up(max_age = "5m")]` — custom per-route max-age
///
/// # Example
///
/// ```ignore
/// use autumn_web::prelude::*;
///
/// // Requires re-authentication within the last 5 minutes.
/// #[delete("/account")]
/// #[step_up]
/// async fn destroy_account() -> AutumnResult<Redirect> {
/// // ... delete account ...
/// Ok(Redirect::to("/bye"))
/// }
///
/// // Custom max-age.
/// #[post("/auth/mfa/remove")]
/// #[step_up(max_age = "2m")]
/// async fn remove_mfa() -> AutumnResult<&'static str> {
/// Ok("MFA removed")
/// }
/// ```
/// Apply a per-route rate limit to a handler.
///
/// The handler is guarded by an additional rate limiter that composes with
/// (and, for the annotated route, is stricter than) the global limiter
/// configured under `[security.rate_limit]`. Requests denied by either
/// limiter respond with `429 Too Many Requests` including a `Retry-After`
/// header and the standard `x-ratelimit-*` headers.
///
/// # Forms
///
/// - `#[throttle(limit = 5, per = "1m")]` — inline limit; keying strategy
/// matches the global limiter.
/// - `#[throttle(limit = 5, per = "1m", key = "ip" | "principal" | "token")]`
/// — inline limit with an explicit key strategy override.
/// - `#[throttle("login")]` — reference a named limiter defined in
/// `[security.rate_limit.named.login]`.
///
/// # Example
///
/// ```ignore
/// use autumn_web::prelude::*;
///
/// #[post("/login")]
/// #[throttle(limit = 5, per = "1m", key = "ip")]
/// async fn login() -> AutumnResult<&'static str> {
/// Ok("welcome back")
/// }
/// ```
///
/// # Limitations
///
/// Like the sibling `#[secured]` / `#[step_up]` guards it mirrors, the throttle
/// check runs inside the handler after `FromRequestParts` extractors, but body
/// extractors (`Json` / `Form` / `Multipart`) are parsed by Axum *before* the
/// throttle check, so an over-limit client can still incur request-body parsing
/// before receiving its `429`. For hard pre-body protection, combine with the
/// global limiter layer under `[security.rate_limit]`.
///
/// # Attribute ordering
///
/// Place the route method attribute (`#[get]` / `#[post]` / …) *above*
/// `#[throttle]`, i.e. method attribute outermost:
///
/// ```ignore
/// #[post("/login")] // method attribute outermost
/// #[throttle(limit = 5, per = "1m", key = "ip")]
/// async fn login() -> Json<Session> { /* … */ }
/// ```
///
/// Both orders enforce throttling correctly (including idempotency-replay
/// accounting). However, only the method-attribute-outermost order lets the
/// route macro see the handler's real return type for `OpenAPI` response-schema
/// generation. When `#[throttle]` expands first it rewrites the return type to
/// `Response` (like the sibling `#[secured]` / `#[step_up]` / `#[authorize]`
/// guards), so a `Json<T>` response schema would be lost from the generated
/// `OpenAPI` document.
/// Gate a route handler on a named feature flag.
///
/// If the flag is disabled for the current actor, the handler responds with
/// `404 Not Found` by default. Provide a `fallback` function to return a
/// custom response instead.
///
/// The flag key is resolved against the `FeatureFlagService` stored in the
/// `AppState` extensions. Unknown flags are treated as **disabled**
/// (fail-closed).
///
/// # Forms
///
/// - `#[feature_flag("key")]` — return 404 when disabled
/// - `#[feature_flag("key", fallback = my_fn)]` — call `my_fn()` when disabled
///
/// # Example
///
/// ```ignore
/// use autumn_web::prelude::*;
///
/// #[get("/beta")]
/// #[feature_flag("beta_dashboard")]
/// async fn beta_dashboard() -> Markup {
/// html! { h1 { "Beta Dashboard" } }
/// }
/// ```
///
/// Enforce a record-level authorization policy on a route handler.
///
/// Resolves the `Policy`
/// registered for the named resource type and calls the matching
/// action method. Short-circuits with the configured deny response
/// (default `404`, optionally `403`) before the handler body runs.
///
/// Coexists with `#[secured]`: `#[secured]` answers "are you in?",
/// `#[authorize]` answers "are you allowed to act on *this record*?"
///
/// # Forms
///
/// ```ignore
/// // Resource arg is auto-detected by snake-cased type name (Post -> `post`).
/// #[authorize("update", resource = Post)]
/// async fn update_post(post: Post) -> AutumnResult<...> { ... }
///
/// // Explicit binding name (overrides the snake-case default).
/// #[authorize("delete", resource = Post, from = target)]
/// async fn destroy(target: Post) -> AutumnResult<...> { ... }
/// ```
/// Collect `#[static_get]` handlers into a `Vec<StaticRouteMeta>`.
///
/// ```ignore
/// use autumn_web::prelude::*;
///
/// #[static_get("/about")]
/// async fn about() -> &'static str { "About" }
///
/// let metas = static_routes![about];
/// ```
/// Define a service for cross-model orchestration and non-DB side effects.
///
/// Generates a `XxxServiceImpl` struct with dependency injection via
/// `FromRequestParts`, so it can be used as a handler parameter just
/// like repositories.
///
/// Use `#[service]` when your logic orchestrates **multiple repositories**
/// or involves **non-DB side effects** (email, API calls, etc.).
/// For single-model CRUD and validation, use `#[repository]` instead.
///
/// # Examples
///
/// ```ignore
/// use autumn_web::service;
///
/// #[service]
/// pub trait OrderService {
/// fn deps(order_repo: PgOrderRepository, inventory_repo: PgInventoryRepository);
///
/// async fn place_order(&self, req: PlaceOrderRequest) -> AutumnResult<Order>;
/// }
///
/// // You implement the business logic:
/// impl OrderServiceImpl {
/// pub async fn place_order(&self, req: PlaceOrderRequest) -> AutumnResult<Order> {
/// let order = self.order_repo.save(&req.into()).await?;
/// self.inventory_repo.reserve(order.id).await?;
/// Ok(order)
/// }
/// }
///
/// // Then use it in handlers, just like a repository:
/// #[get("/orders/{id}")]
/// async fn get_order(svc: OrderServiceImpl) -> AutumnResult<Json<Order>> {
/// // ...
/// }
/// ```
/// Cache the return value of a function based on its arguments.
///
/// Wraps a function with an in-memory cache backed by a per-function
/// static `Cache` (from `autumn_web::cache::Cache`). Arguments
/// must implement `Hash + Eq + Clone`; the return type must be `Clone`.
///
/// # Attributes
///
/// | Attribute | Example | Description |
/// |-----------|---------|-------------|
/// | `ttl` | `"5m"` | Time-to-live per entry (uses `parse_duration` syntax) |
/// | `max` | `1000` | Max entries; oldest evicted on overflow |
/// | `result` | (flag) | Only cache `Ok` values; pass `Err` through uncached |
///
/// # Examples
///
/// ```ignore
/// use autumn_web::cached;
///
/// // Cache with 5-minute TTL, max 100 entries, only cache Ok values
/// #[cached(ttl = "5m", max = 100, result)]
/// async fn get_user(id: i64) -> AutumnResult<User> {
/// db.find(id).await
/// }
///
/// // Cache forever with no size limit
/// #[cached]
/// async fn get_config() -> Vec<String> {
/// load_config_from_disk()
/// }
/// ```
/// Enrich a route handler's auto-generated `OpenAPI` documentation.
///
/// Applied on top of a route macro (`#[get]`, `#[post]`, etc.), this
/// attribute lets you override or add documentation fields that cannot
/// be inferred from the handler signature (summaries, descriptions,
/// tags, custom success status codes).
///
/// The route macro consumes this attribute and folds the metadata into
/// the route's `ApiDoc`. When no route macro is applied, the attribute
/// is a no-op.
///
/// # Supported keys
///
/// | Key | Type | Effect |
/// |-----|------|--------|
/// | `summary` | string | Short one-line description |
/// | `description` | string | Longer multi-line description |
/// | `tag` | string | Single `OpenAPI` tag for grouping |
/// | `tags` | `[string, ...]` | Multiple `OpenAPI` tags |
/// | `operation_id` | string | Override the default operation id |
/// | `status` | integer | Success HTTP status code (defaults to `200`) |
/// | `hidden` | flag / bool | Exclude the route from the generated spec |
/// | `mcp` | flag / bool | Expose this endpoint as an MCP tool (`mcp = false` force-excludes it). Requires the `mcp` feature and a `mount_mcp` call. |
///
/// # Examples
///
/// ```ignore
/// use autumn_web::prelude::*;
///
/// #[get("/users/{id}")]
/// #[api_doc(summary = "Fetch a user by id", tag = "users")]
/// async fn get_user(Path(id): Path<i32>) -> String {
/// format!("User {id}")
/// }
///
/// #[post("/users")]
/// #[api_doc(description = "Create a new user", status = 201)]
/// async fn create_user(Json(req): Json<serde_json::Value>) -> Json<serde_json::Value> {
/// Json(req)
/// }
///
/// #[get("/internal/metrics")]
/// #[api_doc(hidden)]
/// async fn metrics() -> &'static str { "" }
/// ```
const ROUTE_ATTR_NAMES: & = &;
/// Return `true` when an attribute names one of the Autumn route macros.
///
/// We match on the **last** path segment so qualified forms like
/// `#[autumn_web::get("/x")]`, `#[autumn_macros::post("/x")]`, or
/// even `#[crate::get("/x")]` are recognized alongside the bare
/// `#[get("/x")]`. Unqualified identifiers are covered by the same
/// logic because their path has a single segment.
/// Annotate an async function as a WebSocket route handler.
///
/// The function follows the **two-function pattern**: it runs at HTTP
/// upgrade time (with access to Axum extractors) and returns a closure
/// implementing `WsHandler` (from `autumn_web::ws::WsHandler`) that handles the live WebSocket connection.
///
/// The macro generates a GET route that performs the WebSocket upgrade,
/// so it integrates seamlessly with `routes![]`.
///
/// # Examples
///
/// ```ignore
/// use autumn_web::prelude::*;
/// use autumn_web::ws::{WebSocket, Message, WsHandler};
///
/// // Minimal echo handler
/// #[ws("/echo")]
/// async fn echo() -> impl WsHandler {
/// |mut socket: WebSocket| async move {
/// while let Some(Ok(msg)) = socket.recv().await {
/// if let Message::Text(text) = msg {
/// socket.send(Message::Text(text)).await.ok();
/// }
/// }
/// }
/// }
///
/// // With extractors (runs before upgrade)
/// #[ws("/chat")]
/// async fn chat(state: AppState) -> impl WsHandler {
/// let channels = state.channels().clone();
/// |mut socket: WebSocket| async move {
/// // use channels + socket
/// }
/// }
/// ```
/// Translate an i18n key, with **compile-time validation** that the key
/// exists in the default locale's `.ftl` file.
///
/// Re-exported as `autumn_web::t!` (and `autumn_web::prelude::t!`) when the
/// `i18n` feature is enabled on `autumn-web`.
///
/// # Forms
///
/// ```ignore
/// // Without args:
/// t!(locale, "welcome.title")
/// // With named args (Project Fluent's `{ $name }` placeable syntax):
/// t!(locale, "welcome.greeting", name = "Ada")
/// ```
///
/// # Compile-time behaviour
///
/// At expansion time the macro reads `$CARGO_MANIFEST_DIR/i18n/<default>.ftl`
/// (where `<default>` is the value of the `AUTUMN_I18N_DEFAULT_LOCALE`
/// environment variable, defaulting to `"en"`). If the key is not present,
/// the macro emits a `compile_error!` pointing at the literal so the build
/// fails with a clear diagnostic — including a "did you mean" suggestion
/// for typos within Levenshtein distance 3.
///
/// If the file does not exist (e.g. an app that just enabled the feature
/// flag and has not yet authored translations), the macro degrades to a
/// pure runtime call so the build still succeeds. The runtime path will
/// produce the visible `{$key}` marker on miss.
/// Turn a plain state enum into a statically-verified lifecycle.
///
/// Given a declared `initial` state, one or more `terminal` states, and a set
/// of `transitions`, `#[lifecycle]` preserves the original enum and appends:
///
/// 1. Metadata consts (`LIFECYCLE_INITIAL`, `LIFECYCLE_TERMINALS`,
/// `LIFECYCLE_STATES`, `LIFECYCLE_TRANSITIONS`) and a `can_transition_to`
/// runtime check on the enum. Because these reference the enum's own
/// variants, a declared state that is not a real variant is a compile error.
/// 2. A typestate transition module named after the enum in `snake_case`, whose
/// `Machine<S>` exposes a consuming `to_<target>` method *only* for declared
/// edges — firing an undeclared transition does not compile.
///
/// # Example
///
/// ```ignore
/// use autumn_web::lifecycle;
///
/// #[lifecycle(
/// initial = Draft,
/// terminal(Archived),
/// transitions(
/// Draft -> Published,
/// Published -> Archived,
/// Published -> Draft,
/// )
/// )]
/// #[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// pub enum ArticleState { Draft, Published, Archived }
///
/// let m = article_state::Machine::<article_state::Draft>::start();
/// let m = m.to_published(); // only declared edges exist as methods
/// assert_eq!(m.current(), ArticleState::Published);
/// assert!(ArticleState::Draft.can_transition_to(&ArticleState::Published));
/// ```