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
use crate::chunk::chunk_payload_data::{ChunkPayloadData, MessageId, MessageReliability};
use crate::chunk::chunk_selective_ack::GapAckBlock;
use crate::util::*;
use rustc_hash::FxHashMap;
use std::collections::{VecDeque, hash_map::Entry};
/// How far past the cumulative TSN a received DATA chunk may be. A SACK's gap blocks carry
/// 16-bit offsets from the cumulative TSN, so a chunk further ahead cannot be reported (its
/// offset would wrap); such chunks are dropped, as chunks outside the receive window are.
pub(crate) const MAX_RECEIVE_TSN_WINDOW: u32 = u16::MAX as u32;
/// Repeats kept between SACKs, as Chrome's dcSCTP and usrsctp keep.
pub(crate) const MAX_DUPLICATE_TSNS: usize = 20;
/// A fragmented message may have only one retained DATA chunk. Store that TSN
/// inline until another fragment is queued.
#[derive(Debug)]
enum MessageTsns {
One(u32),
Fragmented(VecDeque<u32>),
}
impl MessageTsns {
fn insert(&mut self, tsn: u32) {
match self {
Self::One(first) => {
let pair = if sna32lt(tsn, *first) {
[tsn, *first]
} else {
[*first, tsn]
};
*self = Self::Fragmented(VecDeque::from(pair));
}
Self::Fragmented(tsns) => {
if tsns.back().is_none_or(|last| sna32lt(*last, tsn)) {
tsns.push_back(tsn);
} else {
let index = tsns.partition_point(|&item| sna32lt(item, tsn));
tsns.insert(index, tsn);
}
}
}
}
/// Cumulative acknowledgment removes only a prefix of a message's TSNs.
/// Returns None without mutation if the expected prefix is missing, or
/// Some(true) when the whole index entry can be removed.
fn pop(&mut self, tsn: u32) -> Option<bool> {
match self {
Self::One(first) if *first == tsn => Some(true),
Self::Fragmented(tsns) if tsns.front() == Some(&tsn) => {
tsns.pop_front();
Some(tsns.is_empty())
}
_ => None,
}
}
fn to_vec(&self) -> Vec<u32> {
match self {
Self::One(tsn) => vec![*tsn],
Self::Fragmented(tsns) => tsns.iter().copied().collect(),
}
}
}
#[derive(Default, Debug)]
pub(crate) struct PayloadQueue {
// length: usize,
/// Keyed by TSN; per-chunk lookups on both the send (in-flight) and
/// receive paths. TSNs are window-bounded, so the faster non-SipHash
/// hasher is safe.
chunk_map: FxHashMap<u32, ChunkPayloadData>,
/// TSNs in serial-number order. A `VecDeque` so that `pop` — which almost
/// always removes the front, once per acked/received chunk — is O(1)
/// instead of shifting the whole in-flight window left (`Vec::remove(0)`
/// showed up as ~9% of the end-to-end transfer profile as memmove).
pub(crate) sorted: VecDeque<u32>,
dup_tsn: Vec<u32>,
n_bytes: usize,
/// Sent fragments of messages eligible for abandonment. A whole message
/// uses its candidate TSN directly; only fragmented messages need a group.
message_tsns: FxHashMap<MessageId, MessageTsns>,
#[cfg(test)]
pub(crate) track_lookups: bool,
#[cfg(test)]
pub(crate) lookups: std::cell::Cell<usize>,
}
impl PayloadQueue {
pub(crate) fn new() -> Self {
PayloadQueue::default()
}
/// Insert `tsn` into `sorted`, keeping SCTP serial-number order. Binary-search
/// the insertion point instead of re-sorting the whole vector on every push:
/// re-sorting made a burst of N chunks O(N^2 log N). In-order arrivals — the
/// common case, since TSNs are assigned/received sequentially — land at the
/// end in O(1) amortized.
fn insert_sorted(&mut self, tsn: u32) {
let idx = self.sorted.partition_point(|&x| sna32lt(x, tsn));
self.sorted.insert(idx, tsn);
}
pub(crate) fn can_push(&self, p: &ChunkPayloadData, cumulative_tsn: u32) -> bool {
!(self.chunk_map.contains_key(&p.tsn)
|| sna32lte(p.tsn, cumulative_tsn)
|| p.tsn.wrapping_sub(cumulative_tsn) > MAX_RECEIVE_TSN_WINDOW)
}
fn abandonment_id(p: &ChunkPayloadData) -> Option<MessageId> {
if p.beginning_fragment && p.ending_fragment {
return None;
}
match p.reliability {
MessageReliability::Reliable => None,
_ => p.message_id,
}
}
pub(crate) fn push_no_check(&mut self, p: ChunkPayloadData) {
if let Some(id) = Self::abandonment_id(&p) {
self.message_tsns
.entry(id)
.and_modify(|tsns| tsns.insert(p.tsn))
.or_insert(MessageTsns::One(p.tsn));
}
self.n_bytes += p.user_data.len();
self.insert_sorted(p.tsn);
self.chunk_map.insert(p.tsn, p);
//self.length += 1;
}
/// push pushes a payload data. If the payload data is already in our queue or
/// older than our cumulative_tsn marker, it will be recored as duplications,
/// which can later be retrieved using popDuplicates.
pub(crate) fn push(&mut self, p: ChunkPayloadData, cumulative_tsn: u32) -> bool {
let ok = self.chunk_map.contains_key(&p.tsn);
if ok || sna32lte(p.tsn, cumulative_tsn) {
self.record_duplicate(p.tsn);
return false;
}
self.push_no_check(p);
true
}
/// pop pops only if the oldest chunk's TSN matches the given TSN.
pub(crate) fn pop(&mut self, tsn: u32) -> Option<ChunkPayloadData> {
if self.sorted.front() != Some(&tsn) {
return None;
}
let Entry::Occupied(entry) = self.chunk_map.entry(tsn) else {
return None;
};
// Validate the message index before removing DATA or updating accounting.
if let Some(id) = Self::abandonment_id(entry.get()) {
let tsns = self.message_tsns.get_mut(&id)?;
if tsns.pop(tsn)? {
self.message_tsns.remove(&id);
}
}
let c = entry.remove();
self.sorted.pop_front();
if !c.payload_held {
self.n_bytes -= c.user_data.len();
}
Some(c)
}
pub(crate) fn message_tsns(&self, id: MessageId) -> Vec<u32> {
self.message_tsns
.get(&id)
.map_or_else(Vec::new, MessageTsns::to_vec)
}
/// get returns reference to chunkPayloadData with the given TSN value.
pub(crate) fn get(&self, tsn: u32) -> Option<&ChunkPayloadData> {
#[cfg(test)]
if self.track_lookups {
self.lookups.set(self.lookups.get() + 1);
}
self.chunk_map.get(&tsn)
}
pub(crate) fn get_mut(&mut self, tsn: u32) -> Option<&mut ChunkPayloadData> {
#[cfg(test)]
if self.track_lookups {
self.lookups.set(self.lookups.get() + 1);
}
self.chunk_map.get_mut(&tsn)
}
/// Lists a TSN received again for the next SACK, once per repeat (RFC 9260 section 3.3.4).
pub(crate) fn record_duplicate(&mut self, tsn: u32) {
if self.dup_tsn.len() < MAX_DUPLICATE_TSNS {
self.dup_tsn.push(tsn);
}
}
/// popDuplicates returns an array of TSN values that were found duplicate.
pub(crate) fn pop_duplicates(&mut self) -> Vec<u32> {
std::mem::take(&mut self.dup_tsn)
}
pub(crate) fn get_gap_ack_blocks(&self, cumulative_tsn: u32) -> Vec<GapAckBlock> {
if self.chunk_map.is_empty() {
return vec![];
}
let mut b = GapAckBlock::default();
let mut gap_ack_blocks = vec![];
for (i, tsn) in self.sorted.iter().enumerate() {
// RFC 9260 3.3.4: an offset from the Cumulative TSN Ack, in serial number arithmetic
// (the queued TSNs may have wrapped past zero while the cumulative TSN has not). A
// queued TSN is within `MAX_RECEIVE_TSN_WINDOW` of the cumulative TSN, so the offset
// fits its 16 bits.
let diff = tsn.wrapping_sub(cumulative_tsn) as u16;
if i == 0 {
b.start = diff;
b.end = b.start;
} else if b.end.checked_add(1) == Some(diff) {
b.end += 1;
} else {
gap_ack_blocks.push(b);
b.start = diff;
b.end = diff;
}
}
gap_ack_blocks.push(b);
gap_ack_blocks
}
pub(crate) fn get_gap_ack_blocks_string(&self, cumulative_tsn: u32) -> String {
let mut s = format!("cumTSN={}", cumulative_tsn);
for b in self.get_gap_ack_blocks(cumulative_tsn) {
s += format!(",{}-{}", b.start, b.end).as_str();
}
s
}
pub(crate) fn acknowledge(&mut self, tsn: u32) -> bool {
self.chunk_map
.get_mut(&tsn)
.is_some_and(ChunkPayloadData::acknowledge)
}
/// Release each payload byte once, preserving its acknowledgment state. A held payload
/// ([`Self::hold_acknowledged`]) is dropped now; its bytes were counted out already.
pub(crate) fn release_payload(&mut self, tsn: u32) -> usize {
if let Some(c) = self.chunk_map.get_mut(&tsn) {
let n = c.user_data.len();
if c.payload_held {
c.user_data.clear();
return 0;
}
self.n_bytes -= n;
c.user_data.clear();
n
} else {
0
}
}
/// A chunk a Gap Ack Block acknowledged: its bytes leave the outstanding count, once, and
/// its payload stays until the Cumulative TSN Ack covers the chunk, so that it can be
/// sent again if the receiver reneges (RFC 9260 6.2.1). Returns the bytes counted out.
pub(crate) fn hold_acknowledged(&mut self, tsn: u32) -> usize {
match self.chunk_map.get_mut(&tsn) {
Some(c) if !c.payload_held => {
let n = c.user_data.len();
self.n_bytes -= n;
c.payload_held = true;
n
}
_ => 0,
}
}
/// The receiver reneged on `tsn` (RFC 9260 6.2.1 D iii): it is outstanding again, its
/// bytes with it. Returns whether it was a gap-acknowledged chunk.
pub(crate) fn renege(&mut self, tsn: u32) -> bool {
match self.chunk_map.get_mut(&tsn) {
Some(c) if c.acknowledged && !c.abandoned() => {
c.renege();
if c.payload_held {
c.payload_held = false;
self.n_bytes += c.user_data.len();
}
true
}
_ => false,
}
}
/// The TSNs a Gap Ack Block acknowledged and that are still here (above the Cumulative
/// TSN Ack).
pub(crate) fn gap_acknowledged(&self) -> Vec<u32> {
self.sorted
.iter()
.copied()
.filter(|tsn| {
self.chunk_map
.get(tsn)
.is_some_and(|c| c.acknowledged && !c.abandoned())
})
.collect()
}
/// Takes every chunk, in TSN order, leaving the queue empty: the sent chunks of an
/// association that ended, which were not cumulatively acknowledged.
pub(crate) fn take_all(&mut self) -> Vec<ChunkPayloadData> {
let sorted = std::mem::take(&mut self.sorted);
let mut chunks = std::mem::take(&mut self.chunk_map);
self.message_tsns.clear();
self.n_bytes = 0;
sorted
.into_iter()
.filter_map(|tsn| chunks.remove(&tsn))
.collect()
}
pub(crate) fn get_last_tsn_received(&self) -> Option<&u32> {
self.sorted.back()
}
pub(crate) fn mark_all_to_retrasmit(&mut self) {
for c in self.chunk_map.values_mut() {
if !c.is_outstanding() {
continue;
}
c.retransmit = true;
}
}
/// The bytes of the chunks marked for retransmission: taken as lost, they are outstanding
/// but not in flight (RFC 9260 6.1, 7.2.3).
pub(crate) fn marked_for_retransmission_bytes(&self) -> usize {
self.chunk_map
.values()
.filter(|c| c.retransmit)
.map(|c| c.user_data.len())
.sum()
}
pub(crate) fn get_num_bytes(&self) -> usize {
self.n_bytes
}
/// Marks every outstanding chunk for retransmission (RFC 9260 6.3.3 E3). Returns the
/// bytes of user data newly marked, which go back to the peer's rwnd (6.2.1 C).
pub(crate) fn mark_all_for_retransmission(&mut self) -> usize {
let mut newly = 0;
for c in self.chunk_map.values_mut() {
if !c.is_outstanding() || c.retransmit {
continue;
}
c.retransmit = true;
newly += c.user_data.len();
}
newly
}
pub(crate) fn len(&self) -> usize {
//assert_eq!(self.chunk_map.len(), self.length);
self.chunk_map.len()
}
pub(crate) fn is_empty(&self) -> bool {
self.len() == 0
}
}
#[cfg(test)]
mod tests {
use super::*;
use bytes::Bytes;
#[test]
fn inconsistent_message_index_preserves_data_and_accounting() {
let id = MessageId::new(0).unwrap();
for invalid_index in [
None,
Some(MessageTsns::One(101)),
Some(MessageTsns::Fragmented(VecDeque::from([101, 100]))),
] {
let mut queue = PayloadQueue::new();
for tsn in [100, 101] {
queue.push_no_check(ChunkPayloadData {
tsn,
message_id: Some(id),
reliability: MessageReliability::Rexmit { max_retransmits: 1 },
beginning_fragment: tsn == 100,
ending_fragment: tsn == 101,
user_data: Bytes::from_static(b"data"),
..Default::default()
});
}
if let Some(index) = invalid_index {
queue.message_tsns.insert(id, index);
} else {
queue.message_tsns.remove(&id);
}
let before = queue.message_tsns(id);
assert!(queue.pop(100).is_none());
assert_eq!(VecDeque::from([100, 101]), queue.sorted);
assert_eq!(2, queue.len());
assert_eq!(8, queue.get_num_bytes());
for tsn in [100, 101] {
assert_eq!(
Bytes::from_static(b"data"),
queue.get(tsn).unwrap().user_data
);
}
assert_eq!(before, queue.message_tsns(id));
// Repairing only the index must leave both DATA chunks removable.
queue
.message_tsns
.insert(id, MessageTsns::Fragmented(VecDeque::from([100, 101])));
assert!(queue.pop(100).is_some());
assert!(queue.pop(101).is_some());
assert!(queue.is_empty());
assert!(queue.message_tsns(id).is_empty());
assert_eq!(0, queue.get_num_bytes());
}
}
}