wireframe 0.4.0-alpha1

Simplify building servers and clients for custom binary protocols.
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
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
# Wireframe users' guide

This guide is for Rust developers building servers and clients for binary
protocols with Wireframe v0.4.0-alpha1. It starts from an empty project and
builds up to custom wire formats, production operation, and testing. You do not
need to know Tokio deeply to begin, though you will meet `async` code from the
first example.

Every Rust example here is compiled, and most are run, by the project's test
suite, so what you copy is what was tested. If something does not behave as
described, please [open an issue](https://github.com/leynos/wireframe/issues).

## Find your path

Table 1 suggests where to begin. The sections are ordered to be read from top
to bottom, and each builds on the last, but you can also dip in.

| You want to…                           | Start with                                                                                      |
| -------------------------------------- | ----------------------------------------------------------------------------------------------- |
| See it work in two minutes             | [Your first server]#your-first-server                                                         |
| Understand how the pieces fit          | [How Wireframe thinks]#how-wireframe-thinks                                                   |
| Serve typed messages on several routes | [Routes and envelopes]#routes-and-envelopes, then [Middleware]#middleware                   |
| Speak a protocol that already exists   | [Custom frame codecs]#custom-frame-codecs, then [Connection preambles]#connection-preambles |
| Call a server from Rust                | [The client runtime]#the-client-runtime                                                       |
| Send messages larger than a frame      | [Large messages]#large-messages                                                               |
| Test without opening sockets           | [Testing your protocol]#testing-your-protocol                                                 |
| Go to production                       | [Running servers]#running-servers, then [Observability]#observability                       |
| Receive a request body in chunks       | [Streaming request body consumption]#streaming-request-body-consumption                       |
| Stream replies or push to clients      | [Streaming responses and server pushes]#streaming-responses-and-server-pushes                 |
| Fix something that is going wrong      | [Troubleshooting]#troubleshooting                                                             |
| Upgrade from v0.3.0                    | The [migration guide]v0-4-0-migration-guide.md                                                |

_Table 1: Where to begin, by goal._

## Before you begin

Wireframe needs Rust 1.95 or newer, and runs on Tokio. Both crates declare that
minimum to Cargo, so an older toolchain refuses to build them, and every change
to this repository is checked against it. Add Wireframe to `Cargo.toml`,
pinning the exact version during the alpha because one alpha may change what
the last one offered:

<!-- tested-example: guide-dependencies -->
```toml
[dependencies]
wireframe = "=0.4.0-alpha1"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
bincode = "2"
async-trait = "0.1"
```

`bincode` lets you derive encodable messages, and `async-trait` is what you
will write middleware with. Table 2 lists the optional Cargo features.

| Feature              | Default | Adds                                            |
| -------------------- | ------- | ----------------------------------------------- |
| `metrics`            | Yes     | Emits counters through the `metrics` facade.    |
| `serializer-bincode` | Yes     | The default `BincodeSerializer`.                |
| `serializer-serde`   | No      | The optional Serde bridge.                      |
| `pool`               | No      | Client connection pools through `connect_pool`. |
| `testkit`            | No      | Test drivers in `wireframe::testkit`.           |

_Table 2: Cargo features for applications._

The remaining features (`test-support`, `examples`, `advanced-tests`, and
`benchmark-counters`) exist for this repository's own tests and benchmarks.

## Your first server

This complete program starts a server on a free local port, sends it a message
from a client, and prints the reply:

<!-- tested-example: guide-first-server -->
```rust
use std::{convert::Infallible, error::Error, sync::Arc};

use async_trait::async_trait;
use wireframe::{
    app::{Envelope, Handler, WireframeApp},
    client::WireframeClient,
    message::Message,
    middleware::{HandlerService, Service, ServiceRequest, ServiceResponse, Transform},
    server::WireframeServer,
};

const GREET: u32 = 1;

#[derive(bincode::Encode, bincode::BorrowDecode)]
struct Greeting {
    name: String,
}

#[derive(bincode::Encode, bincode::BorrowDecode)]
struct Reply {
    text: String,
}

struct Greeter;

struct GreeterService<S> {
    inner: S,
}

#[async_trait]
impl<S> Service for GreeterService<S>
where
    S: Service<Error = Infallible> + Send + Sync + 'static,
{
    type Error = Infallible;

    async fn call(&self, request: ServiceRequest) -> Result<ServiceResponse, Infallible> {
        let greeting = Greeting::from_bytes(request.frame()).map(|(greeting, _)| greeting);
        let mut response = self.inner.call(request).await?;
        if let Ok(greeting) = greeting {
            let reply = Reply {
                text: format!("Hello, {}!", greeting.name),
            };
            *response.frame_mut() = reply.to_bytes().expect("a short reply encodes");
        }
        Ok(response)
    }
}

#[async_trait]
impl Transform<HandlerService<Envelope>> for Greeter {
    type Output = HandlerService<Envelope>;

    async fn transform(&self, service: HandlerService<Envelope>) -> Self::Output {
        let id = service.id();
        HandlerService::from_service(id, GreeterService { inner: service })
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let handler: Handler<Envelope> = Arc::new(|_envelope: &Envelope| Box::pin(async {}));
    let app: WireframeApp = WireframeApp::new()?.route(GREET, handler)?.wrap(Greeter)?;

    let server = WireframeServer::from_app(app).bind("127.0.0.1:0".parse()?)?;
    let address = server.local_addr().expect("a bound server has an address");
    let shutdown = server.spawn().await?;

    let mut client = WireframeClient::builder().connect(address).await?;
    let greeting = Greeting {
        name: "Wireframe".into(),
    };
    let request = Envelope::new(GREET, None, greeting.to_bytes()?);
    let response: Envelope = client.call_correlated(request).await?;
    let (reply, _) = Reply::from_bytes(response.payload_bytes())?;
    println!("{}", reply.text);

    client.close().await;
    shutdown.stop();
    shutdown.drained().await?;
    Ok(())
}
```

Save it as `src/main.rs` and `cargo run` it. You should see
`Hello, Wireframe!`. There is a fair amount going on, so here it is in order:

1. **Messages.** `Greeting` and `Reply` are ordinary structs. Deriving bincode's
   traits is enough for Wireframe to provide `to_bytes` and `from_bytes`.
2. **Route.** `route(GREET, handler)` says that message ID 1 goes to this
   handler. The ID travels beside the payload, so it is not part of either type.
3. **Handler.** A handler registered with `route` receives `&Envelope` and
   returns a boxed future of `()`. It can observe the request, but it does not
   produce the reply. Ours does nothing.
4. **Middleware.** `Greeter` wraps the route. It decodes the request, calls the
   inner service, and replaces the response bytes. This is where a `route`
   reply comes from, and it is the part most people find surprising at first.
   When one handler should build its own reply, use
   [a response-producing route]#response-producing-routes instead.
5. **Server.** Port 0 asks the operating system for any free port. `spawn` runs
   the server in the background and returns a handle for shutting it down.
6. **Client.** `call_correlated` stamps a correlation identifier on the request,
   sends it, reads the reply, and checks that the identifier came back.

Without `Greeter`, the program would still run: the default response repeats
the request's payload, so an unwrapped `route` is an echo. That makes a good
first experiment, and it is why the `echo` example in `examples/` is so short.

Next, [How Wireframe thinks](#how-wireframe-thinks) gives you the vocabulary
for everything else.

## How Wireframe thinks

Wireframe uses a separate word for what you are holding at each layer, and
these words are used consistently in the API and in this guide. Table 3 defines
them.

| Layer                 | Term     | Meaning                                                                               |
| --------------------- | -------- | ------------------------------------------------------------------------------------- |
| Transport             | Frame    | The unit on the wire, produced and consumed by a `FrameCodec`.                        |
| Routing               | Envelope | A wrapper carrying a message ID, an optional correlation ID, and payload bytes.       |
| Domain                | Message  | The typed value you encode into, and decode from, payload bytes.                      |
| Transport subdivision | Fragment | A bounded slice of a large payload, plus the metadata needed to put it back together. |

_Table 3: The four layers and their terms._

`Packet` is the trait an envelope implements, and `Envelope` is the type
bundled with Wireframe. You can bring your own.

For screen readers: the following flowchart shows an inbound frame passing
through decoding, envelope deserialization, reassembly, and routing into
middleware and the handler, and the reply passing back out through
serialization and encoding.

<!-- tested-example: guide-request-journey -->
```mermaid
flowchart LR
    Socket([Socket]) --> Decode[Codec decode]
    Decode --> Envelope[Deserialize envelope]
    Envelope --> Reassemble[Reassemble fragments]
    Reassemble --> Assemble[Assemble message]
    Assemble --> Route{Route by ID}
    Route --> Middleware[Middleware]
    Middleware --> Handler[Handler]
    Handler --> Middleware
    Middleware --> Fragment[Fragment]
    Fragment --> Serialize[Serialize]
    Serialize --> Wrap[Codec wrap]
    Wrap --> Hook[before_send]
    Hook --> Encode[Codec encode]
    Encode --> Socket
```

_Figure 1: One buffered request's journey through a Wireframe connection._

Three facts follow from this, and they explain most of the API:

- **A `route` handler observes, and middleware answers.** Its signature returns
  `()`, and its future cannot borrow the envelope, so copy out what you need
  before the `async` block. Such a request sends exactly one response, even if
  it is empty. A handler registered with `route_response` returns the reply
  itself, which may be one frame, several, a stream, or nothing.
- **The order is fixed.** Transport fragments are reassembled before message
  assembly. A buffered handler receives the whole message, and a
  [streaming handler]#streaming-request-body-consumption can run as its
  message frames arrive. On the way out, fragmentation happens before
  serialization, so each fragment is its own frame.
- **An application is immutable once it runs.** You configure a `WireframeApp`
  builder, and the server prepares it once and shares the result among all
  connections. Each connection keeps its own framing, queues, and buffers, and
  serves one request at a time.

### Where to import things from

The crate root is deliberately small: `Result`, `WireframeError`, and
`NoProtocolError`. Other items live in a module named for their domain, such as
`wireframe::app` or `wireframe::client`. For convenience,
`wireframe::prelude::*` gathers the most common ones.

## Routes and envelopes

### Registering routes

`route` maps a message ID to a handler, and returns an error if the ID is
already taken. IDs are shared across `route`,
[`route_response`](#response-producing-routes), and
[`streaming_route`](#streaming-request-body-consumption):

<!-- tested-example: guide-routes -->
```rust
use std::sync::Arc;

use wireframe::{
    WireframeError,
    app::{Envelope, Handler, Packet, WireframeApp},
};

const LOGIN: u32 = 1;
const TELEMETRY: u32 = 2;

fn handler(name: &'static str) -> Handler<Envelope> {
    Arc::new(move |envelope: &Envelope| {
        // The returned future is 'static, so copy what it needs out of the borrow.
        let id = envelope.id();
        Box::pin(async move { println!("{name} handled message {id}") })
    })
}

fn main() -> wireframe::Result<()> {
    let app: WireframeApp = WireframeApp::new()?
        .route(LOGIN, handler("login"))?
        .route(TELEMETRY, handler("telemetry"))?;

    let refused = app.route(LOGIN, handler("impostor"));
    assert!(matches!(refused, Err(WireframeError::DuplicateRoute(LOGIN))));
    Ok(())
}
```

A frame with no matching route is logged and dropped without a response. A
frame that fails to decode counts towards a failure limit: a connection closes
after ten failures with no successfully dispatched message in between.

### Custom envelopes

To give handlers your own type rather than `Envelope`, implement `Packet` (and
`CorrelatableFrame`, which it requires) on it, and name it in the application's
parameters.

This changes what handlers see, not what travels on the wire. A connection
still decodes the serializer's `Envelope`, rebuilds your type from its parts
for the handler, and sends the reply as an `Envelope`, which is also what a
response-producing route returns. To change the layout on the wire, write a
[custom frame codec](#custom-frame-codecs) as well:

<!-- tested-example: guide-custom-envelope -->
```rust
use std::sync::Arc;

use wireframe::{
    app::{Handler, Packet, PacketParts, WireframeApp},
    correlation::CorrelatableFrame,
    serializer::BincodeSerializer,
};

#[derive(bincode::Encode, bincode::BorrowDecode)]
struct Stroke {
    opcode: u16,
    tag: Option<u64>,
    payload: Vec<u8>,
}

impl CorrelatableFrame for Stroke {
    fn correlation_id(&self) -> Option<u64> { self.tag }

    fn set_correlation_id(&mut self, tag: Option<u64>) { self.tag = tag; }
}

impl Packet for Stroke {
    fn id(&self) -> u32 { u32::from(self.opcode) }

    fn into_parts(self) -> PacketParts {
        PacketParts::new(u32::from(self.opcode), self.tag, self.payload)
    }

    fn from_parts(parts: PacketParts) -> Self {
        Self {
            opcode: u16::try_from(parts.id()).unwrap_or(u16::MAX),
            tag: parts.correlation_id(),
            payload: parts.into_payload(),
        }
    }
}

type StrokeApp = WireframeApp<BincodeSerializer, (), Stroke>;

fn main() -> wireframe::Result<()> {
    let draw: Handler<Stroke> = Arc::new(|stroke: &Stroke| {
        let opcode = stroke.opcode;
        Box::pin(async move { println!("drawing opcode {opcode}") })
    });
    let _app = StrokeApp::new()?.route(107, draw)?;
    Ok(())
}
```

### Correlation identifiers

A correlation identifier ties a response to its request. `None` means the frame
is not part of an exchange, such as an unsolicited event, so prefer `None` to
`Some(0)` when there is no identifier. `PacketParts::inherit_correlation` fills
in a missing identifier from the request and logs a mismatch, which is how a
reply keeps the right identifier even if middleware forgets about it.

## Middleware

Middleware is how you read typed requests and write typed replies, and it is
also the place for concerns that span routes, such as counting or
authentication.

### Writing a `Transform`

`wrap` accepts a `Transform` whose output is a `HandlerService`. Two types do
the work: the `Transform` runs once when the application is prepared, and wraps
each route's service in your `Service`, which then runs for every request:

<!-- tested-example: guide-middleware-transform -->
```rust
use std::{
    convert::Infallible,
    sync::{
        Arc,
        atomic::{AtomicUsize, Ordering},
    },
};

use async_trait::async_trait;
use wireframe::{
    app::{Envelope, Handler, Packet, WireframeApp},
    middleware::{HandlerService, Service, ServiceRequest, ServiceResponse, Transform},
};

/// Counts every request that passes through, on any route.
struct Tally {
    tallied: Arc<AtomicUsize>,
}

struct TallyService<S> {
    inner: S,
    tallied: Arc<AtomicUsize>,
}

#[async_trait]
impl<S> Service for TallyService<S>
where
    S: Service<Error = Infallible> + Send + Sync + 'static,
{
    type Error = Infallible;

    async fn call(&self, request: ServiceRequest) -> Result<ServiceResponse, Infallible> {
        self.tallied.fetch_add(1, Ordering::Relaxed);
        self.inner.call(request).await
    }
}

#[async_trait]
impl<E: Packet> Transform<HandlerService<E>> for Tally {
    type Output = HandlerService<E>;

    async fn transform(&self, service: HandlerService<E>) -> Self::Output {
        let id = service.id();
        let tallied = Arc::clone(&self.tallied);
        HandlerService::from_service(
            id,
            TallyService {
                inner: service,
                tallied,
            },
        )
    }
}

fn main() -> wireframe::Result<()> {
    let tallied = Arc::new(AtomicUsize::new(0));
    let handler: Handler<Envelope> = Arc::new(|_: &Envelope| Box::pin(async {}));
    let _app: WireframeApp = WireframeApp::new()?
        .route(1, handler)?
        .wrap(Tally { tallied })?;
    Ok(())
}
```

Each middleware layer wraps the application's routes, and the first `wrap` call
ends up outermost, so it sees the request first and the response last. To
reply, call the inner service and then replace `response.frame_mut()`, as
[the first server](#your-first-server) does. A service can edit the incoming
bytes through `request.frame_mut()` too. `ServiceRequest` and `ServiceResponse`
also expose the correlation identifier.

### What `from_fn` is for

`middleware::from_fn` turns an async function into a `Transform`, which is
handy for composing services of your own and for testing. However, it produces
a different service type from the `HandlerService` that `wrap` requires, so
**it cannot be passed to `WireframeApp::wrap`**. For routed middleware, write a
`Transform` as above.

<!-- tested-example: guide-middleware-from-fn -->
```rust
use std::convert::Infallible;

use wireframe::{
    app::Envelope,
    message::Message,
    middleware::{HandlerService, Next, ServiceRequest, ServiceResponse, from_fn},
};

#[derive(bincode::Encode, bincode::BorrowDecode)]
struct Ping(u8);

#[derive(bincode::Encode, bincode::BorrowDecode)]
struct Pong(u8);

async fn decode_and_respond(
    request: ServiceRequest,
    next: Next<'_, HandlerService<Envelope>>,
) -> Result<ServiceResponse, Infallible> {
    let ping = Ping::from_bytes(request.frame()).map(|(message, _)| message).ok();
    let mut response = next.call(request).await?;

    if let Some(Ping(value)) = ping {
        *response.frame_mut() = Pong(value.wrapping_add(1)).to_bytes().expect("encode Pong");
    }
    Ok(response)
}

let _middleware = from_fn(decode_and_respond);
```

### Versioning a message

Middleware is also a tidy way to retire an old message format without breaking
its clients. Accept versions N and N-1 on the way in, rewrite the older one so
that handlers only ever see the current schema, send only version N out, and
count legacy traffic so that you know when it is safe to remove the adapter:

<!-- tested-example: guide-middleware-versions -->
```rust
use std::convert::Infallible;

use async_trait::async_trait;
use wireframe::{
    app::Envelope,
    message::Message,
    middleware::{HandlerService, Service, ServiceRequest, ServiceResponse, Transform},
};

#[derive(bincode::Encode, bincode::BorrowDecode)]
struct PointV1 {
    id: u64,
    name: String,
}

/// Version 2 adds a field, so a version 1 payload is too short to decode as this.
#[derive(bincode::Encode, bincode::BorrowDecode)]
struct PointV2 {
    id: u64,
    display_name: String,
    intensity: u32,
}

struct UpgradePoints;

struct UpgradeService<S> {
    inner: S,
}

#[async_trait]
impl<S> Service for UpgradeService<S>
where
    S: Service<Error = Infallible> + Send + Sync + 'static,
{
    type Error = Infallible;

    async fn call(&self, mut request: ServiceRequest) -> Result<ServiceResponse, Infallible> {
        if PointV2::from_bytes(request.frame()).is_err()
            && let Ok((v1, _)) = PointV1::from_bytes(request.frame())
        {
            let v2 = PointV2 {
                id: v1.id,
                display_name: v1.name,
                intensity: 0,
            };
            *request.frame_mut() = v2.to_bytes().expect("encode PointV2");
        }
        self.inner.call(request).await
    }
}

#[async_trait]
impl Transform<HandlerService<Envelope>> for UpgradePoints {
    type Output = HandlerService<Envelope>;

    async fn transform(&self, service: HandlerService<Envelope>) -> Self::Output {
        let id = service.id();
        HandlerService::from_service(id, UpgradeService { inner: service })
    }
}
```

Note the order of the checks. Bincode happily decodes a prefix, so trying the
older format first could misread a newer message.

## Packets, payloads, and serialization

A serializer converts envelopes to and from bytes. `WireframeApp` uses
`BincodeSerializer` by default. To use another, install it with
`.serializer(s)` on the builder, or start from
`WireframeApp::with_serializer(s)`.

Message types use the adapter traits `EncodeWith<S>` and `DecodeWith<S>`. Any
type deriving bincode's traits implements `Message`, which provides `to_bytes`
and `from_bytes`, and this is usually all you need. For Serde types, enable the
`serializer-serde` feature, wrap values in `SerdeMessage<T>` (or call
`into_serde_message()`), and implement `SerdeSerializerBridge` on your
serializer.

A few details matter if you write your own serializer:

- Implement `MessageCompatibilitySerializer` if it should accept `Message`
  payloads.
- `Serializer` is not object-safe, so `dyn Serializer` is unavailable. If you
  need runtime polymorphism, wrap concrete serializers in your own adapter.
- Implement `Serializer::deserialize_with_context` to inspect metadata through
  `DeserializeContext`.
- `FrameMetadata::parse` can extract routing information cheaply. After a
  successful parse the framework still fully deserializes, unless
  `should_deserialize_after_parse` returns `false`. If parsing fails, it falls
  back to full deserialization, except when a decode limit was exceeded.
  `BincodeSerializer::parse` itself performs a full decode.

### Limits on what a peer can make you decode

The bundled bincode decoders apply a fixed 16 MiB limit (`MAX_FRAME_LENGTH`) to
peer-provided container lengths. This bounds the work and allocation a declared
length can cause. It is separate from your configured frame size, which still
decides which frames are accepted. Reassembled messages use the same 16 MiB
limit, even if their configured size limit is larger.

An inbound `Envelope` frame must contain exactly one value, so trailing bytes
are a decoding error. The limit relies on bincode's accounting, and is not a
general allocator quota, so protocols with further resource needs should
validate peer input themselves.

## Custom frame codecs

The default codec is a 4-byte big-endian length prefix, with a 1024-byte
maximum frame. To change the limit, use `buffer_capacity`; to change the
format, implement `FrameCodec`.

Changing either clears anything derived from the old framing. `buffer_capacity`
and `with_codec` both clear the fragmentation configuration, and `with_codec`
also removes hooks installed with `with_protocol`, the push-queue template, and
the session registry, because the frame type may change. Call `with_codec`
first, then configure the rest.

### Writing a `FrameCodec`

A codec supplies a frame type and a Tokio decoder and encoder. This one uses
two bytes of length and four bytes of tag. The example imports `Bytes` and
Tokio's codec traits directly, so add `bytes = "1.10.1"` and
`tokio-util = { version = "0.7.16", features = ["codec"] }` as direct
dependencies. These version requirements match this workspace's manifest and
allow compatible minor and patch updates.

<!-- tested-example: guide-frame-codec -->
```rust
use std::{io, sync::Arc};

use bytes::{Buf, BufMut, Bytes, BytesMut};
use tokio_util::codec::{Decoder, Encoder};
use wireframe::{
    app::{Envelope, Handler, WireframeApp},
    codec::FrameCodec,
    serializer::BincodeSerializer,
};

const HEADER_LEN: usize = 6;

#[derive(Debug, Clone)]
struct TaggedFrame {
    tag: u32,
    payload: Bytes,
}

#[derive(Clone)]
struct TagCodec {
    max_frame_length: usize,
}

struct TagDecoder {
    max_frame_length: usize,
}

impl Decoder for TagDecoder {
    type Item = TaggedFrame;
    type Error = io::Error;

    fn decode(&mut self, src: &mut BytesMut) -> io::Result<Option<TaggedFrame>> {
        if src.len() < HEADER_LEN {
            return Ok(None);
        }
        let len = usize::from(u16::from_be_bytes([src[0], src[1]]));
        // Your decoder is what enforces the frame limit.
        if len > self.max_frame_length {
            return Err(io::Error::new(io::ErrorKind::InvalidData, "frame too large"));
        }
        if src.len() < HEADER_LEN + len {
            src.reserve(HEADER_LEN + len - src.len());
            return Ok(None);
        }
        src.advance(2);
        let tag = src.get_u32();
        let payload = src.split_to(len).freeze();
        Ok(Some(TaggedFrame { tag, payload }))
    }
}

struct TagEncoder {
    max_frame_length: usize,
}

impl Encoder<TaggedFrame> for TagEncoder {
    type Error = io::Error;

    fn encode(&mut self, frame: TaggedFrame, dst: &mut BytesMut) -> io::Result<()> {
        if frame.payload.len() > self.max_frame_length {
            return Err(io::Error::new(io::ErrorKind::InvalidInput, "frame too large"));
        }
        let len = u16::try_from(frame.payload.len())
            .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "payload too large"))?;
        dst.reserve(HEADER_LEN + frame.payload.len());
        dst.put_u16(len);
        dst.put_u32(frame.tag);
        dst.extend_from_slice(&frame.payload);
        Ok(())
    }
}

impl FrameCodec for TagCodec {
    type Frame = TaggedFrame;
    type Decoder = TagDecoder;
    type Encoder = TagEncoder;

    fn decoder(&self) -> TagDecoder {
        TagDecoder {
            max_frame_length: self.max_frame_length,
        }
    }

    fn encoder(&self) -> TagEncoder {
        TagEncoder {
            max_frame_length: self.max_frame_length,
        }
    }

    fn frame_payload(frame: &TaggedFrame) -> &[u8] { &frame.payload }

    fn frame_payload_bytes(frame: &TaggedFrame) -> Bytes { frame.payload.clone() }

    fn wrap_payload(&self, payload: Bytes) -> TaggedFrame { TaggedFrame { tag: 0, payload } }

    fn correlation_id(frame: &TaggedFrame) -> Option<u64> { Some(u64::from(frame.tag)) }

    fn max_frame_length(&self) -> usize { self.max_frame_length }
}

fn main() -> wireframe::Result<()> {
    let codec = TagCodec {
        max_frame_length: 4096,
    };
    let echo: Handler<Envelope> = Arc::new(|_: &Envelope| Box::pin(async {}));
    let app: WireframeApp<_, _, Envelope, TagCodec> = WireframeApp::<BincodeSerializer>::new()?
        .with_codec(codec)
        .route(1, echo)?;
    assert_eq!(app.codec().max_frame_length(), 4096);

    let mut encoder = app.codec().encoder();
    let mut encoded = BytesMut::new();
    encoder
        .encode(
            TaggedFrame {
                tag: 0,
                payload: Bytes::from(vec![0; 4096]),
            },
            &mut encoded,
        )
        .map_err(wireframe::WireframeError::from_io)?;
    assert_eq!(encoded.len(), HEADER_LEN + 4096);

    let error = encoder
        .encode(
            TaggedFrame {
                tag: 0,
                payload: Bytes::from(vec![0; 4097]),
            },
            &mut BytesMut::new(),
        )
        .expect_err("the encoder rejects payloads beyond its configured limit");
    assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
    Ok(())
}
```

When you write a codec, keep these rules in mind:

- `frame_payload` returns only the logical payload, without protocol headers.
- `wrap_payload` adds any headers the wire format needs.
- `correlation_id` is for protocols that store it outside the payload. Wireframe
  uses it only when the deserialized envelope lacks an identifier.
- `max_frame_length` sizes buffers and derives budgets and fragmentation
  defaults. Both decoder and encoder must enforce the limit.
- Wireframe clones the codec per connection, so make sure `Clone` produces
  independent state if the codec holds any, such as sequence counters.

See `examples/hotline_codec.rs`, `examples/mysql_codec.rs`, and
`examples/resp_codec.rs` for real protocols. The Hotline and MySQL codecs are
also available from `wireframe::codec::examples`.

### Zero-copy payloads

Storing the payload as `Bytes`, as `TaggedFrame` does, and overriding
`frame_payload_bytes` avoids copying it. The clone only increments a reference
count. In the decoder, use `BytesMut::split_to(...).freeze()` rather than
`.to_vec()`. The default `frame_payload_bytes` copies from the `frame_payload`
slice, so codecs using `Vec<u8>` keep working.

### Codec errors

`CodecError` classifies failures as `Framing`, `Protocol`, `Io`, or `Eof`, the
last of which distinguishes a clean close from a close in the middle of a frame
or header. Unless you install a [recovery policy](#codec-recovery-policies),
**any decoder error closes the connection**.

Return structured errors from your own decoder, because two features depend on
them. The `wireframe_codec_errors_total` metric labels each failure by its
category, and the protocol's [`on_eof` hook](#when-a-peer-vanishes-mid-frame)
runs only for a decoder that reports truncation as `CodecError::Eof`.

## Connection preambles

Some protocols begin with a handshake before any frames, such as a magic number
and version. The server reads and decodes a preamble first, then hands anything
left over to the codec:

<!-- tested-example: guide-server-preamble -->
```rust
use std::time::Duration;

use futures::FutureExt;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use wireframe::{app::WireframeApp, client::WireframeClient, server::WireframeServer};

#[derive(bincode::Encode, bincode::BorrowDecode, Debug, Clone, PartialEq)]
struct Hello {
    magic: [u8; 4],
    version: u16,
}

const MAGIC: [u8; 4] = *b"WIRE";

fn build_app() -> WireframeApp {
    WireframeApp::default()
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let server = WireframeServer::new(build_app)
        .with_preamble::<Hello>()
        .preamble_timeout(Duration::from_secs(2))
        .on_preamble_decode_success(|hello: &Hello, stream| {
            let accepted = hello.magic == MAGIC;
            async move {
                stream.write_all(&[u8::from(accepted)]).await?;
                if accepted {
                    Ok(())
                } else {
                    // An error here closes the connection, so write first.
                    Err(std::io::Error::other("unknown protocol"))
                }
            }
            .boxed()
        })
        .bind("127.0.0.1:0".parse()?)?;
    let address = server.local_addr().expect("a bound server has an address");
    let shutdown = server.spawn().await?;

    let client = WireframeClient::builder()
        .with_preamble(Hello {
            magic: MAGIC,
            version: 3,
        })
        .on_preamble_success(|_hello, stream| {
            async move {
                let mut acknowledgement = [0];
                stream.read_exact(&mut acknowledgement).await?;
                if acknowledgement[0] != 1 {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::ConnectionRefused,
                        "server rejected preamble",
                    ));
                }
                Ok(Vec::new())
            }
            .boxed()
        })
        .connect(address)
        .await?;
    client.close().await;

    shutdown.stop();
    shutdown.drained().await?;
    Ok(())
}
```

Keep these in mind:

- **Call `with_preamble` first**, because it clears any hooks registered
  earlier.
- **A success handler that returns an error closes the connection.** The server
  writes nothing on your behalf, so send any rejection message before returning.
- **`on_preamble_decode_failure`** receives decode errors and timeouts, along
  with the stream, so that you can reply or log before the connection closes.
- **There is always a deadline.** The read is bounded by
  `DEFAULT_PREAMBLE_TIMEOUT` (10 seconds) by default. `preamble_timeout`
  replaces that, and `disable_preamble_timeout` removes it. `Duration::ZERO`
  clamps to 1 ms. The deadline covers only the read.
- **An empty preamble reads nothing.** Without `with_preamble`, or with a type
  that encodes to no bytes, the connection goes straight to your application. A
  client may then stay silent and wait for the server to speak first, through
  [a push]#server-connections-and-push-queues.
- **Preambles are small.** Decoding is limited to 1 KiB.

The [preamble validator guide](preamble-validator.md) goes further, and
[Client preamble exchange](#client-preamble-exchange) covers the other end.

## Connection lifecycle and state

### Setup and teardown

`on_connection_setup` runs once per connection and produces state, and
`on_connection_teardown` receives that state when the stream finishes. Setting
up changes the application's state type, and it resets any teardown hook, so
register setup first:

<!-- tested-example: guide-lifecycle-hooks -->
```rust
use std::sync::{
    Arc,
    atomic::{AtomicUsize, Ordering},
};

use wireframe::{
    app::{Envelope, WireframeApp},
    serializer::BincodeSerializer,
};

struct Link {
    connected_at: std::time::Instant,
}

type LinkApp = WireframeApp<BincodeSerializer, Link, Envelope>;

fn build_app(closed: Arc<AtomicUsize>) -> wireframe::Result<LinkApp> {
    let app: WireframeApp = WireframeApp::new()?;
    app.on_connection_setup(|| async {
        Link {
            connected_at: std::time::Instant::now(),
        }
    })?
    .on_connection_teardown(move |link: Link| {
        let closed = Arc::clone(&closed);
        async move {
            println!("connection lasted {:?}", link.connected_at.elapsed());
            closed.fetch_add(1, Ordering::Relaxed);
        }
    })
}

fn main() -> wireframe::Result<()> {
    let _app = build_app(Arc::new(AtomicUsize::new(0)))?;
    Ok(())
}
```

Teardown runs exactly once when both hooks are registered and setup has
produced state, whether the connection ended cleanly, with a decode, protocol,
or transport error, or because a handler panicked. The transport is released
first, so teardown may wait for the peer to notice. A handler panic is raised
again after teardown, so it is still logged and counted.

Stopping the server does not skip it: the connection notices the stop, ends the
way it would after any other error, and runs teardown. Some endings cannot run
it to completion: setup that failed or never finished, a connection future that
is dropped or aborted, a panic the connection runtime cannot recover, a
teardown callback that itself panics, which is not retried, and a build with
`panic = "abort"`. Put a resource that must be released after a dropped future
or an unrecovered panic behind a `Drop` guard. A `panic = "abort"` build runs
no destructors at all, so cleanup that must survive an abort needs something
outside the process, such as a supervisor or a lease on the external resource.

### Sharing state with handlers

Setup state reaches teardown, but it is **not passed to handlers or
middleware**. To share state with a handler, capture it when you build the
closure:

<!-- tested-example: guide-shared-state -->
```rust
use std::sync::{
    Arc,
    atomic::{AtomicU64, Ordering},
};

use wireframe::{
    app::{Envelope, Handler, WireframeApp},
    message::Message,
};

#[derive(bincode::Encode, bincode::BorrowDecode)]
struct Login {
    username: String,
}

fn build_app(logins: Arc<AtomicU64>) -> wireframe::Result<WireframeApp> {
    let handler: Handler<Envelope> = Arc::new(move |envelope: &Envelope| {
        // Decode before the future, which cannot borrow the envelope.
        let login = Login::from_bytes(envelope.payload_bytes()).map(|(login, _)| login);
        let logins = Arc::clone(&logins);
        Box::pin(async move {
            if let Ok(login) = login {
                let count = logins.fetch_add(1, Ordering::Relaxed) + 1;
                println!("{} is login {count}", login.username);
            }
        })
    });

    let app: WireframeApp = WireframeApp::new()?.route(1, handler)?;
    Ok(app)
}

fn main() -> wireframe::Result<()> {
    let _app = build_app(Arc::new(AtomicU64::new(0)))?;
    Ok(())
}
```

Handlers own their decoding. Use a shared function for validation, or
middleware on buffered routes. Buffered handlers receive an envelope. Streaming
handlers receive routing information and a body stream. Protocol hooks can
access the peer's address through `ConnectionContext`.

### Writing a response directly

`send_response` writes one encoded message to a stream, using the application's
serializer and a length-delimited frame. It lives on the `WireframeApp` builder
rather than on `PreparedApp`, so it is for code that manages its own stream,
not for handlers:

<!-- tested-example: guide-send-response -->
```rust
use tokio::io::{self, AsyncReadExt, AsyncWriteExt};
use wireframe::{
    app::{SendError, WireframeApp},
    message::Message,
};

#[derive(bincode::Encode, bincode::BorrowDecode, Debug, PartialEq)]
struct Ready {
    status: u8,
}

const LENGTH_PREFIX: usize = 4;

#[tokio::main]
async fn main() -> Result<(), SendError> {
    let app: WireframeApp = WireframeApp::default();
    let (mut client, mut server) = io::duplex(64);

    let ready = Ready { status: 1 };
    app.send_response(&mut server, &ready).await?;
    server.shutdown().await?;

    let mut buffer = Vec::new();
    client.read_to_end(&mut buffer).await?;
    let frame = buffer.get(LENGTH_PREFIX..).expect("a length-prefixed frame");
    let (decoded, _) = Ready::from_bytes(frame).expect("decode Ready");
    assert_eq!(decoded, ready);
    Ok(())
}
```

`send_response_framed` writes raw bytes to an existing `Framed` stream, and
`send_response_framed_with_codec` does so through `FrameCodec::wrap_payload`.
All three report failures through `SendError`, and all three bypass
`before_send`. The `Display` output of each variant begins with a stable prefix
you may match on: `serialization error:`, `I/O error:`, or `codec error:`. The
text after the prefix is not part of that contract.

### Driving accepted streams yourself

If you accept streams yourself rather than using `WireframeServer`, prepare the
application once and reuse it. Preparation consumes the builder and builds each
buffered route's middleware chain once. Register every route and middleware
before preparing:

<!-- tested-example: guide-prepared-app -->
```rust
use tokio::io::duplex;
use wireframe::app::{PreparedApp, WireframeApp};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let prepared: PreparedApp = WireframeApp::new()?.prepare().await?;
    let (client, server) = duplex(64);
    drop(client);
    prepared.handle_connection_result(server).await?;
    Ok(())
}
```

`prepare` returns `PrepareError` if a push-queue template has an unusable
capacity or rate, so the problem surfaces before any connection exists.
`handle_connection_result` returns stream and handler I/O errors, and
`handle_connection` logs them instead. Both need a serializer that is
`'static`. The older `WireframeApp::handle_connection` methods are deprecated
because they rebuild the chains for every connection.

## Large messages

Wireframe has two separate mechanisms, and they are easy to confuse:

- **Fragmentation** is transport-level. Wireframe splits an envelope that will
  not fit in a frame, using its own `FRAG` format, and rejoins it at the other
  end. Both ends need to be Wireframe servers or to speak that format.
- **Message assembly** is protocol-level. Your protocol already defines first
  and continuation frames, and you teach Wireframe to parse them.

### Fragmentation

Fragmentation is off by default. Turn it on with `enable_fragmentation()`,
which derives limits from the frame budget, or supply a `FragmentationConfig`:

<!-- tested-example: guide-fragmentation-config -->
```rust
use std::{num::NonZeroUsize, sync::Arc, time::Duration};

use wireframe::{
    app::{Envelope, Handler, WireframeApp},
    fragment::FragmentationConfig,
};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = FragmentationConfig::for_frame_budget(
        1024,
        NonZeroUsize::new(16 * 1024).expect("non-zero"),
        Duration::from_secs(30),
    )
    .expect("the frame budget has room for fragments");

    let handler: Handler<Envelope> = Arc::new(|_: &Envelope| Box::pin(async {}));
    let _app: WireframeApp = WireframeApp::new()?
        .fragmentation(Some(config))
        .route(42, handler)?;
    Ok(())
}
```

Payloads larger than `fragment_payload_cap` (the frame budget less some
overhead) are split into fragments. The reassembler rebuilds the payload before
the message assembler sees it. Four limits protect the reassembling side:

- `max_message_size` caps the reassembled payload. Exceeding it counts as a
  deserialization failure.
- `reassembly_timeout` evicts stale partial messages.
- `max_concurrent_partials` limits incomplete messages per connection.
- `max_buffered_bytes` caps their total size.

Exceeding either of the last two closes the connection immediately.
`for_frame_budget` sets them to `min(frame_budget, 64)` partial messages and
the larger of `frame_budget × 64` and `max_message_size` bytes. Call
`fragmentation(None)` to disable fragmentation again, for example when a
gateway handles it upstream. The `WireframeClient` has no fragmentation support
of its own, so a client talking to a fragmenting server sees `FRAG` payloads.

To work with fragments directly, `Fragmenter` splits and `Reassembler` rejoins:

<!-- tested-example: guide-fragmenter -->
```rust
use std::{num::NonZeroUsize, time::Duration};

use wireframe::fragment::{FragmentHeader, FragmentIndex, Fragmenter, MessageId, Reassembler};

let fragmenter = Fragmenter::new(NonZeroUsize::new(512).expect("non-zero"));
let batch = fragmenter.fragment_bytes([7_u8; 1400]).expect("fragment");
assert_eq!(batch.len(), 3);
assert!(batch.fragments().last().expect("a fragment").header().is_last_fragment());

let limit = NonZeroUsize::new(4096).expect("non-zero");
let mut reassembler = Reassembler::new(limit, Duration::from_secs(30), None, None);
let id = MessageId::new(9);

let first = FragmentHeader::new(id, FragmentIndex::zero(), false);
assert!(reassembler.push(first, [1_u8; 8]).expect("accepted").is_none());

let last = FragmentHeader::new(id, FragmentIndex::new(1), true);
let whole = reassembler
    .push(last, [2_u8; 8])
    .expect("accepted")
    .expect("the final fragment completes the message");
assert_eq!(whole.payload().len(), 16);
```

An empty input produces one final fragment with an empty payload, so a batch is
never empty. `purge_expired` clears stale partial messages from a standalone
`Reassembler`.

### Message assembly

If your protocol has its own multi-frame format, implement `MessageAssembler`
to parse each frame's header. Once configured, it must parse every inbound
payload, including single-frame messages, and it runs after any fragment
reassembly:

<!-- tested-example: guide-message-assembler -->
```rust
use wireframe::{
    app::WireframeApp,
    message_assembler::{FirstFrameHeader, FrameHeader, MessageAssembler, MessageKey, ParsedFrameHeader},
};

struct DemoAssembler;

impl MessageAssembler for DemoAssembler {
    fn parse_frame_header(&self, _payload: &[u8]) -> Result<ParsedFrameHeader, std::io::Error> {
        Ok(ParsedFrameHeader::new(
            FrameHeader::First(FirstFrameHeader {
                message_key: MessageKey(1),
                metadata_len: 0,
                body_len: 0,
                total_body_len: None,
                is_last: true,
            }),
            0,
        ))
    }
}

let app: WireframeApp = WireframeApp::new().expect("builder");
let app = app.with_message_assembler(DemoAssembler);
assert!(app.message_assembler().is_some());
```

`message_assembler` lends you the assembler, and the application keeps
ownership of it. To share one with code that outlives the application, keep it
in an `Arc` of your own, and install a small type that forwards to it.

On a buffered route, incomplete messages stay buffered per `MessageKey` until
they complete or time out. A completed message's `Envelope` payload holds the
metadata followed by the body, with no marker between them. A
[streaming route](#streaming-request-body-consumption) receives these
separately, and can read the body as its frames arrive. Parsing and ordering
failures count towards the deserialization failure limit.

To use the state machine directly, `MessageAssemblyState` handles interleaved
messages:

<!-- tested-example: guide-message-assembly-state -->
```rust
use std::{num::NonZeroUsize, time::Duration};

use wireframe::message_assembler::{
    ContinuationFrameHeader,
    EnvelopeId,
    EnvelopeRouting,
    FirstFrameHeader,
    FirstFrameInput,
    FrameSequence,
    MessageAssemblyState,
    MessageKey,
};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut state = MessageAssemblyState::new(
        NonZeroUsize::new(1_048_576).expect("non-zero"),
        Duration::from_secs(30),
    );

    // The first frame of message 1.
    let first_one = FirstFrameHeader {
        message_key: MessageKey(1),
        metadata_len: 0,
        body_len: 5,
        total_body_len: Some(15),
        is_last: false,
    };
    let routing = EnvelopeRouting {
        envelope_id: EnvelopeId(1),
        correlation_id: None,
    };
    state.accept_first_frame(FirstFrameInput::new(&first_one, routing, vec![], b"hello")?)?;

    // The first frame of message 2 arrives in between.
    let first_two = FirstFrameHeader {
        message_key: MessageKey(2),
        metadata_len: 0,
        body_len: 5,
        total_body_len: None,
        is_last: false,
    };
    let routing = EnvelopeRouting {
        envelope_id: EnvelopeId(2),
        correlation_id: None,
    };
    state.accept_first_frame(FirstFrameInput::new(&first_two, routing, vec![], b"world")?)?;

    // A continuation completes message 1.
    let last_one = ContinuationFrameHeader {
        message_key: MessageKey(1),
        sequence: Some(FrameSequence(1)),
        body_len: 10,
        is_last: true,
    };
    let message = state
        .accept_continuation_frame(&last_one, b" completed")?
        .expect("message 1 is complete");
    assert_eq!(message.body(), b"hello completed");
    Ok(())
}
```

`MessageSeries` validates the order of one message's frames when your protocol
supplies sequence numbers:

<!-- tested-example: guide-message-series -->
```rust
use wireframe::message_assembler::{
    ContinuationFrameHeader,
    FirstFrameHeader,
    FrameSequence,
    MessageKey,
    MessageSeries,
    MessageSeriesError,
    MessageSeriesStatus,
};

fn continuation(sequence: u32, is_last: bool) -> ContinuationFrameHeader {
    ContinuationFrameHeader {
        message_key: MessageKey(1),
        sequence: Some(FrameSequence(sequence)),
        body_len: 5,
        is_last,
    }
}

let first = FirstFrameHeader {
    message_key: MessageKey(1),
    metadata_len: 0,
    body_len: 10,
    total_body_len: None,
    is_last: false,
};
let mut series = MessageSeries::from_first_frame(&first);

assert_eq!(series.accept_continuation(&continuation(1, false)), Ok(MessageSeriesStatus::Incomplete));
assert!(matches!(
    series.accept_continuation(&continuation(3, false)),
    Err(MessageSeriesError::SequenceMismatch { .. })
));
assert_eq!(series.accept_continuation(&continuation(2, false)), Ok(MessageSeriesStatus::Incomplete));
assert!(matches!(
    series.accept_continuation(&continuation(1, false)),
    Err(MessageSeriesError::DuplicateFrame { .. })
));
assert_eq!(series.accept_continuation(&continuation(3, true)), Ok(MessageSeriesStatus::Complete));
assert!(matches!(
    series.accept_continuation(&continuation(4, false)),
    Err(MessageSeriesError::SeriesComplete)
));
```

The first sequenced frame sets the baseline at any value, so a gap before it
goes undetected. Once a series is tracking sequences, an unsequenced frame is
rejected with `MissingSequence`. Other errors include `KeyMismatch` and
`SequenceOverflow`. Protocols that supply no sequence numbers skip these order
checks.

#### Declared total body length

`FirstFrameHeader::total_body_len` is binding, not a hint. If you set it, the
assembler enforces it:

- `DeclaredTotalTooSmall`: a first frame carries more body than it declares.
- `DeclaredTotalExceeded`: a continuation would pass the total, and is rejected
  before its bytes are buffered.
- `DeclaredTotalMismatch`: the completed body is not the declared length.

A rejected continuation or completion removes its partial assembly. Buffered
routes reject the message before dispatch. A live streaming handler may have
read earlier chunks before the mismatch terminates the body. Delivery of the
terminal error can time out or find the receiver gone.

An exact total helps reject an oversized message early. Leaving the field as
`None` opts out of the equality check. The metadata-inclusive size cap still
applies. On a continuation that exceeds both the cap and the declared total,
`MessageTooLarge` takes precedence over `DeclaredTotalExceeded`. The decision
is recorded in
[ADR 015](adrs/adr-0015-declared-total-body-length-is-authoritative.md).

### Streaming request body consumption

Register a message ID with `WireframeApp::streaming_route` to handle large
requests as their frames arrive. The server creates the body channel and hands
the handler `RequestParts` and a `RequestBodyStream`. Install a
[`MessageAssembler`](#message-assembly) for the protocol's multi-frame
requests. With no assembler, the envelope payload arrives as one chunk and the
metadata is empty.

This handler consumes the body and withholds a reply if it receives an error.
It uses `futures::StreamExt` from the `futures` crate. Applications that
acknowledge complete uploads should verify the expected length or content
according to their protocol before replying.

<!-- tested-example: guide-streaming-request-handler -->
```rust
use std::sync::Arc;

use bytes::Bytes;
use futures::StreamExt;
use wireframe::app::{StreamingHandler, WireframeApp};

const UPLOAD: u32 = 42;

fn upload_handler() -> StreamingHandler {
    Arc::new(|parts, mut body| {
        Box::pin(async move {
            while let Some(chunk) = body.next().await {
                match chunk {
                    Ok(bytes) => log::debug!("request {}: {} bytes", parts.id(), bytes.len()),
                    Err(error) => {
                        log::warn!("request {} failed: {error}", parts.id());
                        return None;
                    }
                }
            }
            Some(Bytes::from_static(b"accepted"))
        })
    })
}

fn main() -> wireframe::Result<()> {
    let _app: WireframeApp = WireframeApp::new()?.streaming_route(UPLOAD, upload_handler())?;
    Ok(())
}
```

`RequestParts` carries the message ID, optional correlation ID and
protocol-defined metadata. The handler returns `Option<Bytes>`. A payload
becomes a reply with the request's message and correlation IDs and goes through
the ordinary outbound frame pipeline. `None` sends no reply. Streaming routes
bypass middleware, so put any authentication or validation the route needs in
the handler.

Only one body streams at a time on each connection. Messages that complete
while it is live wait in completion order. A waiting streaming request is
assembled and later delivered as a single chunk. The per-connection queue holds
up to 64 completed messages. A further completion while it is full ends the
connection with `InvalidData`.

Before each chunk is delivered, assembly checks sequence, message size and any
declared body total. A duplicate or a gap leaves the partial assembly available
for recovery. The runtime attempts to deliver `InvalidData` for a terminal
mismatch, `TimedOut` for expiry or a 30-second chunk admission stall,
`UnexpectedEof` for a peer close mid-body, and the decoder's error kind for a
decode failure. If error delivery times out or the receiver is gone, the
runtime logs the outcome. Dropping the stream early causes the remaining frames
to be validated and discarded, preserving framing for later requests. Exceeding
the connection's hard memory cap closes it and drops the handler.

Queued chunks count towards the connection's memory budgets. When the budget or
channel capacity holds up a chunk, the connection pauses reads so pressure
reaches the peer. A chunk can enter an empty queue even if it exceeds the byte
budget, so the consumer can make progress. The hard-cap check still applies
after admission. See [streaming body metrics](#streaming-body-metrics) to
diagnose slow uploads.

Use `RequestBodyReader` when a parser expects `AsyncRead`. Code that owns both
the sender and receiver can also create a bounded `body_channel` directly:

<!-- tested-example: guide-request-body -->
```rust
use bytes::Bytes;
use tokio::io::AsyncReadExt;
use wireframe::request::{RequestBodyReader, RequestParts, body_channel};

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let parts = RequestParts::new(42, Some(123), vec![0x01, 0x02]);
    assert_eq!(parts.id(), 42);
    assert_eq!(parts.correlation_id(), Some(123));
    assert_eq!(parts.metadata(), &[0x01, 0x02]);

    let (sender, stream) = body_channel(8);
    tokio::spawn(async move {
        for chunk in [&b"hello "[..], &b"world"[..]] {
            if sender.send(Ok(Bytes::from_static(chunk))).await.is_err() {
                return;
            }
        }
    });

    let mut reader = RequestBodyReader::new(stream);
    let mut body = Vec::new();
    reader.read_to_end(&mut body).await?;
    assert_eq!(body, b"hello world");
    Ok(())
}
```

See [ADR 002](adrs/adr-0002-streaming-requests-and-shared-message-assembly.md)
for the body types and
[ADR 018](adrs/adr-0018-streaming-request-body-dispatch.md) for how the runtime
dispatches them.

### Per-connection memory budgets

`MemoryBudgets` caps inbound buffering per connection:

<!-- tested-example: guide-memory-budgets -->
```rust
use std::num::NonZeroUsize;

use wireframe::app::{BudgetBytes, MemoryBudgets, WireframeApp};

let bytes = |count: usize| BudgetBytes::new(NonZeroUsize::new(count).expect("non-zero"));
let budgets = MemoryBudgets::new(bytes(16 * 1024), bytes(64 * 1024), bytes(48 * 1024));

let _app: WireframeApp = WireframeApp::new()
    .expect("builder")
    .memory_budgets(budgets);
```

The arguments are bytes per message, per connection, and in flight. Without an
explicit call, Wireframe derives them from `buffer_capacity`, as Table 4 shows.

| Budget                 | Derived value       | With a 1024-byte frame |
| ---------------------- | ------------------- | ---------------------- |
| `bytes_per_message`    | `frame_budget × 16` | 16 KiB                 |
| `bytes_per_connection` | `frame_budget × 64` | 64 KiB                 |
| `bytes_in_flight`      | `frame_budget × 64` | 64 KiB                 |

_Table 4: Default memory budgets._

The budgets protect a connection in three stages. The first applies only with a
`MessageAssembler`. Read pacing and the hard cap count partial fragments,
buffered assemblies, queued body bytes and completed messages waiting behind a
live streaming body.

1. **Per-frame rejection.** A frame that would exceed the connection or
   in-flight budget is rejected, its partial assembly is freed, and the failure
   counts as a deserialization failure. The effective per-message limit is the
   smaller of `max_message_size` and `bytes_per_message`. A buffered
   single-frame message that dispatches immediately retains no partial assembly.
2. **Read pacing.** At 80% of the smaller aggregate cap, the connection pauses
   briefly before reading the next frame, passing back-pressure to the sender.
3. **Hard cap.** Above 100% of that cap, the connection closes with
   `InvalidData`. The total can exceed the cap even when each contributing
   layer stays within its own limit.

The per-message limit counts first-frame metadata plus the accumulated body
across all frames. On the first frame, a larger `total_body_len` declaration
takes the place of the actual body length in that calculation. The runtime
validates the declaration first. A contradiction reports
`DeclaredTotalTooSmall` or `DeclaredTotalMismatch` even when the frame also
exceeds the cap. Once the declaration is valid, the runtime rejects an
oversized first frame with `MessageTooLarge` before buffering it. The cap also
applies to every continuation.

## Protocol hooks

`WireframeProtocol` gathers callbacks for a protocol. Install an implementation
with `with_protocol`, after any `with_codec` call. It must use
`ProtocolError = ()`, and its frame type must be the codec's frame, which is
`Bytes` for the default codec:

<!-- tested-example: guide-protocol-hooks -->
```rust
use bytes::{Bytes, BytesMut};
use wireframe::{
    app::WireframeApp,
    hooks::{ConnectionContext, WireframeProtocol},
};

struct Stamped;

impl WireframeProtocol for Stamped {
    type Frame = Bytes;
    type ProtocolError = ();

    fn before_send(&self, frame: &mut Bytes, _context: &mut ConnectionContext) {
        let mut stamped = BytesMut::from(frame.as_ref());
        stamped.extend_from_slice(b"!");
        *frame = stamped.freeze();
    }
}

let app: WireframeApp = WireframeApp::new().expect("builder");
let _app = app.with_protocol(Stamped);
```

Every hook has a default that does nothing, so implement only what you need.
Table 5 shows when the server calls each one.

| Hook                  | When it runs on a server connection                                                                   |
| --------------------- | ----------------------------------------------------------------------------------------------------- |
| `on_connection_setup` | Once, before the first frame is read, with a `PushHandle` for this connection.                        |
| `before_send`         | Once for every outbound frame: replies and their fragments, streamed frames, terminators, and pushes. |
| `on_command_end`      | After a completed reply's final frame is written, including ordinary `route` replies.                 |
| `stream_end_frame`    | To build the frame that ends a streamed or multi-packet reply.                                        |
| `handle_error`        | When a streamed reply yields a protocol error; the connection then closes without a terminator.       |
| `on_eof`              | When the peer vanishes part-way through a frame.                                                      |

_Table 5: Protocol hooks and when they run._

`before_send` sees the frame after the codec has wrapped it and just before it
is encoded. Whatever it writes must still fit `max_frame_length`. The default
codec rejects an oversized frame, which fails the send and ends the connection,
whereas a custom codec must enforce the limit itself. The
[direct response helpers](#writing-a-response-directly) bypass it.

`ConnectionContext` belongs to one connection, and offers its `connection_id()`
and `peer_addr()`. It cannot yet hold your own data, and state inside your
`WireframeProtocol` value is shared by every connection, so key anything
per-connection by the identifier.

**`on_command_end` is not a cleanup guarantee.** It does not run for a reply
that was cancelled, or whose terminator could not be written. Use connection
teardown for what must happen on close.

To supply callbacks without a whole protocol, when driving a
[`ConnectionActor`](#the-connection-actor) yourself, fill in
`CustomProtocolHooks` and convert it with `.into()`. `ProtocolHooks` is an enum
of `None`, `Protocol`, and `Custom`.

### When a peer vanishes mid-frame

A peer that disconnects between frames has simply finished. One that
disconnects inside a frame has lost something, and `on_eof` tells you what: an
`EofError::MidHeader` or `EofError::MidFrame`, along with the bytes that did
arrive. The built-in codecs support it. A custom decoder opts in by returning
`CodecError::Eof` from `decode_eof`, and should leave the incomplete bytes in
the buffer, so that the hook receives them:

<!-- tested-example: guide-decode-eof -->
```rust
use std::io;

use bytes::{Buf, BytesMut};
use tokio_util::codec::Decoder;
use wireframe::codec::{CodecError, EofError};

const HEADER: usize = 2;

struct ShortFrames;

impl Decoder for ShortFrames {
    type Item = Vec<u8>;
    type Error = io::Error;

    fn decode(&mut self, buffer: &mut BytesMut) -> Result<Option<Vec<u8>>, io::Error> {
        let Some(&[high, low]) = buffer.first_chunk::<HEADER>() else {
            return Ok(None);
        };
        // Two bytes cannot declare more than 64 KiB, which is this format's limit.
        let length = usize::from(u16::from_be_bytes([high, low]));
        if buffer.len() < HEADER + length {
            return Ok(None);
        }
        buffer.advance(HEADER);
        Ok(Some(buffer.split_to(length).to_vec()))
    }

    fn decode_eof(&mut self, buffer: &mut BytesMut) -> Result<Option<Vec<u8>>, io::Error> {
        if let Some(frame) = self.decode(buffer)? {
            return Ok(Some(frame));
        }
        let received = buffer.len();
        match buffer.first_chunk::<HEADER>() {
            // A clean close at a frame boundary.
            None if received == 0 => Ok(None),
            None => Err(CodecError::Eof(EofError::MidHeader {
                bytes_received: received,
                header_size: HEADER,
            })
            .into()),
            Some(header) => Err(CodecError::Eof(EofError::MidFrame {
                bytes_received: received - HEADER,
                expected: usize::from(u16::from_be_bytes(*header)),
            })
            .into()),
        }
    }
}

let mut whole = BytesMut::from(&[0, 2, 7, 7][..]);
assert_eq!(ShortFrames.decode_eof(&mut whole).expect("decodes"), Some(vec![7, 7]));

let mut cut_short = BytesMut::from(&[0, 5, 7][..]);
let error = ShortFrames.decode_eof(&mut cut_short).expect_err("truncated");
let reason = error.get_ref().and_then(|inner| inner.downcast_ref::<CodecError>());
assert!(matches!(reason, Some(CodecError::Eof(EofError::MidFrame { .. }))));
assert_eq!(cut_short.len(), 3, "the bytes are left for `on_eof`");
```

A frame the decoder rejects as malformed is a different matter. It reaches
[the recovery policy](#codec-recovery-policies), and neither `on_eof` nor
`handle_error`.

## Running servers

### Configuring and starting

`WireframeServer` starts unbound. `bind` or `bind_existing_listener` gives you
a server that can report its `local_addr` and run. Prefer `from_app` if you
already have an application. `WireframeServer::new` takes a factory instead,
which it calls **once per server run**, not once per connection. Either way,
the application is prepared before the server reports readiness, and failures
arrive as `ServerError` values:

<!-- tested-example: guide-server-configuration -->
```rust
use std::time::Duration;

use tokio::sync::oneshot;
use wireframe::{
    app::WireframeApp,
    server::{BackoffConfig, WireframeServer},
};

fn build_app() -> WireframeApp {
    WireframeApp::default().read_timeout_ms(250)
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let backoff = BackoffConfig {
        initial_delay: Duration::from_millis(10),
        max_delay: Duration::from_secs(1),
    };
    let (ready_sender, ready) = oneshot::channel();
    let (stop, stopped) = oneshot::channel::<()>();

    let server = WireframeServer::new(build_app)
        .workers(4)
        .accept_backoff(backoff)
        .ready_signal(ready_sender)
        .bind("127.0.0.1:0".parse()?)?;
    assert_eq!(server.worker_count(), 4);

    let running = tokio::spawn(server.run_with_shutdown(async {
        drop(stopped.await);
    }));

    ready.await?;
    stop.send(()).expect("the server is waiting for shutdown");
    running.await??;
    Ok(())
}
```

Each worker runs an accept loop. The default count follows
`std::thread::available_parallelism`, which respects CPU quotas, and is never
below one. Any `accept` failure makes that worker back off exponentially and
retry, up to `max_delay`. A panic in a connection task is caught, logged, and
counted, and other connections carry on.

Per-connection state belongs in `on_connection_setup`, because the application
is shared among all connections.

### Shutting down

There are three ways to stop a server:

- `run` serves until Ctrl+C.
- `run_with_shutdown` serves until the future you give it completes. Dropping
  the returned future also cancels the accept loops and, in time, releases the
  listener, so keep it alive for as long as the server should run.
- `spawn` runs in the background and returns a cloneable `ServerShutdown`.
  `stop()` requests shutdown and is safe to call repeatedly, and
  `drained().await` returns `Ok(())` after the accept loops have exited and
  tracked connection tasks have returned. `ServerError::AbnormalTermination`
  signals an unexpected supervisor exit and gives no confirmation that the
  drain completed. Retain a clone to observe the result. Dropping the last
  clone also requests shutdown.

The listener is released as soon as the last accept loop exits, independently
of in-flight connection tasks. A slow handler can delay `drained()` while the
address is already refusing new connections.

Shutdown closes idle connections and abandons an unfinished preamble. Active
work may be interrupted before a reply is written.

- **A pending request body or reply** can be abandoned on shutdown. A
  handler or other tracked task that has yet to return can still delay
  `drained()`. Bound slow handlers, or use `tokio::time::timeout` to bound the
  caller's wait.
- **A streamed reply** keeps going while its producer and its peer make
  progress. A producer that yields nothing for 30 seconds has its reply
  cancelled, and a write that would block is abandoned.
- **Queued pushes** may be discarded. See
  [closing and shutdown]#pushes-closing-and-shutdown.

For a test that needs a real server with your protocol configuration, pass a
configured, unbound `WireframeServer` to
`wireframe_testing::spawn_wireframe_server`. The returned
`RunningWireframeServer` provides the bound address through `local_addr()`. The
helper installs its own `ready_signal`, so leave that setting unset. Dropping
the handle requests shutdown synchronously. Await `shutdown()` to observe the
drain within its configured timeout. See the
[server lifecycle harness](wireframe-testing-crate.md#protocol-agnostic-server-lifecycle-harness)
for listener and timeout options.

### Limits at a glance

Table 6 summarizes the server's defaults.

| Setting                  | Default                 | What it does                                                                           |
| ------------------------ | ----------------------- | -------------------------------------------------------------------------------------- |
| `buffer_capacity`        | 1024 bytes              | The largest frame; a larger one is a decoder error, which closes the connection.       |
| `read_timeout_ms`        | 100 ms                  | A housekeeping interval: on expiry, stale partial messages are purged.                 |
| Deserialization failures | 10                      | Closes the connection; a fully dispatched message resets the count.                    |
| `preamble_timeout`       | 10 seconds              | Bounds a preamble read; on expiry, the failure handler runs and the connection closes. |
| Decode limit             | 16 MiB                  | Bounds peer-declared container lengths in bundled decoders; fixed.                     |
| Memory budgets           | 16, 64, 64 × frame size | See [memory budgets]#per-connection-memory-budgets.                                  |
| Fragmentation            | Off                     | See [fragmentation]#fragmentation.                                                   |

_Table 6: Server limits and their defaults._

**`read_timeout_ms` does not close idle connections**, despite its name. A
quiet peer stays connected until it disconnects or the process exits. Bound
idle time at the protocol level, such as with a heartbeat, or in front of the
server.

There is no built-in Transport Layer Security (TLS), so terminate it upstream.

## Observability

### Logs

Wireframe emits through both `tracing` and `log`. Connection diagnostics, such
as unrouted messages and rejected frames, go through `log`, while `tracing`
events are also forwarded to any installed `log` logger. Wireframe does not
install anything itself, so without a logger or subscriber these messages are
lost. Install one early in start-up:

<!-- tested-example: guide-tracing-subscriber -->
```rust
fn main() {
    tracing_subscriber::fmt().init();
    // Start the application here.
}
```

This needs `tracing-subscriber` in your own dependencies. Its default features
include the bridge that receives `log` records.

### Metrics

With the default `metrics` feature, Wireframe records through the
[`metrics`](https://crates.io/crates/metrics) facade, so any recorder your
application installs receives them. With the feature off, the helpers do
nothing, so instrumentation can stay in place. Prometheus takes two steps,
because the exporter is your dependency:

<!-- tested-example: guide-prometheus-dependency -->
```toml
[dependencies]
metrics-exporter-prometheus = "0.18"
```

<!-- tested-example: guide-prometheus-recorder -->
```rust
use std::time::Duration;

use metrics_exporter_prometheus::PrometheusBuilder;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let prometheus = PrometheusBuilder::new().install_recorder()?;

    // `install_recorder` does not start the exporter's upkeep task, and without
    // it histogram storage grows until a scrape renders it.
    let upkeep_handle = prometheus.clone();
    std::thread::spawn(move || {
        loop {
            std::thread::sleep(Duration::from_secs(5));
            upkeep_handle.run_upkeep();
        }
    });

    // Start the application after installing the recorder, and serve this text
    // however suits your application.
    let _scrape_output = prometheus.render();
    Ok(())
}
```

`PrometheusBuilder::build` and `install` start the upkeep task for you, so use
those if you would rather let the exporter own it. Table 7 lists the server
metrics. Label values are from fixed sets, so application data never becomes a
label.

| Metric                                                    | Kind      | Records                                                  |
| --------------------------------------------------------- | --------- | -------------------------------------------------------- |
| `wireframe_frames_processed_total`                        | Counter   | Frames, by direction.                                    |
| `wireframe_errors_total`                                  | Counter   | Errors, by kind.                                         |
| `wireframe_connection_panics_total`                       | Counter   | Panicking connection tasks.                              |
| `wireframe_decode_rejections_total`                       | Counter   | Decode limit rejections, by path and reason.             |
| `wireframe_preamble_rejections_total`                     | Counter   | Rejected preambles.                                      |
| `wireframe_app_response_sends_total`                      | Counter   | Response send attempts, by `outcome`.                    |
| `wireframe_application_preparations_total`                | Counter   | Preparation attempts, by `outcome`.                      |
| `wireframe_application_preparation_duration_seconds`      | Histogram | Preparation time, by `outcome`.                          |
| `wireframe_prepared_connection_uses_total`                | Counter   | Connections handled by a `PreparedApp`.                  |
| `wireframe_server_startup_failures_total`                 | Counter   | Failed server starts.                                    |
| `wireframe_server_startup_duration_seconds`               | Histogram | Server start time.                                       |
| `wireframe_server_accept_loops_exited_total`              | Counter   | Accept loops that have exited.                           |
| `wireframe_server_supervisor_cancellations_total`         | Counter   | Supervisor cancellations.                                |
| `wireframe_server_supervisor_abnormal_terminations_total` | Counter   | Unexpected supervisor exits.                             |
| `wireframe_connections_active`                            | Gauge     | Accepted connections, and actors you run yourself.       |
| `wireframe_codec_errors_total`                            | Counter   | Decoder failures, by `error_type` and `recovery_policy`. |
| `wireframe_response_cancellations_total`                  | Counter   | Streamed replies cut short, by `reason`.                 |
| `wireframe_push_writes_abandoned_total`                   | Counter   | Pushed frames dropped before delivery, by `reason`.      |
| `wireframe_push_rate_limited_total`                       | Counter   | `try_push` calls refused by the rate limit.              |
| `wireframe_push_drops_total`                              | Counter   | Pushes lost to a drop policy, by `policy` and `outcome`. |

_Table 7: Server metrics._

A connection counts in `wireframe_connections_active` from `accept` until its
task ends, so the gauge covers the preamble and teardown, and is released after
a panic.

The `recovery_policy` label of `wireframe_codec_errors_total` is the policy
that was applied, rather than the one a hook asked for. The cancellation and
abandonment `reason` labels are `idle_grace_expired` and `shutdown`. The
`outcome` of `wireframe_push_drops_total` is `no_dlq`, `dlq_full`, or
`dlq_closed`, and a frame that the dead-letter queue accepted is not counted.

The `outcome` of `wireframe_app_response_sends_total` is one of `success`,
`serialization_failure`, `codec_rejected`, or `transport_failure`. A failed
send also logs a warning with a matching `category`, along with a `stage` of
`serialize` or `write`, so that logs and metrics can be correlated.

#### Streaming body metrics

The `metrics` feature exposes a process-wide
`wireframe_streaming_body_outcomes_total` counter. Its `outcome` label names
delivery (`delivered`), failure reported to the handler (`terminal`), a body or
chunk discarded before completion (`abandoned`), a bounded wait for chunk
admission or failure delivery (`admission_timeout` or `delivery_timeout`), or a
dispatch with no live or registered handler (`no_handler`).

- `wireframe_streaming_body_bytes_queued` measures bytes queued for handlers,
  including bytes reserved by a chunk waiting for channel space. Read it
  alongside `admission_timeout` to detect pressure. Fragment and assembly
  buffers and parked messages can also hold admission back.
- `wireframe_streaming_bodies_parked` counts complete messages waiting behind
  a live body. It can rise when peers pipeline requests, and drops when the
  queue drains or the connection ends.

Neither gauge identifies a connection. The structured events expose `operation`,
`error_category`, and the message ID or assembly key to help correlate
failures. Some delivery events also carry a correlation ID, which a peer can
omit or reuse. A `prefilled_body` warning with `admission_timeout` means a
completed body could not enter the queue in time. A declared-total breach is
rejected during assembly. Payload bytes are excluded from the logs.

## The client runtime

`WireframeClient` uses the same framing and serialization layers as the server,
so both ends of a protocol share one definition.

### Connecting and calling

Align the frame limit with the server's `buffer_capacity`, because the two are
configured separately and a mismatch fails only once a message crosses the
smaller one:

<!-- tested-example: guide-client-connect -->
```rust,no_run
use std::time::Duration;

use wireframe::{
    app::Envelope,
    client::{ClientCodecConfig, SocketOptions, WireframeClient},
    correlation::CorrelatableFrame,
    message::Message,
};

#[derive(bincode::Encode, bincode::BorrowDecode)]
struct Login {
    username: String,
}

#[derive(bincode::Encode, bincode::BorrowDecode)]
struct LoginAck {
    username: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let socket = SocketOptions::default()
        .nodelay(true)
        .keepalive(Some(Duration::from_secs(30)));

    let mut client = WireframeClient::builder()
        .codec_config(ClientCodecConfig::default().max_frame_length(2048))
        .socket_options(socket)
        .connect("127.0.0.1:7878".parse()?)
        .await?;

    let login = Login {
        username: "guest".to_string(),
    };
    let request = Envelope::new(1, None, login.to_bytes()?);
    let response: Envelope = client.call_correlated(request).await?;
    let (ack, _) = LoginAck::from_bytes(response.payload_bytes())?;
    assert_eq!(ack.username, "guest");
    assert!(response.correlation_id().is_some());

    // Dropping the client without `close` skips the teardown hook.
    client.close().await;
    Ok(())
}
```

To try it against a real server, run the echo example and its login client from
a clone of the repository, in two terminals:

<!-- tested-example: guide-run-client-example -->
```bash
cargo run --example echo --features examples
cargo run --example client_echo_login --features examples
```

Table 8 lists what you can configure on the builder.

| Surface            | API                                    | Default                                        | Use when                                             |
| ------------------ | -------------------------------------- | ---------------------------------------------- | ---------------------------------------------------- |
| Serializer         | `serializer(...)`                      | `BincodeSerializer`                            | The protocol uses another encoding.                  |
| Frame codec        | `codec_config(ClientCodecConfig)`      | 4-byte big-endian prefix, 1024-byte frames     | The server's limit differs from the default.         |
| Socket tuning      | `socket_options(SocketOptions)`        | Operating system defaults                      | You need `TCP_NODELAY` or a keepalive policy.        |
| Preamble           | `with_preamble(T)`                     | Disabled                                       | The protocol negotiates before framed traffic.       |
| Preamble timeout   | `preamble_timeout(Duration)`           | Disabled                                       | A stalled handshake should fail fast.                |
| Setup hook         | `on_connection_setup(...)`             | Disabled                                       | You keep per-connection state.                       |
| Teardown hook      | `on_connection_teardown(...)`          | Disabled                                       | Closing should flush or release something.           |
| Error hook         | `on_error(...)`                        | Disabled                                       | Failures should reach your observability.            |
| Before-send hook   | `before_send(...)`                     | Disabled                                       | You inspect or change bytes before they are written. |
| After-receive hook | `after_receive(...)`                   | Disabled                                       | You inspect or change bytes after they are read.     |
| Tracing            | `tracing_config(TracingConfig)`        | INFO connect and close, DEBUG data; timing off | You want other span levels, or per-command timing.   |
| Pool               | `connect_pool(addr, ClientPoolConfig)` | Disabled; needs the `pool` feature             | You want reusable sockets and bounded fan-out.       |

_Table 8: Client builder configuration._

Call `with_preamble` before `preamble_timeout`, or the timeout is ignored.

For screen readers: the following sequence diagram shows the client lifecycle:
connect, optional preamble exchange, message exchange, error handling, and
teardown.

<!-- tested-example: guide-client-lifecycle -->
```mermaid
sequenceDiagram
    participant App as Application
    participant Builder as WireframeClientBuilder
    participant Stream as TcpStream
    participant Hooks as Client hooks
    App->>Builder: connect(addr)
    Builder->>Stream: apply socket options + connect
    alt preamble configured
        Builder->>Stream: write/read preamble
        Builder->>Builder: preamble success/failure callbacks
    end
    Builder->>Hooks: on_connection_setup
    App->>Stream: send / receive / call / call_correlated
    App->>Hooks: on_error (if operation fails)
    App->>Builder: close()
    Builder->>Hooks: on_connection_teardown
```

_Figure 2: The client connection lifecycle._

### Correlated messages

The client works at two levels. `send`, `receive`, and `call` handle message
types directly. The envelope-aware methods work with any `Packet`, and generate
correlation identifiers from a per-client counter, which `next_correlation_id`
also exposes:

- `send_envelope` sends, generating an identifier if none is set, and returns
  it.
- `receive_envelope` reads the next frame as a packet.
- `call_correlated` does both, and returns `ClientError::CorrelationMismatch`
  if the identifiers differ.

Use `send_envelope` and `receive_envelope` separately when you want more
control:

<!-- tested-example: guide-client-correlation -->
```rust,no_run
use wireframe::{
    app::Envelope,
    client::{ClientError, WireframeClient},
    correlation::CorrelatableFrame,
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut client = WireframeClient::builder()
        .connect("127.0.0.1:7878".parse()?)
        .await?;

    let correlation_id = client.send_envelope(Envelope::new(1, None, b"payload".to_vec())).await?;
    let response: Envelope = client.receive_envelope().await?;
    assert_eq!(response.correlation_id(), Some(correlation_id));

    let outcome: Result<Envelope, ClientError> = client.call_correlated(Envelope::new(1, None, vec![])).await;
    match outcome {
        Ok(response) => println!("{} bytes", response.payload_bytes().len()),
        Err(ClientError::CorrelationMismatch { expected, received }) => {
            eprintln!("expected {expected:?}, received {received:?}");
        }
        Err(other) => eprintln!("request failed: {other}"),
    }
    Ok(())
}
```

### Client preamble exchange

`with_preamble` sends a preamble immediately after connecting. To read the
server's answer, use `on_preamble_success`, which must return any bytes it read
beyond that answer so that they can be replayed to the framing layer:

<!-- tested-example: guide-client-preamble -->
```rust,no_run
use std::time::Duration;

use futures::FutureExt;
use wireframe::{client::WireframeClient, preamble::read_preamble};

#[derive(bincode::Encode, bincode::BorrowDecode)]
struct ClientHello {
    version: u16,
}

#[derive(bincode::BorrowDecode)]
struct ServerAck {
    accepted: bool,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = WireframeClient::builder()
        .with_preamble(ClientHello { version: 1 })
        .preamble_timeout(Duration::from_secs(5))
        .on_preamble_success(|_preamble, stream| {
            async move {
                let (ack, leftover) = read_preamble::<_, ServerAck>(stream)
                    .await
                    .map_err(std::io::Error::other)?;
                if !ack.accepted {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::ConnectionRefused,
                        "server rejected preamble",
                    ));
                }
                Ok(leftover)
            }
            .boxed()
        })
        .on_preamble_failure(|error, _stream| {
            async move {
                eprintln!("preamble exchange failed: {error}");
                Ok(())
            }
            .boxed()
        })
        .connect("127.0.0.1:7878".parse()?)
        .await?;
    client.close().await;
    Ok(())
}
```

Failures surface as `ClientError::PreambleTimeout` when the deadline passes,
`ClientError::PreambleRead` when your callback cannot read or decode the
answer, and `ClientError::PreambleEncode` when encoding or writing fails.
`ClientError::PreambleWrite` exists, but the current client never returns it.

### Lifecycle and request hooks

Lifecycle hooks mirror the server's. Setup runs after connecting and any
preamble, and its state goes to teardown when you call `close()`. Dropping a
client without calling `close()` skips teardown. Register setup first, because
it resets the teardown hook.

The error hook sees failures from `send`, `receive`, and `call` operations. It
does not see failures from connecting or from the preamble, because the client
does not exist yet, or errors yielded by a `ResponseStream`.

Request hooks run on bytes. They are synchronous, so capture an `Arc` for any
mutable state, and several of a kind run in the order they were registered:

<!-- tested-example: guide-client-hooks -->
```rust,no_run
use std::sync::{
    Arc,
    atomic::{AtomicUsize, Ordering},
};

use wireframe::client::WireframeClient;

struct Session {
    requests: AtomicUsize,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let sent = Arc::new(AtomicUsize::new(0));
    let received = Arc::new(AtomicUsize::new(0));
    let (sent_counter, received_counter) = (Arc::clone(&sent), Arc::clone(&received));

    let client = WireframeClient::builder()
        .on_connection_setup(|| async {
            Session {
                requests: AtomicUsize::new(0),
            }
        })
        .on_connection_teardown(|session: Session| async move {
            println!("session ended after {} requests", session.requests.load(Ordering::SeqCst));
        })
        .on_error(|error| {
            let message = error.to_string();
            async move { eprintln!("client error: {message}") }
        })
        .before_send(move |_bytes: &mut Vec<u8>| {
            sent_counter.fetch_add(1, Ordering::SeqCst);
        })
        .after_receive(move |_bytes: &mut bytes::BytesMut| {
            received_counter.fetch_add(1, Ordering::SeqCst);
        })
        .connect("127.0.0.1:7878".parse()?)
        .await?;

    client.close().await;
    Ok(())
}
```

Request hooks fire on `send`, `send_envelope`, `call`, `call_correlated`, the
request in `call_streaming`, `receive`, `receive_envelope`, and
`ResponseStream` polling. Frames from `send_streaming` bypass `before_send`.

### Tracing the client

The client emits `tracing` spans around connection and message operations:
`INFO` for `connect` and `close`, and `DEBUG` for `send`, `receive`, `call`, and
`call_streaming`. `send_streaming` and `receive_streaming` create no spans.
Without a subscriber these cost next to nothing:

<!-- tested-example: guide-client-tracing -->
```rust,no_run
use tracing::Level;
use wireframe::client::{TracingConfig, WireframeClient};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = TracingConfig::default()
        .with_all_levels(Level::TRACE)
        .with_connect_timing(true)
        .with_call_timing(true);

    let client = WireframeClient::builder()
        .tracing_config(config)
        .connect("127.0.0.1:7878".parse()?)
        .await?;
    client.close().await;
    Ok(())
}
```

With timing enabled, an operation emits a `DEBUG` event carrying `elapsed_us`,
on success and on failure. For `call_streaming`, that time ends when the
request has been written, not when the stream ends. Streams also emit
`stream.frames_received` per frame, and `stream.frames_total` when a terminator
arrives.

### Sending large bodies

`send_streaming` sends a body as many frames, prepending your protocol's header
to each chunk:

<!-- tested-example: guide-client-send-streaming -->
```rust,no_run
use std::time::Duration;

use wireframe::client::{SendStreamingConfig, WireframeClient};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut client = WireframeClient::builder()
        .connect("127.0.0.1:7878".parse()?)
        .await?;

    let header = [0xCA, 0xFE, 0xBA, 0xBE];
    let body = vec![0_u8; 4096];
    let config = SendStreamingConfig::default()
        .with_chunk_size(512)
        .with_timeout(Duration::from_secs(5));

    let outcome = client.send_streaming(&header, &body[..], config).await?;
    println!("sent {} frames", outcome.frames_sent());
    Ok(())
}
```

Without `with_chunk_size`, chunks fill `max_frame_length` less the header, and
an oversized chunk is clamped to that. A chunk size of zero, or a header at
least as long as `max_frame_length`, returns `InvalidInput`. `with_timeout`
bounds the whole operation. On expiry you get
`ClientError::Wireframe(WireframeError::Io(_))` with kind `TimedOut`, and
frames already sent remain sent, so assume partial success. The write side is
then shut down, so do not reuse that connection.

### Reading streamed replies

A server reply can span many frames, ending in a terminator. Teach the client
to recognize yours by overriding `Packet::is_stream_terminator`. **The bundled
`Envelope` has no terminator**, so a stream of `Envelope` values only ends when
the connection does, with an `UnexpectedEof` error.

`call_streaming` sends a request and returns a `ResponseStream`:

<!-- tested-example: guide-client-call-streaming -->
```rust
use futures::{SinkExt, StreamExt};
use tokio::net::TcpListener;
use tokio_util::codec::{Framed, LengthDelimitedCodec};
use wireframe::{
    app::{Packet, PacketParts},
    client::WireframeClient,
    correlation::CorrelatableFrame,
    message::Message,
};

/// An envelope whose message ID 0 means "end of stream".
#[derive(bincode::Encode, bincode::BorrowDecode)]
struct Row {
    id: u32,
    correlation_id: Option<u64>,
    payload: Vec<u8>,
}

impl CorrelatableFrame for Row {
    fn correlation_id(&self) -> Option<u64> { self.correlation_id }

    fn set_correlation_id(&mut self, id: Option<u64>) { self.correlation_id = id; }
}

impl Packet for Row {
    fn id(&self) -> u32 { self.id }

    fn into_parts(self) -> PacketParts {
        PacketParts::new(self.id, self.correlation_id, self.payload)
    }

    fn from_parts(parts: PacketParts) -> Self {
        Self {
            id: parts.id(),
            correlation_id: parts.correlation_id(),
            payload: parts.into_payload(),
        }
    }

    fn is_stream_terminator(&self) -> bool { self.id == 0 }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // To keep the wire format in plain sight, this stand-in for a server speaks
    // the same framing with plain Tokio.
    let listener = TcpListener::bind("127.0.0.1:0").await?;
    let address = listener.local_addr()?;
    tokio::spawn(async move {
        let (socket, _) = listener.accept().await.expect("a connection");
        let mut framed = Framed::new(socket, LengthDelimitedCodec::new());
        let bytes = framed.next().await.expect("a request").expect("a frame");
        let (request, _) = Row::from_bytes(&bytes).expect("a valid request");
        for (id, body) in [(1, "first"), (1, "second"), (0, "")] {
            let row = Row {
                id,
                correlation_id: request.correlation_id,
                payload: body.as_bytes().to_vec(),
            };
            let encoded = row.to_bytes().expect("a row encodes");
            framed
                .send(bytes::Bytes::from(encoded))
                .await
                .expect("the client is listening");
        }
    });

    let mut client = WireframeClient::builder().connect(address).await?;
    let request = Row {
        id: 1,
        correlation_id: None,
        payload: vec![],
    };

    let mut rows = client.call_streaming::<Row>(request).await?;
    let mut bodies = Vec::new();
    while let Some(row) = rows.next().await {
        bodies.push(String::from_utf8(row?.payload)?);
    }
    assert_eq!(bodies, ["first", "second"]);
    Ok(())
}
```

If you have already sent the request with `send_envelope`, `receive_streaming`
takes its correlation identifier and returns the same kind of stream. The
stream borrows the client exclusively while it exists. Dropping it releases
that borrow, but does not drain unread response frames. In particular, a later
`call_streaming` can encounter the earlier response's unchecked terminator and
appear to end immediately. Drain the stream through its terminator before
reusing the client. If you abandon the stream, or it yields an error before the
terminator, close the client and reconnect before sending another request.

The stream checks the identifier on every data frame, yielding
`ClientError::StreamCorrelationMismatch` and ending if one differs. The
terminator is not checked, so any terminator ends the stream cleanly. Transport
and decode failures arrive as `ClientError::Wireframe`.

For protocols that interleave data with notices,
`StreamingResponseExt::typed_with` maps each frame to
`Result<Option<Item>, ClientError>`: `Some` yields an item, `None` skips the
frame, and an error ends the stream:

<!-- tested-example: guide-client-typed-with -->
```rust,no_run
use futures::TryStreamExt;
use wireframe::{
    app::{Packet, PacketParts},
    client::{ClientError, StreamingResponseExt, WireframeClient},
    correlation::CorrelatableFrame,
};

#[derive(bincode::BorrowDecode, bincode::Encode)]
struct Frame {
    id: u32,
    correlation_id: Option<u64>,
    payload: Vec<u8>,
}

impl CorrelatableFrame for Frame {
    fn correlation_id(&self) -> Option<u64> { self.correlation_id }

    fn set_correlation_id(&mut self, id: Option<u64>) { self.correlation_id = id; }
}

impl Packet for Frame {
    fn id(&self) -> u32 { self.id }

    fn into_parts(self) -> PacketParts {
        PacketParts::new(self.id, self.correlation_id, self.payload)
    }

    fn from_parts(parts: PacketParts) -> Self {
        Self {
            id: parts.id(),
            correlation_id: parts.correlation_id(),
            payload: parts.into_payload(),
        }
    }

    fn is_stream_terminator(&self) -> bool { self.id == 0 }
}

struct Row(Vec<u8>);

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut client = WireframeClient::builder()
        .connect("127.0.0.1:9000".parse()?)
        .await?;
    let request = Frame {
        id: 1,
        correlation_id: None,
        payload: vec![],
    };

    let rows: Vec<Row> = client
        .call_streaming::<Frame>(request)
        .await?
        .typed_with(|frame| match frame.id {
            1 => Ok(Some(Row(frame.payload))),
            2 => Ok(None), // A progress notice, which this caller ignores.
            other => Err(ClientError::from(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("unexpected frame id {other}"),
            ))),
        })
        .try_collect()
        .await?;

    println!("received {} rows", rows.len());
    Ok(())
}
```

Back-pressure comes from TCP flow control: if you read slowly, the receive
window shrinks and the sender's writes eventually wait. No flow-control
messages are involved.

### Client pools

Enable the `pool` feature to use `connect_pool`. A pool keeps a bounded set of
reusable sockets, each **opened on first use**, so `connect_pool` and `acquire`
can succeed with the server down, and the first operation is what reports it:

<!-- tested-example: guide-client-pool -->
```rust,no_run
use std::time::Duration;

use wireframe::client::{ClientPoolConfig, PoolFairnessPolicy, PoolHandle, WireframeClient};

#[derive(bincode::Encode, bincode::Decode, Debug, PartialEq)]
struct Ping(u8);

#[derive(bincode::Encode, bincode::Decode, Debug, PartialEq)]
struct Pong(u8);

#[tokio::main]
async fn main() -> Result<(), wireframe::client::ClientError> {
    let address = "127.0.0.1:7878".parse().expect("a valid address");
    let pool = WireframeClient::builder()
        .connect_pool(
            address,
            ClientPoolConfig::default()
                .pool_size(2)
                .max_in_flight_per_socket(2)
                .idle_timeout(Duration::from_secs(30))
                .fairness_policy(PoolFairnessPolicy::RoundRobin),
        )
        .await?;

    // A lease suits one piece of work.
    let lease = pool.acquire().await?;
    let pong: Pong = lease.call(&Ping(1)).await?;
    assert_eq!(pong, Pong(1));
    drop(lease);

    // A handle suits a long-lived session that should take fair turns.
    let mut session: PoolHandle<_, _, _> = pool.handle();
    let pong: Pong = session.call(&Ping(2)).await?;
    assert_eq!(pong, Pong(2));

    pool.close().await;
    Ok(())
}
```

Table 9 lists the settings. The `Fifo` fairness policy serves waiting handles
in the order they blocked, whereas `RoundRobin`, the default, rotates among
them.

| Setting                    | Default      | Meaning                                                 |
| -------------------------- | ------------ | ------------------------------------------------------- |
| `pool_size`                | 4            | Sockets to maintain.                                    |
| `max_in_flight_per_socket` | 1            | Callers admitted per socket, not parallel writes on it. |
| `max_waiters`              | 64           | Acquisitions that may wait; 0 is treated as 1.          |
| `idle_timeout`             | 600 s        | Replace a socket idle for this long.                    |
| `fairness_policy`          | `RoundRobin` | How blocked handles take turns.                         |

_Table 9: Client pool settings._

Some behaviour worth knowing:

- **Leases forward requests** rather than exposing a client. Socket I/O stays
  serialized per connection. `max_in_flight_per_socket` is an admission budget.
- **Use a lease for split-phase work**, such as `send` followed by `receive`.
  The slot is reserved until `receive` finishes, and calling `call` on that
  lease in between fails and discards the socket. `PoolHandle` does not pin a
  session to one socket, and does not demultiplex responses.
- **Interrupted work discards the socket**, so a late response cannot reach the
  next caller. This covers a cancelled operation and a lease dropped before its
  reply was read. The next operation reconnects.
- **Preambles and setup hooks run per socket.** Reuse keeps preamble state, and
  replacing a socket runs them again.
- **Slots rotate.** Each acquisition starts one slot further round and skips
  full slots. If all are full, it waits.
- **Saturation is immediate.** Once `max_waiters` is reached, `acquire` returns
  `ClientError::PoolSaturated { limit }`. No socket is affected, so retrying
  later is fine.
- **Closing** rejects new acquisitions with `ClientError::PoolClosed`, resolves
  queued ones the same way, and waits for the scheduler task. Existing leases
  are not revoked, and keep their sockets alive until dropped. If the scheduler
  died, you get `ClientError::SchedulerFailed`. Neither error means a socket is
  dirty, and neither is retried automatically.

### Client pool metrics

Table 10 lists the metrics, all with fixed labels, so they never identify slots
or callers.

| Metric                                               | Kind      | Labels and meaning                                                                            |
| ---------------------------------------------------- | --------- | --------------------------------------------------------------------------------------------- |
| `wireframe_pool_acquisitions_total`                  | Counter   | `mode` (`immediate`, `permit_race`), `outcome` (`granted`, `exhausted`, `shutdown`, `error`). |
| `wireframe_pool_permit_races_started_total`          | Counter   | A blocked race began, because every slot was busy.                                            |
| `wireframe_pool_permit_races_total`                  | Counter   | `outcome` (`granted`, `shutdown`, `error`, `cancelled`).                                      |
| `wireframe_pool_permit_race_duration_seconds`        | Histogram | Time spent blocked, by the same `outcome`.                                                    |
| `wireframe_pool_connection_discards_total`           | Counter   | Sockets discarded, by `reason`. Watch this for socket churn.                                  |
| `wireframe_pool_scheduler_failures_total`            | Counter   | Abnormal scheduler exits.                                                                     |
| `wireframe_pool_bookkeeping_poison_recoveries_total` | Counter   | Recoveries from poisoned internal locks.                                                      |

_Table 10: Client pool metrics._

A rising `exhausted` rate means work is arriving faster than permits can serve
it. Dropping your own `acquire()` future does not end a race, which still
records `granted`, so `cancelled` appears only when a pool and all its handles
are dropped without `close()` in the middle of a race. Compare started and
finished races to find any that stay active.

## Streaming responses and server pushes

A request does not have to produce exactly one frame, and a server does not
have to wait to be asked. This section covers replies made of many frames,
frames the server sends unprompted, and what happens when a frame cannot be
decoded.

For large uploads, see
[streaming request body consumption](#streaming-request-body-consumption).

### Response-producing routes

`route_response` registers a handler that returns a `Response`. Table 11 lists
what that can be.

| Variant                 | Sends                                               |
| ----------------------- | --------------------------------------------------- |
| `Response::Single`      | One frame.                                          |
| `Response::Vec`         | Each frame in the vector.                           |
| `Response::Empty`       | Nothing.                                            |
| `Response::Stream`      | Each frame a stream yields, then your terminator.   |
| `Response::MultiPacket` | Each frame sent to a channel, then your terminator. |

_Table 11: The kinds of response._

For a handler that only computes a reply, this takes less code than middleware:

<!-- tested-example: guide-response-route -->
```rust
use std::sync::Arc;

use wireframe::{
    app::{Envelope, ResponseHandler, WireframeApp},
    client::WireframeClient,
    response::Response,
    server::WireframeServer,
};

const SUM: u32 = 1;

fn sum() -> ResponseHandler<Envelope> {
    Arc::new(|request: &Envelope| {
        let total = request.payload_bytes().iter().copied().fold(0, u8::wrapping_add);
        Box::pin(async move { Response::Single(Envelope::new(SUM, None, vec![total])) })
    })
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let app: WireframeApp = WireframeApp::new()?.route_response(SUM, sum())?;
    let server = WireframeServer::from_app(app).bind("127.0.0.1:0".parse()?)?;
    let address = server.local_addr().expect("a bound server has an address");
    let shutdown = server.spawn().await?;

    let mut client = WireframeClient::builder().connect(address).await?;
    let request = Envelope::new(SUM, None, vec![1, 2, 3]);
    let response: Envelope = client.call_correlated(request).await?;
    assert_eq!(response.payload_bytes(), [6]);

    client.close().await;
    shutdown.stop();
    shutdown.drained().await?;
    Ok(())
}
```

Unlike a `route` handler, this one's future may borrow the request. Frames are
`Envelope` values whatever request type you use. Each inherits the request's
correlation identifier; a frame that names a different one is overwritten, with
a warning. If the request has none, frames keep their own.

A streamed reply ends on the wire only if your protocol says how. Install a
`WireframeProtocol` whose `stream_end_frame` returns a terminator, or a client
will wait for one that never comes. `async-stream` is a convenient way to write
the stream, and goes in your own dependencies:

<!-- tested-example: guide-response-route-stream -->
```rust
use std::sync::Arc;

use bytes::Bytes;
use wireframe::{
    app::{Envelope, ResponseHandler, WireframeApp},
    codec::{FrameCodec, LengthDelimitedFrameCodec},
    hooks::{ConnectionContext, WireframeProtocol},
    response::{FrameStream, Response},
    serializer::{BincodeSerializer, Serializer},
};

const ROWS: u32 = 1;
const END_OF_STREAM: u32 = 0;

struct Rows;

impl WireframeProtocol for Rows {
    type Frame = Bytes;
    type ProtocolError = ();

    fn stream_end_frame(&self, _context: &mut ConnectionContext) -> Option<Bytes> {
        // A terminator is a complete codec frame, because it is written as it is.
        let end = Envelope::new(END_OF_STREAM, None, vec![]);
        let payload = BincodeSerializer.serialize(&end).ok()?;
        Some(LengthDelimitedFrameCodec::new(1024).wrap_payload(Bytes::from(payload)))
    }
}

fn rows() -> ResponseHandler<Envelope> {
    Arc::new(|_request: &Envelope| {
        Box::pin(async {
            let frames: FrameStream<Envelope, ()> = Box::pin(async_stream::try_stream! {
                for row in ["first", "second"] {
                    yield Envelope::new(ROWS, None, row.as_bytes().to_vec());
                }
            });
            Response::Stream(frames)
        })
    })
}

fn main() -> wireframe::Result<()> {
    let app: WireframeApp = WireframeApp::new()?.route_response(ROWS, rows())?;
    let _app = app.with_protocol(Rows);
    Ok(())
}
```

A client reads this with [`call_streaming`](#reading-streamed-replies). Some
behaviour to rely on:

- **Replies are serial.** A connection finishes one reply before it dispatches
  the next request. At most one further request is read ahead.
- **Back-pressure reaches the producer.** Each write is awaited before the
  stream is polled again, so a slow peer slows the stream, and a bounded
  channel makes its senders wait.
- **The terminator is not stamped.** It skips fragmentation and serialization,
  and keeps whatever correlation identifier you gave it. `before_send` still
  sees it, and may change it.
- **A protocol error ends the connection.** If the stream yields one,
  `handle_error` receives it, and no terminator is sent.
- **A silent producer is bounded once the peer cannot be observed.** After the
  peer closes its sending half, or a further request has been read ahead, each
  wait for the next frame is limited to 30 seconds. On expiry the reply is
  cancelled without a terminator, and the connection closes.

Middleware wraps these routes too, but the reply travels separately from the
response bytes. `frame()` is therefore empty after the handler runs, and
editing it changes nothing. Middleware that answers without calling the
handler, or returns a new `ServiceResponse`, replaces the whole reply.

### Building streams and channels

`into_stream` turns any `Response` into a `FrameStream`, which is also a handy
way to test a producer by itself:

<!-- tested-example: guide-response-stream -->
```rust
use async_stream::try_stream;
use futures::TryStreamExt;
use wireframe::response::{FrameStream, Response};

#[derive(Debug, PartialEq)]
struct Frame(u32);

#[tokio::main]
async fn main() {
    let frames: FrameStream<Frame> = Box::pin(try_stream! {
        for value in 0..3 {
            yield Frame(value);
        }
    });
    let response = Response::Stream(frames);

    let collected: Vec<Frame> = response.into_stream().try_collect().await.expect("frames");
    assert_eq!(collected, [Frame(0), Frame(1), Frame(2)]);
}
```

`Response::with_channel` returns a sender and a `Response::MultiPacket`. The
sender waits for room in the channel, which bounds the producer against
whatever is consuming the response. Dropping the last sender ends it:

<!-- tested-example: guide-response-channel -->
```rust
use futures::TryStreamExt;
use wireframe::response::Response;

#[derive(Debug, PartialEq)]
struct Vertex(u32);

#[tokio::main]
async fn main() {
    let (sender, response) = Response::<Vertex>::with_channel(2);

    let producer = tokio::spawn(async move {
        for value in 1..=5 {
            if sender.send(Vertex(value)).await.is_err() {
                return; // The receiver has gone, so stop producing.
            }
        }
    });

    let frames: Vec<Vertex> = response.into_stream().try_collect().await.expect("frames");
    producer.await.expect("the producer finished");
    assert_eq!(frames.len(), 5);
}
```

`Response`, `FrameStream`, and `ConnectionActor` default their protocol error to
`NoProtocolError`, so name the parameter only when a stream carries protocol
failures of its own. `WireframeError` then distinguishes transport failures
from protocol ones. A `route_response` handler is one such case: it uses `()`,
to match the protocol installed with `with_protocol`.

### The connection actor

Every server connection owns a private `ConnectionActor`, which merges its
replies and pushes, and you configure it through the application. Drive one
yourself only if you have a transport Wireframe does not manage. `run` then
collects frames into a `Vec`, and it is up to you to write them somewhere, so
back-pressure reaches your socket only if your write path provides it:

<!-- tested-example: guide-connection-actor -->
```rust
use futures::{StreamExt, stream};
use tokio_util::sync::CancellationToken;
use wireframe::{
    app::{Envelope, Packet},
    connection::ConnectionActor,
    push::PushQueues,
};

#[tokio::main]
async fn main() {
    let (queues, handle) = PushQueues::<Envelope>::builder()
        .high_capacity(8)
        .low_capacity(8)
        .build()
        .expect("valid capacities");

    handle.push_low_priority(Envelope::new(30, None, vec![])).await.expect("queued");
    handle.push_high_priority(Envelope::new(10, None, vec![])).await.expect("queued");

    let reply = stream::iter(vec![Ok(Envelope::new(20, Some(1), vec![]))]).boxed();
    let mut actor: ConnectionActor<Envelope, ()> =
        ConnectionActor::new(queues, handle, Some(reply), CancellationToken::new());

    let mut out = Vec::new();
    actor.run(&mut out).await.expect("the actor drains");
    let mut ids: Vec<u32> = out.iter().map(Envelope::id).collect();
    ids.sort_unstable();
    assert_eq!(ids, [10, 20, 30]);
}
```

Pass a `FairnessConfig` to `set_fairness` to stop sustained high-priority
traffic from starving low-priority frames, and call `enable_fragmentation` to
fragment its output, which is the outbound half only. An actor you drive runs
the hooks you give it through `with_hooks`, and differs from a server
connection in one respect: it stamps its terminator with the request's
identifier if you use `set_multi_packet_with_correlation`, and plain
`set_multi_packet` leaves frames with their own. A frame with a different
identifier from the request is overwritten, with a warning.

A multi-packet channel can end as `drained`, `disconnected`, or `shutdown`. The
first two send the terminator through `before_send`. On `shutdown`, the actor
logs the reason and sends none.

`active_connection_count()` counts accepted connections and the actors you
drive, as `wireframe_connections_active` does.

### Server connections and push queues

Every server connection has push queues, so a server can send frames that no
request asked for. The handle for a connection reaches you in two ways: your
protocol receives it in `on_connection_setup`, and a
[session registry](#session-registry) lets any task look it up:

<!-- tested-example: guide-server-push -->
```rust
use std::{sync::Arc, time::Duration};

use bytes::Bytes;
use wireframe::{
    app::{Envelope, WireframeApp},
    client::WireframeClient,
    codec::{FrameCodec, LengthDelimitedFrameCodec},
    push::PushQueues,
    serializer::{BincodeSerializer, Serializer},
    server::WireframeServer,
    session::SessionRegistry,
};

const NEWS: u32 = 7;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let registry = Arc::new(SessionRegistry::<Bytes>::new());
    let app: WireframeApp = WireframeApp::new()?
        .with_push_queues(PushQueues::<Bytes>::builder().high_capacity(8).low_capacity(32))
        .with_session_registry(Arc::clone(&registry));

    let server = WireframeServer::from_app(app).bind("127.0.0.1:0".parse()?)?;
    let address = server.local_addr().expect("a bound server has an address");
    let shutdown = server.spawn().await?;

    // This client sends nothing. It waits to be told.
    let mut client = WireframeClient::builder().connect(address).await?;
    while registry.active_ids().is_empty() {
        tokio::time::sleep(Duration::from_millis(5)).await;
    }

    // A push is a codec frame, so serialize the envelope and wrap it.
    let news = Envelope::new(NEWS, None, b"hello".to_vec());
    let payload = Bytes::from(BincodeSerializer.serialize(&news).expect("an envelope encodes"));
    let frame = LengthDelimitedFrameCodec::new(1024).wrap_payload(payload);
    for (_id, handle) in registry.active_handles() {
        handle.push_low_priority(frame.clone()).await?;
    }

    let received: Envelope = client.receive_envelope().await?;
    assert_eq!(received.payload_bytes(), b"hello");

    client.close().await;
    shutdown.stop();
    shutdown.drained().await?;
    Ok(())
}
```

`with_push_queues` takes a template that is cloned for each connection, so each
has its own capacity, rate limit, and dead-letter routing, and one busy
connection never delays another. An unusable template fails when the
application is prepared. Pushes are written alongside replies, and between the
frames of a streamed one, with high priority first, and each passes through
`before_send`.

Pushes too large for the codec are refused with `PushError::FrameTooLarge` when
you queue them. A `before_send` hook that enlarges a frame afterwards is not
checked again until the frame is encoded, when it ends the connection.

#### Pushes, closing, and shutdown

- **When a client closes cleanly**, the connection tries to write what is
  already queued, high priority first. It does not wait for producers still
  holding a reservation, whose pushes fail with `PushError::Closed`. A write
  that fails, or that the peer accepts nothing of for 30 seconds, abandons the
  frames behind it.
- **When the server stops**, frames not yet written may be discarded, and later
  pushes fail with `PushError::Closed`. While a handler is running, its
  connection accepts pushes until it has delivered one batch, and even those
  may be abandoned if the peer is not reading.

An accepted push is therefore not a delivery receipt. If a message must arrive,
have your protocol acknowledge it.

### Push queues

`PushQueues` holds outbound frames at two priorities. Capacities default to 1,
and rate limiting is **on** by default at 100 pushes per second, so configure
both:

<!-- tested-example: guide-push-queues -->
```rust
use tokio::sync::mpsc;
use wireframe::push::PushQueues;

let (dead_letters, _dead_letter_receiver) = mpsc::channel(8);
let (_queues, _handle) = PushQueues::<u8>::builder()
    .high_capacity(8)
    .low_capacity(8)
    .rate(Some(100))
    .dlq(Some(dead_letters))
    .build()
    .expect("valid configuration");

// `unlimited` removes the rate limit.
let (_queues, _handle) = PushQueues::<u8>::builder()
    .high_capacity(8)
    .low_capacity(8)
    .unlimited()
    .build()
    .expect("valid configuration");
```

`build` rejects a zero capacity (`PushConfigError::InvalidCapacity`), and a
rate of zero or above `MAX_PUSH_RATE` (`PushConfigError::InvalidRate`).

`push_high_priority` and `push_low_priority` wait for channel capacity, then
for the rate limit. `try_push` shares that limit but never waits. It returns
`PushError::RateLimited` if there is room but no permit, and otherwise applies a
`PushPolicy` to a full queue, optionally warning and forwarding to the
dead-letter queue (DLQ). **`DropIfFull` without a DLQ loses frames, and tells
the producer it succeeded.** `wireframe_push_drops_total` is how you find out.

If the DLQ is itself full or closed, a throttled `DLQ dropped frames` warning
reports how many frames were lost since the last report, along with the DLQ's
state and the frame's priority, policy, and Rust type, but never its contents.
`dlq_log_every_n` and `dlq_log_interval` set the cadence. Only frames that the
DLQ accepted reach its receiver, and you must consume them from there to
inspect them.

The older `WireframeApp::with_push_dlq` is deprecated, and its sink receives
nothing. Give the queue template a `dlq` sender instead.

When you own the queues yourself, `PushQueues::recv` always prefers the
high-priority queue, so it can starve the low-priority one. Fairness exists
only inside `ConnectionActor`. `close` releases resources when no actor is
running.

### Compile-time queue and session configuration

All of the queue builder's setters except `dlq` are `const fn`, so a chain can
run inside a `const fn`, although the builder itself is created at run time.
The frame parameter needs only `Send + 'static`:

<!-- tested-example: guide-const-push-builder -->
```rust
use std::time::Duration;

use wireframe::push::PushQueuesBuilder;

const fn configure<F: Send + 'static>(builder: PushQueuesBuilder<F>) -> PushQueuesBuilder<F> {
    builder
        .high_capacity(8)
        .low_capacity(4)
        .rate(Some(64))
        .dlq_log_interval(Duration::from_secs(5))
}

let builder = configure(PushQueuesBuilder::<Vec<u8>>::default());
drop(builder);
```

`ConnectionId::{new, as_u64}`, `LengthDelimitedFrameCodec::max_frame_length`,
`WireframeError::{from_io, from_codec}`, and `WireframeError::is_clean_close`
are `const` too. See also
[Compile-time configuration](#compile-time-configuration).

### Session registry

`SessionRegistry` stores weak references to `PushHandle` values by
`ConnectionId`, so a background task can find a connection without keeping it
alive. Server connections add themselves before `on_connection_setup` runs, and
leave when their task ends, however it ends. Share a registry with
`with_session_registry`, or take the application's own from
`session_registry()` before you hand the application to the server.

Identifiers start at 1, increase, and are never reused. Use the one a
connection publishes, from `ConnectionContext::connection_id` or
`active_handles`, rather than choosing one. If you keep entries of your own,
prefer a separate registry. `insert` returns `false` instead of displacing a
live entry, and `allocate_and_publish` claims an identifier and inserts in one
step. Dead entries are pruned on lookup and by `active_handles`. `prune`
removes them without collecting handles. Its `DashMap` holds per-bucket locks
while it does this, so busy systems may prefer running it from a maintenance
task:

<!-- tested-example: guide-session-registry -->
```rust
use wireframe::{
    push::PushQueues,
    session::{ConnectionId, SessionRegistry},
};

let (queues, handle) = PushQueues::<u8>::builder()
    .high_capacity(1)
    .low_capacity(1)
    .build()
    .expect("valid capacities");

let registry: SessionRegistry<u8> = SessionRegistry::default();
let id = ConnectionId::new(42);
assert!(registry.insert(id, &handle));
assert!(registry.get(&id).is_some());

drop((queues, handle));
assert!(registry.get(&id).is_none(), "a closed connection leaves no handle behind");
```

### Codec recovery policies

A decoder failure closes the connection unless you install a
`RecoveryPolicyHook`. With one, you choose what happens to each failure:

<!-- tested-example: guide-recovery-hook -->
```rust
use std::time::Duration;

use wireframe::{
    app::WireframeApp,
    codec::{CodecError, CodecErrorContext, RecoveryConfig, RecoveryPolicy, RecoveryPolicyHook},
};

struct Patient;

impl RecoveryPolicyHook for Patient {
    fn recovery_policy(&self, error: &CodecError, _context: &CodecErrorContext) -> RecoveryPolicy {
        match error {
            CodecError::Protocol(_) => RecoveryPolicy::Quarantine,
            other => other.default_recovery_policy(),
        }
    }

    fn quarantine_duration(&self, _error: &CodecError, _context: &CodecErrorContext) -> Duration {
        Duration::from_secs(5)
    }

    fn on_error(&self, error: &CodecError, context: &CodecErrorContext, applied: RecoveryPolicy) {
        tracing::warn!(%error, peer = ?context.peer_address, ?applied, "undecodable frame");
    }
}

let app: WireframeApp = WireframeApp::new().expect("builder");
let _app = app
    .with_recovery_hook(Patient)
    .recovery_config(RecoveryConfig::default().max_consecutive_drops(3));
```

`Drop` discards the frame and reads on, `Quarantine` pauses before reading on,
and `Disconnect` closes the connection. If you do not override
`recovery_policy`, it uses `default_recovery_policy`, as shown in Table 12.

| Error                          | Default policy |
| ------------------------------ | -------------- |
| `FramingError::OversizedFrame` | Drop           |
| `FramingError::EmptyFrame`     | Drop           |
| Other `FramingError`           | Disconnect     |
| Any `ProtocolError`            | Drop           |
| Any I/O error                  | Disconnect     |
| Any `EofError`                 | Disconnect     |

_Table 12: The policies from `default_recovery_policy`._

Your choice is escalated to `Disconnect` in three cases, because reading on
could not help:

- the failure came from `decode_eof`, so the peer has stopped sending;
- the decoder consumed nothing, so it would fail on the same bytes again; or
- there have been more consecutive drops than `max_consecutive_drops` (10 by
  default), a count that restarts whenever a frame decodes.

The second case means recovery depends on the decoder: it must consume a bad
frame before reporting it. **The built-in codec does not consume an oversized
frame**, so that failure always disconnects.

`on_error` and the metric report the policy that was applied. A failure still
buffered when a connection ends for another reason is reported as `Disconnect`,
without asking the hook for a policy. `CodecErrorContext` carries the peer's
address on a server connection, and its other fields stay empty there. The hook
is shared by every connection, and the pause comes from its
`quarantine_duration`, so `RecoveryConfig::quarantine_duration` has no effect.

## Testing your protocol

Networks deliver bytes in whatever pieces they like, and your tests should too.
There are two places to look:

- **`wireframe::testkit`**, behind the `testkit` feature, holds drivers and
  assertions you can use from the main crate.
- **The `wireframe_testing` crate** adds codec fixtures, an observability
  harness, a client and server pair, and allocation counting. It re-exports the
  testkit, and enables that feature for you.

<!-- tested-example: guide-testing-dependencies -->
```toml
[dev-dependencies]
wireframe = { version = "=0.4.0-alpha1", features = ["testkit"] }
wireframe_testing = "=0.4.0-alpha1"
```

### Partial frames and slow peers

The chunked drivers encode payloads, then write them in pieces as small as one
byte:

<!-- tested-example: guide-testing-partial-frames -->
```rust
use std::{num::NonZeroUsize, sync::Arc};

use wireframe::{
    app::{Envelope, Handler, WireframeApp},
    codec::LengthDelimitedFrameCodec,
    serializer::{BincodeSerializer, Serializer},
    testkit::drive_with_partial_frames,
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let echo: Handler<Envelope> = Arc::new(|_: &Envelope| Box::pin(async {}));
    let app: WireframeApp = WireframeApp::new()?.route(1, echo)?;
    let request = BincodeSerializer.serialize(&Envelope::new(1, Some(7), b"hi".to_vec()))?;

    let codec = LengthDelimitedFrameCodec::new(1024);
    let one_byte = NonZeroUsize::new(1).expect("non-zero");
    let replies = drive_with_partial_frames(app, &codec, vec![request.clone()], one_byte).await?;
    assert_eq!(replies, [request]);
    Ok(())
}
```

The slow-I/O helpers pace reads and writes separately, and are designed for
paused Tokio time:

<!-- tested-example: guide-testing-slow-io -->
```rust
use std::{num::NonZeroUsize, sync::Arc, time::Duration};

use wireframe::{
    app::{Envelope, Handler, WireframeApp},
    codec::LengthDelimitedFrameCodec,
    serializer::{BincodeSerializer, Serializer},
    testkit::{SlowIoConfig, SlowIoPacing, drive_with_slow_codec_payloads},
};

#[tokio::main(flavor = "current_thread", start_paused = true)]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let echo: Handler<Envelope> = Arc::new(|_: &Envelope| Box::pin(async {}));
    let app: WireframeApp = WireframeApp::new()?.route(1, echo)?;
    let request = BincodeSerializer.serialize(&Envelope::new(1, Some(7), b"slow".to_vec()))?;

    let pace = |bytes: usize| {
        SlowIoPacing::new(NonZeroUsize::new(bytes).expect("non-zero"), Duration::from_millis(5))
    };
    let config = SlowIoConfig::new()
        .with_writer_pacing(pace(8))
        .with_reader_pacing(pace(32))
        .with_capacity(64);

    let codec = LengthDelimitedFrameCodec::new(1024);
    let replies = drive_with_slow_codec_payloads(app, &codec, vec![request.clone()], config).await?;
    assert_eq!(replies, [request]);
    Ok(())
}
```

Small capacities combined with reader pacing make an application's writes hit
back-pressure quickly. Table 13 lists the drivers. Many also have a
`_with_capacity` form, and `_mut` forms that borrow the application.

| Function family                   | From                | Feeds                               | Returns          |
| --------------------------------- | ------------------- | ----------------------------------- | ---------------- |
| `drive_with_partial_frames`       | `testkit`           | Payloads, in chunks                 | Payload bytes    |
| `drive_with_partial_codec_frames` | `testkit`           | Payloads, in chunks                 | Decoded frames   |
| `drive_with_fragments`            | `testkit`           | A payload, fragmented               | Payload bytes    |
| `drive_with_fragment_frames`      | `testkit`           | A payload, fragmented               | Decoded frames   |
| `drive_with_partial_fragments`    | `testkit`           | Fragments, in chunks                | Payload bytes    |
| `drive_with_slow_frames`          | `testkit`           | Pre-framed bytes, paced             | Raw output bytes |
| `drive_with_slow_payloads`        | `testkit`           | Default-framed payloads, paced      | Raw output bytes |
| `drive_with_slow_codec_payloads`  | `testkit`           | Codec payloads, paced               | Payload bytes    |
| `drive_with_slow_codec_frames`    | `testkit`           | Codec payloads, paced               | Decoded frames   |
| `drive_with_codec_payloads`       | `wireframe_testing` | Payloads                            | Payload bytes    |
| `drive_with_codec_frames`         | `wireframe_testing` | Payloads                            | Decoded frames   |
| `prepare_and_drive_with_frames`   | `wireframe_testing` | Raw frames, prepared once           | Raw output bytes |
| `drive_prepared_with_frames`      | `wireframe_testing` | Raw frames, reusing a `PreparedApp` | Raw output bytes |

_Table 13: In-memory test drivers._

`encode_payloads_with_codec`, `decode_frames_with_codec`, and
`extract_payloads` help you compose your own patterns.

To keep driving one application across several calls, or to size the in-memory
duplex stream yourself, use the mutable variants that take `&mut WireframeApp`
and a capacity. `wireframe_testing::drive_with_frame_with_capacity_mut` feeds
one frame and `wireframe_testing::drive_with_frames_with_capacity_mut` feeds
several. Like the other raw-frame drivers, they write your bytes verbatim, so
each frame must already carry the codec's length prefix: four big-endian bytes
for the default `LengthDelimitedFrameCodec`.

### Malformed input

The fixtures in `wireframe_testing` construct raw Hotline-framed bytes
directly, so they can represent data an encoder would refuse to produce:

<!-- tested-example: guide-testing-fixtures -->
```rust
use wireframe::codec::examples::HotlineFrameCodec;
use wireframe_testing::{
    correlated_hotline_wire,
    decode_frames_with_codec,
    oversized_hotline_wire,
    truncated_hotline_header,
    valid_hotline_wire,
};

let codec = HotlineFrameCodec::new(4096);

let wire = valid_hotline_wire(b"hello", 7);
assert_eq!(decode_frames_with_codec(&codec, &wire).expect("decodes").len(), 1);

let wire = oversized_hotline_wire(4096);
assert!(decode_frames_with_codec(&codec, &wire).is_err());

let wire = truncated_hotline_header();
assert!(decode_frames_with_codec(&codec, &wire).is_err());

let wire = correlated_hotline_wire(42, &[b"a", b"b"]);
assert_eq!(decode_frames_with_codec(&codec, &wire).expect("decodes").len(), 2);
```

The others are `valid_hotline_frame`, `mismatched_total_size_wire`,
`truncated_hotline_payload`, and `sequential_hotline_wire`.

### Asserting on reassembly

`wireframe::testkit::reassembly` offers assertions that return a `Result`
rather than panicking, so the same helper works in `rstest` tests and in
`rstest-bdd` steps:

<!-- tested-example: guide-testing-reassembly -->
```rust
use wireframe::{
    message_assembler::MessageKey,
    testkit::{MessageAssemblySnapshot, TestResult, assert_message_assembly_completed_for_key},
};

fn check(snapshot: MessageAssemblySnapshot<'_>) -> TestResult {
    assert_message_assembly_completed_for_key(snapshot, MessageKey(7), b"done")?;
    Ok(())
}
```

For message assembly, there are `assert_message_assembly_incomplete`,
`_completed`, `_completed_for_key`, `_error`, `_buffered_count`,
`_total_buffered_bytes`, and `_evicted`. For fragments, there are
`assert_fragment_reassembly_absent`, `_completed_len`, `_completed_bytes`,
`_error`, `_buffered_messages`, and `_evicted`. Existing
`wireframe_testing::reassembly` imports keep working.

### Logs and metrics

`ObservabilityHandle` captures logs and metrics in one fixture:

<!-- tested-example: guide-testing-observability -->
```rust
use wireframe_testing::ObservabilityHandle;

let mut observability = ObservabilityHandle::new();
observability.clear();

metrics::with_local_recorder(observability.recorder(), || {
    wireframe::metrics::inc_codec_error("framing", "drop");
});

observability.snapshot();
assert_eq!(
    observability.counter(
        wireframe::metrics::CODEC_ERRORS,
        &[("error_type", "framing"), ("recovery_policy", "drop")],
    ),
    1
);
```

Metrics are captured per thread, so the code under test must run on the same
thread as the handle. In async tests, use
`#[tokio::test(flavor = "current_thread")]`. This needs `metrics` in your own
dev-dependencies.

The assertion helpers `assert_counter`, `assert_no_metric`,
`assert_codec_error_counter`, `assert_histogram_recorded`,
`assert_log_contains`, and `assert_log_at_level` **return a `Result` without
panicking**, so propagate them with `?`, or the test asserts nothing. `counter`,
`counter_without_labels`, and `codec_error_counter` read values from the
latest snapshot.

### A real client and server

`wireframe_testing::client_pair` starts a real `WireframeServer` and a connected
`WireframeClient` over a loopback socket, for tests that need the whole
network path. `echo_app_factory` supplies a ready-made application with route 1
and invocation counting:

<!-- tested-example: guide-testing-pair -->
```rust
use std::sync::{Arc, atomic::AtomicUsize};

use wireframe_testing::{TestResult, echo_app_factory, spawn_wireframe_pair};

#[tokio::main]
async fn main() -> TestResult<()> {
    let counter = Arc::new(AtomicUsize::new(0));
    let mut pair = spawn_wireframe_pair(
        echo_app_factory(&counter),
        |builder| builder.max_frame_length(2048),
    )
    .await?;

    assert!(pair.local_addr().port() > 0);

    pair.shutdown().await?;
    Ok(())
}
```

`pair.client_mut()` gives you the client. `spawn_wireframe_pair_default` uses
default client settings. If the client cannot connect, the server is torn down,
so nothing leaks into later tests.

### Counting allocations

`wireframe_testing::benchmark_alloc_support` helps you keep allocation budgets.
Rust permits one `#[global_allocator]` per binary, and a library cannot install
it for you, so a benchmark binary opts in:

<!-- tested-example: guide-allocator -->
```rust
use std::alloc::System;

use wireframe_testing::benchmark_alloc_support::{INSTRUMENTED_SYSTEM, StatsAlloc, count_allocations};

#[global_allocator]
static GLOBAL_ALLOCATOR: &StatsAlloc<System> = &INSTRUMENTED_SYSTEM;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let count = count_allocations(|| {
        let buffer: Vec<u8> = vec![0; 1024];
        std::hint::black_box(buffer.len());
        Ok(())
    })?;
    println!("{count} allocations");
    Ok(())
}
```

`count_allocations` opens a window, runs your closure, and closes the window
even on error. `count_allocations_or_panic` is for binaries that treat a failed
measurement as fatal. `count_allocation_traffic` also reports the bytes
requested, as an `AllocationTraffic`; growing a buffer adds only the growth, so
this does not measure copying. `allocation_count`, `reset_allocation_count`, and
`is_allocation_counting_enabled` work on the current count. Call
`verify_allocation_harness` once before measuring, so that a misconfigured
binary fails rather than recording zeros.

The value includes reallocations, and everything running in the window, such as
the runtime and harness. Compare values across runs of the same binary rather
than treating them as absolute costs.

### Counting copied bytes

The `benchmark-counters` feature counts the payload bytes that Wireframe
copies. It exists for this repository's baselines, and costs an atomic
increment at each copy, so leave it off in applications. With the feature
disabled, the functions in `wireframe::benchmark_counters` remain and report
zero. `snapshot` returns a `CopiedBytes` with four fields, `serialized`,
`handoff`, `framed`, and `deserialized`, and `reset` clears them. The counters
belong to the process, so run one measurement at a time.

## Compile-time configuration

Much of the configuration can run in a `const` context, so a value can be
computed by the compiler and checked in a `static` or `const` item. This
matters when a value must exist before `main` runs, and it turns some
configuration mistakes into compile errors. It covers:

- **Application builder.** `WireframeApp::codec`, `fragmentation`,
  `memory_budgets`, and `recovery_config`, plus `Envelope::new` and
  `PacketParts::new`.
- **Codec errors.** `CodecError::is_clean_close`, `error_type`, and
  `default_recovery_policy`, and the `RecoveryConfig` methods
  `max_consecutive_drops`, `quarantine_duration`, and `log_dropped_frames`.
- **Top-level errors.** `WireframeError::from_io`, `from_codec`, and
  `is_clean_close`.
- **Error context.** `CodecErrorContext` with `with_connection_id`,
  `with_peer_address`, and `with_correlation_id`.
- **Codec parameters.** `HotlineFrameCodec::new` and `MysqlFrameCodec::new`.
  Their `max_frame_length` is a trait method, and so stays a run-time read.
- **Message assembly.** `ParsedFrameHeader::new`, `FirstFrameHeader`,
  `FrameHeader`, `MessageKey`, `EnvelopeId`, `CorrelationId`,
  `EnvelopeRouting`, and `AssembledMessage::new`.
- **Requests and middleware.** `RequestParts::new`, `id`, `correlation_id`, and
  `metadata_mut`, as well as `FrameContainer`, `FromFn::new`, `Next::new`, and
  the correlation accessors on `ServiceRequest` and `ServiceResponse`.
- **Connection and queue tuning.** `ConnectionActor::set_fairness` and
  `enable_fragmentation`, and the queue builder setters.
- **Fragment metadata.** Constructors and accessors. `FragmentFrame`,
  `FragmentParts`, and `ReassembledMessage` own `Vec<u8>` values, so these can
  be called in a `const fn`, but generally not from a `const` item.

This example builds a recovery policy, an error context, and a codec, then
asserts on the policy without any run-time call:

<!-- tested-example: guide-const-config -->
```rust
use std::{
    net::{Ipv4Addr, SocketAddr, SocketAddrV4},
    time::Duration,
};

use wireframe::codec::{
    examples::HotlineFrameCodec,
    CodecError,
    CodecErrorContext,
    EofError,
    RecoveryConfig,
    RecoveryPolicy,
};

const CLEAN_CLOSE: CodecError = CodecError::Eof(EofError::CleanClose);
const RECOVERY_POLICY: RecoveryPolicy = CLEAN_CLOSE.default_recovery_policy();
const IS_CLEAN_CLOSE: bool = CLEAN_CLOSE.is_clean_close();

// `RecoveryConfig::default()` is not a `const fn`, so a const item spells the
// fields out; the builder methods are `const` and chain from there.
const RECOVERY_CONFIG: RecoveryConfig = RecoveryConfig {
    max_consecutive_drops: 0,
    quarantine_duration: Duration::ZERO,
    log_dropped_frames: false,
}
.max_consecutive_drops(3)
.quarantine_duration(Duration::from_secs(5))
.log_dropped_frames(true);

const ERROR_CONTEXT: CodecErrorContext = CodecErrorContext {
    connection_id: None,
    peer_address: None,
    correlation_id: None,
    codec_state: None,
}
.with_connection_id(7)
.with_peer_address(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 8080)))
.with_correlation_id(9);

const HOTLINE_CODEC: HotlineFrameCodec = HotlineFrameCodec::new(1024);

const _: () = assert!(matches!(RECOVERY_POLICY, RecoveryPolicy::Disconnect));
const _: () = assert!(IS_CLEAN_CLOSE);
```

A `const fn` cannot run a destructor, which sets the main limit.
`CodecErrorContext` holds an `Option<String>`, and `WireframeError` has a
destructor, so a `const fn` may borrow or return these, but it can never drop
one. This is why `from_io` takes its payload by value and returns the result.

Client configuration works the same way. Most builder setters and socket
shorthands are `const`, along with `TracingConfig`'s setters and
`SendStreamingConfig::with_chunk_size` and `with_timeout`:

<!-- tested-example: guide-const-client -->
```rust
use std::time::Duration;

use wireframe::client::{SocketOptions, TracingConfig, WireframeClientBuilder};

const fn configure(
    builder: WireframeClientBuilder,
    socket_options: SocketOptions,
    tracing: TracingConfig,
) -> WireframeClientBuilder {
    builder
        .socket_options(socket_options)
        .tracing_config(tracing)
        .nodelay(true)
        .keepalive(Some(Duration::from_secs(30)))
        .reuseaddr(true)
}

let builder = configure(
    WireframeClientBuilder::new(),
    SocketOptions::default(),
    TracingConfig::default().with_connect_timing(true),
);
drop(builder);
```

Setters that clamp their input, such as `ClientCodecConfig::max_frame_length`,
`ClientPoolConfig::pool_size`, and `idle_timeout`, are ordinary functions, as
is every `Default::default`. `connect` and `connect_pool` perform I/O, so they
stay at run time. `reuseport` exists only on Unix outside Solaris, illumos, and
Cygwin. The trybuild fixtures in `tests/ui/` keep these promises honest.

## Troubleshooting

### My server does not reply as I expect

- **The reply is my own request.** That is the default for `route`, which echoes
  the request's payload. Write the reply in [middleware]#middleware, or use
  [`route_response`]#response-producing-routes.
- **Middleware sees an empty response.** The route uses `route_response`, whose
  reply travels separately.
- **`wrap(from_fn(...))` does not compile.** `wrap` requires a `Transform` that
  outputs a `HandlerService`, [as described here]#what-from_fn-is-for.
- **`WireframeApp::new()` needs type annotations.** Annotate the binding, as in
  `let app: WireframeApp = WireframeApp::new()?;`, so that its default
  parameters apply.
- **My handler will not compile because of a lifetime.** A `route` handler's
  future is `'static`, so copy data out of the envelope before the `async`
  block.
- **My hooks, pushes, or registry stopped working.** `with_codec` removes the
  protocol, the push-queue template, and the session registry, so call it first.
- **Fragmentation stopped working.** `buffer_capacity` and `with_codec` clear
  it, so configure it afterwards.
- **`on_eof` never fires.** It needs a decoder that reports truncation as
  `CodecError::Eof`, and does not run for a clean close. See
  [When a peer vanishes mid-frame]#when-a-peer-vanishes-mid-frame.
- **My recovery hook asked for `Drop`, but the connection closed.** The decoder
  probably consumed nothing. See [recovery policies]#codec-recovery-policies.
- **My client is disconnected before it sends anything.** If you configured a
  preamble, the server waits for it under the 10-second
  [preamble deadline]#connection-preambles.
- **I see no warnings.** You need a `log` logger or a `tracing` subscriber, as
  described in [Logs]#logs.
- **Shutdown hangs after the port closes.** `drained()` still waits for
  tracked connection tasks. See [Shutting down]#shutting-down.

### My client gets an error

- **Small requests work and larger ones fail.** Suspect a frame-budget
  mismatch. The client usually reports
  `ClientError::Wireframe(WireframeError::Io(_))`, because the peer closes the
  connection after rejecting the frame. Align
  `ClientCodecConfig::max_frame_length` with the server's `buffer_capacity`.
- **`ClientError::PreambleTimeout`.** The handshake stalled before framed
  traffic began. Check that the server actually reads or replies during the
  preamble.
- **`ClientError::PreambleRead(_)`.** Your success callback could not read or
  decode the answer, usually because of a schema mismatch. Check too that it
  returns any leftover bytes it consumed.
- **`ClientError::PreambleEncode(_)`.** Serializing or writing the preamble
  failed. Write failures are wrapped in `bincode::EncodeError`, so they appear
  here too.
- **The wrong protocol is on that port.** A port expecting TLS, Hypertext
  Transfer Protocol (HTTP), or something else usually produces
  `ClientError::Wireframe(WireframeError::Io(_))` after the first request, or a
  decode error if the reply happens to resemble a frame. Check the host and
  port, and remember that built-in client TLS is future work.
- **`CorrelationMismatch` or `StreamCorrelationMismatch`.** The reply did not
  preserve the request's identifier, so check that the server echoes or stamps
  it.
- **My stream never ends.** The bundled `Envelope` has no terminator, so the
  client needs its own type, as
  [Reading streamed replies]#reading-streamed-replies describes. The server
  needs a protocol with a `stream_end_frame`.
- **Other calls are blocked.** A `ResponseStream` borrows the client
  exclusively until drained or dropped.
- **`connect_pool` succeeded, then the first call failed.** Pool sockets open
  on first use.
- **Transport disconnects.** Treat
  `ClientError::Wireframe(WireframeError::Io(_))` as a network or peer failure,
  and apply your own reconnect or retry policy. To match on these:

<!-- tested-example: guide-client-error-mapping -->
```rust
use wireframe::{
    WireframeError,
    client::{ClientError, ClientProtocolError},
};

fn describe(error: &ClientError) -> String {
    match error {
        ClientError::Wireframe(WireframeError::Io(error)) => format!("transport failure: {error}"),
        ClientError::Wireframe(WireframeError::Protocol(ClientProtocolError::Deserialize(error))) => {
            format!("decode failure: {error}")
        }
        other => format!("other client error: {other}"),
    }
}
```

## Where to go next

- The [API reference]https://docs.rs/wireframe documents every public type.
- The `examples/` directory has complete programs, which the
  [README]../README.md#examples lists.
- The [design document]rust-binary-router-library-design.md explains the
  architecture and why.
- The [`wireframe_testing` guide]wireframe-testing-crate.md goes deeper on
  test helpers.
- The
  [production resilience guide]hardening-wireframe-a-guide-to-production-resilience.md
  covers hardening.
- The [developers' guide]developers-guide.md is the place to start
  contributing, and the [roadmap]roadmap.md shows what is coming.