// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! One direction of one byte stream, waiting to go out. //! //! CRYPTO frames and STREAM frames are the same thing twice: an offset, a //! length and some octets, reassembled at the far end into an ordered stream. //! §19.6 of RFC 9000 says as much — a CRYPTO frame "is similar to a STREAM //! frame, except that it does not have a Stream ID, it is not flow //! controlled, and it does not have a FIN". So the sending side of both is //! this: a buffer of what has been produced, a watermark of what has been put //! in a packet, and a range of what has to go again because the packet //! carrying it was lost. //! //! ## Why the buffer is borrowed //! //! Because a struct that owned it could not be returned by value: the slice //! would point into the copy it was built in. Every buffer in this library is //! lent by whoever will outlive it, which for a connection means the //! connection's own storage. //! //! ## What is kept, and for how long //! //! Everything, until the connection ends. Nothing here drops the prefix that //! has been acknowledged, because a handshake is a few thousand octets and //! the bookkeeping to do otherwise costs more than the memory does. A stream //! carrying a large request would want that prefix released as it is //! acknowledged, and this is where that would go. const std = @import("std"); const assert = std.debug.assert; pub const Error = error{ /// More was written than the buffer holds. BufferFull, }; /// A chunk to put in a frame. pub const Chunk = struct { offset: u64, data: []const u8, /// Whether this chunk ends the stream, which sets FIN on a STREAM frame. /// Always false for CRYPTO, which has no such bit. fin: bool = false, }; /// How many acknowledged ranges may wait above the prefix at once. const max_gaps = 8; /// A half-open range of stream offsets. const Range = struct { lo: u64, hi: u64 }; pub const Outgoing = struct { buffer: []u8, /// The stream offset that `buffer[0]` holds. /// /// Non-zero once anything has been dropped off the front. A stream is /// longer than any buffer a connection is willing to keep for it -- a /// megabyte of response body through a four-kilobyte buffer -- so the /// buffer is a window rather than the stream, and this is where the window /// starts. Offsets everywhere else are absolute, because that is what goes /// on the wire; this is the one place the difference is reconciled. base: u64 = 0, /// How much has been produced, as an absolute offset. len: u64 = 0, /// How much has been put in a packet at least once. sent: u64 = 0, /// The half-open range that a lost packet carried and that therefore has /// to go again. /// /// One range rather than a list, and losses are merged into it by taking /// the union: two lost packets with a delivered one between them produce /// a range covering all three, so the middle is sent a second time. That /// is wasteful and never wrong — a receiver takes the first arrival of an /// octet and ignores the rest — and it bounds the bookkeeping to two /// integers. resend_lo: u64 = 0, resend_hi: u64 = 0, /// Whether the producer has said there is no more. finished: bool = false, /// Whether the frame carrying the end has gone out. fin_sent: bool = false, /// How much of the stream the peer has acknowledged, as a contiguous /// prefix. /// /// A prefix, with the ranges that sit above it held in `acked_above` /// until the gap below them is filled. /// /// This used to be a prefix alone, on the argument that an /// acknowledgement which does not touch it may be dropped because the /// range will be declared lost, sent again and acknowledged again. That /// argument is false, and the way it fails is a stream that stops for /// ever: a range the peer *acknowledged* is not lost, so loss detection /// will never declare it so, so it is never sent again and never /// acknowledged again. Those octets are then held for the life of the /// connection, and since `compact` frees the acknowledged prefix and /// nothing above it, the window never empties and the writer waits for /// room that cannot come. /// /// Acknowledgements arrive out of order as a matter of course, and not /// only across frames: §19.3.1's range arithmetic is subtractive -- /// "largest = previous_smallest - gap - 2" -- so the ranges within one /// ACK frame descend, and a single frame covering packets 5 to 7 and 1 /// to 3 hands over the offsets above the hole before the ones below it. /// Packet 4 is then declared lost and sent again, which carries the /// prefix over the hole but not over what was dropped behind it. /// /// One stream on a quiet path has no holes and so hides all of this, /// which is why it survived until two concurrent downloads were asked /// for. acked_prefix: u64 = 0, /// Acknowledged ranges waiting for the prefix to reach them. /// /// Eight, which is more reordering than a path produces between one /// stream's packets; overflow is handled by giving a range back rather /// than by forgetting it, so a pathological path costs bandwidth instead /// of progress. acked_above: [max_gaps]Range = undefined, acked_above_len: usize = 0, /// An empty stream at offset zero, borrowing `buffer` as its window. /// /// The buffer's length is how much may be held at once -- written and not /// yet acknowledged -- and it must outlive the `Outgoing`, which keeps a /// slice of it rather than a copy. Its contents need no initializing. pub fn init(buffer: []u8) Outgoing { return .{ .buffer = buffer }; } test init { var storage: [1024]u8 = undefined; const o: Outgoing = .init(&storage); try testing.expect(!o.pending()); try testing.expectEqual(@as(?u64, null), o.finalSize()); } /// Adds to the end of the stream. /// /// The octets are copied in, so `data` need not outlive the call. All of /// it goes in or none of it does. Writing after `finish` is a programming /// error, and asserted. /// /// `BufferFull` means the window is full of octets that may still be /// needed -- either not yet sent, or sent and not yet acknowledged -- and /// the caller has to wait rather than give up. That is the difference /// between a buffer and a stream: the room comes back, and it comes back /// when the peer says so. pub fn write(o: *Outgoing, data: []const u8) Error!void { assert(!o.finished); if (o.held() + data.len > o.buffer.len) o.compact(); if (o.held() + data.len > o.buffer.len) return error.BufferFull; const at: usize = @intCast(o.len - o.base); @memcpy(o.buffer[at..][0..data.len], data); o.len += data.len; } test write { var storage: [8]u8 = undefined; var o: Outgoing = .init(&storage); try o.write("hello"); try testing.expectError(error.BufferFull, o.write("world")); // Once the peer has acknowledged the front, there is room again. o.advance(o.next(8).?); o.onAcked(0, 5); try o.write("world"); try testing.expectEqualStrings("world", o.next(8).?.data); } /// Moves this window's octets into a different buffer. /// /// Everything this struct remembers is a *stream* offset rather than an /// index into the buffer -- `base`, `len`, `acked_prefix`, the resend /// range -- so a window that changes buffers changes nothing else. What /// has to move is the held prefix, which `compact` keeps at the front and /// `write` appends behind, so it is one copy and not a rebuild. /// /// The new buffer must be able to hold what the old one does. Growing is /// the use for this; shrinking one that is not empty would be throwing /// away octets the peer has not acknowledged, which §13.3 still expects /// this endpoint to be able to send again. Afterwards nothing points into /// the old buffer, so it may be freed or reused -- but any `Chunk` that /// `next` returned before the move still does, and is stale. pub fn rehome(o: *Outgoing, buffer: []u8) void { const keeping = o.held(); assert(buffer.len >= keeping); if (keeping > 0) @memcpy(buffer[0..keeping], o.buffer[0..keeping]); o.buffer = buffer; } test rehome { var small: [4]u8 = undefined; var large: [16]u8 = undefined; var o: Outgoing = .init(&small); try o.write("abcd"); try testing.expectError(error.BufferFull, o.write("efgh")); // The same stream, in a bigger window: nothing is resent or renumbered. o.rehome(&large); try o.write("efgh"); const chunk = o.next(16).?; try testing.expectEqual(@as(u64, 0), chunk.offset); try testing.expectEqualStrings("abcdefgh", chunk.data); } /// How much of the stream the window is holding. fn held(o: *const Outgoing) usize { return @intCast(o.len - o.base); } /// Drops the front of the window, as far as is safe. /// /// Safe means acknowledged and not waiting to be sent again: §13.3 of RFC /// 9000 makes a lost frame's *contents* what gets retransmitted, so an /// octet stays needed until the peer has said it arrived. A range marked /// lost can overlap acknowledged octets -- `markLost` merges ranges by /// taking the union -- so the floor is the lower of the two rather than /// the acknowledged prefix alone. fn compact(o: *Outgoing) void { var floor = o.acked_prefix; if (o.resend_hi > o.resend_lo) floor = @min(floor, o.resend_lo); if (floor <= o.base) return; const drop: usize = @intCast(floor - o.base); const keep = o.held() - drop; std.mem.copyForwards(u8, o.buffer[0..keep], o.buffer[drop..][0..keep]); o.base = floor; } /// Says that what has been written is all there is. /// /// It fixes the final size, and the next chunk to reach the end carries /// FIN -- or, if everything has already gone out, an empty chunk carries /// it alone. No more may be written afterwards. Repeating it is harmless. pub fn finish(o: *Outgoing) void { o.finished = true; } test finish { var storage: [16]u8 = undefined; var o: Outgoing = .init(&storage); try o.write("bye"); o.advance(o.next(16).?); // Everything has gone out already, so the end goes on its own. o.finish(); const end = o.next(16).?; try testing.expect(end.fin); try testing.expectEqual(@as(u64, 3), end.offset); try testing.expectEqual(@as(usize, 0), end.data.len); } /// The final size of this stream, once it has one. /// /// §4.5: "the amount of flow control credit that is consumed by a /// stream... one higher than the offset of the byte with the largest /// offset sent on the stream, or zero if no bytes were sent." Both ends /// have to agree on it, which is why it travels on the frame that ends /// the stream rather than being inferred. /// /// Here that is everything written, which is what the FIN will declare /// once it goes out. A stream reset part way has a different one -- only /// what was sent -- and `stream.Send.finalSize` is where that is counted. pub fn finalSize(o: *const Outgoing) ?u64 { return if (o.finished) o.len else null; } test finalSize { var storage: [16]u8 = undefined; var o: Outgoing = .init(&storage); try o.write("twelve bytes"); // Not known until the producer says there is no more. try testing.expectEqual(@as(?u64, null), o.finalSize()); o.finish(); try testing.expectEqual(@as(?u64, 12), o.finalSize()); } /// Whether the next chunk would be data that has already been sent once. /// /// §4.1 of RFC 9000 counts flow control in offsets and not in /// transmissions -- "the sum of the final sizes" -- so a retransmission /// spends no credit, and must not be refused when there is none left. /// Refusing it is a deadlock: the credit that would pay for it can only /// be granted by a peer that has received what it is waiting for. pub fn resending(o: *const Outgoing) bool { return o.resend_hi > o.resend_lo; } test resending { var storage: [16]u8 = undefined; var o: Outgoing = .init(&storage); try o.write("abcdef"); o.advance(o.next(16).?); try testing.expect(!o.resending()); // The packet carrying it was lost, so what comes next is old data. o.markLost(0, 6); try testing.expect(o.resending()); } /// Whether anything is waiting to go out — data lost and owed again, data /// never yet sent, or the end of the stream on its own. /// /// The question a sender asks before building a frame, and the same one /// `next` answers with a chunk: this is true exactly when `next` would not /// return null. Flow control is not consulted, because it is not counted /// here. pub fn pending(o: *const Outgoing) bool { if (o.resend_hi > o.resend_lo) return true; if (o.len > o.sent) return true; return o.finished and !o.fin_sent; } test pending { var storage: [16]u8 = undefined; var o: Outgoing = .init(&storage); try testing.expect(!o.pending()); try o.write("data"); try testing.expect(o.pending()); o.advance(o.next(16).?); try testing.expect(!o.pending()); // The end still has to be said, even with no data left to carry it. o.finish(); try testing.expect(o.pending()); } /// The next piece to put in a frame, of at most `max` octets, or null if /// there is nothing to say. /// /// Recovery before novelty: a peer missing the middle of a stream cannot /// use anything sent after it, so sending new data first would be /// building on a gap. /// /// Nothing changes until the chunk is handed to `advance`, so asking /// twice gives the same answer, and a chunk that does not make it into a /// packet can simply be forgotten. Its `data` points into the window and /// is valid until the next `write`, `rehome` or `advance`. pub fn next(o: *const Outgoing, max: usize) ?Chunk { if (o.resend_hi > o.resend_lo) { const at: usize = @intCast(o.resend_lo - o.base); const len = @min(@as(usize, @intCast(o.resend_hi - o.resend_lo)), max); return .{ .offset = o.resend_lo, .data = o.buffer[at..][0..len], // The end travels with the last octet, and a retransmission // of the last octet carries it again. .fin = o.finished and o.resend_lo + len == o.len, }; } const at: usize = @intCast(o.sent - o.base); if (o.len > o.sent) { const len = @min(@as(usize, @intCast(o.len - o.sent)), max); return .{ .offset = o.sent, .data = o.buffer[at..][0..len], .fin = o.finished and o.sent + len == o.len, }; } // §3.1: a stream can end with no data at all, and the empty frame // carrying the FIN is what tells the peer its final size is zero. if (o.finished and !o.fin_sent) { return .{ .offset = o.sent, .data = &.{}, .fin = true }; } return null; } test next { var storage: [16]u8 = undefined; var o: Outgoing = .init(&storage); try o.write("abcdefgh"); o.finish(); // At most `max` octets, and the end only on the chunk that reaches it. const first = o.next(5).?; try testing.expectEqualStrings("abcde", first.data); try testing.expect(!first.fin); o.advance(first); const last = o.next(5).?; try testing.expectEqual(@as(u64, 5), last.offset); try testing.expectEqualStrings("fgh", last.data); try testing.expect(last.fin); o.advance(last); try testing.expectEqual(@as(?Chunk, null), o.next(5)); } /// Notes that a chunk has gone out. /// /// `chunk` must be the one `next` just returned, or a prefix of it with /// `fin` cleared -- which is how `stream.Send.next` cuts a chunk to the /// peer's flow control limit -- with nothing else changing the stream in /// between. A chunk carrying FIN marks the end as sent. pub fn advance(o: *Outgoing, chunk: Chunk) void { if (chunk.fin) o.fin_sent = true; if (o.resend_hi > o.resend_lo) { o.resend_lo += chunk.data.len; if (o.resend_lo >= o.resend_hi) { o.resend_lo = 0; o.resend_hi = 0; } return; } o.sent += chunk.data.len; } test advance { var storage: [16]u8 = undefined; var o: Outgoing = .init(&storage); try o.write("abcdef"); // Until a chunk is advanced past, it is offered again. const chunk = o.next(4).?; try testing.expectEqual(chunk.offset, o.next(4).?.offset); o.advance(chunk); try testing.expectEqual(@as(u64, 4), o.next(4).?.offset); } /// Notes that the peer acknowledged `len` octets at `offset`, which is /// what an acknowledged packet's frame for this stream carried. /// /// A range that meets the prefix extends it, and then pulls in whatever /// was waiting above; one that does not is kept until the gap below it /// is filled. Ranges already acknowledged, wholly or partly, are /// harmless. The prefix is what `write` reclaims room from. /// /// An empty range changes nothing, and that includes the empty frame /// that carries a FIN on its own: whether the end itself was acknowledged /// is not recorded here (see `allAcked`). pub fn onAcked(o: *Outgoing, offset: u64, len: usize) void { if (len == 0) return; const hi = offset + len; if (hi <= o.acked_prefix) return; // A range that straddles the prefix is trimmed to the part above it, // which then meets the prefix exactly. const lo = @max(offset, o.acked_prefix); if (lo == o.acked_prefix) { o.acked_prefix = hi; o.absorb(); return; } o.remember(lo, hi); } test onAcked { var storage: [16]u8 = undefined; var o: Outgoing = .init(&storage); try o.write("abcdefgh"); o.advance(o.next(4).?); o.advance(o.next(4).?); // The second packet is acknowledged first; it waits above the gap. o.onAcked(4, 4); try testing.expectEqual(@as(u64, 0), o.acked_prefix); // Then the first, and the two join up. o.onAcked(0, 4); try testing.expectEqual(@as(u64, 8), o.acked_prefix); } /// Moves every stored range that has become contiguous into the prefix. fn absorb(o: *Outgoing) void { var moved = true; while (moved) { moved = false; var i: usize = 0; while (i < o.acked_above_len) { const r = o.acked_above[i]; if (r.lo > o.acked_prefix) { i += 1; continue; } if (r.hi > o.acked_prefix) o.acked_prefix = r.hi; o.forgetGap(i); moved = true; } } } /// Keeps a range that is not yet contiguous with the prefix, merging it /// with any it touches. fn remember(o: *Outgoing, lo_in: u64, hi_in: u64) void { var lo = lo_in; var hi = hi_in; var i: usize = 0; while (i < o.acked_above_len) { const r = o.acked_above[i]; if (r.hi < lo or r.lo > hi) { i += 1; continue; } lo = @min(lo, r.lo); hi = @max(hi, r.hi); o.forgetGap(i); } if (o.acked_above_len == max_gaps) { // Nowhere to put another. The lowest stored range is given back // rather than dropped: sending it again is waste, because the // peer already has it, where forgetting it is a prefix that can // never pass it. var lowest: usize = 0; for (o.acked_above[0..o.acked_above_len], 0..) |r, j| { if (r.lo < o.acked_above[lowest].lo) lowest = j; } const given_back = o.acked_above[lowest]; o.forgetGap(lowest); o.markLost(given_back.lo, @intCast(given_back.hi - given_back.lo)); } o.acked_above[o.acked_above_len] = .{ .lo = lo, .hi = hi }; o.acked_above_len += 1; } fn forgetGap(o: *Outgoing, i: usize) void { o.acked_above_len -= 1; o.acked_above[i] = o.acked_above[o.acked_above_len]; } /// §3.1: whether the stream is finished and every octet of it has been /// acknowledged, which is what `stream.Send.onAcked` takes for the /// "Data Recvd" state — the only way the sending half of a stream /// terminates without a reset. /// /// The end itself is not tracked here: a stream whose data was all /// acknowledged reports true as soon as `finish` is called, whether or /// not the frame carrying FIN has been sent or acknowledged. That is /// right when the FIN rode on the last data frame, and premature when it /// went out on an empty frame of its own, which is why `stream.Send` /// also waits for the end's acknowledgement (`Send.fin_acked`). pub fn allAcked(o: *const Outgoing) bool { if (!o.finished) return false; return o.acked_prefix >= o.len; } test allAcked { var storage: [16]u8 = undefined; var o: Outgoing = .init(&storage); try o.write("done"); o.finish(); const chunk = o.next(16).?; try testing.expect(chunk.fin); o.advance(chunk); try testing.expect(!o.allAcked()); o.onAcked(chunk.offset, chunk.data.len); try testing.expect(o.allAcked()); } /// Merges a lost frame's contribution into the range to send again. /// /// `offset` and `len` are what the lost packet's frame for this stream /// carried; an empty range does nothing. Only octets are requeued here. /// If the frame carried FIN, the caller clears `fin_sent` itself so that /// the end goes again with the last octet. /// /// A range the peer has already acknowledged is dropped rather than /// queued. It arrives here whenever the same octets travelled in two /// packets and the later one was acknowledged first, and it is not merely /// wasteful to keep: the window is trimmed to what is still held, so a /// range below `base` would point at octets this buffer no longer has. pub fn markLost(o: *Outgoing, offset: u64, len: usize) void { if (len == 0) return; const from = @max(offset, o.acked_prefix); if (offset + len <= from) return; const hi = offset + len; if (o.resend_hi == o.resend_lo) { o.resend_lo = from; o.resend_hi = hi; return; } o.resend_lo = @min(o.resend_lo, from); o.resend_hi = @max(o.resend_hi, hi); } test markLost { var storage: [16]u8 = undefined; var o: Outgoing = .init(&storage); try o.write("abcdefgh"); o.advance(o.next(4).?); o.advance(o.next(4).?); try o.write("ij"); // The first packet was lost: it goes again before the new octets. o.markLost(0, 4); const again = o.next(16).?; try testing.expectEqual(@as(u64, 0), again.offset); try testing.expectEqualStrings("abcd", again.data); } }; const testing = std.testing; test "an acknowledgement that arrives out of order is not thrown away" { // Acknowledgements do not arrive in offset order. A packet is lost and // the ones behind it are not; two streams share a connection and their // packets interleave; the path reorders. Any of those acknowledges a // range above the contiguous prefix before the piece below it. // // Dropping that acknowledgement is not a lost optimisation, it is a // stream that stops for ever: those octets were sent, so nothing will // send them again, and they were never credited, so the window they sit // in is never freed. The writer waits for room that cannot come, and // from outside the connection simply stops with nothing in flight and no // timer armed. var storage: [64]u8 = undefined; var o: Outgoing = .init(&storage); try o.write("0123456789ab"); const first = o.next(4).?; o.advance(first); const second = o.next(4).?; o.advance(second); const third = o.next(4).?; o.advance(third); // Out of order, and with a gap that is filled last. o.onAcked(8, 4); try testing.expectEqual(@as(u64, 0), o.acked_prefix); o.onAcked(4, 4); try testing.expectEqual(@as(u64, 0), o.acked_prefix); // The piece below them arrives, and everything above it becomes // contiguous at once. o.onAcked(0, 4); try testing.expectEqual(@as(u64, 12), o.acked_prefix); try testing.expect(o.allAcked() == false); // not finished, so not "Data Recvd" } test "a lost range the peer already acknowledged is not queued again" { // The same octets travel twice whenever a frame is retransmitted, and // the two packets can be answered in either order -- so a loss signal for // a range that has since been acknowledged is ordinary, not exotic. It // arrives from the loss detector, from the probe timeout, and from a // packet dropped out of a full tracking table. // // Queuing it would do more than waste a round trip. `compact` frees the // acknowledged prefix and stops at whatever the resend window still // needs, so a resend range below the prefix pins the buffer at a point // the peer has already confirmed, and the stream fills and never empties. var storage: [64]u8 = undefined; var o: Outgoing = .init(&storage); try o.write("hello, world"); const chunk = o.next(12).?; o.advance(chunk); o.onAcked(0, 12); try testing.expect(!o.pending()); // Entirely behind the acknowledged prefix: nothing to do. o.markLost(0, 12); try testing.expect(!o.pending()); // Straddling it: only the part the peer has not confirmed. try o.write("!"); const tail = o.next(1).?; o.advance(tail); o.markLost(6, 7); const again = o.next(16).?; try testing.expectEqual(@as(u64, 12), again.offset); try testing.expectEqualStrings("!", again.data); } test "what is written comes out in order, in pieces of the caller's choosing" { var storage: [64]u8 = undefined; var o: Outgoing = .init(&storage); try testing.expect(!o.pending()); try o.write("hello, "); try o.write("world"); try testing.expect(o.pending()); const first = o.next(5).?; try testing.expectEqual(@as(u64, 0), first.offset); try testing.expectEqualStrings("hello", first.data); try testing.expect(!first.fin); o.advance(first); const second = o.next(64).?; try testing.expectEqual(@as(u64, 5), second.offset); try testing.expectEqualStrings(", world", second.data); o.advance(second); try testing.expect(!o.pending()); try testing.expectEqual(@as(?Chunk, null), o.next(64)); } test "RFC 9000 4.5: the end travels with the last octet" { var storage: [64]u8 = undefined; var o: Outgoing = .init(&storage); try o.write("abcdef"); o.finish(); try testing.expectEqual(@as(?u64, 6), o.finalSize()); // A chunk that stops short does not carry it. const partial = o.next(3).?; try testing.expect(!partial.fin); o.advance(partial); // The one that reaches the end does, so the stream costs no extra frame // to close. const rest = o.next(64).?; try testing.expectEqualStrings("def", rest.data); try testing.expect(rest.fin); o.advance(rest); try testing.expect(!o.pending()); } test "RFC 9000 3.1: a stream can end with nothing in it" { // "Send STREAM + FIN" from the Ready state, with no data ever written: // the empty frame is what tells the peer the final size is zero, and // there is no other way to say it. var storage: [8]u8 = undefined; var o: Outgoing = .init(&storage); o.finish(); try testing.expect(o.pending()); const chunk = o.next(64).?; try testing.expectEqual(@as(usize, 0), chunk.data.len); try testing.expect(chunk.fin); o.advance(chunk); try testing.expect(!o.pending()); try testing.expectEqual(@as(?u64, 0), o.finalSize()); } test "a lost piece goes again, before anything new" { var storage: [64]u8 = undefined; var o: Outgoing = .init(&storage); try o.write("0123456789"); const first = o.next(4).?; o.advance(first); const second = o.next(4).?; o.advance(second); try testing.expectEqual(@as(u64, 8), o.sent); // The packet carrying "0123" is declared lost. o.markLost(0, 4); const again = o.next(64).?; try testing.expectEqual(@as(u64, 0), again.offset); try testing.expectEqualStrings("0123", again.data); o.advance(again); // And only then does the new data follow. const new = o.next(64).?; try testing.expectEqual(@as(u64, 8), new.offset); try testing.expectEqualStrings("89", new.data); } test "two losses either side of a delivered piece resend the middle too" { // The union is deliberate: one range instead of a list, at the cost of // sending again what the peer already has. A receiver takes the first // arrival of an octet and ignores the rest, so the cost is bandwidth and // never correctness. var storage: [64]u8 = undefined; var o: Outgoing = .init(&storage); try o.write("0123456789"); o.advance(o.next(64).?); o.markLost(0, 2); o.markLost(6, 2); const again = o.next(64).?; try testing.expectEqual(@as(u64, 0), again.offset); try testing.expectEqualStrings("01234567", again.data); } test "RFC 9000 3.1: the sending half ends when everything has been acknowledged" { var storage: [64]u8 = undefined; var o: Outgoing = .init(&storage); try o.write("0123456789"); o.finish(); // Sent is not acknowledged: "Data Sent" is a state the stream sits in // while it retransmits. while (o.next(4)) |chunk| o.advance(chunk); try testing.expect(!o.allAcked()); o.onAcked(0, 4); try testing.expect(!o.allAcked()); o.onAcked(4, 4); try testing.expect(!o.allAcked()); o.onAcked(8, 2); try testing.expect(o.allAcked()); } test "an acknowledgement out of order waits for the one before it" { // The watermark is a prefix, so an acknowledgement for a later range does // not count until the earlier one arrives. What makes that safe is that // the earlier range will be declared lost and sent again, and the prefix // advances when *that* is acknowledged — a lagging watermark costs a // retransmission and never a stuck stream. var storage: [64]u8 = undefined; var o: Outgoing = .init(&storage); try o.write("0123456789"); o.finish(); while (o.next(64)) |chunk| o.advance(chunk); o.onAcked(5, 5); try testing.expectEqual(@as(u64, 0), o.acked_prefix); try testing.expect(!o.allAcked()); // And once the gap is filled, everything below it counts at once. o.onAcked(0, 10); try testing.expect(o.allAcked()); } test "an unfinished stream is never fully acknowledged" { // §3.1 has no path from "Send" to "Data Recvd": the final size has to be // known before everything can be known to have arrived. var storage: [64]u8 = undefined; var o: Outgoing = .init(&storage); try o.write("abc"); while (o.next(64)) |chunk| o.advance(chunk); o.onAcked(0, 3); try testing.expect(!o.allAcked()); o.finish(); // Finishing adds the empty FIN frame, which has to go out and be // acknowledged like anything else. try testing.expect(o.allAcked()); } test "writing more than the buffer holds is an error, not a truncation" { var storage: [4]u8 = undefined; var o: Outgoing = .init(&storage); try o.write("abc"); try testing.expectError(error.BufferFull, o.write("de")); // And nothing was written: a partial write would leave the stream with a // hole in it that nothing could fill. try testing.expectEqual(@as(usize, 3), o.len); } test "acknowledged ranges that meet each other are merged" { var storage: [64]u8 = undefined; var o: Outgoing = .init(&storage); try o.write("0123456789ab"); for (0..3) |_| o.advance(o.next(4).?); // Two ranges above the prefix that touch: 4..8 and 8..12 become one, so // filling the hole at 0..4 carries the prefix to the end in one step. o.onAcked(8, 4); o.onAcked(4, 4); try testing.expectEqual(@as(usize, 1), o.acked_above_len); o.onAcked(0, 4); try testing.expectEqual(@as(u64, 12), o.acked_prefix); } test "a duplicate acknowledgement below the prefix changes nothing" { var storage: [64]u8 = undefined; var o: Outgoing = .init(&storage); try o.write("0123456789ab"); for (0..3) |_| o.advance(o.next(4).?); o.onAcked(0, 8); try testing.expectEqual(@as(u64, 8), o.acked_prefix); o.onAcked(0, 4); try testing.expectEqual(@as(u64, 8), o.acked_prefix); try testing.expectEqual(@as(usize, 0), o.acked_above_len); // One that straddles the prefix extends it rather than being kept apart. o.onAcked(4, 8); try testing.expectEqual(@as(u64, 12), o.acked_prefix); } test "more gaps than can be held give a range back instead of losing it" { var storage: [128]u8 = undefined; var o: Outgoing = .init(&storage); try o.write("0123456789abcdefghijklmnopqrstuv" ++ "0123456789abcdefghijklmnopqrstuv"); for (0..16) |_| o.advance(o.next(4).?); // Every other range acknowledged, lowest first, so the ninth has nowhere // to go: eight is what `max_gaps` holds. for (0..max_gaps) |i| o.onAcked((i + 1) * 8, 4); try testing.expectEqual(@as(usize, max_gaps), o.acked_above_len); try testing.expect(!o.pending()); o.onAcked((max_gaps + 1) * 8, 4); try testing.expectEqual(@as(usize, max_gaps), o.acked_above_len); // The lowest was given back rather than forgotten, so it is queued to be // sent again and the prefix can still reach past it. try testing.expect(o.pending()); try testing.expectEqual(@as(u64, 8), o.resend_lo); }