ruststream-macros 0.6.2

Procedural macros for the RustStream messaging 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
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
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
//! Expansion of the `#[subscriber]` forms: the handler signature is dissected into
//! [`HandlerParts`], then one of the definition impls (plain, publishing, injected, batch,
//! batch publishing) is generated around the original function body; the input axis (typed vs
//! raw bytes) is a flag on the plain, injected, and publishing expansions, not a form.

use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::{Error, FnArg, Ident, ItemFn, LitStr, Pat, PatType, ReturnType, Type, TypePath};

use crate::parse::{
    FailurePolicyArg, SubscriberArgs, WorkersArg, doc_description, position_type,
    publish_result_reply, source_tokens, vec_element,
};

pub(crate) fn subscriber(args: &SubscriberArgs, func: &ItemFn) -> syn::Result<TokenStream> {
    reject_raw_combinations(args)?;
    let parts = handler_parts(args, func)?;
    let body = if args.raw.is_some() {
        // The remaining combinations are already rejected above; publish_raw(..) selects the
        // byte reply form, otherwise raw is the plain form (injected when the signature
        // carries Out / Seek parameters - the input axis makes raw compose with them).
        match &args.publish_raw {
            Some(reply_topic) => expand_publishing(&parts, func, reply_topic, true, true)?,
            None if !parts.outs.is_empty() || parts.seek.is_some() => expand_injected(&parts, true),
            None => expand_subscribing(&parts, true),
        }
    } else if let Some(reply_topic) = &args.publish_raw {
        expand_publishing(&parts, func, reply_topic, true, false)?
    } else {
        match (&args.batch, &args.publish) {
            (true, Some(reply_topic)) => expand_batch_publishing(&parts, func, reply_topic)?,
            (true, None) if !parts.outs.is_empty() || parts.seek.is_some() => {
                expand_batch_injected(&parts, func)
            }
            (true, None) => expand_batch(&parts, func),
            (false, Some(reply_topic)) => {
                expand_publishing(&parts, func, reply_topic, false, false)?
            }
            (false, None) if !parts.outs.is_empty() || parts.seek.is_some() => {
                expand_injected(&parts, false)
            }
            (false, None) => expand_subscribing(&parts, false),
        }
    };
    Ok(body.into())
}

/// Rejects the argument combinations the byte-level forms do not take: `raw` with batches (one
/// delivery's bytes only) or the decode failure policy (there is no decode step), an encoded
/// `publish(..)` reply off raw bytes (the reply of a raw handler is bytes - `publish_raw`), both
/// reply clauses at once, and a batch with a byte reply.
fn reject_raw_combinations(args: &SubscriberArgs) -> syn::Result<()> {
    if let (Some(_), Some(publish_raw)) = (&args.publish, &args.publish_raw) {
        return Err(Error::new(
            publish_raw.span(),
            "publish(..) and publish_raw(..) are mutually exclusive: one reply, one destination",
        ));
    }
    if let Some(publish_raw) = &args.publish_raw
        && args.batch
    {
        return Err(Error::new_spanned(
            publish_raw,
            "publish_raw(..) is not supported together with batch(..) yet; publish per message \
             or use the encoded batch reply form",
        ));
    }
    let Some(raw) = &args.raw else {
        return Ok(());
    };
    if args.publish.is_some() {
        return Err(Error::new(
            raw.span(),
            "the reply of a raw handler is bytes and is never encoded; use \
             publish_raw(\"dest\") instead of publish(..)",
        ));
    }
    if args.batch {
        return Err(Error::new(
            raw.span(),
            "raw is not supported together with batch(..); a raw handler takes one delivery's \
             payload as `&[u8]`",
        ));
    }
    if let Some(failure) = &args.on_failure
        && failure.decode.is_some()
    {
        return Err(Error::new(
            raw.span(),
            "on_failure(decode = ..) does not apply to raw: the payload is not decoded; keep \
             only on_failure(panic = ..)",
        ));
    }
    Ok(())
}

/// The pieces of the handler shared by every expansion form, extracted from the signature.
struct HandlerParts<'a> {
    vis: &'a syn::Visibility,
    name: &'a Ident,
    block: &'a syn::Block,
    pat: &'a Pat,
    input_ty: &'a Type,
    description: TokenStream2,
    source_ty: TokenStream2,
    source_expr: TokenStream2,
    input_schema: TokenStream2,
    message_meta: TokenStream2,
    ctx_param: TokenStream2,
    ctx_ty: TokenStream2,
    state_ty: Option<TokenStream2>,
    extractors: Vec<(&'a Pat, &'a Type)>,
    outs: Vec<OutParam<'a>>,
    seek: Option<(&'a Pat, &'a Type)>,
    workers_method: TokenStream2,
    failure_method: TokenStream2,
}

/// The per-delivery context type the handler named in its `ctx: &mut Context<'_, C>` parameter,
/// projected from the first `Ctx<K>` extractor's key when there is no ctx parameter, or `()`
/// when neither names one. Threaded into the single-subscriber `SubscriberDef::Context` so a
/// macro handler can read broker fields by key or take them as parameters.
fn context_type(func: &ItemFn) -> TokenStream2 {
    let Some(FnArg::Typed(PatType { ty, .. })) = func.sig.inputs.get(1) else {
        return quote!(());
    };
    // The second parameter is the context only when it is `&mut Context<..>`; otherwise it is an
    // extractor, so the handler named no context type explicitly.
    if !is_context_param(ty) {
        return inferred_context_type(func);
    }
    // Dig the second generic argument (after the lifetime) out of `&mut Context<'_, C>`.
    if let Type::Reference(reference) = &**ty
        && let Type::Path(path) = &*reference.elem
        && let Some(segment) = path.path.segments.last()
        && let syn::PathArguments::AngleBracketed(args) = &segment.arguments
    {
        for arg in &args.args {
            if let syn::GenericArgument::Type(context_ty) = arg {
                return quote!(#context_ty);
            }
        }
    }
    quote!(())
}

/// The context type projected from the first `Ctx<K>` extractor parameter's key, for handlers
/// without a `&mut Context` parameter. Emitted as `<K as ContextField>::Context`, so the
/// compiler resolves the type; further `Ctx` keys are checked against it by the extractor
/// bounds. Purely syntactic (the last path segment `Ctx` with exactly one type argument): a
/// type alias hides the shape and falls back to `()`.
fn inferred_context_type(func: &ItemFn) -> TokenStream2 {
    for arg in func.sig.inputs.iter().skip(1) {
        if let FnArg::Typed(PatType { ty, .. }) = arg
            && let Some(key) = ctx_extractor_key(ty)
        {
            return quote!(<#key as ::ruststream::ContextField>::Context);
        }
    }
    quote!(())
}

/// One `Out<impl Bounds[, Marker]>` handler parameter: the binding pattern, the capability
/// bounds the publisher generic carries, and the slot marker type (the implicit `DefaultSlot`
/// when the parameter names none).
struct OutParam<'a> {
    pat: &'a Pat,
    bounds: &'a syn::punctuated::Punctuated<syn::TypeParamBound, syn::Token![+]>,
    marker: TokenStream2,
}

/// The type arguments of an `Out<..>`-shaped parameter type, when the type has that shape.
/// Purely syntactic (the last path segment `Out` with one or two type arguments), like the
/// `Ctx<K>` probe below.
fn out_param_args(ty: &Type) -> Option<Vec<&Type>> {
    let Type::Path(path) = ty else {
        return None;
    };
    let segment = path.path.segments.last()?;
    if segment.ident != "Out" {
        return None;
    }
    let syn::PathArguments::AngleBracketed(args) = &segment.arguments else {
        return None;
    };
    let types: Vec<&Type> = args
        .args
        .iter()
        .filter_map(|arg| match arg {
            syn::GenericArgument::Type(ty) => Some(ty),
            _ => None,
        })
        .collect();
    if types.is_empty() || types.len() > 2 {
        return None;
    }
    Some(types)
}

/// The seeker type `K` of a `Seek<K>`-shaped parameter type, when the type has that shape.
/// Purely syntactic (the last path segment `Seek` with exactly one type argument), like the
/// `Out<P>` probe above.
fn seek_param_type(ty: &Type) -> Option<&Type> {
    let Type::Path(path) = ty else {
        return None;
    };
    let segment = path.path.segments.last()?;
    if segment.ident != "Seek" {
        return None;
    }
    let syn::PathArguments::AngleBracketed(args) = &segment.arguments else {
        return None;
    };
    let mut types = args.args.iter().filter_map(|arg| match arg {
        syn::GenericArgument::Type(ty) => Some(ty),
        _ => None,
    });
    let seeker = types.next()?;
    if types.next().is_some() {
        return None;
    }
    Some(seeker)
}

/// The key type `K` of a `Ctx<K>`-shaped parameter type, when the type has that shape.
fn ctx_extractor_key(ty: &Type) -> Option<&Type> {
    let Type::Path(path) = ty else {
        return None;
    };
    let segment = path.path.segments.last()?;
    if segment.ident != "Ctx" {
        return None;
    }
    let syn::PathArguments::AngleBracketed(args) = &segment.arguments else {
        return None;
    };
    let mut types = args.args.iter().filter_map(|arg| match arg {
        syn::GenericArgument::Type(ty) => Some(ty),
        _ => None,
    });
    let key = types.next()?;
    if types.next().is_some() {
        return None;
    }
    Some(key)
}

/// The application-state type the handler named as the third generic of its
/// `ctx: &mut Context<'_, C, St>` parameter, or `None` when it named none (only `Context` or
/// `Context<'_, C>`). When present, the handler is bound to that state type; when absent, the
/// generated [`Handler`] impl is generic over the state, so the handler mounts on an app with any
/// state.
fn state_type(func: &ItemFn) -> Option<TokenStream2> {
    let FnArg::Typed(PatType { ty, .. }) = func.sig.inputs.get(1)? else {
        return None;
    };
    // Only a `&mut Context<..>` second parameter names a state; a second extractor parameter does
    // not.
    if !is_context_param(ty) {
        return None;
    }
    // Collect the type arguments of `&mut Context<'_, C, St>` (skipping the lifetime); the second is
    // the state type.
    if let Type::Reference(reference) = &**ty
        && let Type::Path(path) = &*reference.elem
        && let Some(segment) = path.path.segments.last()
        && let syn::PathArguments::AngleBracketed(args) = &segment.arguments
    {
        let mut types = args.args.iter().filter_map(|arg| match arg {
            syn::GenericArgument::Type(ty) => Some(ty),
            _ => None,
        });
        let _context_ty = types.next();
        if let Some(state_ty) = types.next() {
            return Some(quote!(#state_ty));
        }
    }
    None
}

/// True when a handler parameter is the optional per-delivery `&mut Context<..>` (matched by the
/// path's last segment being `Context`), as opposed to an extractor parameter.
fn is_context_param(ty: &Type) -> bool {
    if let Type::Reference(reference) = ty
        && reference.mutability.is_some()
        && let Type::Path(path) = &*reference.elem
        && let Some(segment) = path.path.segments.last()
    {
        return segment.ident == "Context";
    }
    false
}

/// The handler's extractor parameters: every parameter after the message that is not the optional
/// `&mut Context`. Each is resolved through [`FromContext`] before the body runs. `ctx_present`
/// reports whether the second parameter is the context (and so is skipped here).
fn collect_extractors(func: &ItemFn, ctx_present: bool) -> syn::Result<Vec<(&Pat, &Type)>> {
    let start = if ctx_present { 2 } else { 1 };
    let mut extractors = Vec::new();
    for arg in func.sig.inputs.iter().skip(start) {
        let FnArg::Typed(PatType { pat, ty, .. }) = arg else {
            return Err(Error::new_spanned(
                arg,
                "a #[subscriber] handler cannot take `self`",
            ));
        };
        if is_context_param(ty) {
            return Err(Error::new_spanned(
                ty,
                "the `&mut Context` parameter must come immediately after the message, before any \
                 extractor parameters",
            ));
        }
        extractors.push((&**pat, &**ty));
    }
    Ok(extractors)
}

/// The predicates binding each extractor type to [`FromContext`] for the handler's context `C`
/// and state `S`. Added to the generated call impl so a state-specific extractor compiles
/// without forcing the handler to name a `&mut Context`.
fn extractor_preds(
    extractors: &[(&Pat, &Type)],
    ctx_ty: &TokenStream2,
    state: &TokenStream2,
) -> Vec<TokenStream2> {
    extractors
        .iter()
        .map(|(_, ty)| quote!(#ty: ::ruststream::runtime::FromContext<#ctx_ty, #state>))
        .collect()
}

/// Renders a predicate list as a `where` clause, or nothing when the list is empty.
fn where_clause(preds: &[TokenStream2]) -> TokenStream2 {
    if preds.is_empty() {
        return quote!();
    }
    quote!(where #(#preds),*)
}

/// [`extractor_preds`] rendered as a full `where` clause, for the expansions without slot
/// bounds of their own.
fn extractor_where(
    extractors: &[(&Pat, &Type)],
    ctx_ty: &TokenStream2,
    state: &TokenStream2,
) -> TokenStream2 {
    where_clause(&extractor_preds(extractors, ctx_ty, state))
}

/// The `let` bindings that resolve each extractor from the context before the body runs. A failed
/// extraction runs `reject` (a `return` settling the delivery by the rejection's `HandlerResult`).
fn extractor_prelude(
    extractors: &[(&Pat, &Type)],
    ctx_param: &TokenStream2,
    ctx_ty: &TokenStream2,
    state: &TokenStream2,
    reject: &TokenStream2,
) -> TokenStream2 {
    let binds = extractors.iter().map(|(pat, ty)| {
        quote! {
            let #pat = match <#ty as ::ruststream::runtime::FromContext<#ctx_ty, #state>>::from_context(
                &mut *#ctx_param,
            )
            .await
            {
                ::core::result::Result::Ok(__rs_value) => __rs_value,
                ::core::result::Result::Err(__rs_err) => { #reject; }
            };
        }
    });
    quote!(#(#binds)*)
}

/// Renders the `on_failure(..)` clause as an override of the def's defaulted `failure_policies`
/// method, or nothing when the clause is absent. Only the keys named in the clause are set; the
/// rest keep the runtime defaults.
fn failure_method(args: &SubscriberArgs) -> TokenStream2 {
    let Some(failure) = &args.on_failure else {
        return quote!();
    };
    let panic = failure
        .panic
        .as_ref()
        .map(failure_policy_tokens)
        .map(|policy| quote!(.with_panic(#policy)));
    let decode = failure
        .decode
        .as_ref()
        .map(failure_policy_tokens)
        .map(|policy| quote!(.with_decode(#policy)));
    quote! {
        fn failure_policies(&self) -> ::ruststream::runtime::FailurePolicies {
            ::ruststream::runtime::FailurePolicies::default() #panic #decode
        }
    }
}

/// Renders one [`FailurePolicyArg`] as the matching `FailurePolicy` value.
fn failure_policy_tokens(policy: &FailurePolicyArg) -> TokenStream2 {
    match policy {
        FailurePolicyArg::FailFast => quote!(::ruststream::runtime::FailurePolicy::FailFast),
        FailurePolicyArg::Drop => quote!(::ruststream::runtime::FailurePolicy::Drop),
        FailurePolicyArg::Retry => quote!(::ruststream::runtime::FailurePolicy::Retry),
        FailurePolicyArg::RetryAfter(expr) => {
            quote!(::ruststream::runtime::FailurePolicy::RetryAfter(#expr))
        }
        FailurePolicyArg::Skip => quote!(::ruststream::runtime::FailurePolicy::Skip),
    }
}

/// Renders the `workers(..)` clause as an override of the def's defaulted `workers` method, or
/// nothing when the clause is absent.
fn workers_method(args: &SubscriberArgs) -> syn::Result<TokenStream2> {
    let Some(WorkersArg { count, by_key }) = &args.workers else {
        return Ok(quote!());
    };
    if count.base10_parse::<usize>()? == 0 {
        return Err(Error::new(
            count.span(),
            "workers(0) is not a policy; the minimum is 1",
        ));
    }
    if let Some(marker) = by_key {
        if args.batch {
            return Err(Error::new(
                marker.span(),
                "by_key lanes order single messages per key; they do not apply to batch(..) \
                 forms",
            ));
        }
        return Ok(quote! {
            fn workers(&self) -> ::ruststream::runtime::Workers {
                // The macro rejects workers(0) at expansion, so the None arm is unreachable;
                // MIN keeps the lowering panic-free.
                ::ruststream::runtime::Workers::keyed(
                    match ::core::num::NonZeroUsize::new(#count) {
                        ::core::option::Option::Some(count) => count,
                        ::core::option::Option::None => ::core::num::NonZeroUsize::MIN,
                    },
                )
            }
        });
    }
    Ok(quote! {
        fn workers(&self) -> ::ruststream::runtime::Workers {
            // The macro rejects workers(0) at expansion, so the None arm is unreachable;
            // MIN keeps the lowering panic-free.
            ::ruststream::runtime::Workers::pool(
                match ::core::num::NonZeroUsize::new(#count) {
                    ::core::option::Option::Some(count) => count,
                    ::core::option::Option::None => ::core::num::NonZeroUsize::MIN,
                },
            )
        }
    })
}

/// Splits the `Out<..>` parameters out of the extractor list, in signature order.
///
/// Each must carry its capability as `impl Trait` (the concrete publisher type is inferred at
/// the include site) and a distinct marker; a single parameter may omit the marker and binds
/// the implicit `DefaultSlot`.
fn split_outs<'a>(extractors: &mut Vec<(&'a Pat, &'a Type)>) -> syn::Result<Vec<OutParam<'a>>> {
    let mut outs = Vec::new();
    let mut kept = Vec::new();
    for (pat, ty) in extractors.drain(..) {
        let Some(args) = out_param_args(ty) else {
            kept.push((pat, ty));
            continue;
        };
        let Type::ImplTrait(capability) = args[0] else {
            return Err(Error::new_spanned(
                args[0],
                "an Out parameter names the capability it needs, not a publisher type: write \
                 `Out<impl Publisher>` (or a capability like `impl OwnedTransactions`); the \
                 concrete publisher is inferred from the policy attached at the include site",
            ));
        };
        let marker = args.get(1).map_or_else(
            || quote!(::ruststream::runtime::DefaultSlot),
            |marker| quote!(#marker),
        );
        outs.push(OutParam {
            pat,
            bounds: &capability.bounds,
            marker,
        });
    }
    *extractors = kept;
    if outs.len() > 3 {
        return Err(Error::new_spanned(
            outs[3].pat,
            "a #[subscriber] handler takes at most three Out parameters",
        ));
    }
    for (index, out) in outs.iter().enumerate() {
        let name = out.marker.to_string();
        if outs
            .iter()
            .skip(index + 1)
            .any(|other| other.marker.to_string() == name)
        {
            return Err(Error::new_spanned(
                out.pat,
                "every Out parameter needs its own slot marker: two parameters bind the same \
                 slot (name each with `Out<impl Publisher, MyMarker>` and derive the markers \
                 with #[derive(OutSlot)])",
            ));
        }
    }
    Ok(outs)
}

/// Splits the (at most one) `Seek<K>` parameter out of the extractor list, rejecting a
/// duplicate.
fn split_seek<'a>(
    extractors: &mut Vec<(&'a Pat, &'a Type)>,
) -> syn::Result<Option<(&'a Pat, &'a Type)>> {
    let mut seek = None;
    extractors.retain(|(pat, ty)| {
        if let Some(seeker_ty) = seek_param_type(ty) {
            // Only the first Seek parameter is kept; a duplicate is rejected below.
            if seek.is_none() {
                seek = Some((*pat, seeker_ty));
                return false;
            }
        }
        true
    });
    if let Some((_, dup)) = extractors
        .iter()
        .find(|(_, ty)| seek_param_type(ty).is_some())
    {
        return Err(Error::new_spanned(
            dup,
            "a #[subscriber] handler takes at most one Seek parameter",
        ));
    }
    Ok(seek)
}

/// Resolves the message parameter's referent into the def's input type per form: batch unwraps
/// the `&[T]` slice to its element, raw accepts only `&[u8]` (its type is never emitted), and the
/// plain form takes `&T`. Each misuse gets an error naming the fix.
fn input_type<'a>(
    args: &SubscriberArgs,
    reference: &'a syn::TypeReference,
) -> syn::Result<&'a Type> {
    if args.batch {
        return match &*reference.elem {
            Type::Slice(slice) => Ok(&slice.elem),
            other => Err(Error::new_spanned(
                other,
                "a batch handler takes the whole batch as a slice: `&[T]`",
            )),
        };
    }
    if args.raw.is_some() {
        return match &*reference.elem {
            elem if is_u8_slice(elem) => Ok(elem),
            other => Err(Error::new_spanned(
                other,
                "a raw subscriber receives the payload bytes: make the message parameter \
                 `&[u8]`, or drop `raw` to decode into a typed value",
            )),
        };
    }
    if matches!(&*reference.elem, Type::Slice(_)) {
        return Err(Error::new_spanned(
            &reference.elem,
            "a slice parameter needs the batch source form: #[subscriber(batch(..))]; for the \
             undecoded payload bytes use #[subscriber(.., raw)]",
        ));
    }
    Ok(&reference.elem)
}

/// True when `ty` is syntactically `[u8]`, the only message parameter shape the raw form takes.
fn is_u8_slice(ty: &Type) -> bool {
    if let Type::Slice(slice) = ty
        && let Type::Path(TypePath {
            qself: None, path, ..
        }) = &*slice.elem
    {
        return path.is_ident("u8");
    }
    false
}

fn handler_parts<'a>(args: &SubscriberArgs, func: &'a ItemFn) -> syn::Result<HandlerParts<'a>> {
    let first = func.sig.inputs.first().ok_or_else(|| {
        Error::new_spanned(
            &func.sig,
            "a #[subscriber] handler must take exactly one message parameter",
        )
    })?;
    let FnArg::Typed(PatType { pat, ty, .. }) = first else {
        return Err(Error::new_spanned(
            first,
            "a #[subscriber] handler cannot take `self`",
        ));
    };
    let Type::Reference(reference) = &**ty else {
        return Err(Error::new_spanned(
            ty,
            "the message parameter must be a reference `&T`",
        ));
    };
    let input_ty = input_type(args, reference)?;
    let description = doc_description(&func.attrs);
    let (source_ty, source_expr) = source_tokens(&args.source)?;
    // `start_at(<position>)` wraps the source in the core `StartAt` decorator, so the
    // subscription is sought to the position before the first delivery. Orthogonal to the
    // definition form: every form carries a `Source`.
    let (source_ty, source_expr) = match &args.start_at {
        Some(position) => {
            let position_ty = position_type(position)?;
            (
                quote!(::ruststream::StartAt<#source_ty, #position_ty>),
                quote!(::ruststream::StartAt::new(#source_expr, #position)),
            )
        }
        None => (source_ty, source_expr),
    };

    // Captures the input type's JSON Schema for AsyncAPI when it implements `JsonSchema` (and the
    // `asyncapi` feature is on), via the autoref-specialization probe; `None` otherwise. The
    // concrete input type makes the trait selection resolve at the call site.
    let input_schema = quote! {
        fn input_schema(&self) -> ::core::option::Option<::std::string::String> {
            #[allow(unused_imports)]
            use ::ruststream::__private::NoSchemaProbe as _;
            ::ruststream::__private::Probe::<#input_ty>::new().schema_json()
        }
    };

    // Captures the input type's `Message` name / description when it implements that trait, via
    // the same autoref-specialization probe; `None` otherwise.
    let message_meta = quote! {
        fn message_name(&self) -> ::core::option::Option<&'static str> {
            #[allow(unused_imports)]
            use ::ruststream::__private::NoMessageProbe as _;
            ::ruststream::__private::Probe::<#input_ty>::new().message_name()
        }

        fn message_description(&self) -> ::core::option::Option<&'static str> {
            #[allow(unused_imports)]
            use ::ruststream::__private::NoMessageProbe as _;
            ::ruststream::__private::Probe::<#input_ty>::new().message_description()
        }
    };

    // Optional second handler parameter: the per-delivery `&mut Context`. If the user declares it,
    // bind it to their name; otherwise generate an ignored binding. Any later by-value parameter is
    // an extractor, resolved through `FromContext` before the body.
    let ctx_arg = func
        .sig
        .inputs
        .get(1)
        .filter(|arg| matches!(arg, FnArg::Typed(pt) if is_context_param(&pt.ty)));
    let ctx_param = if let Some(FnArg::Typed(PatType { pat, .. })) = ctx_arg {
        quote!(#pat)
    } else {
        quote!(_ctx)
    };
    let mut extractors = collect_extractors(func, ctx_arg.is_some())?;
    let outs = split_outs(&mut extractors)?;
    let seek = split_seek(&mut extractors)?;
    let ctx_ty = context_type(func);
    let state_ty = state_type(func);

    let workers_method = workers_method(args)?;
    let failure_method = failure_method(args);

    Ok(HandlerParts {
        vis: &func.vis,
        name: &func.sig.ident,
        block: &func.block,
        pat,
        input_ty,
        description,
        source_ty,
        source_expr,
        input_schema,
        message_meta,
        ctx_param,
        ctx_ty,
        state_ty,
        extractors,
        outs,
        seek,
        workers_method,
        failure_method,
    })
}

/// Splits a batch publishing handler's declared return type into the reply element type and the
/// body that yields `Result<Vec<Reply>, HandlerResult>`. `-> Result<Vec<Reply>, HandlerResult>` is
/// passed through; a plain `-> Vec<Reply>` is wrapped in `Ok`. Both checks are syntactic, like the
/// single-message publish form: a type alias is not seen through.
fn batch_reply_body<'a>(
    func: &'a ItemFn,
    block: &syn::Block,
) -> syn::Result<(&'a Type, TokenStream2)> {
    let declared_ty = match &func.sig.output {
        ReturnType::Type(_, ty) => &**ty,
        ReturnType::Default => {
            return Err(Error::new_spanned(
                &func.sig,
                "a batch publishing handler must return the replies: Vec<Reply>, or \
                 Result<Vec<Reply>, HandlerResult>",
            ));
        }
    };
    if let Some(ok_ty) = publish_result_reply(declared_ty) {
        let Some(elem) = vec_element(ok_ty) else {
            return Err(Error::new_spanned(
                ok_ty,
                "a batch publishing handler replies with a Vec: Result<Vec<Reply>, HandlerResult>",
            ));
        };
        Ok((elem, quote!((async move #block).await)))
    } else {
        let Some(elem) = vec_element(declared_ty) else {
            return Err(Error::new_spanned(
                declared_ty,
                "a batch publishing handler returns the replies: Vec<Reply>, or \
                 Result<Vec<Reply>, HandlerResult>",
            ));
        };
        Ok((
            elem,
            quote!(::core::result::Result::Ok((async move #block).await)),
        ))
    }
}

fn expand_batch_publishing(
    parts: &HandlerParts<'_>,
    func: &ItemFn,
    reply_topic: &LitStr,
) -> syn::Result<TokenStream2> {
    let HandlerParts {
        vis,
        name,
        block,
        pat,
        input_ty,
        description,
        source_ty,
        source_expr,
        input_schema,
        message_meta,
        ctx_param,
        ctx_ty: _,
        state_ty,
        extractors,
        outs,
        seek,
        workers_method,
        failure_method,
    } = parts;

    let (reply_elem, call_body) = batch_reply_body(func, block)?;
    // The injection tuple is shared with the other forms; an Out parameter selects the
    // two-attachment builder (`.out(marker, ..)` next to `.publisher(..)`).
    let form = if outs.is_empty() {
        quote!(::ruststream::runtime::forms::BatchPublishing)
    } else {
        quote!(::ruststream::runtime::forms::BatchPublishingOut)
    };
    let SlotScaffold {
        def_target,
        def_generics,
        generics: out_generics,
        scaffold: scaffold_items,
        out_bounds,
    } = slot_scaffold(vis, name, outs, seek.is_some());
    let (injection_tys, injection_bindings) = injection_pieces(outs, &out_generics, *seek);

    // Like the single-message publishing form: the handler implements `BatchPublishingCall` only
    // for its named state (mounts on a matching app), or generically when it names none (mounts on
    // any app). The metadata-only `BatchPublishingDef` is unconditional.
    let (state_generic, state_in_ctx) = state_pieces(state_ty.as_ref());
    // The batch context is always `()`; extractors resolve against it.
    let unit_ctx = quote!(());
    let def_where = where_clause(&out_bounds);
    let mut call_preds = extractor_preds(extractors, &unit_ctx, &state_in_ctx);
    call_preds.extend(out_bounds.iter().cloned());
    let call_where = where_clause(&call_preds);
    let prelude = extractor_prelude(
        extractors,
        ctx_param,
        &unit_ctx,
        &state_in_ctx,
        &quote!(
            return ::core::result::Result::Err(::core::convert::Into::<
                ::ruststream::runtime::HandlerResult,
            >::into(__rs_err),)
        ),
    );
    Ok(quote! {
        #[allow(non_camel_case_types)]
        #vis struct #name;

        impl ::ruststream::runtime::IncludeDef for #name {
            type Form = #form;
        }

        #scaffold_items

        impl<#def_generics> ::ruststream::runtime::BatchPublishingDef for #def_target
        #def_where
        {
            type Input = ::ruststream::runtime::Decoded<#input_ty>;
            type Injections = (#(#injection_tys,)*);
            type Reply = #reply_elem;
            type Source = #source_ty;

            fn source(&self) -> Self::Source { #source_expr }
            fn reply_name(&self) -> &str { #reply_topic }

            #workers_method

            #failure_method

            fn description(&self) -> ::core::option::Option<&str> {
                #description
            }

            #input_schema

            #message_meta
        }

        impl<#state_generic #def_generics>
            ::ruststream::runtime::BatchPublishingCall<#state_in_ctx> for #def_target
            #call_where
        {
            async fn call(
                &self,
                #pat: &[#input_ty],
                __rs_inj: &Self::Injections,
                #ctx_param: &mut ::ruststream::runtime::Context<'_, (), #state_in_ctx>,
            ) -> ::core::result::Result<
                ::std::vec::Vec<#reply_elem>,
                ::ruststream::runtime::HandlerResult,
            > {
                #prelude
                #injection_bindings
                #call_body
            }
        }
    })
}

fn expand_batch(parts: &HandlerParts<'_>, func: &ItemFn) -> TokenStream2 {
    let HandlerParts {
        vis,
        name,
        block,
        pat,
        input_ty,
        description,
        source_ty,
        source_expr,
        input_schema,
        message_meta,
        ctx_param,
        ctx_ty: _,
        state_ty,
        extractors,
        outs: _,
        seek: _,
        workers_method,
        failure_method,
    } = parts;

    // Pin the body's type to the declared return type before the `IntoBatchResult` conversion:
    // the trait has several impls, so an open-ended tail like `.collect()` cannot infer through
    // the conversion alone.
    let outcome_ty = match &func.sig.output {
        ReturnType::Type(_, ty) => quote!(#ty),
        ReturnType::Default => quote!(()),
    };

    // As for `expand_subscribing`: a batch handler that names a state type is bound to it, one that
    // names none is generic over the state, so it mounts on an app with any state type.
    let (impl_generics, state_in_ctx) = match &state_ty {
        Some(state_ty) => (quote!(), quote!(#state_ty)),
        None => (
            quote!(<__RsState: ::core::marker::Send + ::core::marker::Sync>),
            quote!(__RsState),
        ),
    };
    // The batch context is always `()`; extractors resolve against it.
    let unit_ctx = quote!(());
    let where_clause = extractor_where(extractors, &unit_ctx, &state_in_ctx);
    let prelude = extractor_prelude(
        extractors,
        ctx_param,
        &unit_ctx,
        &state_in_ctx,
        &quote!(
            return ::ruststream::runtime::IntoBatchResult::into_batch_result(
                ::core::convert::Into::<::ruststream::runtime::HandlerResult>::into(__rs_err),
            )
        ),
    );

    quote! {
            #[derive(Clone, Copy)]
            #[allow(non_camel_case_types)]
            #vis struct #name;

            impl #impl_generics
                ::ruststream::runtime::SliceHandler<#input_ty, #state_in_ctx> for #name
                #where_clause
            {
                async fn handle_slice(
                    &self,
                    #pat: &[#input_ty],
                    #ctx_param: &mut ::ruststream::runtime::Context<'_, (), #state_in_ctx>,
                ) -> ::ruststream::runtime::BatchResult {
                    #prelude
                    let outcome: #outcome_ty = (async move #block).await;
                    ::ruststream::runtime::IntoBatchResult::into_batch_result(outcome)
                }
            }

            impl ::ruststream::runtime::IncludeDef for #name {
                type Form = ::ruststream::runtime::forms::Batch;
            }

            impl ::ruststream::runtime::BatchDef for #name {
                type Input = ::ruststream::runtime::Decoded<#input_ty>;
                type Handler = Self;
                type Source = #source_ty;

                fn source(&self) -> Self::Source { #source_expr }

                #workers_method

            #failure_method

                fn description(&self) -> ::core::option::Option<&str> {
                    #description
                }

                #input_schema

                #message_meta

                fn into_handler(self) -> Self { self }
            }
    }
}

/// The injected batch form: `batch(..)` with Out / Seek parameters. Mirrors `expand_injected`
/// at the batch shape (slice input, `IntoBatchResult` conversion, unit context).
fn expand_batch_injected(parts: &HandlerParts<'_>, func: &ItemFn) -> TokenStream2 {
    let HandlerParts {
        vis,
        name,
        block,
        pat,
        input_ty,
        description,
        source_ty,
        source_expr,
        input_schema,
        message_meta,
        ctx_param,
        ctx_ty: _,
        state_ty,
        extractors,
        outs,
        seek,
        workers_method,
        failure_method,
    } = parts;

    // The injection tuple is shared with the single-message form; only the form token differs
    // (the batch mount arms drive batches, not a per-message stream).
    let form = if outs.is_empty() {
        quote!(::ruststream::runtime::forms::BatchSeek)
    } else {
        quote!(::ruststream::runtime::forms::BatchOut)
    };
    let SlotScaffold {
        def_target,
        def_generics,
        generics: out_generics,
        scaffold: scaffold_items,
        out_bounds,
    } = slot_scaffold(vis, name, outs, seek.is_some());
    let (injection_tys, injection_bindings) = injection_pieces(outs, &out_generics, *seek);

    // As for `expand_batch`: pin the body's type before the `IntoBatchResult` conversion.
    let outcome_ty = match &func.sig.output {
        ReturnType::Type(_, ty) => quote!(#ty),
        ReturnType::Default => quote!(()),
    };
    let (state_generic, state_in_ctx) = state_pieces(state_ty.as_ref());
    // The batch context is always `()`; extractors resolve against it.
    let unit_ctx = quote!(());
    let def_where = where_clause(&out_bounds);
    let mut call_preds = extractor_preds(extractors, &unit_ctx, &state_in_ctx);
    call_preds.extend(out_bounds.iter().cloned());
    let call_where = where_clause(&call_preds);
    let prelude = extractor_prelude(
        extractors,
        ctx_param,
        &unit_ctx,
        &state_in_ctx,
        &quote!(
            return ::ruststream::runtime::IntoBatchResult::into_batch_result(
                ::core::convert::Into::<::ruststream::runtime::HandlerResult>::into(__rs_err),
            )
        ),
    );

    quote! {
        #[derive(Clone, Copy)]
        #[allow(non_camel_case_types)]
        #vis struct #name;

        impl ::ruststream::runtime::IncludeDef for #name {
            type Form = #form;
        }

        #scaffold_items

        impl<#def_generics> ::ruststream::runtime::BatchInjectDef for #def_target
        #def_where
        {
            type Input = ::ruststream::runtime::Decoded<#input_ty>;
            type Source = #source_ty;
            type Injections = (#(#injection_tys,)*);

            fn source(&self) -> Self::Source { #source_expr }

            #workers_method

            #failure_method

            fn description(&self) -> ::core::option::Option<&str> {
                #description
            }

            #input_schema

            #message_meta
        }

        impl<#state_generic #def_generics>
            ::ruststream::runtime::BatchInjectCall<#state_in_ctx> for #def_target
            #call_where
        {
            async fn call(
                &self,
                #pat: &[#input_ty],
                __rs_inj: &Self::Injections,
                #ctx_param: &mut ::ruststream::runtime::Context<'_, (), #state_in_ctx>,
            ) -> ::ruststream::runtime::BatchResult {
                #prelude
                #injection_bindings
                let outcome: #outcome_ty = (async move #block).await;
                ::ruststream::runtime::IntoBatchResult::into_batch_result(outcome)
            }
        }
    }
}

/// The reply-publishing form. `bare` marks the `publish_raw` (byte reply) variant - the same
/// definition and machinery, with the form token selecting the bare-policy default commit
/// instead of the typed-codec one - and `raw_input` selects the byte input kind (the handler
/// borrows the payload as `&[u8]`).
fn expand_publishing(
    parts: &HandlerParts<'_>,
    func: &ItemFn,
    reply_topic: &LitStr,
    bare: bool,
    raw_input: bool,
) -> syn::Result<TokenStream2> {
    let HandlerParts {
        vis,
        name,
        block,
        pat,
        input_ty,
        description,
        source_ty,
        source_expr,
        input_schema,
        message_meta,
        ctx_param,
        ctx_ty,
        state_ty,
        extractors,
        outs,
        seek,
        workers_method,
        failure_method,
    } = parts;

    let (reply_ty, call_body) = publishing_reply(func, block, bare)?;
    // The injection tuple is shared with the plain forms; the form token additionally selects
    // the Out-taking builder (which grows the `.out(..)` attachments next to `.publisher(..)`).
    let form = match (bare, !outs.is_empty()) {
        (false, false) => quote!(::ruststream::runtime::forms::Publishing),
        (false, true) => quote!(::ruststream::runtime::forms::PublishingOut),
        (true, false) => quote!(::ruststream::runtime::forms::RawReply),
        (true, true) => quote!(::ruststream::runtime::forms::RawReplyOut),
    };
    let SlotScaffold {
        def_target,
        def_generics,
        generics: out_generics,
        scaffold: scaffold_items,
        out_bounds,
    } = slot_scaffold(vis, name, outs, seek.is_some());
    let (injection_tys, injection_bindings) = injection_pieces(outs, &out_generics, *seek);
    let (input_kind, input_param, input_schema, message_meta) =
        input_pieces(input_ty, input_schema, message_meta, raw_input);

    // As for `expand_subscribing`: a publishing handler that names a state type implements
    // `PublishingCall` only for that state (mounts on a matching app); one that names none is
    // generic over the state (mounts on any app). The metadata-only `PublishingDef` is unconditional.
    let (state_generic, state_in_ctx) = state_pieces(state_ty.as_ref());
    let def_where = where_clause(&out_bounds);
    let mut call_preds = extractor_preds(extractors, ctx_ty, &state_in_ctx);
    call_preds.extend(out_bounds.iter().cloned());
    let call_where = where_clause(&call_preds);
    let prelude = extractor_prelude(
        extractors,
        ctx_param,
        ctx_ty,
        &state_in_ctx,
        &quote!(
            return ::core::result::Result::Err(::core::convert::Into::<
                ::ruststream::runtime::HandlerResult,
            >::into(__rs_err),)
        ),
    );
    Ok(quote! {
        #[allow(non_camel_case_types)]
        #vis struct #name;

        impl ::ruststream::runtime::IncludeDef for #name {
            type Form = #form;
        }

        #scaffold_items

        impl<#def_generics> ::ruststream::runtime::PublishingDef for #def_target
        #def_where
        {
            type Input = #input_kind;
            type Injections = (#(#injection_tys,)*);
            type Reply = #reply_ty;
            type Context = #ctx_ty;
            type Source = #source_ty;

            fn source(&self) -> Self::Source { #source_expr }
            fn reply_name(&self) -> &str { #reply_topic }

            #workers_method

            #failure_method

            fn description(&self) -> ::core::option::Option<&str> {
                #description
            }

            #input_schema

            #message_meta
        }

        impl<#state_generic #def_generics>
            ::ruststream::runtime::PublishingCall<#state_in_ctx> for #def_target
            #call_where
        {
            async fn call(
                &self,
                #pat: #input_param,
                __rs_inj: &Self::Injections,
                #ctx_param: &mut ::ruststream::runtime::Context<'_, #ctx_ty, #state_in_ctx>,
            ) -> ::core::result::Result<#reply_ty, ::ruststream::runtime::HandlerResult> {
                #prelude
                #injection_bindings
                #call_body
            }
        }
    })
}

/// Resolves a publishing handler's reply type and call body from its return type.
/// `-> Result<Reply, HandlerResult>` lets the handler skip the publish: `Err(result)` is
/// returned to the dispatcher as-is. A plain `-> Reply` is wrapped in `Ok` here. The check
/// is syntactic, so a type alias hiding the `Result` is treated as a plain reply type.
fn publishing_reply<'a>(
    func: &'a ItemFn,
    block: &syn::Block,
    bare: bool,
) -> syn::Result<(&'a Type, TokenStream2)> {
    let declared_ty = match &func.sig.output {
        ReturnType::Type(_, ty) => &**ty,
        ReturnType::Default => {
            return Err(Error::new_spanned(
                &func.sig,
                if bare {
                    "a publish_raw handler must return the reply bytes: Vec<u8>, or \
                     Result<Vec<u8>, HandlerResult>"
                } else {
                    "a publishing handler must return the reply value"
                },
            ));
        }
    };
    Ok(match publish_result_reply(declared_ty) {
        Some(reply_ty) => (reply_ty, quote!((async move #block).await)),
        None => (
            declared_ty,
            quote!(::core::result::Result::Ok((async move #block).await)),
        ),
    })
}

/// The input-axis pieces of a definition form: the input kind, the concrete parameter type
/// the generated call binds, and the schema / message metadata. A typed parameter decodes
/// into an owned value the handler borrows; a raw one borrows the payload itself and carries
/// no schema or message metadata.
fn input_pieces(
    input_ty: &Type,
    input_schema: &TokenStream2,
    message_meta: &TokenStream2,
    raw: bool,
) -> (TokenStream2, TokenStream2, TokenStream2, TokenStream2) {
    if raw {
        (
            quote!(::ruststream::runtime::RawBytes),
            quote!(&[u8]),
            quote!(),
            quote!(),
        )
    } else {
        (
            quote!(::ruststream::runtime::Decoded<#input_ty>),
            quote!(&#input_ty),
            input_schema.clone(),
            message_meta.clone(),
        )
    }
}

/// Everything the slot-carrying expansions share: where the definition traits land, the impls
/// tying the user-visible unit struct to the hidden publisher-generic definition, and the
/// pieces the def / call impls interpolate.
struct SlotScaffold {
    /// The definition impls' target: the unit struct itself (no Out parameters) or the hidden
    /// generic struct applied to its publisher generics.
    def_target: TokenStream2,
    /// The publisher generic parameters of the definition impls (empty without Out parameters).
    def_generics: TokenStream2,
    /// One publisher generic ident per Out parameter (`__RsOut0`, ...), in signature order.
    generics: Vec<Ident>,
    /// The hidden generic struct plus the unit struct's `HasSlots` / `BindSlots` impls.
    scaffold: TokenStream2,
    /// The `__RsOutN: <bounds> + 'static` predicates for the hidden definition's impls.
    out_bounds: Vec<TokenStream2>,
}

/// Builds the [`SlotScaffold`]: without Out parameters the definition stays on the unit struct
/// and every slot piece is empty; with them, the unit struct the user passes to `include` keeps
/// marker metadata (`HasSlots`) plus the source-to-definition instantiation (`BindSlots`), and
/// the definition traits land on a hidden struct generic over the slot publishers, so the
/// concrete types are inferred from the include-site attachments.
fn slot_scaffold(
    vis: &syn::Visibility,
    name: &Ident,
    outs: &[OutParam<'_>],
    has_seek: bool,
) -> SlotScaffold {
    if outs.is_empty() {
        return SlotScaffold {
            def_target: quote!(#name),
            def_generics: quote!(),
            generics: Vec::new(),
            scaffold: quote!(),
            out_bounds: Vec::new(),
        };
    }
    let hidden_ident = Ident::new(&format!("__RsOutDef_{name}"), name.span());
    let generics: Vec<Ident> = (0..outs.len())
        .map(|index| Ident::new(&format!("__RsOut{index}"), name.span()))
        .collect();
    let markers: Vec<&TokenStream2> = outs.iter().map(|out| &out.marker).collect();
    let sources: Vec<Ident> = (0..outs.len())
        .map(|index| Ident::new(&format!("__RsSrc{index}"), name.span()))
        .collect();
    let source_values: Vec<Ident> = (0..outs.len())
        .map(|index| Ident::new(&format!("__rs_src{index}"), name.span()))
        .collect();
    let out_bounds: Vec<TokenStream2> = outs
        .iter()
        .zip(&generics)
        .map(|(out, generic)| {
            let bounds = out.bounds;
            // The dispatch machinery shares the injected value across worker tasks, so
            // Send + Sync are structural, not optional; adding them here keeps broker-defined
            // capability bounds (which need not imply them) as ergonomic as the core ones.
            quote!(#generic: #bounds + ::core::marker::Send + ::core::marker::Sync + 'static)
        })
        .collect();
    // A trailing Seek parameter resolves off the subscription itself, so its extra is a unit.
    let seek_extra = has_seek.then(|| quote!((),));
    let scaffold = quote! {
        #[doc(hidden)]
        #[allow(non_camel_case_types)]
        #vis struct #hidden_ident<#(#generics),*>(
            ::core::marker::PhantomData<fn() -> (#(#generics,)*)>,
        );

        impl ::ruststream::runtime::HasSlots for #name {
            type Markers = (#(#markers,)*);
        }

        impl<__RsC, #(#sources),*> ::ruststream::runtime::BindSlots<__RsC, (#(#sources,)*)>
            for #name
        where
            __RsC: ::ruststream::ConnectedBroker,
            #(#sources: ::ruststream::PublishPolicy<__RsC>,)*
        {
            type Bound = #hidden_ident<
                #(::ruststream::runtime::SlotPublisher<
                    <#sources as ::ruststream::PublishPolicy<__RsC>>::Live,
                    #markers,
                >,)*
            >;
            type Extra = (#(#sources,)* #seek_extra);

            fn bind(self, sources: (#(#sources,)*)) -> (Self::Bound, Self::Extra) {
                let (#(#source_values,)*) = sources;
                (
                    #hidden_ident(::core::marker::PhantomData),
                    (#(#source_values,)* #seek_extra),
                )
            }
        }
    };
    SlotScaffold {
        def_target: quote!(#hidden_ident<#(#generics),*>),
        def_generics: quote!(#(#generics),*),
        generics,
        scaffold,
        out_bounds,
    }
}

/// Collects the canonical injection tuple (Out parameters in signature order, then Seek), and
/// the `let` bindings resolving each user pattern from the resolved tuple. An `Out(x)` /
/// `Seek(x)`-shaped pattern binds the injected value itself; any other pattern binds a
/// reference to the whole marker struct. `out_generics` supplies the publisher generic per Out
/// parameter (empty when the handler has none).
fn injection_pieces(
    outs: &[OutParam<'_>],
    out_generics: &[Ident],
    seek: Option<(&Pat, &Type)>,
) -> (Vec<TokenStream2>, TokenStream2) {
    let mut injection_tys = Vec::new();
    let mut bindings = Vec::new();
    for (index, (out, generic)) in outs.iter().zip(out_generics).enumerate() {
        let marker = &out.marker;
        injection_tys.push(quote!(::ruststream::runtime::Out<#generic, #marker>));
        bindings.push(injection_binding(out.pat, index));
    }
    if let Some((seek_pat, seeker_ty)) = seek {
        injection_tys.push(quote!(::ruststream::runtime::Seek<#seeker_ty>));
        bindings.push(injection_binding(seek_pat, outs.len()));
    }
    (injection_tys, quote!(#(#bindings)*))
}

/// One injected parameter's binding: a single-element tuple-struct pattern (`Out(x)`,
/// `Seek(x)`) binds the wrapped value by reference, through the user's own path (so their
/// import stays used) with a rest pattern absorbing the marker field; any other pattern binds
/// the whole element.
fn injection_binding(pat: &Pat, index: usize) -> TokenStream2 {
    let index = syn::Index::from(index);
    if let Pat::TupleStruct(tuple) = pat
        && tuple.elems.len() == 1
    {
        let path = &tuple.path;
        let inner = &tuple.elems[0];
        return quote!(let #path(#inner, ..) = &__rs_inj.#index;);
    }
    quote!(let #pat = &__rs_inj.#index;)
}

/// The state generic of a call impl and the state type used in its `Context`: a handler that
/// names a state type is bound to it (no generic), one that names none is generic over the
/// state, so it mounts on an app with any state type. The generic ends with a trailing comma
/// so it composes with the slot generics.
fn state_pieces(state_ty: Option<&TokenStream2>) -> (TokenStream2, TokenStream2) {
    match state_ty {
        Some(state_ty) => (quote!(), quote!(#state_ty)),
        None => (
            quote!(__RsState: ::core::marker::Send + ::core::marker::Sync,),
            quote!(__RsState),
        ),
    }
}

/// The form token of an injected definition: an Out parameter needs publisher attachments at
/// the include site, so it selects the builder form; injections resolved off the subscription
/// alone mount eagerly.
fn injected_form(has_out: bool) -> TokenStream2 {
    if has_out {
        quote!(::ruststream::runtime::forms::Out)
    } else {
        quote!(::ruststream::runtime::forms::Seek)
    }
}

/// The startup-injection form: `Out` / `Seek` parameters travel as one tuple resolved by the
/// runtime after the subscription opens, so any combination shares this single expansion.
/// `raw` selects the byte input kind (the handler borrows the payload as `&[u8]`).
///
/// A Seek-only handler keeps the definition on the unit struct itself; Out parameters move the
/// definition onto the hidden publisher-generic struct, connected through [`slot_scaffold`].
fn expand_injected(parts: &HandlerParts<'_>, raw: bool) -> TokenStream2 {
    let HandlerParts {
        vis,
        name,
        block,
        pat,
        input_ty,
        description,
        source_ty,
        source_expr,
        input_schema,
        message_meta,
        ctx_param,
        ctx_ty,
        state_ty,
        extractors,
        outs,
        seek,
        workers_method,
        failure_method,
    } = parts;

    let form = injected_form(!outs.is_empty());
    let SlotScaffold {
        def_target,
        def_generics,
        generics: out_generics,
        scaffold: scaffold_items,
        out_bounds,
    } = slot_scaffold(vis, name, outs, seek.is_some());
    let (injection_tys, injection_bindings) = injection_pieces(outs, &out_generics, *seek);
    let (input_kind, input_param, input_schema, message_meta) =
        input_pieces(input_ty, input_schema, message_meta, raw);

    let (state_generic, state_in_ctx) = state_pieces(state_ty.as_ref());
    let def_where = where_clause(&out_bounds);
    let mut call_preds = extractor_preds(extractors, ctx_ty, &state_in_ctx);
    call_preds.extend(out_bounds.iter().cloned());
    let call_where = where_clause(&call_preds);
    let prelude = extractor_prelude(
        extractors,
        ctx_param,
        ctx_ty,
        &state_in_ctx,
        &quote!(
            return ::ruststream::runtime::IntoSettle::into_settle(::core::convert::Into::<
                ::ruststream::runtime::HandlerResult,
            >::into(__rs_err),)
        ),
    );

    quote! {
        #[derive(Clone, Copy)]
        #[allow(non_camel_case_types)]
        #vis struct #name;

        impl ::ruststream::runtime::IncludeDef for #name {
            type Form = #form;
        }

        #scaffold_items

        impl<#def_generics> ::ruststream::runtime::InjectDef for #def_target
        #def_where
        {
            type Input = #input_kind;
            type Context = #ctx_ty;
            type Source = #source_ty;
            type Injections = (#(#injection_tys,)*);

            fn source(&self) -> Self::Source { #source_expr }

            #workers_method

            #failure_method

            fn description(&self) -> ::core::option::Option<&str> {
                #description
            }

            #input_schema

            #message_meta
        }

        impl<#state_generic #def_generics>
            ::ruststream::runtime::InjectCall<#state_in_ctx> for #def_target
            #call_where
        {
            async fn call(
                &self,
                #pat: #input_param,
                __rs_inj: &Self::Injections,
                #ctx_param: &mut ::ruststream::runtime::Context<'_, #ctx_ty, #state_in_ctx>,
            ) -> ::ruststream::runtime::Settle {
                #prelude
                #injection_bindings
                ::ruststream::runtime::IntoSettle::into_settle(
                    (async move #block).await,
                )
            }
        }
    }
}

fn expand_subscribing(parts: &HandlerParts<'_>, raw: bool) -> TokenStream2 {
    let HandlerParts {
        vis,
        name,
        block,
        pat,
        input_ty,
        description,
        source_ty,
        source_expr,
        input_schema,
        message_meta,
        ctx_param,
        ctx_ty,
        state_ty,
        extractors,
        outs: _,
        seek: _,
        workers_method,
        failure_method,
    } = parts;

    let (input_kind, input_param, input_schema, message_meta) =
        input_pieces(input_ty, input_schema, message_meta, raw);
    // The handler runs over the input kind's borrowed target: `Handler<T>` for a typed
    // parameter, `Handler<[u8]>` for a raw one - the mount adapter lends it the payload itself.
    let input_target = if raw { quote!([u8]) } else { quote!(#input_ty) };
    let form = if raw {
        quote!(::ruststream::runtime::forms::RawSubscribing)
    } else {
        quote!(::ruststream::runtime::forms::Subscribing)
    };

    // A handler that names a state type is bound to it; one that does not is generic over the
    // state, so it mounts on an app with any state type. Either shape satisfies the mount-site
    // `Handler<Target, Context, St>` bound, the former only for its `St`, the latter for every
    // `St`.
    let (impl_generics, state_in_ctx) = match &state_ty {
        Some(state_ty) => (quote!(), quote!(#state_ty)),
        None => (
            quote!(<__RsState: ::core::marker::Send + ::core::marker::Sync>),
            quote!(__RsState),
        ),
    };
    let where_clause = extractor_where(extractors, ctx_ty, &state_in_ctx);
    let prelude = extractor_prelude(
        extractors,
        ctx_param,
        ctx_ty,
        &state_in_ctx,
        &quote!(
            return ::ruststream::runtime::IntoSettle::into_settle(::core::convert::Into::<
                ::ruststream::runtime::HandlerResult,
            >::into(__rs_err),)
        ),
    );

    quote! {
            #[derive(Clone, Copy)]
            #[allow(non_camel_case_types)]
            #vis struct #name;

            impl #impl_generics
                ::ruststream::runtime::Handler<#input_target, #ctx_ty, #state_in_ctx> for #name
                #where_clause
            {
                async fn handle(
                    &self,
                    #pat: #input_param,
                    #ctx_param: &mut ::ruststream::runtime::Context<'_, #ctx_ty, #state_in_ctx>,
                ) -> ::ruststream::runtime::Settle {
                    #prelude
                    ::ruststream::runtime::IntoSettle::into_settle(
                        (async move #block).await,
                    )
                }
            }

            impl ::ruststream::runtime::IncludeDef for #name {
                type Form = #form;
            }

            impl ::ruststream::runtime::SubscriberDef for #name {
                type Input = #input_kind;
                type Context = #ctx_ty;
                type Handler = Self;
                type Source = #source_ty;

                fn source(&self) -> Self::Source { #source_expr }

                #workers_method

            #failure_method

                fn description(&self) -> ::core::option::Option<&str> {
                    #description
                }

                #input_schema

                #message_meta

                fn into_handler(self) -> Self { self }
            }
    }
}