livekit-data-stream 0.1.1

Data stream core logic for LiveKit
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
// Copyright 2025 LiveKit, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use bytes::Bytes;
use livekit_common::{EncryptionType, ParticipantIdentity};
use parking_lot::RwLock;
use std::{collections::HashMap, sync::Arc};
use tokio::sync::{
    mpsc::{self, UnboundedReceiver, UnboundedSender},
    watch,
};

use crate::{
    info::AnyStreamInfo,
    types::{Chunk, CompressionType, Header, Packet, StreamId, Trailer},
    utils::{StreamError, StreamProgress, StreamResult},
};

use super::{
    events::{
        ChunkReceived, InputEvent, OutputEvent, PacketReceived, StreamOpened, TrailerReceived,
    },
    stream_reader::AnyStreamReader,
};

/// Max data stream payload size, defaults to 5gb
const DEFAULT_MAX_PAYLOAD_BYTE_LENGTH: usize = (5e9) as usize;

struct Descriptor {
    progress: StreamProgress,
    chunk_tx: UnboundedSender<StreamResult<Bytes>>,
    /// Publishes `progress` updates to the reader's `progress()` stream.
    progress_tx: watch::Sender<StreamProgress>,
    encryption_type: EncryptionType,
    /// Identity of the participant sending this stream; used to abort the stream
    /// if that participant disconnects mid-send.
    sender_identity: ParticipantIdentity,
    is_internal: bool,
    /// Whether this is a text stream (decompressed output is reframed on UTF-8 boundaries).
    is_text: bool,
    /// Per-stream deflate-raw decompressor; `Some` if the header declared `DEFLATE_RAW`.
    decompressor: Option<DeflateDecompressState>,
    /// Highest chunk index processed so far (compressed streams; for dedup/gap detection).
    last_chunk_index: Option<u64>,
    /// Map of all attributes associated with string, so that any attributes within the trailer can
    /// be stored after stream creation.
    attributes_map: Arc<RwLock<HashMap<String, String>>>,
}

/// Streaming deflate-raw decompressor state for one compressed stream.
///
/// Backed by `async-compression`'s push-style (`AsyncWrite`) decoder: ordered compressed chunks
/// are written into it and the decompressed output lands in the inner `Vec`, which is drained per
/// chunk. Because the manager runs as an actor (see [`Manager::run`]), the decode is
/// awaited directly on the run-loop task — no lock is held across the `.await`, and it behaves
/// identically across every async backend the SDK supports.
struct DeflateDecompressState {
    decoder: async_compression::futures::write::DeflateDecoder<Vec<u8>>,
    /// Number of bytes which have been emitted by the compressor
    output_bytes_length: usize,
    /// Max number of bytes which the compressor can take in before erroring
    max_byte_length: usize,
    /// Decompressed text bytes not yet yielded because they end mid-codepoint.
    pending_text: Vec<u8>,
}

impl DeflateDecompressState {
    fn new(max_byte_length: usize) -> Self {
        // The `deflate` algorithm is raw DEFLATE (no zlib header/checksum), matching the wire
        // contract.
        Self {
            decoder: async_compression::futures::write::DeflateDecoder::new(Vec::new()),
            output_bytes_length: 0,
            max_byte_length,
            pending_text: Vec::new(),
        }
    }

    /// Feeds compressed `input` through the stateful decompressor, returning all
    /// decompressed output produced so far.
    async fn push(&mut self, input: &[u8]) -> StreamResult<Vec<u8>> {
        use futures_util::io::AsyncWriteExt;

        self.decoder.write_all(input).await.map_err(|_| StreamError::Decompression)?;

        // Flush so all currently-decodable output lands in the inner `Vec`.
        self.decoder.flush().await.map_err(|_| StreamError::Decompression)?;

        let output_bytes = std::mem::take(self.decoder.get_mut());
        self.output_bytes_length += output_bytes.len();
        if self.output_bytes_length > self.max_byte_length {
            return Err(StreamError::PayloadTooLarge);
        }

        Ok(output_bytes)
    }

    /// Appends `decompressed` text bytes and returns the longest valid-UTF-8 prefix,
    /// retaining any trailing incomplete codepoint for the next chunk.
    fn reframe_text(&mut self, decompressed: Vec<u8>) -> Bytes {
        self.pending_text.extend_from_slice(&decompressed);
        let valid = match std::str::from_utf8(&self.pending_text) {
            Ok(_) => self.pending_text.len(),
            Err(e) => e.valid_up_to(),
        };
        let mut before = std::mem::take(&mut self.pending_text);
        let after = before.split_off(valid);
        self.pending_text = after;
        Bytes::from(before)
    }
}

/// Batch size used to incrementally pull decompressed output from an inline payload.
const INFLATE_BATCH_BYTE_LENGTH: usize = 16 * 1024;

async fn inflate_raw(data: &[u8], max_byte_length: usize) -> StreamResult<Vec<u8>> {
    use futures_util::io::AsyncReadExt;
    let mut decoder = async_compression::futures::bufread::DeflateDecoder::new(
        futures_util::io::Cursor::new(data),
    );
    let mut out = Vec::new();
    let mut batch = [0u8; INFLATE_BATCH_BYTE_LENGTH];
    loop {
        let n = decoder.read(&mut batch).await.map_err(|_| StreamError::Decompression)?;
        if n == 0 {
            break;
        }
        out.extend_from_slice(&batch[..n]);
        if out.len() > max_byte_length {
            return Err(StreamError::PayloadTooLarge);
        }
    }
    Ok(out)
}

/// Cheap, cloneable, `Send + Sync` handle used to feed [`InputEvent`]s into the manager's run
/// loop.
///
/// Dropping the last handle stops the loop (via [`InputEvent::Shutdown`]).
#[derive(Clone)]
pub struct ManagerInput {
    input_tx: UnboundedSender<InputEvent>,
    _drop_guard: Arc<DropGuard>,
}

/// Sends [`InputEvent::Shutdown`] when the last [`ManagerInput`] is dropped.
struct DropGuard {
    input_tx: UnboundedSender<InputEvent>,
}

impl Drop for DropGuard {
    fn drop(&mut self) {
        let _ = self.input_tx.send(InputEvent::Shutdown);
    }
}

impl ManagerInput {
    fn new(input_tx: UnboundedSender<InputEvent>) -> Self {
        Self { input_tx: input_tx.clone(), _drop_guard: Arc::new(DropGuard { input_tx }) }
    }

    /// Feeds an event to the manager's run loop. Fails only if the loop has already stopped.
    pub fn send(&self, event: InputEvent) -> StreamResult<()> {
        self.input_tx.send(event).map_err(|_| StreamError::Internal)
    }
}

/// Actor that owns all incoming-stream state and processes [`InputEvent`]s on a single task
/// (see [`Self::run`]). Because it owns its state directly (no shared `Mutex`), its handlers can
/// `.await` decompression on the run-loop task.
pub struct Manager {
    inner: ManagerInner,
    input_rx: UnboundedReceiver<InputEvent>,
    output_tx: UnboundedSender<OutputEvent>,

    /// Topics whose streams are handled internally by the SDK (e.g. RPC) and never surfaced as
    /// application events. Supplied by the host crate so this crate stays decoupled from RPC.
    reserved_topics: Vec<&'static str>,

    /// Max number of bytes that a data stream can contain before it is deemed to be malicious
    max_payload_byte_length: usize,
}

#[derive(Default)]
struct ManagerInner {
    open_streams: HashMap<StreamId, Descriptor>,
}

impl Manager {
    pub fn new(
        reserved_topics: Vec<&'static str>,
        max_payload_byte_length: Option<usize>,
    ) -> (Self, ManagerInput, UnboundedReceiver<OutputEvent>) {
        // Unbounded: inbound wire packets must never be dropped (a dropped chunk is an
        // unrecoverable `MissedChunk`) and must not head-of-line-block the engine event loop.
        let (input_tx, input_rx) = mpsc::unbounded_channel();
        let (output_tx, output_rx) = mpsc::unbounded_channel();
        let manager = Self {
            inner: ManagerInner::default(),
            input_rx,
            output_tx,

            reserved_topics,
            max_payload_byte_length: max_payload_byte_length
                .unwrap_or(DEFAULT_MAX_PAYLOAD_BYTE_LENGTH),
        };
        (manager, ManagerInput::new(input_tx), output_rx)
    }

    /// Runs the manager's event loop until the input channel closes (all
    /// [`ManagerInput`]s dropped) or [`InputEvent::Shutdown`] is received. On exit,
    /// dropping `self` closes every open reader.
    pub async fn run(mut self) {
        while let Some(event) = self.input_rx.recv().await {
            match event {
                InputEvent::PacketReceived(PacketReceived { packet, participant_identity }) => {
                    match packet {
                        Packet::Header { header, encryption_type } => {
                            self.handle_header(header, participant_identity, encryption_type).await
                        }
                        Packet::Chunk { chunk, encryption_type } => {
                            self.handle_chunk(chunk, participant_identity, encryption_type).await
                        }
                        Packet::Trailer(trailer) => {
                            self.handle_trailer(trailer, participant_identity)
                        }
                    }
                }
                InputEvent::AbortStreamsFrom(identity) => self.handle_abort(identity),
                InputEvent::Shutdown => break,
            }
        }
    }

    /// Handles an incoming header packet.
    async fn handle_header(
        &mut self,
        mut header: Header,
        participant_identity: ParticipantIdentity,
        encryption_type: EncryptionType,
    ) {
        let is_internal = self.is_internal_topic(&header.topic);

        // A compression type from a future protocol version can't be decoded; drop the stream
        // (a conforming sender never sends compression a recipient didn't advertise support for,
        // so this is a defensive backstop).
        if header.compression == CompressionType::Unrecognized {
            log::warn!(
                "Stream '{}' received with an unrecognized compression type, dropping",
                header.stream_id
            );
            return;
        }

        // Read the v2 signals before `try_from_with_encryption` consumes the header.
        // Under test-utils, clone rather than take so the header still carries the
        // inline content when the info's `is_inline` diagnostic is computed from it.
        let inline_content = if cfg!(feature = "test-utils") {
            header.inline_content.clone()
        } else {
            header.inline_content.take()
        };
        let is_compressed = header.compression == CompressionType::DeflateRaw;

        let Ok(info) = AnyStreamInfo::try_from_with_encryption(header, encryption_type)
            .inspect_err(|e| log::error!("Invalid header: {}", e))
        else {
            return;
        };

        let id: StreamId = info.id().into();
        let is_text = matches!(info, AnyStreamInfo::Text(_));
        let bytes_total = info.total_length();
        let stream_encryption_type = info.encryption_type();
        let attributes_map = info.attributes_map();

        if self.inner.open_streams.contains_key(&id) {
            log::error!("Stream '{}' already open", id);
            return;
        }

        let (stream_reader, chunk_tx, progress_tx) = AnyStreamReader::from(info);
        let _ = self.output_tx.send(
            StreamOpened { stream_reader, participant_identity: participant_identity.clone() }
                .into(),
        );

        if bytes_total.is_some_and(|total| total > self.max_payload_byte_length as u64) {
            let _ = chunk_tx.send(Err(StreamError::PayloadTooLarge));
            return;
        }

        // Inline single-packet stream: synthesize the complete content now; no chunk/trailer
        // packets will follow, so we never register an open descriptor.
        if let Some(content) = inline_content {
            let content = if is_compressed {
                match inflate_raw(&content, self.max_payload_byte_length).await {
                    Ok(decompressed) => decompressed,
                    Err(error) => {
                        // Defensive: a conforming sender never sends a compressed stream we
                        // can't read, but drop gracefully if it happens.
                        let _ = chunk_tx.send(Err(error));
                        return;
                    }
                }
            } else {
                if content.len() > self.max_payload_byte_length {
                    let _ = chunk_tx.send(Err(StreamError::PayloadTooLarge));
                    return;
                }
                content
            };
            // The whole payload arrives at once, so publish a single completed progress update.
            let _ = progress_tx.send(StreamProgress {
                chunk_index: 0,
                bytes_processed: content.len() as u64,
                bytes_total,
            });
            // The full payload is complete and (for text) valid UTF-8, so deliver it as one chunk.
            if !content.is_empty() {
                let _ = chunk_tx.send(Ok(Bytes::from(content)));
            }
            // Dropping `chunk_tx` closes the reader.
            return;
        }

        let descriptor = Descriptor {
            progress: StreamProgress { bytes_total, ..Default::default() },
            chunk_tx,
            progress_tx,
            encryption_type: stream_encryption_type,
            sender_identity: participant_identity,
            is_internal,
            is_text,
            decompressor: is_compressed
                .then(|| DeflateDecompressState::new(self.max_payload_byte_length)),
            last_chunk_index: None,
            attributes_map,
        };
        self.inner.open_streams.insert(id, descriptor);
    }

    /// Returns whether a given streams is handled internally by the SDK
    /// (e.g. `lk.rpc_request`) and associated events should not be surfaced to the application.
    fn is_internal(&self, id: &StreamId) -> bool {
        self.inner.open_streams.get(id).is_some_and(|d| d.is_internal)
    }

    /// Returns whether streams created on the given topic are handled internally by the SDK
    /// (e.g. `lk.rpc_request`) and should not be surfaced to the application.
    ///
    /// When possible, prefer [`Self::is_internal`] instead.
    fn is_internal_topic(&self, topic: &str) -> bool {
        self.reserved_topics.iter().any(|t| t == &topic)
    }

    /// Handles an incoming chunk packet.
    async fn handle_chunk(
        &mut self,
        chunk: Chunk,
        participant_identity: ParticipantIdentity,
        encryption_type: EncryptionType,
    ) {
        let id = chunk.stream_id.clone();
        if !self.is_internal(&id) {
            let _ = self.output_tx.send(OutputEvent::ChunkReceived(ChunkReceived {
                chunk: chunk.clone(),
                participant_identity,
            }));
        }

        let inner = &mut self.inner;
        let Some(descriptor) = inner.open_streams.get_mut(&id) else {
            return;
        };

        if descriptor.encryption_type != encryption_type.into() {
            inner.close_stream_with_error(&id, StreamError::EncryptionTypeMismatch);
            return;
        }

        if let Some(decompressor) = &mut descriptor.decompressor {
            // --- Compressed stream: feed chunks through one stateful decompressor. ---
            // Duplicate index (reconnect replay): drop with a warning.
            if let Some(last) = descriptor.last_chunk_index {
                if chunk.chunk_index <= last {
                    log::warn!(
                        "Dropping duplicate chunk {} for compressed stream '{}'",
                        chunk.chunk_index,
                        id
                    );
                    return;
                }
            }
            // A gap is unrecoverable for a stateful decompressor.
            let expected = descriptor.last_chunk_index.map(|i| i + 1).unwrap_or(0);
            if chunk.chunk_index != expected {
                inner.close_stream_with_error(&id, StreamError::MissedChunk);
                return;
            }
            descriptor.last_chunk_index = Some(chunk.chunk_index);

            // Confine the decompressor borrow so we can re-borrow `inner` afterwards.
            let result: StreamResult<(u64, Bytes)> = {
                match decompressor.push(&chunk.content).await {
                    Ok(decompressed) => {
                        let uncompressed_byte_count = decompressed.len() as u64;
                        let yielded = if descriptor.is_text {
                            decompressor.reframe_text(decompressed)
                        } else {
                            Bytes::from(decompressed)
                        };
                        Ok((uncompressed_byte_count, yielded))
                    }
                    Err(error) => Err(error),
                }
            };

            let (uncompressed_byte_count, to_yield) = match result {
                Ok(value) => value,
                Err(error) => {
                    inner.close_stream_with_error(&id, error);
                    return;
                }
            };

            // Count decompressed bytes against the (uncompressed) total length.
            descriptor.progress.bytes_processed += uncompressed_byte_count;
            if let Some(total) = descriptor.progress.bytes_total {
                if descriptor.progress.bytes_processed > total {
                    inner.close_stream_with_error(&id, StreamError::LengthExceeded);
                    return;
                }
            }
            if !to_yield.is_empty() {
                inner.yield_chunk(&id, to_yield);
            }
            inner.publish_progress(&id);
            return;
        }

        // --- Uncompressed (v1) stream: contiguous chunks, content delivered as-is. ---
        if descriptor.progress.chunk_index != chunk.chunk_index {
            inner.close_stream_with_error(&id, StreamError::MissedChunk);
            return;
        }

        descriptor.progress.chunk_index += 1;
        descriptor.progress.bytes_processed += chunk.content.len() as u64;
        let bytes_processed = descriptor.progress.bytes_processed;
        let bytes_total = descriptor.progress.bytes_total;

        if bytes_processed > self.max_payload_byte_length as u64 {
            inner.close_stream_with_error(&id, StreamError::PayloadTooLarge);
            return;
        }
        if bytes_total.is_some_and(|total| bytes_processed > total) {
            inner.close_stream_with_error(&id, StreamError::LengthExceeded);
            return;
        }
        inner.yield_chunk(&id, Bytes::from(chunk.content));
        inner.publish_progress(&id);
    }

    /// Handles an incoming trailer packet.
    fn handle_trailer(&mut self, trailer: Trailer, participant_identity: ParticipantIdentity) {
        let id = trailer.stream_id.clone();
        if !self.is_internal(&id) {
            let _ = self
                .output_tx
                .send(TrailerReceived { trailer: trailer.clone(), participant_identity }.into());
        }

        let inner = &mut self.inner;
        let Some(descriptor) = inner.open_streams.get_mut(&id) else {
            return;
        };

        // Move over any attributes from the trailer into the stream-scoped attribute list.
        {
            let mut attributes_write = descriptor.attributes_map.write();
            attributes_write.extend(trailer.attributes);
        }

        if !match descriptor.progress.bytes_total {
            Some(total) => descriptor.progress.bytes_processed >= total,
            None => true,
        } {
            inner.close_stream_with_error(&id, StreamError::Incomplete);
            return;
        }
        if !trailer.reason.is_empty() {
            inner.close_stream_with_error(&id, StreamError::AbnormalEnd(trailer.reason));
            return;
        }
        inner.close_stream(&id);
    }

    /// Aborts every open stream being sent by the given participant, erroring each
    /// reader with [`StreamError::AbnormalEnd`].
    ///
    /// Called when a remote participant disconnects: any streams it had in flight to
    /// this receiver are terminated so their readers observe an error rather than
    /// hanging forever waiting for chunks that will never arrive.
    fn handle_abort(&mut self, identity: ParticipantIdentity) {
        self.inner.close_matching_streams_with_error(|_id, descriptor| {
            if descriptor.sender_identity == identity {
                let reason = format!(
                    "Participant {} unexpectedly disconnected in the middle of sending data",
                    identity
                );
                Err(StreamError::AbnormalEnd(reason))
            } else {
                Ok(())
            }
        });
    }
}

impl ManagerInner {
    fn yield_chunk(&mut self, id: &StreamId, chunk: Bytes) {
        let Some(descriptor) = self.open_streams.get_mut(id) else {
            return;
        };
        if descriptor.chunk_tx.send(Ok(chunk)).is_err() {
            // Reader has been dropped, close the stream.
            self.close_stream(id);
        }
    }

    /// Publishes the descriptor's current progress to the reader's `progress()` stream.
    fn publish_progress(&self, id: &StreamId) {
        if let Some(descriptor) = self.open_streams.get(id) {
            // `StreamProgress` is `Copy`; a send error just means the reader was dropped, which the
            // chunk channel already handles, so ignore it.
            let _ = descriptor.progress_tx.send(descriptor.progress);
        }
    }

    fn close_stream(&mut self, id: &StreamId) {
        // Dropping the sender closes the channel.
        self.open_streams.remove(id);
    }

    fn close_stream_with_error(&mut self, id: &StreamId, error: StreamError) {
        if let Some(descriptor) = self.open_streams.remove(id) {
            let _ = descriptor.chunk_tx.send(Err(error));
        }
    }

    fn close_matching_streams_with_error(
        &mut self,
        checker: impl Fn(&StreamId, &Descriptor) -> Result<(), StreamError>,
    ) {
        self.open_streams.retain(|id, descriptor| match checker(id, &descriptor) {
            Ok(_) => true,
            Err(error) => {
                let _ = descriptor.chunk_tx.send(Err(error));
                false
            }
        });
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        incoming::StreamReader,
        info::TextStreamInfo,
        test_utils::pseudo_random_text,
        types::{ByteHeader, StreamId, TextHeader},
    };
    use futures_util::{io::AsyncReadExt, Stream};
    use std::collections::HashMap;

    const SENDER: &str = "alice";

    async fn deflate_raw(data: &[u8]) -> Vec<u8> {
        let mut encoder = async_compression::futures::bufread::DeflateEncoder::new(
            futures_util::io::Cursor::new(data),
        );
        let mut out = Vec::new();
        encoder.read_to_end(&mut out).await.expect("DeflateEncoder::read_to_end failed");
        out
    }

    fn attrs(pairs: &[(&str, &str)]) -> HashMap<String, String> {
        pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()
    }

    #[allow(clippy::too_many_arguments)]
    fn text_header(
        id: &str,
        total_length: Option<u64>,
        attributes: HashMap<String, String>,
        inline_content: Option<Vec<u8>>,
        compression: CompressionType,
    ) -> Header {
        Header {
            stream_id: StreamId::from(id),
            timestamp: 0,
            topic: "topic".to_string(),
            mime_type: "text/plain".to_string(),
            total_length,
            attributes,
            content_header: Some(TextHeader::default().into()),
            inline_content,
            compression,
        }
    }

    fn byte_header(
        id: &str,
        total_length: Option<u64>,
        inline_content: Option<Vec<u8>>,
        compression: CompressionType,
    ) -> Header {
        Header {
            stream_id: StreamId::from(id),
            timestamp: 0,
            topic: "topic".to_string(),
            mime_type: "application/octet-stream".to_string(),
            total_length,
            attributes: HashMap::new(),
            content_header: Some(ByteHeader { name: "file".to_string() }.into()),
            inline_content,
            compression,
        }
    }

    fn chunk(id: &str, index: u64, content: Vec<u8>) -> Chunk {
        Chunk { stream_id: StreamId::from(id), chunk_index: index, content, ..Default::default() }
    }

    fn trailer(id: &str) -> Trailer {
        Trailer { stream_id: StreamId::from(id), ..Default::default() }
    }

    fn trailer_with_attrs(id: &str, attributes: HashMap<String, String>) -> Trailer {
        Trailer { stream_id: StreamId::from(id), reason: String::new(), attributes }
    }

    async fn read_text(reader: AnyStreamReader) -> StreamResult<String> {
        match reader {
            AnyStreamReader::Text(r) => r.read_all().await,
            _ => panic!("expected a text reader"),
        }
    }

    async fn read_bytes(reader: AnyStreamReader) -> StreamResult<Bytes> {
        match reader {
            AnyStreamReader::Byte(r) => r.read_all().await,
            _ => panic!("expected a byte reader"),
        }
    }

    fn text_info(reader: &AnyStreamReader) -> &TextStreamInfo {
        match reader {
            AnyStreamReader::Text(r) => r.info(),
            _ => panic!("expected a text reader"),
        }
    }

    /// Drives an [`Manager`] actor for tests: spawns its `run` loop, exposes
    /// `send_*` helpers to feed events, and `next_opened` to await the reader for a new stream.
    struct Harness {
        input: ManagerInput,
        output_rx: UnboundedReceiver<OutputEvent>,
    }

    impl Harness {
        fn new(reserved_topics: Vec<&'static str>) -> Self {
            Self::new_with_max_payload_length(reserved_topics, None)
        }

        fn new_with_max_payload_length(
            reserved_topics: Vec<&'static str>,
            max_payload_byte_length: Option<usize>,
        ) -> Self {
            let (manager, input, output_rx) =
                Manager::new(reserved_topics, max_payload_byte_length);
            tokio::spawn(manager.run());
            Self { input, output_rx }
        }

        fn send_packet(&self, packet: Packet) {
            self.send_packet_from(packet, SENDER);
        }

        fn send_packet_from(&self, packet: Packet, identity: &str) {
            let event = InputEvent::PacketReceived(PacketReceived {
                packet,
                participant_identity: ParticipantIdentity::from(identity),
            });
            self.input.send(event).expect("Harness::send_packet failed");
        }

        fn abort(&self, identity: ParticipantIdentity) {
            self.input.send(InputEvent::AbortStreamsFrom(identity)).unwrap();
        }

        /// Awaits the next opened stream's reader (skipping back-compat chunk/trailer outputs).
        async fn next_opened(&mut self) -> (AnyStreamReader, ParticipantIdentity) {
            loop {
                match self.output_rx.recv().await.expect("a stream should be opened") {
                    OutputEvent::StreamOpened(StreamOpened {
                        stream_reader,
                        participant_identity,
                    }) => {
                        return (stream_reader, participant_identity);
                    }
                    _ => continue,
                }
            }
        }
    }

    mod v1_legacy_multi_packet {
        use super::*;

        #[tokio::test]
        async fn v1_text_stream_round_trips() {
            let mut h = Harness::new(vec![]);
            let text = "hello world";
            h.send_packet(Packet::Header {
                header: text_header(
                    "s1",
                    Some(text.len() as u64),
                    attrs(&[("foo", "bar")]),
                    None,
                    CompressionType::None,
                ),
                encryption_type: EncryptionType::None,
            });
            let (reader, identity) = h.next_opened().await;
            assert_eq!(identity.as_str(), SENDER);
            assert_eq!(text_info(&reader).attributes().get("foo"), Some(&"bar".to_string()));
            h.send_packet(Packet::Chunk {
                chunk: chunk("s1", 0, text.as_bytes().to_vec()),
                encryption_type: EncryptionType::None,
            });
            h.send_packet(Packet::Trailer(trailer("s1")));
            assert_eq!(read_text(reader).await.unwrap(), text);
        }

        #[tokio::test]
        async fn v1_byte_stream_round_trips() {
            let mut h = Harness::new(vec![]);
            h.send_packet(Packet::Header {
                header: byte_header("s1", Some(4), None, CompressionType::None),
                encryption_type: EncryptionType::None,
            });
            let (reader, _) = h.next_opened().await;
            h.send_packet(Packet::Chunk {
                chunk: chunk("s1", 0, vec![1, 2, 3, 4]),
                encryption_type: EncryptionType::None,
            });
            h.send_packet(Packet::Trailer(trailer("s1")));
            assert_eq!(read_bytes(reader).await.unwrap(), Bytes::from(vec![1u8, 2, 3, 4]));
        }

        #[tokio::test]
        async fn v1_merges_trailer_attributes() {
            let mut h = Harness::new(vec![]);
            let text = "hi";
            h.send_packet(Packet::Header {
                header: text_header(
                    "s1",
                    Some(text.len() as u64),
                    attrs(&[("foo", "bar"), ("baz", "quux")]),
                    None,
                    CompressionType::None,
                ),
                encryption_type: EncryptionType::None,
            });
            let (reader, _) = h.next_opened().await;
            h.send_packet(Packet::Chunk {
                chunk: chunk("s1", 0, text.as_bytes().to_vec()),
                encryption_type: EncryptionType::None,
            });
            h.send_packet(Packet::Trailer(trailer_with_attrs(
                "s1",
                attrs(&[("hello", "world"), ("foo", "updated")]),
            )));
            // NOTE: trailer-attribute merging is asserted via the reader info after close.
            let info_attrs = text_info(&reader).attributes().clone();
            assert_eq!(read_text(reader).await.unwrap(), text);
            // The header attributes are present on the reader info at open time.
            assert_eq!(info_attrs.get("baz"), Some(&"quux".to_string()));
        }

        #[tokio::test]
        async fn v1_errors_when_too_few_bytes() {
            let mut h = Harness::new(vec![]);
            h.send_packet(Packet::Header {
                header: text_header("s1", Some(5), HashMap::new(), None, CompressionType::None),
                encryption_type: EncryptionType::None,
            });
            let (reader, _) = h.next_opened().await;
            h.send_packet(Packet::Chunk {
                chunk: chunk("s1", 0, vec![b'x']),
                encryption_type: EncryptionType::None,
            });
            h.send_packet(Packet::Trailer(trailer("s1")));
            assert!(matches!(read_text(reader).await, Err(StreamError::Incomplete)));
        }

        #[tokio::test]
        async fn v1_errors_when_too_many_bytes() {
            let mut h = Harness::new(vec![]);
            h.send_packet(Packet::Header {
                header: byte_header("s1", Some(3), None, CompressionType::None),
                encryption_type: EncryptionType::None,
            });
            let (reader, _) = h.next_opened().await;
            h.send_packet(Packet::Chunk {
                chunk: chunk("s1", 0, vec![1, 2, 3, 4, 5]),
                encryption_type: EncryptionType::None,
            });
            h.send_packet(Packet::Trailer(trailer("s1")));
            assert!(matches!(read_bytes(reader).await, Err(StreamError::LengthExceeded)));
        }

        #[tokio::test]
        async fn v1_max_payload_size_breached_with_unknown_total() {
            // A stream with no declared total must still be bounded by the receiver's cap.
            let mut h = Harness::new_with_max_payload_length(vec![], Some(1_000));
            h.send_packet(Packet::Header {
                header: byte_header("s1", None, None, CompressionType::None),
                encryption_type: EncryptionType::None,
            });
            let (reader, _) = h.next_opened().await;
            for i in 0..3 {
                h.send_packet(Packet::Chunk {
                    chunk: chunk("s1", i, vec![0u8; 400]),
                    encryption_type: EncryptionType::None,
                });
            }
            assert!(matches!(read_bytes(reader).await, Err(StreamError::PayloadTooLarge)));
        }

        #[tokio::test]
        async fn v1_max_payload_size_fast_fails_on_declared_total() {
            // A header declaring a total above the cap is rejected before any chunks arrive.
            let mut h = Harness::new_with_max_payload_length(vec![], Some(1_000));
            h.send_packet(Packet::Header {
                header: byte_header("s1", Some(2_000), None, CompressionType::None),
                encryption_type: EncryptionType::None,
            });
            let (reader, _) = h.next_opened().await;
            assert!(matches!(read_bytes(reader).await, Err(StreamError::PayloadTooLarge)));
        }

        #[tokio::test]
        async fn v1_payload_exactly_at_max_payload_size_succeeds() {
            // The cap is inclusive: a payload of exactly max_payload_byte_length is accepted.
            let mut h = Harness::new_with_max_payload_length(vec![], Some(1_000));
            h.send_packet(Packet::Header {
                header: byte_header("s1", Some(1_000), None, CompressionType::None),
                encryption_type: EncryptionType::None,
            });
            let (reader, _) = h.next_opened().await;
            h.send_packet(Packet::Chunk {
                chunk: chunk("s1", 0, vec![7u8; 1_000]),
                encryption_type: EncryptionType::None,
            });
            h.send_packet(Packet::Trailer(trailer("s1")));
            assert_eq!(read_bytes(reader).await.unwrap().len(), 1_000);
        }

        #[tokio::test]
        async fn v1_drops_on_encryption_type_mismatch() {
            let mut h = Harness::new(vec![]);
            h.send_packet(Packet::Header {
                header: text_header("s1", Some(2), HashMap::new(), None, CompressionType::None),
                encryption_type: EncryptionType::None,
            });
            let (reader, _) = h.next_opened().await;
            h.send_packet(Packet::Chunk {
                chunk: chunk("s1", 0, vec![b'h', b'i']),
                encryption_type: EncryptionType::Gcm,
            });
            assert!(matches!(read_text(reader).await, Err(StreamError::EncryptionTypeMismatch)));
        }

        #[tokio::test]
        async fn v1_trailer_attributes_merged_after_close() {
            let mut h = Harness::new(vec![]);
            let text = "hello world";
            h.send_packet(Packet::Header {
                header: text_header(
                    "s1",
                    Some(text.len() as u64),
                    attrs(&[("foo", "bar"), ("baz", "quux")]),
                    None,
                    CompressionType::None,
                ),
                encryption_type: EncryptionType::None,
            });
            let (reader, _) = h.next_opened().await;
            let info = text_info(&reader).clone();
            h.send_packet(Packet::Chunk {
                chunk: chunk("s1", 0, text.as_bytes().to_vec()),
                encryption_type: EncryptionType::None,
            });
            h.send_packet(Packet::Trailer(trailer_with_attrs(
                "s1",
                attrs(&[("hello", "world"), ("foo", "updated")]),
            )));
            assert_eq!(read_text(reader).await.unwrap(), text);
            // The trailer attributes are merged into the stream's attributes, overriding the header's.
            let merged = info.attributes();
            assert_eq!(merged.get("baz"), Some(&"quux".to_string()));
            assert_eq!(merged.get("hello"), Some(&"world".to_string()));
            assert_eq!(merged.get("foo"), Some(&"updated".to_string()));
        }
    }

    // --- v2 inline -----------------------------------------------------------------------
    mod v2_inline {
        use super::*;

        #[tokio::test]
        async fn v2_inline_uncompressed_text() {
            let mut h = Harness::new(vec![]);
            let text = "inline hello";
            h.send_packet(Packet::Header {
                header: text_header(
                    "s1",
                    Some(text.len() as u64),
                    attrs(&[("foo", "bar")]),
                    Some(text.as_bytes().to_vec()),
                    CompressionType::None,
                ),
                encryption_type: EncryptionType::None,
            });
            let (reader, _) = h.next_opened().await;
            assert_eq!(text_info(&reader).attributes().get("foo"), Some(&"bar".to_string()));
            // No chunk/trailer packets are fed.
            assert_eq!(read_text(reader).await.unwrap(), text);
        }

        #[tokio::test]
        async fn v2_inline_uncompressed_byte() {
            let mut h = Harness::new(vec![]);
            h.send_packet(Packet::Header {
                header: byte_header("s1", Some(3), Some(vec![1, 2, 3]), CompressionType::None),
                encryption_type: EncryptionType::None,
            });
            let (reader, _) = h.next_opened().await;
            assert_eq!(read_bytes(reader).await.unwrap(), Bytes::from(vec![1u8, 2, 3]));
        }

        #[tokio::test]
        async fn v2_inline_compressed_text() {
            let mut h = Harness::new(vec![]);
            let text = "hello hello compressible world";
            let compressed = deflate_raw(text.as_bytes()).await;
            h.send_packet(Packet::Header {
                header: text_header(
                    "s1",
                    Some(text.len() as u64),
                    attrs(&[("foo", "bar")]),
                    Some(compressed),
                    CompressionType::DeflateRaw,
                ),
                encryption_type: EncryptionType::None,
            });
            let (reader, _) = h.next_opened().await;
            assert_eq!(text_info(&reader).attributes().get("foo"), Some(&"bar".to_string()));
            assert_eq!(read_text(reader).await.unwrap(), text);
        }

        #[tokio::test]
        async fn v2_inline_compressed_byte() {
            let mut h = Harness::new(vec![]);
            let payload: Vec<u8> = (0..2000).map(|i| (i % 7) as u8).collect();
            let compressed = deflate_raw(&payload).await;
            h.send_packet(Packet::Header {
                header: byte_header(
                    "s1",
                    Some(payload.len() as u64),
                    Some(compressed),
                    CompressionType::DeflateRaw,
                ),
                encryption_type: EncryptionType::None,
            });
            let (reader, _) = h.next_opened().await;
            assert_eq!(read_bytes(reader).await.unwrap(), Bytes::from(payload));
        }

        #[tokio::test]
        async fn v2_inline_compressed_max_payload_size_breached() {
            // A tiny compressed inline payload that inflates far past the configured cap must be
            // rejected (decompression-bomb guard on the inline path).
            let mut h = Harness::new_with_max_payload_length(vec![], Some(1_000));
            let text = pseudo_random_text(50_000);
            let compressed = deflate_raw(text.as_bytes()).await;
            h.send_packet(Packet::Header {
                header: text_header(
                    "s1",
                    Some(text.len() as u64),
                    HashMap::new(),
                    Some(compressed),
                    CompressionType::DeflateRaw,
                ),
                encryption_type: EncryptionType::None,
            });
            let (reader, _) = h.next_opened().await;
            assert!(matches!(read_text(reader).await, Err(StreamError::PayloadTooLarge)));
        }

        #[tokio::test]
        async fn v2_inline_uncompressed_max_payload_size_breached() {
            // The cap applies to uncompressed inline payloads too. No declared total, so the
            // inline content check (not the header fast-fail) is what trips.
            let mut h = Harness::new_with_max_payload_length(vec![], Some(1_000));
            h.send_packet(Packet::Header {
                header: byte_header("s1", None, Some(vec![0u8; 2_000]), CompressionType::None),
                encryption_type: EncryptionType::None,
            });
            let (reader, _) = h.next_opened().await;
            assert!(matches!(read_bytes(reader).await, Err(StreamError::PayloadTooLarge)));
        }

        #[tokio::test]
        async fn v2_inline_zero_length_text() {
            let mut h = Harness::new(vec![]);
            h.send_packet(Packet::Header {
                header: text_header(
                    "s1",
                    Some(0),
                    HashMap::new(),
                    Some(vec![]), // present-but-empty inline payload
                    CompressionType::None,
                ),
                encryption_type: EncryptionType::None,
            });
            let (reader, _) = h.next_opened().await;
            assert_eq!(read_text(reader).await.unwrap(), "");
        }
    }

    // --- v2 multi-packet compressed ------------------------------------------------------

    mod v2_multi_packet_compressed {
        use super::*;

        #[tokio::test]
        async fn v2_multipacket_compressed_text() {
            let mut h = Harness::new(vec![]);
            // ~60 KB of pseudo-random lowercase so the compressed output spans multiple chunks.
            let text = pseudo_random_text(60_000);
            let compressed = deflate_raw(text.as_bytes()).await;
            let chunk_pieces: Vec<&[u8]> = compressed.chunks(15_000).collect();
            assert!(chunk_pieces.len() >= 2, "expected multi-packet compressed stream");

            h.send_packet(Packet::Header {
                header: text_header(
                    "s1",
                    Some(text.len() as u64),
                    HashMap::new(),
                    None,
                    CompressionType::DeflateRaw,
                ),
                encryption_type: EncryptionType::None,
            });
            let (reader, _) = h.next_opened().await;
            for (i, piece) in chunk_pieces.iter().enumerate() {
                h.send_packet(Packet::Chunk {
                    chunk: chunk("s1", i as u64, piece.to_vec()),
                    encryption_type: EncryptionType::None,
                });
            }
            h.send_packet(Packet::Trailer(trailer("s1")));
            assert_eq!(read_text(reader).await.unwrap(), text);
        }

        #[tokio::test]
        async fn errors_open_streams_on_sender_disconnect() {
            let mut h = Harness::new(vec![]);
            h.send_packet(Packet::Header {
                header: text_header("s1", Some(10), HashMap::new(), None, CompressionType::None),
                encryption_type: EncryptionType::None,
            });
            let (reader, _) = h.next_opened().await;
            // Partial content, no trailer: the sender then drops.
            h.send_packet(Packet::Chunk {
                chunk: chunk("s1", 0, vec![b'h', b'e', b'l', b'l', b'o']),
                encryption_type: EncryptionType::None,
            });
            h.abort(ParticipantIdentity::from(SENDER));
            assert!(matches!(read_text(reader).await, Err(StreamError::AbnormalEnd(_))));
        }

        #[tokio::test]
        async fn abort_only_affects_matching_sender() {
            let mut h = Harness::new(vec![]);
            h.send_packet_from(
                Packet::Header {
                    header: text_header("s1", Some(5), HashMap::new(), None, CompressionType::None),
                    encryption_type: EncryptionType::None,
                },
                "bob",
            );
            let (reader, _) = h.next_opened().await;
            h.send_packet_from(
                Packet::Chunk {
                    chunk: chunk("s1", 0, vec![b'h', b'e', b'l', b'l', b'o']),
                    encryption_type: EncryptionType::None,
                },
                "bob",
            );
            // A different participant disconnecting must not disturb bob's stream.
            h.abort(ParticipantIdentity::from(SENDER));
            h.send_packet_from(Packet::Trailer(trailer("s1")), "bob");
            assert_eq!(read_text(reader).await.unwrap(), "hello");
        }

        #[tokio::test]
        async fn v2_compressed_gap_errors() {
            let mut h = Harness::new(vec![]);
            let text = pseudo_random_text(60_000);
            let compressed = deflate_raw(text.as_bytes()).await;
            let pieces: Vec<&[u8]> = compressed.chunks(15_000).collect();
            assert!(pieces.len() >= 2);
            h.send_packet(Packet::Header {
                header: text_header(
                    "s1",
                    Some(text.len() as u64),
                    HashMap::new(),
                    None,
                    CompressionType::DeflateRaw,
                ),
                encryption_type: EncryptionType::None,
            });
            let (reader, _) = h.next_opened().await;
            h.send_packet(Packet::Chunk {
                chunk: chunk("s1", 0, pieces[0].to_vec()),
                encryption_type: EncryptionType::None,
            });
            // Skip index 1 -> feed index 2: a gap is a hard error.
            h.send_packet(Packet::Chunk {
                chunk: chunk("s1", 2, pieces[1].to_vec()),
                encryption_type: EncryptionType::None,
            });
            assert!(matches!(read_text(reader).await, Err(StreamError::MissedChunk)));
        }

        #[tokio::test]
        async fn v2_max_payload_size_breached() {
            let text = pseudo_random_text(60_000);
            let compressed = deflate_raw(text.as_bytes()).await;

            // Use a max payload size one byte below the size of the compressed data
            let mut h =
                Harness::new_with_max_payload_length(vec![], Some(50_000 /* less than 60k */));

            // Feed all data in
            h.send_packet(Packet::Header {
                header: text_header(
                    "s1",
                    Some(text.len() as u64),
                    HashMap::new(),
                    None,
                    CompressionType::DeflateRaw,
                ),
                encryption_type: EncryptionType::None,
            });
            let (reader, _) = h.next_opened().await;
            for (i, byte_chunk) in compressed.chunks(15_000).enumerate() {
                h.send_packet(Packet::Chunk {
                    chunk: chunk("s1", i as u64, byte_chunk.to_vec()),
                    encryption_type: EncryptionType::None,
                });
            }

            // And make sure a PayloadTooLarge error gets raised
            assert!(matches!(read_text(reader).await, Err(StreamError::PayloadTooLarge)));
        }

        #[tokio::test]
        async fn v2_multipacket_compressed_byte_stream() {
            let mut h = Harness::new(vec![]);
            let data = pseudo_random_text(60_000).into_bytes();
            let compressed = deflate_raw(&data).await;
            let pieces: Vec<&[u8]> = compressed.chunks(15_000).collect();
            assert!(pieces.len() >= 2, "expected multi-packet compressed stream");

            h.send_packet(Packet::Header {
                header: byte_header(
                    "s1",
                    Some(data.len() as u64),
                    None,
                    CompressionType::DeflateRaw,
                ),
                encryption_type: EncryptionType::None,
            });
            let (reader, _) = h.next_opened().await;
            for (i, piece) in pieces.iter().enumerate() {
                h.send_packet(Packet::Chunk {
                    chunk: chunk("s1", i as u64, piece.to_vec()),
                    encryption_type: EncryptionType::None,
                });
            }
            h.send_packet(Packet::Trailer(trailer("s1")));
            assert_eq!(read_bytes(reader).await.unwrap(), Bytes::from(data));
        }

        #[tokio::test]
        async fn v2_compressed_errors_when_too_few_bytes() {
            let mut h = Harness::new(vec![]);
            let text = "hello world"; // 11 bytes decompressed
            let compressed = deflate_raw(text.as_bytes()).await;
            h.send_packet(Packet::Header {
                header: text_header(
                    "s1",
                    Some(16), // more than the decompressed payload
                    HashMap::new(),
                    None,
                    CompressionType::DeflateRaw,
                ),
                encryption_type: EncryptionType::None,
            });
            let (reader, _) = h.next_opened().await;
            h.send_packet(Packet::Chunk {
                chunk: chunk("s1", 0, compressed),
                encryption_type: EncryptionType::None,
            });
            h.send_packet(Packet::Trailer(trailer("s1")));
            // The receiver counts DECOMPRESSED bytes against totalLength.
            assert!(matches!(read_text(reader).await, Err(StreamError::Incomplete)));
        }

        #[tokio::test]
        async fn v2_compressed_errors_when_too_many_bytes() {
            let mut h = Harness::new(vec![]);
            let text = "hello world"; // 11 bytes decompressed
            let compressed = deflate_raw(text.as_bytes()).await;
            h.send_packet(Packet::Header {
                header: text_header(
                    "s1",
                    Some(5), // fewer than the decompressed payload
                    HashMap::new(),
                    None,
                    CompressionType::DeflateRaw,
                ),
                encryption_type: EncryptionType::None,
            });
            let (reader, _) = h.next_opened().await;
            h.send_packet(Packet::Chunk {
                chunk: chunk("s1", 0, compressed),
                encryption_type: EncryptionType::None,
            });
            h.send_packet(Packet::Trailer(trailer("s1")));
            assert!(matches!(read_text(reader).await, Err(StreamError::LengthExceeded)));
        }

        #[tokio::test]
        async fn v2_compressed_duplicate_chunk_dropped() {
            let mut h = Harness::new(vec![]);
            let text = pseudo_random_text(60_000);
            let compressed = deflate_raw(text.as_bytes()).await;
            let pieces: Vec<&[u8]> = compressed.chunks(15_000).collect();
            assert!(pieces.len() >= 2);

            h.send_packet(Packet::Header {
                header: text_header(
                    "s1",
                    Some(text.len() as u64),
                    HashMap::new(),
                    None,
                    CompressionType::DeflateRaw,
                ),
                encryption_type: EncryptionType::None,
            });
            let (reader, _) = h.next_opened().await;
            h.send_packet(Packet::Chunk {
                chunk: chunk("s1", 0, pieces[0].to_vec()),
                encryption_type: EncryptionType::None,
            });
            // A replayed chunk (e.g. reconnect logic) must be dropped, not fed to the stateful
            // decompressor a second time.
            h.send_packet(Packet::Chunk {
                chunk: chunk("s1", 0, pieces[0].to_vec()),
                encryption_type: EncryptionType::None,
            });
            for (i, piece) in pieces.iter().enumerate().skip(1) {
                h.send_packet(Packet::Chunk {
                    chunk: chunk("s1", i as u64, piece.to_vec()),
                    encryption_type: EncryptionType::None,
                });
            }
            h.send_packet(Packet::Trailer(trailer("s1")));
            assert_eq!(read_text(reader).await.unwrap(), text);
        }

        #[tokio::test]
        async fn v2_compressed_text_reframes_multibyte_utf8() {
            let mut h = Harness::new(vec![]);
            let text = "😀你好世界 café — ¡ñandú! ".repeat(500);
            let compressed = deflate_raw(text.as_bytes()).await;
            // Split the compressed bytes at an arbitrary midpoint: the decompressor's output at the
            // seam can land mid-codepoint, exercising the UTF-8 reframing stage.
            let split = compressed.len() / 2;

            h.send_packet(Packet::Header {
                header: text_header(
                    "s1",
                    Some(text.len() as u64), // NOTE: byte length
                    HashMap::new(),
                    None,
                    CompressionType::DeflateRaw,
                ),
                encryption_type: EncryptionType::None,
            });
            let (reader, _) = h.next_opened().await;
            h.send_packet(Packet::Chunk {
                chunk: chunk("s1", 0, compressed[..split].to_vec()),
                encryption_type: EncryptionType::None,
            });
            h.send_packet(Packet::Chunk {
                chunk: chunk("s1", 1, compressed[split..].to_vec()),
                encryption_type: EncryptionType::None,
            });
            h.send_packet(Packet::Trailer(trailer("s1")));
            assert_eq!(read_text(reader).await.unwrap(), text);
        }

        #[tokio::test]
        async fn v2_unknown_compression_type_is_ignored() {
            let mut h = Harness::new(vec![]);
            // A compression type from a future protocol version arrives at the proto layer; the
            // receiver can't decode it, so per the spec's defensive-drop behavior (mirroring the web
            // SDK) the stream must be ignored rather than delivered as if uncompressed.
            let proto_header = livekit_protocol::data_stream::Header {
                stream_id: "s1".to_string(),
                timestamp: 0,
                topic: "topic".to_string(),
                mime_type: "text/plain".to_string(),
                total_length: Some(11),
                content_header: Some(
                    livekit_protocol::data_stream::header::ContentHeader::TextHeader(
                        livekit_protocol::data_stream::TextHeader::default(),
                    ),
                ),
                compression: 99, // <== HERE, potential future compression value
                inline_content: None,
                ..Default::default()
            };
            h.send_packet(Packet::Header {
                header: Header::from(proto_header),
                encryption_type: EncryptionType::None,
            });
            // A well-formed second stream: if the bogus stream was correctly dropped, this is the
            // next (and only) stream to open.
            h.send_packet(Packet::Header {
                header: text_header("s2", Some(2), HashMap::new(), None, CompressionType::None),
                encryption_type: EncryptionType::None,
            });
            let (reader, _) = h.next_opened().await;
            assert_eq!(
                text_info(&reader).id,
                "s2",
                "a stream with an unrecognized compression type must be dropped"
            );
        }

        #[tokio::test]
        async fn v2_compressed_merges_trailer_attributes() {
            let mut h = Harness::new(vec![]);
            let text = "hello world";
            let compressed = deflate_raw(text.as_bytes()).await;
            h.send_packet(Packet::Header {
                header: text_header(
                    "s1",
                    Some(text.len() as u64),
                    attrs(&[("foo", "bar")]),
                    None,
                    CompressionType::DeflateRaw,
                ),
                encryption_type: EncryptionType::None,
            });
            let (reader, _) = h.next_opened().await;
            let info = text_info(&reader).clone();
            h.send_packet(Packet::Chunk {
                chunk: chunk("s1", 0, compressed),
                encryption_type: EncryptionType::None,
            });
            h.send_packet(Packet::Trailer(trailer_with_attrs("s1", attrs(&[("hello", "world")]))));
            assert_eq!(read_text(reader).await.unwrap(), text);
            let merged = info.attributes();
            assert_eq!(merged.get("foo"), Some(&"bar".to_string()));
            assert_eq!(merged.get("hello"), Some(&"world".to_string()));
        }
    }

    mod progress {
        use super::*;

        /// Returns the reader's progress stream regardless of its concrete kind. Boxed because the two
        /// `progress()` impls are distinct opaque types that don't unify across match arms.
        fn progress_of(
            reader: &AnyStreamReader,
        ) -> std::pin::Pin<Box<dyn Stream<Item = StreamProgress> + Send + '_>> {
            match reader {
                AnyStreamReader::Byte(r) => Box::pin(r.progress()),
                AnyStreamReader::Text(r) => Box::pin(r.progress()),
            }
        }

        /// Drains a progress stream to completion (the stream ends when the sender closes).
        async fn collect_progress(
            stream: impl Stream<Item = StreamProgress>,
        ) -> Vec<StreamProgress> {
            use futures_util::StreamExt;
            let mut stream = std::pin::pin!(stream);
            let mut out = Vec::new();
            while let Some(progress) = stream.next().await {
                out.push(progress);
            }
            out
        }

        /// The last value reaches the total, values never decrease, and the stream terminates.
        fn assert_progress_completes(values: &[StreamProgress], total: u64) {
            let last = values.last().expect("progress stream yielded at least one value");
            assert_eq!(last.bytes_processed(), total);
            assert_eq!(last.bytes_total(), Some(total));
            assert_eq!(last.percentage(), Some(1.0));
            assert!(
                values.windows(2).all(|w| w[0].bytes_processed() <= w[1].bytes_processed()),
                "progress must be monotonically non-decreasing: {values:?}"
            );
        }

        #[tokio::test]
        async fn progress_reports_completion_uncompressed_bytes() {
            let mut h = Harness::new(vec![]);
            let total = 12u64;
            h.send_packet(Packet::Header {
                header: byte_header("s1", Some(total), None, CompressionType::None),
                encryption_type: EncryptionType::None,
            });
            let (reader, _) = h.next_opened().await;
            let progress = progress_of(&reader);
            // Feed the payload across several contiguous chunks; keep `reader` alive so the chunk
            // channel stays open while progress is observed.
            for (i, piece) in
                [vec![1, 2, 3, 4], vec![5, 6, 7, 8], vec![9, 10, 11, 12]].into_iter().enumerate()
            {
                h.send_packet(Packet::Chunk {
                    chunk: chunk("s1", i as u64, piece),
                    encryption_type: EncryptionType::None,
                });
            }
            h.send_packet(Packet::Trailer(trailer("s1")));

            let values = collect_progress(progress).await;
            assert_progress_completes(&values, total);
            drop(reader);
        }

        #[tokio::test]
        async fn progress_reports_completion_compressed_text() {
            let mut h = Harness::new(vec![]);
            let text = pseudo_random_text(60_000);
            let total = text.len() as u64;
            let compressed = deflate_raw(text.as_bytes()).await;
            let pieces: Vec<&[u8]> = compressed.chunks(15_000).collect();
            assert!(pieces.len() >= 2, "expected multi-packet compressed stream");

            h.send_packet(Packet::Header {
                header: text_header(
                    "s1",
                    Some(total),
                    HashMap::new(),
                    None,
                    CompressionType::DeflateRaw,
                ),
                encryption_type: EncryptionType::None,
            });
            let (reader, _) = h.next_opened().await;
            let progress = progress_of(&reader);
            for (i, piece) in pieces.iter().enumerate() {
                h.send_packet(Packet::Chunk {
                    chunk: chunk("s1", i as u64, piece.to_vec()),
                    encryption_type: EncryptionType::None,
                });
            }
            h.send_packet(Packet::Trailer(trailer("s1")));

            let values = collect_progress(progress).await;
            assert_progress_completes(&values, total);
            drop(reader);
        }

        #[tokio::test]
        async fn progress_reports_completion_inline() {
            let mut h = Harness::new(vec![]);
            let text = "inline hello";
            let total = text.len() as u64;
            h.send_packet(Packet::Header {
                header: text_header(
                    "s1",
                    Some(total),
                    HashMap::new(),
                    Some(text.as_bytes().to_vec()),
                    CompressionType::None,
                ),
                encryption_type: EncryptionType::None,
            });
            let (reader, _) = h.next_opened().await;
            // The whole payload arrives in the header, so progress jumps straight to complete.
            let values = collect_progress(progress_of(&reader)).await;
            assert_progress_completes(&values, total);
            drop(reader);
        }
    }

    #[tokio::test]
    async fn empty_chunks_are_ignored() {
        let mut h = Harness::new(vec![]);
        let text = "hello world";
        h.send_packet(Packet::Header {
            header: text_header(
                "s1",
                Some(text.len() as u64),
                HashMap::new(),
                None,
                CompressionType::None,
            ),
            encryption_type: EncryptionType::None,
        });
        let (reader, _) = h.next_opened().await;
        // An empty chunk must not count against totalLength or corrupt the stream.
        h.send_packet(Packet::Chunk {
            chunk: chunk("s1", 0, vec![]),
            encryption_type: EncryptionType::None,
        });
        h.send_packet(Packet::Chunk {
            chunk: chunk("s1", 1, text.as_bytes().to_vec()),
            encryption_type: EncryptionType::None,
        });
        h.send_packet(Packet::Trailer(trailer("s1")));
        assert_eq!(read_text(reader).await.unwrap(), text);
    }

    #[tokio::test]
    async fn trailer_with_reason_errors_abnormal_end() {
        let mut h = Harness::new(vec![]);
        h.send_packet(Packet::Header {
            header: text_header("s1", Some(5), HashMap::new(), None, CompressionType::None),
            encryption_type: EncryptionType::None,
        });
        let (reader, _) = h.next_opened().await;
        h.send_packet(Packet::Chunk {
            chunk: chunk("s1", 0, b"hello".to_vec()),
            encryption_type: EncryptionType::None,
        });
        h.send_packet(Packet::Trailer(Trailer {
            stream_id: StreamId::from("s1"),
            reason: "cancelled".to_string(),
            attributes: HashMap::new(),
        }));
        assert!(
            matches!(read_text(reader).await, Err(StreamError::AbnormalEnd(r)) if r == "cancelled")
        );
    }

    #[tokio::test]
    async fn text_stream_with_attachments_round_trips() {
        let mut h = Harness::new(vec![]);
        let text = "hello world";

        // Text stream whose header references an attachment stream id, body inline.
        let text_hdr =
            TextHeader { attached_stream_ids: vec![StreamId::from("att1")], ..Default::default() };
        h.send_packet(Packet::Header {
            header: Header {
                stream_id: StreamId::from("s1"),
                timestamp: 0,
                topic: "topic".to_string(),
                mime_type: "text/plain".to_string(),
                total_length: Some(text.len() as u64),
                attributes: HashMap::new(),
                content_header: Some(text_hdr.into()),
                inline_content: Some(text.as_bytes().to_vec()),
                compression: CompressionType::None,
            },
            encryption_type: EncryptionType::None,
        });
        let (text_reader, _) = h.next_opened().await;
        assert_eq!(text_info(&text_reader).attached_stream_ids, vec!["att1".to_string()]);
        assert_eq!(read_text(text_reader).await.unwrap(), text);

        // The attachment arrives as its own byte stream under the referenced id.
        h.send_packet(Packet::Header {
            header: byte_header("att1", Some(3), None, CompressionType::None),
            encryption_type: EncryptionType::None,
        });
        let (byte_reader, _) = h.next_opened().await;
        h.send_packet(Packet::Chunk {
            chunk: chunk("att1", 0, vec![1, 2, 3]),
            encryption_type: EncryptionType::None,
        });
        h.send_packet(Packet::Trailer(trailer("att1")));
        assert_eq!(read_bytes(byte_reader).await.unwrap(), Bytes::from(vec![1u8, 2, 3]));
    }
}