repe 8.0.1

Rust implementation of the REPE RPC protocol (JSON-focused)
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
//! Streaming transfer of a serialized, optionally zstd-compressed in-memory
//! value over ordinary REPE request/response — the **Serialized Value Stream
//! (SVS)** wire contract.
//!
//! SVS moves a large value (multi-GB even compressed) from a producer to a
//! consumer without either side materializing a full serialized or compressed
//! copy. The value is BEVE-serialized and, on the compressed path, zstd-encoded
//! as it is produced; the bytes cross the wire as a sequence of opaque chunks
//! pulled one round trip at a time, so flow control is the request/response
//! cadence itself — no ACK window, no unbounded queue. The receiver chooses, per
//! transfer, to write the compressed bytes to a file, decompress them to a file,
//! or stream-decode them straight into a `T`.
//!
//! A producer may also stream **opaque, already-serialized bytes** verbatim from
//! any [`Read`] ([`RouterValueStreamExt::with_reader_stream`]) rather than
//! re-serializing a value. That is the fit when the bytes already exist in their
//! final on-disk form: the consumer pulls them with [`pull_to_file`] /
//! [`pull_to_file_async`] (or the format-agnostic [`pull_consume_async`]) and,
//! with [`Compression::None`], writes a byte-identical copy. SVS does not commit
//! a content digest on the wire, so when end-to-end integrity matters the
//! producer and consumer agree on one out of band and the consumer recomputes it
//! over the streamed bytes with [`pull_to_file_verified_async`], which vetoes the
//! atomic rename on a mismatch. A producer that would rather commit that digest
//! *in* the single streaming pass than agree on one out of band can instead emit
//! the body through [`with_writer_stream`], teeing its bytes through a hasher as
//! it encodes and appending the digest as a trailer; it produces an app-framed
//! `payload || digest` stream tagged [`BodyFormat::RawBinary`], covering the
//! logical (pre-compression) bytes. The consumer of such a stream lifts the
//! trailer off and checks it in one pass with [`pull_to_file_trailer_verified`]
//! (or its async form): it holds the last N bytes back, hashes only the payload
//! prefix, and commits the payload — trailer stripped — only if the check passes.
//!
//! This module is the repe-rs **reference implementation** of the SVS contract.
//! The normative wire definition (routes, `stream_id` encoding, the `last`-flag
//! placement, the `format`/`compression` tags) lives in the REPE org repository
//! next to the base REPE spec; everything in this module beyond those wire fields
//! (chunk sizing, the bounded producer channel, the lookahead that detects the
//! final chunk) is local engine policy and not part of the contract.
//!
//! # Directions
//!
//! * **Download** (server produces, client pulls) — the primary direction.
//!   Register a producer with [`RouterValueStreamExt::with_value_stream`] (a
//!   serde value), [`with_typed_value_stream`] / [`with_complex_value_stream`] (a
//!   bulk numeric / complex array), [`with_reader_stream`] (opaque bytes from a
//!   [`Read`]), or [`with_writer_stream`] (bytes the app writes straight into the
//!   stream sink in one pass, e.g. teeing through a hasher to append a trailing
//!   content digest). Pull with [`pull_value`] / [`pull_to_beve_file`] /
//!   [`pull_to_beve_zst_file`] / [`pull_to_file`] / [`pull_to_vec`] (or the
//!   general [`pull_stream`]) over the synchronous [`Client`], with the
//!   format-agnostic [`pull_consume`] hatch and [`pull_to_file_trailer_verified`]
//!   (strip + verify an in-stream digest trailer, commit payload-only) alongside
//!   them. From async code, drive an [`AsyncClient`] (or a `WebSocketClient`) with
//!   [`pull_value_async`] / [`pull_typed_slice_async`] /
//!   [`pull_complex_slice_async`] / [`pull_to_file_async`] / [`pull_to_vec_async`]
//!   / [`pull_to_file_verified_async`] / [`pull_to_file_trailer_verified_async`],
//!   or the format-agnostic [`pull_consume_async`]: these run the blocking decoder
//!   on a `spawn_blocking` thread fed by an async pull loop, so they never park
//!   the runtime.
//!
//! [`with_typed_value_stream`]: RouterValueStreamExt::with_typed_value_stream
//! [`with_complex_value_stream`]: RouterValueStreamExt::with_complex_value_stream
//! [`with_reader_stream`]: RouterValueStreamExt::with_reader_stream
//! [`with_writer_stream`]: RouterValueStreamExt::with_writer_stream
//!
//! # Where the producer may run
//!
//! A `next` request blocks the handler until the producer has the next chunk
//! ready — that block *is* the backpressure. It must therefore run somewhere a
//! blocking handler is fine: the synchronous [`Server`](crate::Server) (one
//! thread per connection) or the WebSocket server (the `next` handler reports
//! [`Execution::OffReader`](crate::Execution), so it runs off the reader task).
//! The inline async TCP server ([`AsyncServer`](crate::AsyncServer)) runs handlers
//! on the connection's runtime task and does not honor `OffReader`, so a producer
//! registered there would park a runtime worker; use the sync or WebSocket server
//! for SVS producers.

use crate::async_client::AsyncClient;
use crate::client::Client;
use crate::constants::{BodyFormat, ErrorCode, QueryFormat};
use crate::error::RepeError;
use crate::message::{Message, create_error_message};
use crate::server::{Execution, HandlerErased, Router};
use beve::Complex;
use beve::from_slice as beve_from_slice;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
use std::sync::{Arc, Mutex};
use std::thread;

/// The SVS contract version this implementation speaks, reported in the `open`
/// response and validated by the client.
pub const SVS_VERSION: u8 = 1;

/// Reserved namespace for SVS routes. Routes beginning with `_` are reserved for
/// REPE protocol extensions; SVS claims `/_svs`.
pub const ROUTE_OPEN: &str = "/_svs/open";
/// Route for pulling the next chunk of a download stream. See [`ROUTE_OPEN`].
pub const ROUTE_NEXT: &str = "/_svs/next";
/// Route for releasing a stream early (request or notify). See [`ROUTE_OPEN`].
pub const ROUTE_CANCEL: &str = "/_svs/cancel";

/// The codec applied over the serialized value bytes, orthogonal to the
/// serialization `format`. Wire values match the SVS `compression` tag.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum Compression {
    /// `compression = 0`: the chunk stream is the serialized value verbatim.
    None = 0,
    /// `compression = 1`: the chunk stream is a zstd frame over the serialized
    /// value.
    Zstd = 1,
}

impl Compression {
    fn from_u8(v: u8) -> Option<Self> {
        match v {
            0 => Some(Compression::None),
            1 => Some(Compression::Zstd),
            _ => None,
        }
    }
}

/// Local producer-side knobs (SVS §5 "local policy" — none of these are on the
/// wire, so a producer and consumer interoperate regardless of how they are set).
#[derive(Debug, Clone, Copy)]
pub struct StreamOpts {
    /// Target size of each chunk pushed into the session channel. Keep this a few
    /// MiB at most so a WebSocket binary frame stays modest; 1 MiB by default.
    pub chunk_bytes: usize,
    /// Codec applied over the serialized bytes.
    pub compression: Compression,
    /// zstd compression level when `compression` is [`Compression::Zstd`].
    pub zstd_level: i32,
    /// Bounded depth of the per-stream producer channel. This is where memory is
    /// bounded and backpressure lives: the serializer parks once this many chunks
    /// are buffered ahead of the consumer.
    pub session_depth: usize,
}

impl Default for StreamOpts {
    fn default() -> Self {
        Self {
            chunk_bytes: 1 << 20,
            compression: Compression::Zstd,
            zstd_level: 3,
            session_depth: 4,
        }
    }
}

// ---- wire message bodies (BEVE) ------------------------------------------------

#[derive(Serialize, Deserialize)]
struct OpenRequest {
    resource: String,
}

#[derive(Serialize, Deserialize)]
struct OpenResponse {
    version: u8,
    stream_id: u64,
    /// Serialization format of the logical content, using REPE `BodyFormat`
    /// values (`1` = BEVE here).
    format: u16,
    /// Codec over the serialized bytes (`0` = none, `1` = zstd).
    compression: u8,
}

#[derive(Serialize, Deserialize)]
struct NextRequest {
    stream_id: u64,
}

#[derive(Serialize, Deserialize)]
struct CancelRequest {
    stream_id: u64,
    reason: String,
}

// ---- server: producer session -------------------------------------------------

/// One message in the producer→handler channel. Terminating the stream with an
/// explicit [`Msg::End`] / [`Msg::Fail`] (rather than relying on the channel
/// closing) keeps the "did it finish cleanly?" answer ordered with the chunks: a
/// truncated production surfaces as `Fail`, never as a silently-short clean end.
enum Msg {
    Chunk(Vec<u8>),
    End,
    Fail(String),
}

/// A `Write` sink that batches the producer's byte stream into fixed-size chunks
/// and pushes each into the bounded session channel. A send failure (the receiver
/// was dropped — the consumer cancelled or disconnected) surfaces as a broken
/// pipe, which aborts the in-progress serialize/compress pass.
struct ChunkSink {
    tx: SyncSender<Msg>,
    buf: Vec<u8>,
    chunk_bytes: usize,
}

impl ChunkSink {
    fn new(tx: SyncSender<Msg>, chunk_bytes: usize) -> Self {
        Self {
            tx,
            buf: Vec::with_capacity(chunk_bytes),
            chunk_bytes,
        }
    }

    fn send_chunk(&mut self) -> io::Result<()> {
        let chunk = std::mem::replace(&mut self.buf, Vec::with_capacity(self.chunk_bytes));
        self.tx
            .send(Msg::Chunk(chunk))
            .map_err(|_| io::Error::new(io::ErrorKind::BrokenPipe, "svs stream cancelled"))
    }

    /// Flush the trailing partial chunk (if any). Does not close the channel; the
    /// caller sends [`Msg::End`]/[`Msg::Fail`] explicitly afterward.
    fn flush_remaining(&mut self) -> io::Result<()> {
        if self.buf.is_empty() {
            Ok(())
        } else {
            self.send_chunk()
        }
    }
}

impl Write for ChunkSink {
    fn write(&mut self, mut data: &[u8]) -> io::Result<usize> {
        let total = data.len();
        while !data.is_empty() {
            let space = self.chunk_bytes - self.buf.len();
            let take = space.min(data.len());
            self.buf.extend_from_slice(&data[..take]);
            data = &data[take..];
            if self.buf.len() >= self.chunk_bytes {
                self.send_chunk()?;
            }
        }
        Ok(total)
    }

    fn flush(&mut self) -> io::Result<()> {
        // A chunk boundary is a size decision, not a flush decision: the zstd
        // encoder flushes mid-frame and the receiver concatenates regardless, so
        // an intermediate flush must NOT emit a short chunk. The trailing partial
        // is pushed once, by `flush_remaining` at the end.
        Ok(())
    }
}

/// A producer-side closure that writes the full logical body to a sink: a
/// generic serde value (`to_writer_streaming`), a bulk typed numeric array
/// (`to_writer_typed_slice`), or a bulk complex array (`to_writer_complex_slice`).
/// Boxed so one producer engine serves every body shape.
type BodyWriter = Box<dyn FnOnce(&mut dyn Write) -> io::Result<()> + Send>;

/// Map a beve encode error to an `io::Error` for the producer pipeline.
fn beve_to_io(e: beve::Error) -> io::Error {
    io::Error::other(e.to_string())
}

/// Run the (write→compress→chunk) pipeline to completion, reporting the outcome
/// through the channel. Always ends with exactly one `End` or `Fail` before the
/// channel closes.
fn produce(body: BodyWriter, tx: SyncSender<Msg>, opts: StreamOpts) {
    let mut sink = ChunkSink::new(tx.clone(), opts.chunk_bytes);
    let result = (|| -> io::Result<()> {
        match opts.compression {
            Compression::None => body(&mut sink)?,
            Compression::Zstd => {
                let mut enc = zstd::stream::write::Encoder::new(&mut sink, opts.zstd_level)?;
                body(&mut enc)?;
                enc.finish()?;
            }
        }
        sink.flush_remaining()
    })();
    // Send the terminal marker before `sink` (and its channel handle) drop, so the
    // consumer observes End/Fail in order rather than a bare channel close.
    let _ = match result {
        Ok(()) => tx.send(Msg::End),
        Err(e) => tx.send(Msg::Fail(e.to_string())),
    };
}

/// Per-stream consumer-facing state: the receiving end of the producer channel
/// plus the one-chunk lookahead used to mark the final chunk with `last = 1`.
struct Session {
    rx: Receiver<Msg>,
    lookahead: Option<Vec<u8>>,
    done: bool,
}

impl Session {
    fn recv(&self) -> Msg {
        self.rx.recv().unwrap_or_else(|_| {
            // The producer always sends End/Fail before dropping the sender, so a
            // bare close means the producer thread vanished (panic).
            Msg::Fail("svs producer ended without completing".to_string())
        })
    }

    /// Return the next chunk and whether it is the last. Blocks until the
    /// producer has the *following* chunk (or its terminal marker) ready — that
    /// block is the backpressure. Returns `Err` if the producer failed, so a
    /// truncated production never masquerades as a clean `last`.
    fn pull(&mut self) -> Result<(Vec<u8>, bool), String> {
        let current = match self.lookahead.take() {
            Some(c) => c,
            None => match self.recv() {
                Msg::Chunk(c) => c,
                Msg::End => return Ok((Vec::new(), true)),
                Msg::Fail(e) => return Err(e),
            },
        };
        match self.recv() {
            Msg::Chunk(next) => {
                self.lookahead = Some(next);
                Ok((current, false))
            }
            Msg::End => Ok((current, true)),
            Msg::Fail(e) => Err(e),
        }
    }
}

/// Server-side table of live download sessions, shared by the `open`/`next`/
/// `cancel` handlers. Each session is behind its own lock so a `next` can block
/// on production without holding the table lock.
struct SessionTable {
    next_id: AtomicU64,
    sessions: Mutex<HashMap<u64, Arc<Mutex<Session>>>>,
}

impl SessionTable {
    fn new() -> Self {
        Self {
            next_id: AtomicU64::new(1),
            sessions: Mutex::new(HashMap::new()),
        }
    }

    fn get(&self, stream_id: u64) -> Option<Arc<Mutex<Session>>> {
        self.sessions.lock().unwrap().get(&stream_id).cloned()
    }

    fn remove(&self, stream_id: u64) {
        self.sessions.lock().unwrap().remove(&stream_id);
    }
}

struct OpenHandler<F> {
    table: Arc<SessionTable>,
    make_body: F,
    opts: StreamOpts,
    /// The logical content's serialization format, reported in the `open`
    /// response so the consumer can reject an incompatible output. BEVE for the
    /// value/typed/complex producers, raw-binary for the opaque byte producer.
    format: u16,
}

impl<F> HandlerErased for OpenHandler<F>
where
    F: Fn(&str) -> Option<BodyWriter> + Send + Sync + 'static,
{
    fn handle(&self, req: &Message) -> Result<Message, RepeError> {
        let open: OpenRequest = match beve_from_slice(&req.body) {
            Ok(v) => v,
            Err(_) => {
                return Ok(error_like(
                    req,
                    ErrorCode::InvalidBody,
                    "svs open: expected BEVE { resource: string }",
                ));
            }
        };
        let Some(body) = (self.make_body)(&open.resource) else {
            return Ok(error_like(
                req,
                ErrorCode::MethodNotFound,
                format!("svs open: unknown resource '{}'", open.resource),
            ));
        };

        let stream_id = self.table.next_id.fetch_add(1, Ordering::Relaxed);
        let (tx, rx) = sync_channel::<Msg>(self.opts.session_depth);
        let opts = self.opts;
        thread::spawn(move || produce(body, tx, opts));

        self.table.sessions.lock().unwrap().insert(
            stream_id,
            Arc::new(Mutex::new(Session {
                rx,
                lookahead: None,
                done: false,
            })),
        );

        let resp = OpenResponse {
            version: SVS_VERSION,
            stream_id,
            format: self.format,
            compression: self.opts.compression as u8,
        };
        beve_response(req, &resp)
    }
}

struct NextHandler {
    table: Arc<SessionTable>,
}

impl HandlerErased for NextHandler {
    fn execution(&self) -> Execution {
        // The pull blocks until the producer has the next chunk; on the WebSocket
        // server that must happen off the reader task so it stays free to decode a
        // concurrent `cancel`.
        Execution::OffReader
    }

    fn handle(&self, req: &Message) -> Result<Message, RepeError> {
        let next: NextRequest = match beve_from_slice(&req.body) {
            Ok(v) => v,
            Err(_) => {
                return Ok(error_like(
                    req,
                    ErrorCode::InvalidBody,
                    "svs next: expected BEVE { stream_id: u64 }",
                ));
            }
        };
        let Some(session) = self.table.get(next.stream_id) else {
            return Ok(error_like(
                req,
                ErrorCode::InvalidQuery,
                format!("svs next: unknown stream_id {}", next.stream_id),
            ));
        };

        // Pull under the per-session lock (not the table lock), then release it
        // before touching the table again to keep a single lock order.
        let outcome = {
            let mut guard = session.lock().unwrap();
            if guard.done {
                Err("svs next: stream already finished".to_string())
            } else {
                let pulled = guard.pull();
                if matches!(pulled, Ok((_, true)) | Err(_)) {
                    guard.done = true;
                }
                pulled
            }
        };

        match outcome {
            Ok((chunk, last)) => {
                if last {
                    self.table.remove(next.stream_id);
                }
                Ok(chunk_response(req, chunk, last))
            }
            Err(msg) => {
                self.table.remove(next.stream_id);
                Ok(error_like(req, ErrorCode::InternalError, msg))
            }
        }
    }
}

struct CancelHandler {
    table: Arc<SessionTable>,
}

impl HandlerErased for CancelHandler {
    fn handle(&self, req: &Message) -> Result<Message, RepeError> {
        // A malformed cancel still releases nothing but must not error a notify;
        // parse leniently and drop whatever stream_id we can read.
        if let Ok(cancel) = beve_from_slice::<CancelRequest>(&req.body) {
            self.table.remove(cancel.stream_id);
        }
        // Dropping the session drops the receiver, which aborts a parked producer
        // send. Acknowledge so a request-form cancel gets a reply (a notify-form
        // cancel ignores it).
        beve_response(req, &CancelAck { ok: true })
    }
}

#[derive(Serialize, Deserialize)]
struct CancelAck {
    ok: bool,
}

/// Register the three SVS routes onto `router` backed by `make_body`, the
/// producer-side factory mapping a resource to a [`BodyWriter`] (or `None`).
/// `format` is the logical content's serialization format reported in the `open`
/// response (BEVE for the serde/typed/complex producers, raw-binary for the
/// opaque byte producer).
fn register_svs<F>(router: Router, make_body: F, format: u16, opts: StreamOpts) -> Router
where
    F: Fn(&str) -> Option<BodyWriter> + Send + Sync + 'static,
{
    let table = Arc::new(SessionTable::new());
    let open: Arc<dyn HandlerErased> = Arc::new(OpenHandler {
        table: Arc::clone(&table),
        make_body,
        opts,
        format,
    });
    let next: Arc<dyn HandlerErased> = Arc::new(NextHandler {
        table: Arc::clone(&table),
    });
    let cancel: Arc<dyn HandlerErased> = Arc::new(CancelHandler {
        table: Arc::clone(&table),
    });
    router
        .with_erased_handler(ROUTE_OPEN, open)
        .with_erased_handler(ROUTE_NEXT, next)
        .with_erased_handler(ROUTE_CANCEL, cancel)
}

/// Extension trait that registers an SVS download producer onto a [`Router`].
///
/// Each registration installs the `/_svs/open`, `/_svs/next`, and `/_svs/cancel`
/// routes and serves **one** value shape; a router carries a single SVS producer
/// (a second registration replaces the routes). `resolve` maps an opaque resource
/// key (the `resource` field of the `open` request) to the value to stream, or
/// `None` if there is no such resource. The body is BEVE-encoded and, per
/// `opts.compression`, zstd-compressed as it is pulled; it is never copied whole.
///
/// See the [module docs](crate::value_stream) for where the producer may run
/// (sync or WebSocket server, not the inline async server).
pub trait RouterValueStreamExt: Sized {
    /// Stream an arbitrary `Serialize` value, decoded by the consumer with
    /// [`pull_value`] (generic, per-element serde).
    fn with_value_stream<T, F>(self, resolve: F, opts: StreamOpts) -> Self
    where
        T: Serialize + Send + 'static,
        F: Fn(&str) -> Option<T> + Send + Sync + 'static;

    /// Stream a bulk numeric array `Vec<T>` in BEVE typed-array form, so the
    /// consumer can decode it at memcpy speed with [`pull_typed_slice`]. Use this
    /// over [`with_value_stream`](Self::with_value_stream) for large primitive
    /// arrays (samples, matrices) where per-element serde is the bottleneck.
    fn with_typed_value_stream<T, F>(self, resolve: F, opts: StreamOpts) -> Self
    where
        T: beve::BeveTypedSlice + Send + 'static,
        F: Fn(&str) -> Option<Vec<T>> + Send + Sync + 'static;

    /// Stream a bulk complex array `Vec<Complex<T>>` in BEVE complex-array form,
    /// decoded by the consumer with [`pull_complex_slice`]. For large IQ buffers.
    fn with_complex_value_stream<T, F>(self, resolve: F, opts: StreamOpts) -> Self
    where
        T: beve::BeveTypedSlice + Send + 'static,
        F: Fn(&str) -> Option<Vec<Complex<T>>> + Send + Sync + 'static;

    /// Stream **opaque, already-serialized bytes** verbatim from a producer-side
    /// [`Read`] — no re-serialization. The stream is tagged
    /// `format = RawBinary`, so the consumer pulls it with [`pull_to_file`] /
    /// [`pull_to_file_async`] / [`pull_consume_async`] (the BEVE-typed pullers
    /// reject it).
    ///
    /// This is the right producer when the bytes already exist in their final
    /// on-disk form and must cross the wire unchanged: a file the server already
    /// wrote, a buffer it already encoded with its own serializer. With
    /// [`Compression::None`] the chunk stream is those exact bytes, so the
    /// consumer can write a byte-identical copy and verify it with its own
    /// digest. The element-type coupling of [`with_value_stream`] (the consumer
    /// must decode through *this* crate's serializer) does not apply.
    ///
    /// `resolve` maps a resource key to the byte source, or `None` if there is no
    /// such resource. Use `R = Box<dyn Read + Send>` to serve more than one
    /// concrete source type (e.g. a `File` for one resource, a `Cursor` for
    /// another) from a single registration.
    ///
    /// [`with_value_stream`]: Self::with_value_stream
    fn with_reader_stream<R, F>(self, resolve: F, opts: StreamOpts) -> Self
    where
        R: Read + Send + 'static,
        F: Fn(&str) -> Option<R> + Send + Sync + 'static;

    /// Stream **app-written bytes** from a producer-side closure that writes the
    /// full logical body directly into the stream sink, tagged with the caller's
    /// `format`. This is the write-side counterpart to
    /// [`with_reader_stream`](Self::with_reader_stream): the closure *owns the
    /// `Write`*, so it can serialize (or otherwise emit) the body **in a single
    /// pass** rather than materializing it first.
    ///
    /// The capability this adds over
    /// [`with_value_stream`](Self::with_value_stream) — where the engine owns the
    /// encode and the application never sees the sink — is a **single-pass digest
    /// seam**: the closure can tee its bytes through a hasher as it encodes and
    /// append a trailing digest, computing an end-to-end content digest as a
    /// by-product of the one streaming pass, with no second serialization pass.
    /// Frame it as `payload || digest` and tag it [`BodyFormat::RawBinary`] so a
    /// consumer pulls it with [`pull_to_file_trailer_verified`] — which holds the
    /// trailer back, hashes only the payload, and commits the payload alone on a
    /// match — rather than mistaking `payload || digest` for a bare decodable
    /// value. (A consumer that wants the raw `payload || digest` bytes can still
    /// pull them whole with [`pull_to_file`] / [`pull_consume_async`] and split the
    /// trailer by hand. Tagging a plain, trailer-free write as [`BodyFormat::Beve`]
    /// and pulling it with [`pull_value`] is also valid.)
    ///
    /// The digest such a closure computes covers the **logical** (pre-compression)
    /// bytes it writes; `opts.compression` is applied by the engine afterward and
    /// is transparent end to end, so the consumer recovers the same
    /// `payload || digest` after decompressing.
    ///
    /// `resolve` maps a resource key to the writer closure, or `None` if there is
    /// no such resource. Use
    /// `W = Box<dyn FnOnce(&mut dyn Write) -> std::io::Result<()> + Send>` to serve
    /// more than one concrete closure type from a single registration.
    fn with_writer_stream<W, F>(self, format: BodyFormat, resolve: F, opts: StreamOpts) -> Self
    where
        W: FnOnce(&mut dyn Write) -> io::Result<()> + Send + 'static,
        F: Fn(&str) -> Option<W> + Send + Sync + 'static;
}

impl RouterValueStreamExt for Router {
    fn with_value_stream<T, F>(self, resolve: F, opts: StreamOpts) -> Self
    where
        T: Serialize + Send + 'static,
        F: Fn(&str) -> Option<T> + Send + Sync + 'static,
    {
        register_svs(
            self,
            move |resource| {
                resolve(resource).map(|value| {
                    Box::new(move |w: &mut dyn Write| {
                        beve::to_writer_streaming(w, &value).map_err(beve_to_io)
                    }) as BodyWriter
                })
            },
            BodyFormat::Beve as u16,
            opts,
        )
    }

    fn with_typed_value_stream<T, F>(self, resolve: F, opts: StreamOpts) -> Self
    where
        T: beve::BeveTypedSlice + Send + 'static,
        F: Fn(&str) -> Option<Vec<T>> + Send + Sync + 'static,
    {
        register_svs(
            self,
            move |resource| {
                resolve(resource).map(|values| {
                    Box::new(move |w: &mut dyn Write| {
                        beve::to_writer_typed_slice(w, &values).map_err(beve_to_io)
                    }) as BodyWriter
                })
            },
            BodyFormat::Beve as u16,
            opts,
        )
    }

    fn with_complex_value_stream<T, F>(self, resolve: F, opts: StreamOpts) -> Self
    where
        T: beve::BeveTypedSlice + Send + 'static,
        F: Fn(&str) -> Option<Vec<Complex<T>>> + Send + Sync + 'static,
    {
        register_svs(
            self,
            move |resource| {
                resolve(resource).map(|values| {
                    Box::new(move |w: &mut dyn Write| {
                        beve::to_writer_complex_slice(w, &values).map_err(beve_to_io)
                    }) as BodyWriter
                })
            },
            BodyFormat::Beve as u16,
            opts,
        )
    }

    fn with_reader_stream<R, F>(self, resolve: F, opts: StreamOpts) -> Self
    where
        R: Read + Send + 'static,
        F: Fn(&str) -> Option<R> + Send + Sync + 'static,
    {
        register_svs(
            self,
            move |resource| {
                resolve(resource).map(|mut reader| {
                    Box::new(move |w: &mut dyn Write| io::copy(&mut reader, w).map(|_| ()))
                        as BodyWriter
                })
            },
            BodyFormat::RawBinary as u16,
            opts,
        )
    }

    fn with_writer_stream<W, F>(self, format: BodyFormat, resolve: F, opts: StreamOpts) -> Self
    where
        W: FnOnce(&mut dyn Write) -> io::Result<()> + Send + 'static,
        F: Fn(&str) -> Option<W> + Send + Sync + 'static,
    {
        register_svs(
            self,
            move |resource| resolve(resource).map(|writer| Box::new(writer) as BodyWriter),
            format as u16,
            opts,
        )
    }
}

// ---- response framing helpers (server) ----------------------------------------

fn error_like(req: &Message, code: ErrorCode, msg: impl AsRef<str>) -> Message {
    let mut err = create_error_message(code, msg.as_ref());
    err.header.id = req.header.id;
    err
}

fn beve_response<T: Serialize>(req: &Message, value: &T) -> Result<Message, RepeError> {
    Ok(Message::builder()
        .id(req.header.id)
        .body_bytes(beve::to_vec(value)?)
        .body_format(BodyFormat::Beve)
        .build())
}

/// Frame a `next` response: the `last` flag rides in a 1-byte raw-binary query so
/// it never wraps the zero-copy chunk body, which stays raw binary.
fn chunk_response(req: &Message, chunk: Vec<u8>, last: bool) -> Message {
    Message::builder()
        .id(req.header.id)
        .query_format(QueryFormat::RawBinary)
        .query_bytes(vec![last as u8])
        .body_format(BodyFormat::RawBinary)
        .body_bytes(chunk)
        .build()
}

// ---- client: pull driver ------------------------------------------------------

/// What the client does with the pulled byte stream (SVS §2: the receiver's
/// choice). The output must be consistent with the `format`/`compression` the
/// `open` response reports, or [`pull_stream`] cancels and errors rather than
/// producing a mislabeled file.
#[derive(Debug, Clone, Copy)]
pub enum StreamOutput<'a> {
    /// Write the chunk stream to a file as received. Requires a compressed stream
    /// (`compression = zstd`), since the bytes are the `.beve.zst` payload.
    BeveZstdFile(&'a Path),
    /// Decompress the chunk stream to a `.beve` file. Requires `compression =
    /// zstd` and `format = BEVE`.
    BeveFile(&'a Path),
    /// Stream-decode the value into a `T`. Requires `format = BEVE`; a compressed
    /// stream is decompressed on the way in. Returns `Some(T)`.
    Value,
    /// Write the logical content to a file, format-agnostic: a `compression =
    /// none` stream is copied verbatim (a byte-identical copy of an opaque
    /// [`with_reader_stream`](RouterValueStreamExt::with_reader_stream) source), a
    /// `compression = zstd` stream is decompressed on the way in. No `format`
    /// constraint, so it accepts a raw-binary stream the [`BeveFile`] mode would
    /// reject.
    ///
    /// [`BeveFile`]: StreamOutput::BeveFile
    RawFile(&'a Path),
}

/// Pull `resource` from an SVS producer reachable through `client` into `out`.
///
/// Returns `Ok(Some(T))` for [`StreamOutput::Value`] and `Ok(None)` for the file
/// outputs. File outputs are written to a temporary sibling path and renamed only
/// after the terminating `last = 1` chunk and a flush, so a dropped connection
/// never leaves a truncated file that looks complete (SVS §4).
pub fn pull_stream<T: DeserializeOwned>(
    client: &Client,
    resource: &str,
    out: StreamOutput<'_>,
) -> Result<Option<T>, RepeError> {
    let open = open_stream(client, resource)?;

    // Validate the chosen output against the returned tags before pulling a byte;
    // cancel the stream if we cannot honor them.
    if let Err(e) = check_output(out, &open) {
        let _ = cancel_stream(
            client,
            open.stream_id,
            "output incompatible with stream tags",
        );
        return Err(e);
    }

    match out {
        StreamOutput::BeveZstdFile(path) => {
            write_file(client, open.stream_id, path, |reader, file| {
                io::copy(reader, file)?;
                Ok(())
            })?;
            Ok(None)
        }
        StreamOutput::BeveFile(path) => {
            write_file(client, open.stream_id, path, |reader, file| {
                let mut dec = zstd::stream::read::Decoder::new(reader).map_err(RepeError::Io)?;
                io::copy(&mut dec, file)?;
                Ok(())
            })?;
            Ok(None)
        }
        StreamOutput::Value => {
            let reader = ChunkReader::new(client, open.stream_id);
            let value = match open.compression {
                Compression::None => beve::from_reader_streaming::<_, T>(reader)?,
                Compression::Zstd => {
                    let dec = zstd::stream::read::Decoder::new(reader).map_err(RepeError::Io)?;
                    beve::from_reader_streaming::<_, T>(dec)?
                }
            };
            // The value decoded fully; release any remainder of the stream the
            // decoder did not need to read. Best-effort.
            let _ = cancel_stream(client, open.stream_id, "value fully decoded");
            Ok(Some(value))
        }
        StreamOutput::RawFile(path) => {
            let compression = open.compression;
            write_file(client, open.stream_id, path, |reader, file| {
                match compression {
                    Compression::None => {
                        io::copy(reader, file)?;
                    }
                    Compression::Zstd => {
                        let mut dec =
                            zstd::stream::read::Decoder::new(reader).map_err(RepeError::Io)?;
                        io::copy(&mut dec, file)?;
                    }
                }
                Ok(())
            })?;
            Ok(None)
        }
    }
}

/// Convenience: pull `resource` and decode it into a `T` ([`StreamOutput::Value`]).
pub fn pull_value<T: DeserializeOwned>(client: &Client, resource: &str) -> Result<T, RepeError> {
    pull_stream::<T>(client, resource, StreamOutput::Value)
        .map(|v| v.expect("StreamOutput::Value always yields Some"))
}

/// Convenience: pull `resource` and write the compressed bytes to `path` as a
/// `.beve.zst` file ([`StreamOutput::BeveZstdFile`]).
pub fn pull_to_beve_zst_file(
    client: &Client,
    resource: &str,
    path: &Path,
) -> Result<(), RepeError> {
    pull_stream::<()>(client, resource, StreamOutput::BeveZstdFile(path)).map(|_| ())
}

/// Convenience: pull `resource`, decompress it, and write a `.beve` file
/// ([`StreamOutput::BeveFile`]).
pub fn pull_to_beve_file(client: &Client, resource: &str, path: &Path) -> Result<(), RepeError> {
    pull_stream::<()>(client, resource, StreamOutput::BeveFile(path)).map(|_| ())
}

/// Convenience: pull `resource` and write its logical content to `path`,
/// format-agnostic ([`StreamOutput::RawFile`]). For a `compression = none`
/// opaque byte stream this writes a byte-identical copy of the producer's source;
/// a compressed stream is decompressed first. The file is committed atomically
/// (temp sibling, renamed only after the terminating chunk and an fsync).
pub fn pull_to_file(client: &Client, resource: &str, path: &Path) -> Result<(), RepeError> {
    pull_stream::<()>(client, resource, StreamOutput::RawFile(path)).map(|_| ())
}

/// Sync, format-agnostic escape hatch: pull `resource` and hand its logical
/// content to `consume` as a blocking [`Read`] on the calling thread (a
/// `compression = zstd` stream is decompressed on the way in; `none` is delivered
/// verbatim). This is the synchronous counterpart of [`pull_consume_async`] and,
/// like it, places no `format` constraint, so it drives an opaque
/// [`with_reader_stream`](RouterValueStreamExt::with_reader_stream) producer as
/// well as a BEVE one.
///
/// A truncated / dropped transfer surfaces as a read error inside `consume` (the
/// underlying `next` request fails), so a value built from a short read is
/// `consume` returning `Err`, never a silent success. The stream is released
/// (best-effort `cancel`) after `consume` returns, whether or not it drained every
/// chunk — so a `consume` that stops early (like [`pull_value`]'s partial decode)
/// still frees the server session.
pub fn pull_consume<V, F>(client: &Client, resource: &str, consume: F) -> Result<V, RepeError>
where
    F: FnOnce(&mut dyn Read) -> Result<V, RepeError>,
{
    let open = open_stream(client, resource)?;
    let reader = ChunkReader::new(client, open.stream_id);
    let result = match open.compression {
        Compression::None => {
            let mut reader = reader;
            consume(&mut reader)
        }
        Compression::Zstd => match zstd::stream::read::Decoder::new(reader) {
            Ok(mut dec) => consume(&mut dec),
            Err(e) => Err(RepeError::Io(e)),
        },
    };
    let _ = cancel_stream(client, open.stream_id, "consume complete");
    result
}

/// Convenience: pull `resource` and return its entire logical content as a
/// `Vec<u8>` (a `compression = zstd` stream is decompressed first). Sync
/// counterpart of [`pull_to_vec_async`].
///
/// This materializes the whole payload in memory, so it defeats the streaming
/// bound — use it only for payloads known to be small; for large transfers pull to
/// a file ([`pull_to_file`]) or decode straight into a value ([`pull_value`])
/// instead.
pub fn pull_to_vec(client: &Client, resource: &str) -> Result<Vec<u8>, RepeError> {
    pull_consume(client, resource, |reader| {
        let mut buf = Vec::new();
        reader.read_to_end(&mut buf)?;
        Ok(buf)
    })
}

/// Pull an app-framed `payload || trailer` stream, verify the trailer against a
/// digest computed over the payload, and commit **the payload only** to `path`
/// (the trailer is stripped). This removes the plain-pull + split + verify +
/// re-truncate boilerplate an in-stream digest — the
/// [`with_writer_stream`](RouterValueStreamExt::with_writer_stream) single-pass
/// seam — otherwise forces on the consumer.
///
/// The last `trailer_len` bytes of the logical content are held back as the
/// claimed trailer; every earlier byte is written to a temp file *and* fed to
/// `digest`. After the stream terminates cleanly, `verify(digest, &trailer)` is
/// called with the finalized `digest` accumulator and the held trailer bytes: on
/// `Ok`, the payload-only file is renamed into place atomically (temp sibling,
/// fsync, rename); on `Err`, the temp file is discarded and nothing is committed
/// at `path`. A truncated transfer is caught upstream of `verify` (it surfaces as
/// the pull error) and likewise commits nothing; a stream shorter than
/// `trailer_len` is a malformed frame and errors.
///
/// The digest covers the logical (pre-compression) bytes, matching what a
/// [`with_writer_stream`](RouterValueStreamExt::with_writer_stream) producer
/// hashes through its tee, so producer-side `opts.compression` is transparent
/// here. Sync counterpart of [`pull_to_file_trailer_verified_async`].
pub fn pull_to_file_trailer_verified<D, F>(
    client: &Client,
    resource: &str,
    path: &Path,
    trailer_len: usize,
    digest: D,
    verify: F,
) -> Result<(), RepeError>
where
    D: Write,
    F: FnOnce(D, &[u8]) -> Result<(), RepeError>,
{
    let tmp_path = temp_sibling(path);
    let (guard, digest, trailer) = pull_consume(client, resource, |reader| {
        let mut digest = digest;
        let mut guard = TempFile::create(&tmp_path)?;
        let trailer = {
            let tee = TeeWriter {
                file: guard.file_mut(),
                digest: &mut digest,
            };
            let mut hold = TrailerHold::new(tee, trailer_len);
            io::copy(reader, &mut hold)?;
            hold.into_trailer()?
        };
        guard.file_mut().flush()?;
        guard.file_mut().sync_all()?;
        Ok((guard, digest, trailer))
    })?;
    // The stream terminated cleanly (a truncation would have surfaced as the pull
    // error above, discarding `guard`). Let the caller finalize the digest and
    // compare it to the held trailer; only an `Ok` commits the payload-only file.
    verify(digest, &trailer)?;
    guard.commit(path)
}

/// Pull `resource` as a bulk numeric array decoded straight into a `Vec<T>` at
/// memcpy speed (beve's `read_typed_slice_from_reader`), skipping the per-element
/// serde walk [`pull_value`] would do for a `Vec<T>`.
///
/// Pair with a server registered via
/// [`RouterValueStreamExt::with_typed_value_stream`], which emits the BEVE
/// typed-array wire form this reader requires. A compressed stream is decompressed
/// on the way in. Errors if the stream is not a typed array of `T` (e.g. a generic
/// `with_value_stream` producer, or a mismatched element type).
pub fn pull_typed_slice<T: beve::BeveTypedSlice>(
    client: &Client,
    resource: &str,
) -> Result<Vec<T>, RepeError> {
    let open = open_stream(client, resource)?;
    if let Err(e) = require_beve(&open) {
        let _ = cancel_stream(
            client,
            open.stream_id,
            "format incompatible with bulk decode",
        );
        return Err(e);
    }
    let reader = ChunkReader::new(client, open.stream_id);
    let result: Result<Vec<T>, RepeError> = match open.compression {
        Compression::None => {
            beve::read_typed_slice_from_reader::<T, _>(reader).map_err(RepeError::from)
        }
        Compression::Zstd => match zstd::stream::read::Decoder::new(reader) {
            Ok(dec) => beve::read_typed_slice_from_reader::<T, _>(dec).map_err(RepeError::from),
            Err(e) => Err(RepeError::Io(e)),
        },
    };
    // Release the stream whether or not the decode used every chunk (and on error).
    let _ = cancel_stream(client, open.stream_id, "bulk typed slice complete");
    result
}

/// Complex twin of [`pull_typed_slice`]: pull `resource` as a bulk
/// `Vec<Complex<T>>` (beve's `read_complex_slice_from_reader`). Pair with a server
/// registered via [`RouterValueStreamExt::with_complex_value_stream`]. For large
/// IQ buffers.
pub fn pull_complex_slice<T: beve::BeveTypedSlice>(
    client: &Client,
    resource: &str,
) -> Result<Vec<Complex<T>>, RepeError> {
    let open = open_stream(client, resource)?;
    if let Err(e) = require_beve(&open) {
        let _ = cancel_stream(
            client,
            open.stream_id,
            "format incompatible with bulk decode",
        );
        return Err(e);
    }
    let reader = ChunkReader::new(client, open.stream_id);
    let result: Result<Vec<Complex<T>>, RepeError> = match open.compression {
        Compression::None => {
            beve::read_complex_slice_from_reader::<T, _>(reader).map_err(RepeError::from)
        }
        Compression::Zstd => match zstd::stream::read::Decoder::new(reader) {
            Ok(dec) => beve::read_complex_slice_from_reader::<T, _>(dec).map_err(RepeError::from),
            Err(e) => Err(RepeError::Io(e)),
        },
    };
    let _ = cancel_stream(client, open.stream_id, "bulk complex slice complete");
    result
}

/// The bulk slice readers require the stream's logical format to be BEVE (the
/// typed/complex array is BEVE-encoded).
fn require_beve(open: &OpenInfo) -> Result<(), RepeError> {
    if open.format != BodyFormat::Beve as u16 {
        return Err(RepeError::Io(io::Error::new(
            io::ErrorKind::InvalidData,
            format!(
                "svs: bulk slice decode needs format=BEVE, got format {}",
                open.format
            ),
        )));
    }
    Ok(())
}

struct OpenInfo {
    stream_id: u64,
    format: u16,
    compression: Compression,
}

/// BEVE body of an `open` request for `resource`.
fn open_request_body(resource: &str) -> Result<Vec<u8>, RepeError> {
    Ok(beve::to_vec(&OpenRequest {
        resource: resource.to_string(),
    })?)
}

/// BEVE body of a `next` request for `stream_id`.
fn next_request_body(stream_id: u64) -> Result<Vec<u8>, RepeError> {
    Ok(beve::to_vec(&NextRequest { stream_id })?)
}

/// BEVE body of a `cancel` request for `stream_id` carrying a human `reason`.
fn cancel_request_body(stream_id: u64, reason: &str) -> Result<Vec<u8>, RepeError> {
    Ok(beve::to_vec(&CancelRequest {
        stream_id,
        reason: reason.to_string(),
    })?)
}

/// Validate and parse an `open` response into the stream's [`OpenInfo`]. Shared
/// by the sync and async pull drivers.
fn parse_open_response(resp: &Message) -> Result<OpenInfo, RepeError> {
    let open: OpenResponse = resp.beve_body()?;
    if open.version != SVS_VERSION {
        return Err(RepeError::Io(io::Error::new(
            io::ErrorKind::InvalidData,
            format!(
                "svs open: server contract version {} != supported {}",
                open.version, SVS_VERSION
            ),
        )));
    }
    let Some(compression) = Compression::from_u8(open.compression) else {
        return Err(RepeError::Io(io::Error::new(
            io::ErrorKind::InvalidData,
            format!("svs open: unknown compression tag {}", open.compression),
        )));
    };
    Ok(OpenInfo {
        stream_id: open.stream_id,
        format: open.format,
        compression,
    })
}

fn open_stream(client: &Client, resource: &str) -> Result<OpenInfo, RepeError> {
    let body = open_request_body(resource)?;
    let resp = client.call_with_formats(
        ROUTE_OPEN,
        QueryFormat::JsonPointer as u16,
        Some(&body),
        BodyFormat::Beve as u16,
    )?;
    parse_open_response(&resp)
}

fn check_output(out: StreamOutput<'_>, open: &OpenInfo) -> Result<(), RepeError> {
    let beve = BodyFormat::Beve as u16;
    let mismatch = |msg: String| {
        Err(RepeError::Io(io::Error::new(
            io::ErrorKind::InvalidData,
            msg,
        )))
    };
    match out {
        StreamOutput::BeveZstdFile(_) => {
            if open.compression != Compression::Zstd {
                return mismatch(
                    "svs: .beve.zst output needs a zstd-compressed stream".to_string(),
                );
            }
        }
        StreamOutput::BeveFile(_) => {
            if open.compression != Compression::Zstd {
                return mismatch("svs: .beve output needs a zstd-compressed stream".to_string());
            }
            if open.format != beve {
                return mismatch(format!(
                    "svs: .beve output needs format=BEVE, got format {}",
                    open.format
                ));
            }
        }
        StreamOutput::Value => {
            if open.format != beve {
                return mismatch(format!(
                    "svs: value decode needs format=BEVE, got format {}",
                    open.format
                ));
            }
        }
        // Format-agnostic: any stream's logical content can land in a raw file.
        StreamOutput::RawFile(_) => {}
    }
    Ok(())
}

/// Drive the pull into a temp file via `fill`, then commit atomically: flush,
/// fsync, and rename onto `final_path` only after the stream terminated. The temp
/// file is removed if anything fails before the rename.
fn write_file<Fill>(
    client: &Client,
    stream_id: u64,
    final_path: &Path,
    fill: Fill,
) -> Result<(), RepeError>
where
    Fill: FnOnce(&mut ChunkReader<'_>, &mut std::fs::File) -> Result<(), RepeError>,
{
    let tmp_path = temp_sibling(final_path);
    let mut guard = TempFile::create(&tmp_path)?;
    let mut reader = ChunkReader::new(client, stream_id);

    let result = (|| {
        fill(&mut reader, guard.file_mut())?;
        if !reader.last_seen {
            // The fill loop returned without the terminating chunk — treat as a
            // truncated transfer rather than committing a short file.
            return Err(RepeError::Io(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "svs: stream ended without a final chunk",
            )));
        }
        guard.file_mut().flush()?;
        guard.file_mut().sync_all()?;
        Ok(())
    })();

    match result {
        Ok(()) => guard.commit(final_path),
        Err(e) => {
            // On failure, also tell the server to release the stream; the temp
            // file is removed by the guard's Drop.
            let _ = cancel_stream(client, stream_id, "receiver aborted");
            Err(e)
        }
    }
}

fn temp_sibling(final_path: &Path) -> PathBuf {
    let mut name = final_path
        .file_name()
        .map(|s| s.to_os_string())
        .unwrap_or_default();
    name.push(".svspart");
    final_path.with_file_name(name)
}

/// Owns a temp file and removes it on drop unless [`commit`](TempFile::commit)
/// renamed it into place first.
struct TempFile {
    path: PathBuf,
    file: Option<std::fs::File>,
}

impl TempFile {
    fn create(path: &Path) -> Result<Self, RepeError> {
        let file = std::fs::File::create(path)?;
        Ok(Self {
            path: path.to_path_buf(),
            file: Some(file),
        })
    }

    fn file_mut(&mut self) -> &mut std::fs::File {
        self.file.as_mut().expect("temp file open until commit")
    }

    fn commit(mut self, final_path: &Path) -> Result<(), RepeError> {
        self.file = None; // close before rename (Windows cannot rename an open file)
        match std::fs::rename(&self.path, final_path) {
            Ok(()) => {
                self.path = final_path.to_path_buf(); // committed; Drop must not remove it
                Ok(())
            }
            Err(e) => {
                // The handle is already closed, so `Drop` (file == None) will not
                // clean up: remove the orphaned temp file here before surfacing the
                // error, or a failed rename would leak a complete `.svspart`.
                let _ = std::fs::remove_file(&self.path);
                Err(RepeError::Io(e))
            }
        }
    }
}

impl Drop for TempFile {
    fn drop(&mut self) {
        if self.file.is_some() {
            // Not committed — close and remove the partial temp file.
            self.file = None;
            let _ = std::fs::remove_file(&self.path);
        }
    }
}

/// A `Read` adapter that issues `next` requests on demand and surfaces the
/// terminating `last = 1` as EOF. Modes that need a decoder wrap this; the raw
/// file mode reads it directly.
struct ChunkReader<'a> {
    client: &'a Client,
    stream_id: u64,
    buf: Vec<u8>,
    pos: usize,
    finished: bool,
    last_seen: bool,
}

impl<'a> ChunkReader<'a> {
    fn new(client: &'a Client, stream_id: u64) -> Self {
        Self {
            client,
            stream_id,
            buf: Vec::new(),
            pos: 0,
            finished: false,
            last_seen: false,
        }
    }

    fn fetch(&mut self) -> io::Result<()> {
        let body = beve::to_vec(&NextRequest {
            stream_id: self.stream_id,
        })
        .map_err(|e| io::Error::other(e.to_string()))?;
        let resp = self
            .client
            .call_with_formats(
                ROUTE_NEXT,
                QueryFormat::JsonPointer as u16,
                Some(&body),
                BodyFormat::Beve as u16,
            )
            .map_err(|e| io::Error::other(e.to_string()))?;
        let last = resp.query.first().copied() == Some(1);
        self.buf = resp.body;
        self.pos = 0;
        if last {
            self.last_seen = true;
            self.finished = true;
        }
        Ok(())
    }
}

impl Read for ChunkReader<'_> {
    fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {
        loop {
            if self.pos < self.buf.len() {
                let n = out.len().min(self.buf.len() - self.pos);
                out[..n].copy_from_slice(&self.buf[self.pos..self.pos + n]);
                self.pos += n;
                return Ok(n);
            }
            if self.finished {
                return Ok(0);
            }
            self.fetch()?;
            // After a fetch the buffer may be empty (a final empty `last` chunk);
            // loop once more, where `finished` now short-circuits to EOF.
        }
    }
}

fn cancel_stream(client: &Client, stream_id: u64, reason: &str) -> Result<(), RepeError> {
    let body = cancel_request_body(stream_id, reason)?;
    // Notify form: best-effort, no reply awaited (SVS §2.3).
    client.notify_with_formats(
        ROUTE_CANCEL,
        QueryFormat::JsonPointer as u16,
        Some(&body),
        BodyFormat::Beve as u16,
    )
}

// ---- client: async pull driver (over `AsyncClient`) ---------------------------
//
// The SVS receiver is a blocking pull loop feeding a blocking decoder
// (`beve::from_reader_streaming` / the bulk slice readers / `zstd`'s `Read`
// decoder) — none of which are `async`. To drive a pull from async code without
// blocking the runtime, we split the two halves across the async/blocking
// boundary: an async task issues `next` requests and feeds each chunk into a
// bounded channel, while a `spawn_blocking` task runs the decoder over a blocking
// `Read` that drains that channel. The bound supplies backpressure (the SVS
// round trip itself), so neither side runs ahead of the other.

mod sealed {
    pub trait Sealed {}
    impl Sealed for crate::async_client::AsyncClient {}
    #[cfg(feature = "websocket")]
    impl Sealed for crate::websocket_client::WebSocketClient {}
}

/// The async REPE transport an SVS pull is driven over. Implemented for the
/// async-TCP [`AsyncClient`] and, with the `websocket` feature, the
/// [`WebSocketClient`](crate::WebSocketClient) — both expose the same
/// request/notify-with-formats calls the pull loop needs, so the async pullers
/// accept either. Sealed: it abstracts over the in-crate async clients and is not
/// meant to be implemented downstream.
//
// `async fn` in a public trait normally warns (callers can't name/bound the
// returned future), but every use here `.await`s it inline on the caller's task
// — never spawned — so no `Send` bound is needed and the warning does not apply.
#[allow(async_fn_in_trait)]
pub trait AsyncSvsClient: sealed::Sealed {
    /// Request/response with explicit query/body formats (drives `open` / `next`).
    async fn svs_call(
        &self,
        path: &str,
        query_format: u16,
        body: Option<&[u8]>,
        body_format: u16,
    ) -> Result<Message, RepeError>;

    /// Fire-and-forget notify with explicit formats (drives best-effort `cancel`).
    async fn svs_notify(
        &self,
        path: &str,
        query_format: u16,
        body: Option<&[u8]>,
        body_format: u16,
    ) -> Result<(), RepeError>;
}

impl AsyncSvsClient for AsyncClient {
    async fn svs_call(
        &self,
        path: &str,
        query_format: u16,
        body: Option<&[u8]>,
        body_format: u16,
    ) -> Result<Message, RepeError> {
        self.call_with_formats(path, query_format, body, body_format)
            .await
    }

    async fn svs_notify(
        &self,
        path: &str,
        query_format: u16,
        body: Option<&[u8]>,
        body_format: u16,
    ) -> Result<(), RepeError> {
        self.notify_with_formats(path, query_format, body, body_format)
            .await
    }
}

#[cfg(feature = "websocket")]
impl AsyncSvsClient for crate::websocket_client::WebSocketClient {
    async fn svs_call(
        &self,
        path: &str,
        query_format: u16,
        body: Option<&[u8]>,
        body_format: u16,
    ) -> Result<Message, RepeError> {
        self.call_with_formats(path, query_format, body, body_format)
            .await
    }

    async fn svs_notify(
        &self,
        path: &str,
        query_format: u16,
        body: Option<&[u8]>,
        body_format: u16,
    ) -> Result<(), RepeError> {
        self.notify_with_formats(path, query_format, body, body_format)
            .await
    }
}

/// Chunks held in flight between the async pull task and the blocking decoder.
/// Small: the SVS round trip already paces the producer, so this only needs to
/// cover the gap between a `next` completing and the decoder consuming it.
const ASYNC_PULL_DEPTH: usize = 4;

/// A blocking [`Read`] over a channel of chunks. Lives on the `spawn_blocking`
/// thread and is fed by [`pull_loop_async`]; `blocking_recv` parks that thread
/// (never the runtime) until the next chunk or end-of-stream arrives.
struct ChannelReader {
    rx: tokio::sync::mpsc::Receiver<Vec<u8>>,
    buf: Vec<u8>,
    pos: usize,
}

impl ChannelReader {
    fn new(rx: tokio::sync::mpsc::Receiver<Vec<u8>>) -> Self {
        Self {
            rx,
            buf: Vec::new(),
            pos: 0,
        }
    }
}

impl Read for ChannelReader {
    fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {
        loop {
            if self.pos < self.buf.len() {
                let n = out.len().min(self.buf.len() - self.pos);
                out[..n].copy_from_slice(&self.buf[self.pos..self.pos + n]);
                self.pos += n;
                return Ok(n);
            }
            match self.rx.blocking_recv() {
                Some(chunk) => {
                    self.buf = chunk;
                    self.pos = 0;
                }
                // Sender dropped: the pull loop reached `last` (or errored). The
                // decoder sees a clean EOF; a short read surfaces as its own error.
                None => return Ok(0),
            }
        }
    }
}

/// Issue `next` requests over `client` and feed each non-empty chunk into `tx`
/// until the `last` flag. Returns early (without error) if the decoder finished
/// and dropped its receiver. `tx` drops on return, signalling EOF to the reader.
async fn pull_loop_async<C: AsyncSvsClient>(
    client: &C,
    stream_id: u64,
    tx: tokio::sync::mpsc::Sender<Vec<u8>>,
) -> Result<(), RepeError> {
    let body = next_request_body(stream_id)?;
    loop {
        let resp = client
            .svs_call(
                ROUTE_NEXT,
                QueryFormat::JsonPointer as u16,
                Some(&body),
                BodyFormat::Beve as u16,
            )
            .await?;
        let last = resp.query.first().copied() == Some(1);
        if !resp.body.is_empty() && tx.send(resp.body).await.is_err() {
            // Decoder is done and dropped the receiver; nothing left to feed.
            return Ok(());
        }
        if last {
            return Ok(());
        }
    }
}

/// Best-effort async `cancel` (notify form, no reply awaited; SVS §2.3).
async fn cancel_stream_async<C: AsyncSvsClient>(
    client: &C,
    stream_id: u64,
    reason: &str,
) -> Result<(), RepeError> {
    let body = cancel_request_body(stream_id, reason)?;
    client
        .svs_notify(
            ROUTE_CANCEL,
            QueryFormat::JsonPointer as u16,
            Some(&body),
            BodyFormat::Beve as u16,
        )
        .await
}

/// Send the `open` request over an async client and parse the response into an
/// [`OpenInfo`]. Shared by every async puller; the per-puller format check (if
/// any) runs on the returned `OpenInfo`.
async fn open_async<C: AsyncSvsClient>(client: &C, resource: &str) -> Result<OpenInfo, RepeError> {
    let body = open_request_body(resource)?;
    let resp = client
        .svs_call(
            ROUTE_OPEN,
            QueryFormat::JsonPointer as u16,
            Some(&body),
            BodyFormat::Beve as u16,
        )
        .await?;
    parse_open_response(&resp)
}

/// Pull an already-opened stream and consume it: the async pull loop and the
/// blocking `consume` run concurrently across the channel, with `consume`
/// receiving a `Read` over the (optionally zstd-decompressed) chunk stream.
///
/// A pull/network error is surfaced *before* `consume`'s value, so a truncated
/// transfer never returns a value built from a short read: the value (and
/// anything it owns, e.g. an uncommitted temp file) is dropped on that path.
async fn run_pull<V, F, C: AsyncSvsClient>(
    client: &C,
    open: OpenInfo,
    consume: F,
) -> Result<V, RepeError>
where
    V: Send + 'static,
    F: FnOnce(Box<dyn Read>) -> Result<V, RepeError> + Send + 'static,
{
    let (tx, rx) = tokio::sync::mpsc::channel::<Vec<u8>>(ASYNC_PULL_DEPTH);
    let compression = open.compression;
    // Starts immediately on a blocking thread; runs concurrently with the pull
    // loop below, the two paced by the channel bound.
    let consume_task = tokio::task::spawn_blocking(move || -> Result<V, RepeError> {
        let reader: Box<dyn Read> = match compression {
            Compression::None => Box::new(ChannelReader::new(rx)),
            Compression::Zstd => Box::new(
                zstd::stream::read::Decoder::new(ChannelReader::new(rx)).map_err(RepeError::Io)?,
            ),
        };
        consume(reader)
    });

    let pull_res = pull_loop_async(client, open.stream_id, tx).await;
    let consume_res = consume_task.await;
    // Best-effort release; the stream is spent (or the pull failed) either way.
    let _ = cancel_stream_async(client, open.stream_id, "pull complete").await;

    // A pull/network error explains any consume-side EOF, so surface it first.
    pull_res?;
    match consume_res {
        Ok(v) => v,
        Err(join_err) => Err(RepeError::Io(io::Error::other(format!(
            "svs consume task failed: {join_err}"
        )))),
    }
}

/// Open `resource`, require it be BEVE, and `run_pull` it. Shared by the async
/// value and bulk-slice pullers (which all decode BEVE).
async fn pull_beve_async<V, F, C: AsyncSvsClient>(
    client: &C,
    resource: &str,
    decode: F,
) -> Result<V, RepeError>
where
    V: Send + 'static,
    F: FnOnce(Box<dyn Read>) -> Result<V, RepeError> + Send + 'static,
{
    let open = open_async(client, resource).await?;
    if let Err(e) = require_beve(&open) {
        let _ = cancel_stream_async(client, open.stream_id, "format incompatible").await;
        return Err(e);
    }
    run_pull(client, open, decode).await
}

/// Async counterpart of [`pull_value`]: pull `resource` and decode the whole
/// stream into a `T` via BEVE (streaming, optionally zstd-decompressed).
///
/// `client` is any [`AsyncSvsClient`] — the async-TCP [`AsyncClient`] or, with
/// the `websocket` feature, the [`WebSocketClient`](crate::WebSocketClient). The
/// producer must run on a server that honours
/// [`Execution::OffReader`](crate::Execution) (the sync [`Server`](crate::Server)
/// or the WebSocket server), not the inline async server.
pub async fn pull_value_async<T: DeserializeOwned + Send + 'static, C: AsyncSvsClient>(
    client: &C,
    resource: &str,
) -> Result<T, RepeError> {
    pull_beve_async(client, resource, |reader| {
        beve::from_reader_streaming::<_, T>(reader).map_err(RepeError::from)
    })
    .await
}

/// Async counterpart of [`pull_typed_slice`]: bulk-decode a streamed numeric
/// array straight into a `Vec<T>` (memcpy of the little-endian payload). Accepts
/// any [`AsyncSvsClient`].
pub async fn pull_typed_slice_async<T: beve::BeveTypedSlice + Send + 'static, C: AsyncSvsClient>(
    client: &C,
    resource: &str,
) -> Result<Vec<T>, RepeError> {
    pull_beve_async(client, resource, |reader| {
        beve::read_typed_slice_from_reader::<T, _>(reader).map_err(RepeError::from)
    })
    .await
}

/// Async counterpart of [`pull_complex_slice`]: bulk-decode a streamed complex
/// array straight into a `Vec<Complex<T>>`. Accepts any [`AsyncSvsClient`].
pub async fn pull_complex_slice_async<
    T: beve::BeveTypedSlice + Send + 'static,
    C: AsyncSvsClient,
>(
    client: &C,
    resource: &str,
) -> Result<Vec<Complex<T>>, RepeError> {
    pull_beve_async(client, resource, |reader| {
        beve::read_complex_slice_from_reader::<T, _>(reader).map_err(RepeError::from)
    })
    .await
}

/// Async, format-agnostic escape hatch: pull `resource` and hand its logical
/// content to `consume` as a blocking [`Read`] (a `compression = zstd` stream is
/// decompressed on the way in; `none` is delivered verbatim). Unlike
/// [`pull_value_async`] this places no `format` constraint, so it drives an
/// opaque [`with_reader_stream`](RouterValueStreamExt::with_reader_stream)
/// producer as well as a BEVE one.
///
/// `consume` runs on a `spawn_blocking` thread and may block freely. The value it
/// returns is delivered only if the pull completed cleanly; on a truncated /
/// dropped transfer this returns the pull error and the value is dropped (so a
/// temp file `consume` opened is discarded rather than committed — see
/// [`pull_to_file_async`] / [`pull_to_file_verified_async`], which build on this).
pub async fn pull_consume_async<V, F, C: AsyncSvsClient>(
    client: &C,
    resource: &str,
    consume: F,
) -> Result<V, RepeError>
where
    V: Send + 'static,
    F: FnOnce(Box<dyn Read>) -> Result<V, RepeError> + Send + 'static,
{
    let open = open_async(client, resource).await?;
    run_pull(client, open, consume).await
}

/// A [`Write`] that forwards every byte to two sinks. Used to write a file while
/// feeding the same bytes to a digest in a single pass.
struct TeeWriter<'a, A: Write, B: Write> {
    file: &'a mut A,
    digest: &'a mut B,
}

impl<A: Write, B: Write> Write for TeeWriter<'_, A, B> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.file.write_all(buf)?;
        self.digest.write_all(buf)?;
        Ok(buf.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        self.file.flush()?;
        self.digest.flush()
    }
}

/// A [`Write`] that forwards all but the last `trailer_len` bytes to `inner`,
/// holding the most recent `trailer_len` bytes back so they can be lifted off as a
/// trailer once the whole stream has been written. Used to strip and recover an
/// app-appended digest trailer (`payload || digest`) in a single pass, feeding the
/// held-back bytes to neither the file nor the digest, and without buffering more
/// than `trailer_len` bytes at a time.
struct TrailerHold<W: Write> {
    inner: W,
    hold: Vec<u8>,
    trailer_len: usize,
}

impl<W: Write> TrailerHold<W> {
    fn new(inner: W, trailer_len: usize) -> Self {
        Self {
            inner,
            hold: Vec::with_capacity(trailer_len),
            trailer_len,
        }
    }

    /// Consume the adapter and return the held trailer (exactly `trailer_len`
    /// bytes). Errors if fewer than `trailer_len` bytes were ever written — the
    /// stream was too short to carry the claimed trailer.
    fn into_trailer(self) -> io::Result<Vec<u8>> {
        if self.hold.len() < self.trailer_len {
            return Err(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                format!(
                    "svs: stream of {} logical byte(s) is shorter than the {}-byte trailer",
                    self.hold.len(),
                    self.trailer_len
                ),
            ));
        }
        Ok(self.hold)
    }
}

impl<W: Write> Write for TrailerHold<W> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let n = self.trailer_len;
        if buf.len() >= n {
            // Every held byte is now older than the last `n` bytes of the stream,
            // so it is committed payload: flush it, then flush `buf`'s prefix, and
            // hold `buf`'s final `n` bytes as the new tail.
            if !self.hold.is_empty() {
                self.inner.write_all(&self.hold)?;
                self.hold.clear();
            }
            let split = buf.len() - n;
            self.inner.write_all(&buf[..split])?;
            self.hold.extend_from_slice(&buf[split..]);
        } else {
            // A short write cannot displace the whole tail; append and shed only
            // the overflow beyond the last `n` bytes.
            self.hold.extend_from_slice(buf);
            if self.hold.len() > n {
                let overflow = self.hold.len() - n;
                self.inner.write_all(&self.hold[..overflow])?;
                self.hold.drain(..overflow);
            }
        }
        Ok(buf.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        self.inner.flush()
    }
}

/// Async counterpart of [`pull_to_file`]: pull `resource` and write its logical
/// content to `path`, committed atomically (temp sibling, renamed only after the
/// terminating chunk and an fsync). A `compression = none` opaque byte stream is
/// written verbatim; a compressed stream is decompressed first. Returns the
/// number of content bytes written.
///
/// To verify content integrity before the file is published, use
/// [`pull_to_file_verified_async`].
pub async fn pull_to_file_async<C: AsyncSvsClient>(
    client: &C,
    resource: &str,
    path: &Path,
) -> Result<u64, RepeError> {
    let tmp_path = temp_sibling(path);
    let (guard, bytes) = pull_consume_async(client, resource, move |mut reader| {
        let mut guard = TempFile::create(&tmp_path)?;
        let bytes = io::copy(&mut reader, guard.file_mut())?;
        guard.file_mut().flush()?;
        guard.file_mut().sync_all()?;
        Ok((guard, bytes))
    })
    .await?;
    guard.commit(path)?;
    Ok(bytes)
}

/// Async file pull with a caller-supplied integrity gate. As content bytes are
/// written to the temp file they are also fed to `digest` (any [`Write`] — a
/// hasher, a CRC accumulator); after the stream completes cleanly and before the
/// temp file is renamed into place, `verify(digest)` is called. If it returns
/// `Err`, the temp file is discarded and nothing is committed at `path`; if it
/// returns `Ok`, the file is renamed in atomically.
///
/// This is the integrity seam SVS itself does not commit on the wire: the
/// producer and consumer agree on a content digest out of band (e.g. carried in
/// an application manifest), the consumer recomputes it here in one pass over the
/// streamed bytes, and a mismatch vetoes publication. A truncated transfer is
/// caught upstream of `verify` (it surfaces as the pull error) and likewise
/// commits nothing.
pub async fn pull_to_file_verified_async<C, D, V>(
    client: &C,
    resource: &str,
    path: &Path,
    digest: D,
    verify: V,
) -> Result<(), RepeError>
where
    C: AsyncSvsClient,
    D: Write + Send + 'static,
    V: FnOnce(D) -> Result<(), RepeError>,
{
    let tmp_path = temp_sibling(path);
    let (guard, digest) = pull_consume_async(client, resource, move |mut reader| {
        let mut guard = TempFile::create(&tmp_path)?;
        let mut digest = digest;
        {
            let mut tee = TeeWriter {
                file: guard.file_mut(),
                digest: &mut digest,
            };
            io::copy(&mut reader, &mut tee)?;
        }
        guard.file_mut().flush()?;
        guard.file_mut().sync_all()?;
        Ok((guard, digest))
    })
    .await?;
    // The stream terminated cleanly (a truncation would have surfaced as the pull
    // error above, before this point, discarding `guard`). Let the caller accept
    // or reject the content; only an accept commits the file.
    verify(digest)?;
    guard.commit(path)
}

/// Async counterpart of [`pull_to_vec`]: pull `resource` and return its entire
/// logical content as a `Vec<u8>` (a `compression = zstd` stream is decompressed
/// first). Accepts any [`AsyncSvsClient`].
///
/// Like the sync version this buffers the whole payload in memory and so defeats
/// the streaming bound — use it only for small payloads; for large transfers use
/// [`pull_to_file_async`] or [`pull_value_async`].
pub async fn pull_to_vec_async<C: AsyncSvsClient>(
    client: &C,
    resource: &str,
) -> Result<Vec<u8>, RepeError> {
    pull_consume_async(client, resource, |mut reader| {
        let mut buf = Vec::new();
        reader.read_to_end(&mut buf)?;
        Ok(buf)
    })
    .await
}

/// Async counterpart of [`pull_to_file_trailer_verified`]: pull an app-framed
/// `payload || trailer` stream, verify the trailer against a digest computed over
/// the payload, and commit **the payload only** to `path` (the trailer is
/// stripped).
///
/// The last `trailer_len` bytes are held back as the claimed trailer; every
/// earlier byte is written to a temp file and fed to `digest`. After a clean EOF,
/// `verify(digest, &trailer)` decides the commit: `Ok` renames the payload-only
/// file into place atomically; `Err` discards it. A truncated transfer surfaces as
/// the pull error before `verify` runs and commits nothing; a stream shorter than
/// `trailer_len` errors. This is the in-stream-digest parallel to
/// [`pull_to_file_verified_async`] (which instead hashes the *whole* stream against
/// an out-of-band digest and keeps every byte). The digest covers the logical
/// (pre-compression) bytes, so producer-side `opts.compression` is transparent.
///
/// `digest` runs on the `spawn_blocking` decode thread (hence `Send + 'static`);
/// `verify` runs on the caller's task after the pull completes.
pub async fn pull_to_file_trailer_verified_async<C, D, F>(
    client: &C,
    resource: &str,
    path: &Path,
    trailer_len: usize,
    digest: D,
    verify: F,
) -> Result<(), RepeError>
where
    C: AsyncSvsClient,
    D: Write + Send + 'static,
    F: FnOnce(D, &[u8]) -> Result<(), RepeError>,
{
    let tmp_path = temp_sibling(path);
    let (guard, digest, trailer) = pull_consume_async(client, resource, move |mut reader| {
        let mut digest = digest;
        let mut guard = TempFile::create(&tmp_path)?;
        let trailer = {
            let tee = TeeWriter {
                file: guard.file_mut(),
                digest: &mut digest,
            };
            let mut hold = TrailerHold::new(tee, trailer_len);
            io::copy(&mut reader, &mut hold)?;
            hold.into_trailer()?
        };
        guard.file_mut().flush()?;
        guard.file_mut().sync_all()?;
        Ok((guard, digest, trailer))
    })
    .await?;
    verify(digest, &trailer)?;
    guard.commit(path)
}

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

    fn drain(rx: &Receiver<Msg>) -> Vec<Vec<u8>> {
        let mut out = Vec::new();
        while let Ok(msg) = rx.recv() {
            match msg {
                Msg::Chunk(c) => out.push(c),
                Msg::End | Msg::Fail(_) => break,
            }
        }
        out
    }

    #[test]
    fn chunk_sink_splits_on_size_and_flushes_remainder() {
        let (tx, rx) = sync_channel::<Msg>(64);
        let mut sink = ChunkSink::new(tx, 4);
        // 10 bytes at chunk size 4 -> [4][4][2].
        sink.write_all(&[0u8; 10]).unwrap();
        sink.flush_remaining().unwrap();
        drop(sink);
        let chunks = drain(&rx);
        assert_eq!(
            chunks.iter().map(|c| c.len()).collect::<Vec<_>>(),
            vec![4, 4, 2]
        );
        assert_eq!(chunks.concat().len(), 10);
    }

    #[test]
    fn chunk_sink_intermediate_flush_does_not_emit_short_chunk() {
        let (tx, rx) = sync_channel::<Msg>(64);
        let mut sink = ChunkSink::new(tx, 8);
        sink.write_all(&[1u8; 3]).unwrap();
        sink.flush().unwrap(); // must not push a 3-byte chunk
        sink.write_all(&[2u8; 7]).unwrap(); // now 10 buffered -> one 8-chunk emitted
        sink.flush_remaining().unwrap();
        drop(sink);
        let chunks = drain(&rx);
        assert_eq!(
            chunks.iter().map(|c| c.len()).collect::<Vec<_>>(),
            vec![8, 2]
        );
    }

    fn session_from(msgs: Vec<Msg>) -> Session {
        let (tx, rx) = sync_channel::<Msg>(msgs.len().max(1));
        for m in msgs {
            tx.send(m).unwrap();
        }
        drop(tx);
        Session {
            rx,
            lookahead: None,
            done: false,
        }
    }

    #[test]
    fn pull_marks_only_the_final_chunk_last() {
        let mut s = session_from(vec![
            Msg::Chunk(vec![1]),
            Msg::Chunk(vec![2]),
            Msg::Chunk(vec![3]),
            Msg::End,
        ]);
        assert_eq!(s.pull().unwrap(), (vec![1], false));
        assert_eq!(s.pull().unwrap(), (vec![2], false));
        assert_eq!(s.pull().unwrap(), (vec![3], true));
    }

    #[test]
    fn pull_single_chunk_is_last() {
        let mut s = session_from(vec![Msg::Chunk(vec![9, 9]), Msg::End]);
        assert_eq!(s.pull().unwrap(), (vec![9, 9], true));
    }

    #[test]
    fn pull_zero_chunk_stream_is_empty_last() {
        let mut s = session_from(vec![Msg::End]);
        assert_eq!(s.pull().unwrap(), (Vec::<u8>::new(), true));
    }

    #[test]
    fn pull_surfaces_producer_failure_instead_of_clean_end() {
        // The lookahead peek encounters the failure before the buffered chunk
        // could be mislabeled `last`, so the failure surfaces as an error rather
        // than a clean terminus — the buffered chunk is discarded, not delivered.
        let mut s = session_from(vec![Msg::Chunk(vec![1]), Msg::Fail("boom".into())]);
        assert_eq!(s.pull().unwrap_err(), "boom");
    }

    #[test]
    fn pull_dropped_producer_is_an_error_not_a_terminus() {
        let (tx, rx) = sync_channel::<Msg>(1);
        tx.send(Msg::Chunk(vec![7])).unwrap();
        drop(tx); // vanish without End/Fail
        let mut s = Session {
            rx,
            lookahead: None,
            done: false,
        };
        // First pull yields the buffered chunk, peek sees the bare close -> error.
        assert!(s.pull().is_err());
    }

    #[test]
    fn trailer_hold_splits_payload_from_trailer_one_byte_at_a_time() {
        let mut sink = Vec::new();
        {
            let mut hold = TrailerHold::new(&mut sink, 4);
            for b in 0u8..10 {
                hold.write_all(&[b]).unwrap();
            }
            assert_eq!(hold.into_trailer().unwrap(), vec![6, 7, 8, 9]);
        }
        assert_eq!(sink, vec![0, 1, 2, 3, 4, 5]);
    }

    #[test]
    fn trailer_hold_splits_across_mixed_write_sizes() {
        // A big write, then single-byte writes, then another big write: the last
        // `trailer_len` bytes overall are the trailer regardless of write alignment.
        let mut sink = Vec::new();
        {
            let mut hold = TrailerHold::new(&mut sink, 4);
            hold.write_all(&[0, 1, 2, 3, 4, 5]).unwrap();
            hold.write_all(&[6]).unwrap();
            hold.write_all(&[7]).unwrap();
            hold.write_all(&[8, 9, 10, 11, 12]).unwrap();
            assert_eq!(hold.into_trailer().unwrap(), vec![9, 10, 11, 12]);
        }
        assert_eq!(sink, (0u8..=8).collect::<Vec<_>>());
    }

    #[test]
    fn trailer_hold_exact_length_yields_empty_payload() {
        let mut sink = Vec::new();
        {
            let mut hold = TrailerHold::new(&mut sink, 4);
            hold.write_all(&[1, 2, 3, 4]).unwrap();
            assert_eq!(hold.into_trailer().unwrap(), vec![1, 2, 3, 4]);
        }
        assert!(sink.is_empty(), "an all-trailer stream leaves no payload");
    }

    #[test]
    fn trailer_hold_shorter_than_trailer_errors() {
        let mut sink = Vec::new();
        let mut hold = TrailerHold::new(&mut sink, 8);
        hold.write_all(&[1, 2, 3]).unwrap();
        assert_eq!(
            hold.into_trailer().unwrap_err().kind(),
            io::ErrorKind::UnexpectedEof
        );
    }

    #[test]
    fn tempfile_commit_cleans_up_on_rename_failure() {
        // `commit` closes the file handle before renaming (Windows requires it),
        // which disarms the `Drop` cleanup — so its own failure path must remove the
        // temp file explicitly, or a failed rename leaks a complete `.svspart`.
        let base = std::env::temp_dir().join(format!("svs-tf-commit-{}", std::process::id()));
        std::fs::create_dir_all(&base).unwrap();
        let tmp = base.join("payload.svspart");
        // Target is a NON-EMPTY directory: renaming a file onto it fails on both
        // Unix (EISDIR/ENOTEMPTY) and Windows.
        let target = base.join("target");
        std::fs::create_dir_all(target.join("occupant")).unwrap();

        let mut guard = TempFile::create(&tmp).unwrap();
        guard.file_mut().write_all(b"complete payload").unwrap();
        assert!(
            guard.commit(&target).is_err(),
            "renaming onto a non-empty directory must fail"
        );
        assert!(
            !tmp.exists(),
            "a rename failure must not orphan the temp file"
        );

        std::fs::remove_dir_all(&base).ok();
    }
}