Something went wrong. Try again.
QUIC for Zig 0.17: RFC 9000-9002 with TLS 1.3, as a sans-I/O core plus a socket layer, with datagrams, multipath and raw public keys.
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Streams: RFC 9000 §2, §3 and §4.//!//! A stream is an ordered byte stream with no other structure QUIC can see//! (§2.2), and a connection carries many of them independently — which is the//! one thing QUIC has that TCP does not, and the reason a lost packet stalls//! one stream instead of all of them.//!//! What is here is the part with no I/O in it: who may open which stream//! (§2.1), the two halves of a stream's state machine (§3.1 and §3.2), and//! the flow control accounting that decides how much either end may send//! (§4). The buffers are lent in by the connection, for the same reason as//! everywhere else in this library.//!//! ## The two halves are genuinely separate//!//! §3 describes a sending part and a receiving part with their own states,//! and a bidirectional stream is one of each rather than a single machine//! with more states. That is not a presentational choice: §4.4 says//! "RESET_STREAM terminates one direction of a stream abruptly. For a//! bidirectional stream, RESET_STREAM has no effect on data flow in the//! opposite direction." An implementation that fused them has to invent a//! rule for what a reset does to the other side, and every such rule is//! wrong.//!//! ## Flow control is a limit, not a window//!//! §4.1: a receiver advertises "the limit of total bytes it is prepared to//! receive", an absolute offset rather than an allowance to be spent. That//! makes MAX_DATA and MAX_STREAM_DATA idempotent — a retransmitted one grants//! nothing extra, and one that arrives out of order and says *less* than the//! last is simply ignored, which is why §4.1 can say "a sender MUST ignore//! any MAX_STREAM_DATA or MAX_DATA frames that do not increase flow control//! limits" rather than having to order them.
const std = @import("std");const assert = std.debug.assert;
const outgoing = @import("outgoing.zig");const reassembly = @import("reassembly.zig");
pub const Outgoing = outgoing.Outgoing;
pub const Error = error{ /// §4.1: the peer sent more than the limit it was given. "A receiver MUST /// close the connection with an error of type FLOW_CONTROL_ERROR if the /// sender violates the advertised connection or stream data limits." FlowControlError, /// §4.5: the peer said the stream ends in two different places, or sent /// something at or past where it said it ended. FinalSizeError, /// §4.6: the peer opened more streams than it was allowed to. StreamLimitError, /// §3.3: a frame that this stream's state does not permit — sending on a /// unidirectional stream the peer opened, say. StreamStateError,};
/// Who opened a stream, which the low bit of its identifier says. §2.1:/// "Client-initiated streams have even-numbered stream IDs (with the bit set/// to 0), and server-initiated streams have odd-numbered stream IDs".pub const Initiator = enum(u1) { client = 0, server = 1 };
/// Whether a stream carries data one way or both, which the second-lowest bit/// says.pub const Directionality = enum(u1) { bidirectional = 0, unidirectional = 1 };
/// §2.1's four stream types, in the encoding the identifier itself uses.pub const Kind = enum(u2) { client_bidirectional = 0x0, server_bidirectional = 0x1, client_unidirectional = 0x2, server_unidirectional = 0x3,
/// Who opens streams of this kind: the low bit. pub fn initiator(k: Kind) Initiator { return @fromBackingInt(@intCast(@backingInt(k) & 0x1)); }
test initiator { try testing.expectEqual(Initiator.client, Kind.client_unidirectional.initiator()); try testing.expectEqual(Initiator.server, Kind.server_bidirectional.initiator()); }
/// Which way streams of this kind carry data: the second-lowest bit. pub fn directionality(k: Kind) Directionality { return @fromBackingInt(@intCast(@backingInt(k) >> 1)); }
test directionality { try testing.expectEqual(Directionality.bidirectional, Kind.client_bidirectional.directionality()); try testing.expectEqual(Directionality.unidirectional, Kind.server_unidirectional.directionality()); }};
/// A stream identifier: a 62-bit integer whose low two bits are not part of/// the count.////// §2.1: "The stream space for each type begins at the minimum value (0x00/// through 0x03, respectively); successive streams of each type are created/// with numerically increasing stream IDs." So the four types interleave in/// one number space, and the *index* of a stream within its type is the/// identifier shifted down by two — which is what every limit in §4.6 is/// counted in.pub const Id = struct { value: u64,
/// §16: a varint holds 62 bits, so this is the largest expressible /// identifier. pub const max = std.math.maxInt(u62);
/// Which of §2.1's four types this stream is: the low two bits. pub fn kind(id: Id) Kind { return @fromBackingInt(@intCast(@as(u2, @truncate(id.value)))); }
test kind { // Stream 6 is the second stream a client opened in one direction. const id: Id = .{ .value = 6 }; try testing.expectEqual(Kind.client_unidirectional, id.kind()); }
/// Who opened this stream. pub fn initiator(id: Id) Initiator { return id.kind().initiator(); }
test initiator { try testing.expectEqual(Initiator.client, (Id{ .value = 4 }).initiator()); try testing.expectEqual(Initiator.server, (Id{ .value = 5 }).initiator()); }
/// Whether this stream carries data one way or both. pub fn directionality(id: Id) Directionality { return id.kind().directionality(); }
test directionality { try testing.expectEqual(Directionality.bidirectional, (Id{ .value = 4 }).directionality()); try testing.expectEqual(Directionality.unidirectional, (Id{ .value = 7 }).directionality()); }
/// Which stream of its type this is, counting from zero. pub fn index(id: Id) u64 { return id.value >> 2; }
test index { // Stream 9 is the third bidirectional stream the server opened. const id: Id = .{ .value = 9 }; try testing.expectEqual(Kind.server_bidirectional, id.kind()); try testing.expectEqual(@as(u64, 2), id.index()); }
/// The identifier of the stream of type `k` numbered `index_` within it /// -- the inverse of `kind` and `index`. /// /// `index_` must fit in the 60 bits a varint leaves above the type, which /// is asserted: the same 2^60 that §4.6 caps a stream limit at. pub fn make(k: Kind, index_: u64) Id { assert(index_ <= max >> 2); return .{ .value = (index_ << 2) | @backingInt(k) }; }
test make { const id: Id = .make(.server_unidirectional, 1); try testing.expectEqual(@as(u64, 7), id.value); try testing.expectEqual(Kind.server_unidirectional, id.kind()); try testing.expectEqual(@as(u64, 1), id.index()); }
/// Whether this endpoint may send on this stream. /// /// §3.1: a unidirectional stream has a sending part only at the end that /// opened it. Writing to the other one is not a thing that can be /// expressed, and §19.8 makes a STREAM frame for it a /// STREAM_STATE_ERROR. pub fn canSend(id: Id, role: Initiator) bool { if (id.directionality() == .bidirectional) return true; return id.initiator() == role; }
test canSend { // A server may send on a unidirectional stream it opened, but not on // one the client opened. try testing.expect(Id.make(.server_unidirectional, 0).canSend(.server)); try testing.expect(!Id.make(.client_unidirectional, 0).canSend(.server)); }
/// Whether this endpoint may receive on this stream — the mirror of /// `canSend`. pub fn canReceive(id: Id, role: Initiator) bool { if (id.directionality() == .bidirectional) return true; return id.initiator() != role; }
test canReceive { try testing.expect(Id.make(.client_unidirectional, 0).canReceive(.server)); try testing.expect(!Id.make(.client_unidirectional, 0).canReceive(.client)); }
/// Whether this endpoint opened it, given which end this endpoint is. pub fn isLocal(id: Id, role: Initiator) bool { return id.initiator() == role; }
test isLocal { const id: Id = .make(.client_bidirectional, 3); try testing.expect(id.isLocal(.client)); try testing.expect(!id.isLocal(.server)); }};
/// §4.1's limit: an absolute offset a peer may not send past.////// Used at both levels and in both directions, because the rule is the same/// one four times over: what differs is only what is being counted.pub const Credit = struct { /// The largest total the far end may send. limit: u64, /// How much of it is spoken for. used: u64 = 0,
/// A limit with none of it spent: the starting point that an /// `initial_max_data` or `initial_max_stream_data` transport parameter /// gives. pub fn init(limit: u64) Credit { return .{ .limit = limit }; }
test init { const c: Credit = .init(1000); try testing.expectEqual(@as(u64, 1000), c.available()); try testing.expect(!c.blocked()); }
/// How much more may be sent before the limit is reached; zero, never /// an underflow, when `used` has been pushed past it. pub fn available(c: Credit) u64 { return c.limit -| c.used; }
test available { var c: Credit = .init(100); try c.spend(30); try testing.expectEqual(@as(u64, 70), c.available()); }
/// Spends credit, or says there is not enough. /// /// The check is `>` rather than `>=` because the limit is the largest /// offset that may be *reached*: a limit of 100 permits octets 0 through /// 99, which is a total of 100 octets. /// /// `FlowControlError` spends nothing, so the caller may report it and /// the count stays what it was. pub fn spend(c: *Credit, n: u64) Error!void { if (c.used + n > c.limit) return error.FlowControlError; c.used += n; }
test spend { var c: Credit = .init(100); try c.spend(100); try testing.expectError(error.FlowControlError, c.spend(1)); try testing.expectEqual(@as(u64, 100), c.used); }
/// Raises the limit, or ignores the attempt. /// /// §4.1: "Once a receiver advertises a limit for the connection or a /// stream, it is not an error to advertise a smaller limit, but the /// smaller limit has no effect." Which is what makes a retransmitted or /// reordered MAX_DATA harmless rather than something that has to be /// sequenced. pub fn grant(c: *Credit, new_limit: u64) void { c.limit = @max(c.limit, new_limit); }
test grant { var c: Credit = .init(100); c.grant(250); try testing.expectEqual(@as(u64, 250), c.limit); // A stale MAX_DATA arriving late takes nothing back. c.grant(200); try testing.expectEqual(@as(u64, 250), c.limit); }
/// Whether the far end has run out. pub fn blocked(c: Credit) bool { return c.used >= c.limit; }
test blocked { var c: Credit = .init(10); try c.spend(9); try testing.expect(!c.blocked()); try c.spend(1); try testing.expect(c.blocked()); }};
/// §3.1: the sending half of a stream.pub const Send = struct { pub const State = enum { /// Created, with nothing sent yet. ready, /// Sending data. send, /// The frame carrying the end has gone out; only retransmissions /// remain. data_sent, /// Everything, including the end, has been acknowledged. Terminal. data_received, /// A reset has been decided on. No more data goes out, and the /// RESET_STREAM is owed or in flight until it is acknowledged. reset_sent, /// The RESET_STREAM was acknowledged. Terminal. reset_received, };
state: State = .ready, data: Outgoing, /// What the peer will let this stream send, from its /// `initial_max_stream_data` and then MAX_STREAM_DATA. credit: Credit, /// §19.4's error code, once a reset has been asked for. reset_code: ?u64 = null, /// Whether the RESET_STREAM frame still has to go out. /// /// §3.5 is the reason this is not implicit in the state: a STOP_SENDING /// "SHOULD" be answered with a RESET_STREAM, and an endpoint that moved /// straight to the terminal state would answer it with silence -- the /// peer asked this end to stop and is never told that it did. The stream /// is therefore not finished with while this is set, or its slot would be /// reclaimed before the frame it still owes was written. reset_pending: bool = false, /// Whether the peer has acknowledged a frame carrying the end. /// /// Not the same as every octet having been acknowledged: when the end /// goes out on an empty frame of its own, after the data, the data can be /// acknowledged while that frame is lost. Taking the one for the other /// leaves the stream in "Data Recvd" with nothing that would send the /// end again. fin_acked: bool = false,
/// A sending half in "Ready", with `buffer` lent as its window and /// `limit` the peer's initial flow control limit for the stream. /// /// The buffer must outlive the `Send` -- see `Outgoing.init` -- and its /// length bounds how much may be written and not yet acknowledged. pub fn init(buffer: []u8, limit: u64) Send { return .{ .data = .init(buffer), .credit = .init(limit) }; }
test init { var window: [256]u8 = undefined; const s: Send = .init(&window, 1000); try testing.expectEqual(Send.State.ready, s.state); try testing.expectEqual(@as(?outgoing.Chunk, null), s.next(64)); }
/// Queues `bytes` to go out on this stream, copying them. /// /// Flow control does not refuse a write: what the peer has not yet /// allowed waits in the buffer, and `next` holds it back. What does /// refuse one is `BufferFull`, when the window is holding all it can /// until the peer acknowledges some of it, and `StreamStateError` once /// the stream has been finished or reset. pub fn write(s: *Send, bytes: []const u8) (Error || outgoing.Error)!void { // The state is not the thing to ask. §3.1 moves a stream to "Data // Sent" when the frame carrying the FIN *goes out*, which can be // several calls after the application said it was done — and nothing // may be written in between either. "An endpoint MUST NOT send data // on a stream at or beyond the final size", and the final size is // settled the moment the application finishes the stream. if (s.data.finished) return error.StreamStateError; switch (s.state) { .ready, .send => {}, else => return error.StreamStateError, } try s.data.write(bytes); }
test write { var window: [8]u8 = undefined; var s: Send = .init(&window, 4); // More than the peer allows yet is accepted, and waits. try s.write("abcdef"); try testing.expectEqualStrings("abcd", s.next(64).?.data); // More than the window holds is not. try testing.expectError(error.BufferFull, s.write("ghi")); }
/// Says the application has written all it will, fixing the stream's /// final size at what has been written. The FIN goes out with the last /// octet, through `next`. /// /// `StreamStateError` if the stream was already finished or has been /// reset: §4.5 lets a final size be settled only once. pub fn finish(s: *Send) Error!void { if (s.data.finished) return error.StreamStateError; switch (s.state) { .ready, .send => s.data.finish(), else => return error.StreamStateError, } }
test finish { var window: [64]u8 = undefined; var s: Send = .init(&window, 100); try s.write("request"); try s.finish(); try testing.expect(s.next(64).?.fin); try testing.expectError(error.StreamStateError, s.finish()); try testing.expectError(error.StreamStateError, s.write("more")); }
/// §3.5: abandon this direction. Asked for by the application, or forced /// by a STOP_SENDING from the peer. /// /// Moves to "Reset Sent" with a RESET_STREAM owed (`reset_pending`), and /// from then on `next` offers no more data, retransmissions included. /// Once the half is terminal -- "Data Recvd", or already reset -- there /// is nothing to abandon and this does nothing, keeping the first code. pub fn reset(s: *Send, code: u64) void { switch (s.state) { .ready, .send, .data_sent => { s.reset_code = code; s.state = .reset_sent; s.reset_pending = true; }, else => {}, } }
test reset { var window: [64]u8 = undefined; var s: Send = .init(&window, 100); try s.write("abandoned"); s.reset(0x10c);
try testing.expectEqual(Send.State.reset_sent, s.state); try testing.expect(s.reset_pending); try testing.expectEqual(@as(?u64, 0x10c), s.reset_code); try testing.expectEqual(@as(?outgoing.Chunk, null), s.next(64)); }
/// §19.4's Final Size for the RESET_STREAM frame: "the final size of the /// stream by the RESET_STREAM sender". /// /// What was *sent*, not what was written. §4.5 defines it: "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 how /// much flow control credit the stream consumed, and the receiver charges /// this number against the limit it granted -- so it can only be what the /// sender was allowed to send, and a receiver checks exactly that. /// /// This used to be everything written, on the reasoning that the sender's /// own total was the number to report. It is not: octets written and /// still waiting for flow control never left, and counting them declares /// a stream longer than the peer permitted. A reset while the stream was /// blocked -- an upload abandoned part way, with its buffer full -- then /// had the peer close the whole connection. Found by zig-http's HTTP/3 /// client cancelling a streamed request body. /// /// `data.sent` only ever grows -- a retransmission resends below it -- so /// it is the highest offset any STREAM frame has reached. pub fn finalSize(s: *const Send) u64 { return s.data.sent; }
test finalSize { var window: [64]u8 = undefined; var s: Send = .init(&window, 4); try s.write("abcdefgh"); s.advance(s.next(64).?);
// Eight written, four allowed and sent: the reset declares four. s.reset(0); try testing.expectEqual(@as(u64, 4), s.finalSize()); }
/// Notes that the RESET_STREAM has gone out, clearing `reset_pending`. /// /// The half is not terminal yet: §13.3 has the frame "sent until /// acknowledged", so it stays in "Reset Sent" until `resetAcked`, and /// `resetLost` owes the frame again if the packet carrying it is lost. pub fn resetSent(s: *Send) void { s.reset_pending = false; }
test resetSent { var window: [64]u8 = undefined; var s: Send = .init(&window, 100); s.reset(0); s.resetSent(); try testing.expect(!s.reset_pending); // Written, and not yet known to have arrived. try testing.expect(!s.isTerminal()); }
/// The packet carrying this half's RESET_STREAM was lost, so the frame /// is owed again (§13.3: "a RESET_STREAM frame is sent until /// acknowledged"). Does nothing once it has been acknowledged. pub fn resetLost(s: *Send) void { if (s.state == .reset_sent) s.reset_pending = true; }
test resetLost { var window: [64]u8 = undefined; var s: Send = .init(&window, 100); s.reset(0x10c); s.resetSent(); s.resetLost(); try testing.expect(s.reset_pending); // The frame goes out again with the code it had the first time. try testing.expectEqual(@as(?u64, 0x10c), s.reset_code); }
/// The peer acknowledged a packet carrying this half's RESET_STREAM: /// §3.1's "Reset Recvd", which is terminal. A copy of the frame still /// waiting to be repeated is no longer needed. pub fn resetAcked(s: *Send) void { if (s.state != .reset_sent) return; s.state = .reset_received; s.reset_pending = false; }
test resetAcked { var window: [64]u8 = undefined; var s: Send = .init(&window, 100); s.reset(0); s.resetSent(); s.resetAcked(); try testing.expectEqual(Send.State.reset_received, s.state); try testing.expect(s.isTerminal()); }
/// The next chunk to put in a STREAM frame, of at most `max` octets. /// /// Null when there is nothing to send *or* when flow control will not /// allow it, and the caller cannot tell those apart from here — `blocked` /// is the question to ask, since §4.1 wants a STREAM_DATA_BLOCKED frame /// in the second case and silence in the first. Also null once the half /// is reset or terminal. /// /// Spends nothing: the chunk is a proposal until `advance` says it went /// into a packet. pub fn next(s: *const Send, max: usize) ?outgoing.Chunk { switch (s.state) { .ready, .send, .data_sent => {}, else => return null, } const chunk = s.data.next(max) orelse return null;
// §2.2: "An endpoint MUST NOT send data on any stream without // ensuring that it is within the flow control limits set by its // peer." The limit is on the highest offset reached, so a chunk is // cut to fit rather than refused — the peer's limit says where this // stream may stop, not how much may travel at once. const end = chunk.offset + chunk.data.len; if (end <= s.credit.limit) return chunk; if (chunk.offset >= s.credit.limit) return null; const room: usize = @intCast(s.credit.limit - chunk.offset); return .{ .offset = chunk.offset, .data = chunk.data[0..room], // Cut short, so this no longer reaches the end of the stream. .fin = false, }; }
test next { var window: [64]u8 = undefined; var s: Send = .init(&window, 5); try s.write("hello, world"); try s.finish();
// Cut at the peer's limit, and without the FIN it can no longer carry. const chunk = s.next(64).?; try testing.expectEqualStrings("hello", chunk.data); try testing.expect(!chunk.fin); }
/// Notes that a chunk from `next` has gone out, with the same contract /// as `Outgoing.advance`. /// /// Moves "Ready" to "Send", and to "Data Sent" once the FIN has gone, /// and records the highest offset reached in `credit.used`. A /// retransmission reaches nowhere new and so spends no credit. pub fn advance(s: *Send, chunk: outgoing.Chunk) void { s.data.advance(chunk); s.credit.used = @max(s.credit.used, chunk.offset + chunk.data.len); if (s.state == .ready) s.state = .send; if (s.data.fin_sent) s.state = .data_sent; }
test advance { var window: [64]u8 = undefined; var s: Send = .init(&window, 100); try s.write("abc"); s.advance(s.next(2).?); try testing.expectEqual(Send.State.send, s.state); try testing.expectEqual(@as(u64, 2), s.credit.used);
try s.finish(); s.advance(s.next(64).?); try testing.expectEqual(Send.State.data_sent, s.state); }
/// Notes that the peer acknowledged a frame carrying `len` octets at /// `offset` of this stream, and whether that frame carried the end /// (`fin`). Moves to "Data Recvd" once every octet *and* the end have /// been acknowledged. pub fn onAcked(s: *Send, offset: u64, len: usize, fin: bool) void { s.data.onAcked(offset, len); if (fin) s.fin_acked = true; // §3.1: "Once all stream data has been successfully acknowledged, the // sending part of the stream enters the 'Data Recvd' state, which is // a terminal state." The end is part of the stream data: §4.5 has // the final size travel on the frame that carries it. if (s.state == .data_sent and s.fin_acked and s.data.allAcked()) s.state = .data_received; }
test onAcked { var window: [64]u8 = undefined; var s: Send = .init(&window, 100); try s.write("body"); try s.finish(); s.advance(s.next(64).?);
// One frame carried all four octets and the end. s.onAcked(0, 4, true); try testing.expectEqual(Send.State.data_received, s.state); try testing.expect(s.isTerminal()); }
/// §3.1: whether this half has reached a terminal state and will send /// nothing more. /// /// "Reset Sent" is not terminal: the RESET_STREAM has to be repeated /// until it is acknowledged (§13.3), and reclaiming the stream's slot any /// sooner would leave nothing to repeat it from. pub fn isTerminal(s: *const Send) bool { return switch (s.state) { .data_received, .reset_received => true, .ready, .send, .data_sent, .reset_sent => false, }; }
test isTerminal { var window: [64]u8 = undefined; var s: Send = .init(&window, 100); try s.write("x"); try s.finish(); s.advance(s.next(64).?); // Sent, but not yet known to have arrived. try testing.expect(!s.isTerminal()); s.onAcked(0, 1, true); try testing.expect(s.isTerminal()); }
/// §4.1: whether new data is waiting that the peer's limit will not let /// out, which is what a STREAM_DATA_BLOCKED frame reports. /// /// A retransmission below the limit is not blocked, since it spends no /// credit, and neither is an empty frame carrying only the FIN at the /// limit itself: it reaches no further than the peer allowed. pub fn blocked(s: *const Send) bool { const chunk = s.data.next(1) orelse return false; return chunk.offset + chunk.data.len > s.credit.limit; }
test blocked { var window: [64]u8 = undefined; var s: Send = .init(&window, 3); try s.write("abcdef"); s.advance(s.next(64).?); try testing.expect(s.blocked()); s.grant(6); try testing.expect(!s.blocked()); }
test "an end exactly at the limit is not blocked" { // The FIN carries no data, so it spends no credit: a stream that has // sent exactly what it was allowed can still say it is finished. var window: [64]u8 = undefined; var s: Send = .init(&window, 3); try s.write("abc"); s.advance(s.next(64).?); try s.finish(); try testing.expect(s.next(64).?.fin); try testing.expect(!s.blocked()); }
/// Raises the peer's limit on this stream from a MAX_STREAM_DATA frame. /// /// §4.1: "A sender MUST ignore any MAX_STREAM_DATA or MAX_DATA frames /// that do not increase flow control limits." pub fn grant(s: *Send, limit: u64) void { s.credit.grant(limit); }
test grant { var window: [64]u8 = undefined; var s: Send = .init(&window, 2); try s.write("abcd"); s.advance(s.next(64).?); try testing.expectEqual(@as(?outgoing.Chunk, null), s.next(64));
s.grant(4); try testing.expectEqualStrings("cd", s.next(64).?.data); }};
/// §3.2: the receiving half of a stream.pub const Recv = struct { pub const State = enum { /// Data is arriving. receiving, /// The peer has said where the stream ends, but not all of it is /// here. size_known, /// Everything has arrived. data_received, /// The peer reset it. reset_received, };
state: State = .receiving, data: reassembly.Reassembler, /// What this endpoint will let the peer send, from its own /// `initial_max_stream_data` and then MAX_STREAM_DATA. credit: Credit, /// §4.5: "Once a final size for a stream is known, it cannot change." final_size: ?u64 = null, /// How much has been handed to the application, which is what a /// MAX_STREAM_DATA is computed from. consumed: u64 = 0, /// The peer's RESET_STREAM error code. reset_code: ?u64 = null, /// §3.5: whether a STOP_SENDING still has to go out, and with what code. /// /// Asking the peer to stop is a request rather than a state change here: /// this endpoint keeps receiving until the peer answers, because §3.5 is /// explicit that "STOP_SENDING... requests that a peer cease /// transmission" and data already in flight will still arrive. stop_pending: bool = false, stop_code: u64 = 0,
/// A receiving half in "Recv", reassembling into `buffer` with `present` /// as its bitmap, and allowing the peer to send up to `limit`. /// /// Both slices are borrowed, as for `reassembly.Reassembler.init`, and /// `present` needs `Reassembler.bitmapLen(buffer.len)` octets. `limit` /// should not exceed what `buffer` can hold beyond what has been read, /// or a peer keeping within it can still be refused with /// `WindowExceeded`. pub fn init(buffer: []u8, present: []u8, limit: u64) Recv { return .{ .data = .init(buffer, present), .credit = .init(limit) }; }
test init { var window: [256]u8 = undefined; var present: [reassembly.Reassembler.bitmapLen(window.len)]u8 = undefined; const r: Recv = .init(&window, &present, window.len); try testing.expectEqual(Recv.State.receiving, r.state); try testing.expectEqual(@as(u64, 256), r.credit.available()); }
/// §3.5: asks the peer to stop sending on this stream. /// /// Only worth asking while there is something still to come: once every /// octet has arrived, or the peer has reset the stream, there is nothing /// left for it to stop doing and §3.5 says so -- "a STOP_SENDING frame /// can be sent for streams in the 'Recv' or 'Size Known' states". A peer /// that has announced the end but not yet delivered all of it can still /// be asked. In any other state this does nothing. /// /// Sets `stop_pending` and `stop_code` for the connection to write the /// frame; the state itself does not change. pub fn stopSending(r: *Recv, code: u64) void { switch (r.state) { .receiving, .size_known => { r.stop_pending = true; r.stop_code = code; }, .data_received, .reset_received => {}, } }
test stopSending { var window: [64]u8 = undefined; var present: [reassembly.Reassembler.bitmapLen(window.len)]u8 = undefined; var r: Recv = .init(&window, &present, window.len); _ = try r.receive(0, "unwanted", false);
r.stopSending(0x10c); try testing.expect(r.stop_pending); try testing.expectEqual(@as(u64, 0x10c), r.stop_code); // Still receiving: whatever is already in flight will arrive. try testing.expectEqual(Recv.State.receiving, r.state); }
/// Notes that the STOP_SENDING has gone out, clearing `stop_pending`. /// `stopLost` owes it again if the packet carrying it is lost. pub fn stopSent(r: *Recv) void { r.stop_pending = false; }
test stopSent { var window: [64]u8 = undefined; var present: [reassembly.Reassembler.bitmapLen(window.len)]u8 = undefined; var r: Recv = .init(&window, &present, window.len); r.stopSending(0); r.stopSent(); try testing.expect(!r.stop_pending); }
/// The packet carrying this half's STOP_SENDING was lost, so the frame /// is owed again -- unless the peer has sent everything or reset the /// stream, either of which leaves nothing to stop. §13.3: "STOP_SENDING /// ... is sent until the receiving part of the stream enters either a /// 'Data Recvd' or 'Reset Recvd' state." pub fn stopLost(r: *Recv) void { switch (r.state) { .receiving, .size_known => r.stop_pending = true, .data_received, .reset_received => {}, } }
test stopLost { var window: [64]u8 = undefined; var present: [reassembly.Reassembler.bitmapLen(window.len)]u8 = undefined; var r: Recv = .init(&window, &present, window.len); r.stopSending(0x10c); r.stopSent(); r.stopLost(); try testing.expect(r.stop_pending);
// Once the peer has reset the stream there is nothing left to stop. r.stopSent(); _ = try r.reset(0x10c, 0); r.stopLost(); try testing.expect(!r.stop_pending); }
/// One STREAM frame's worth. /// /// Returns how much *new* flow control credit this consumed, which the /// connection needs for its own level: §4.1 counts "the sum of the /// absolute byte offsets of all streams", so a retransmission of octets /// already seen costs nothing and a frame that extends the stream costs /// the difference. /// /// Every error is one §4 makes a connection error -- `FlowControlError` /// past the limit, `FinalSizeError` for an end that contradicts itself, /// and the reassembler's `WindowExceeded` or `OffsetTooLarge` -- so the /// half is not left in any state worth continuing from: the credit may /// already have been charged when the reassembler refuses the octets. /// After a reset, data within the final size is ignored and charges /// nothing; data past it is still `FinalSizeError`. pub fn receive(r: *Recv, offset: u64, data: []const u8, fin: bool) (Error || reassembly.Error)!u64 { const end = offset + data.len;
// §4.5: "A receiver SHOULD treat receipt of data at or beyond the // final size as an error of type FINAL_SIZE_ERROR, even after a // stream is closed." And a FIN that moves the end is the same error // from the other direction. if (r.final_size) |size| { if (end > size) return error.FinalSizeError; if (fin and end != size) return error.FinalSizeError; }
// §4.4: "On receipt of a RESET_STREAM frame, an endpoint will tear // down state for the matching stream and ignore further data // arriving on that stream" -- once it has passed the check above. if (r.state == .reset_received) return 0;
// The same contradiction arriving in the other order, which is the // one a reordering path produces: data reaching offset 20 and then a // FIN saying the stream ended at 10. `credit.used` is the highest // offset anything has reached, so this is the test for whether the // end being claimed is behind something already here. if (fin and end < r.credit.used) return error.FinalSizeError;
// §4.1: the limit is on the highest offset, so what is charged is how // much further this frame reaches than anything before it. const charged = end -| r.credit.used; try r.credit.spend(charged);
try r.data.insert(offset, data);
if (fin) { r.final_size = end; r.state = .size_known; } if (r.final_size) |size| { if (r.data.nextOffset() + r.data.readable().len >= size) { r.state = .data_received; } } return charged; }
test receive { var window: [64]u8 = undefined; var present: [reassembly.Reassembler.bitmapLen(window.len)]u8 = undefined; var r: Recv = .init(&window, &present, window.len);
// The second frame first: it is charged for reaching offset 10. try testing.expectEqual(@as(u64, 10), try r.receive(5, "world", true)); try testing.expectEqual(Recv.State.size_known, r.state); // The first fills the hole and reaches nowhere new, so costs nothing. try testing.expectEqual(@as(u64, 0), try r.receive(0, "hello", false)); try testing.expectEqual(Recv.State.data_received, r.state); try testing.expectEqualStrings("helloworld", r.readable()); }
/// §19.4: the peer abandoned this direction, and said how much it had /// sent so that both ends still agree on the flow control consumed. /// /// Returns the credit that arrival charges, which may be more than /// anything that actually arrived — the point of the Final Size field is /// that the connection-level accounting stays correct across data that /// was thrown away. /// /// `FinalSizeError` if a FIN or an earlier reset already fixed a /// different final size, or if data has already arrived past /// `final_size`; `FlowControlError` if the final size is past the limit /// this end granted. Unread data is not discarded here; /// what `readable` returns is still there. pub fn reset(r: *Recv, code: u64, final_size: u64) Error!u64 { if (r.final_size) |size| { if (size != final_size) return error.FinalSizeError; } // §4.5: a final size behind data already received says the peer sent // past it, which "an endpoint MUST NOT" do. `credit.used` is the // highest offset anything has reached. if (final_size < r.credit.used) return error.FinalSizeError; const charged = final_size -| r.credit.used; try r.credit.spend(charged); r.final_size = final_size; r.reset_code = code; r.state = .reset_received; return charged; }
test reset { var window: [64]u8 = undefined; var present: [reassembly.Reassembler.bitmapLen(window.len)]u8 = undefined; var r: Recv = .init(&window, &present, window.len); _ = try r.receive(0, "partial", false);
// The peer had sent twenty octets; only the first seven arrived, and // the other thirteen are charged all the same. try testing.expectEqual(@as(u64, 13), try r.reset(0x10c, 20)); try testing.expectEqual(Recv.State.reset_received, r.state); try testing.expectEqual(@as(?u64, 0x10c), r.reset_code); }
/// What can be handed to the application: the contiguous run from where /// it last stopped. Valid until the next `receive` or `consume`. pub fn readable(r: *Recv) []const u8 { return r.data.readable(); }
test readable { var window: [64]u8 = undefined; var present: [reassembly.Reassembler.bitmapLen(window.len)]u8 = undefined; var r: Recv = .init(&window, &present, window.len); _ = try r.receive(0, "GET /", false); _ = try r.receive(9, "HTTP", false); // Only up to the gap at offset 5. try testing.expectEqualStrings("GET /", r.readable()); }
/// Takes `n` octets of what `readable` returned, which must not be more /// than it returned. What `limitToAdvertise` offers moves with this. pub fn consume(r: *Recv, n: usize) void { r.data.consume(n); r.consumed += n; }
test consume { var window: [64]u8 = undefined; var present: [reassembly.Reassembler.bitmapLen(window.len)]u8 = undefined; var r: Recv = .init(&window, &present, window.len); _ = try r.receive(0, "abcdef", false); r.consume(4); try testing.expectEqualStrings("ef", r.readable()); try testing.expectEqual(@as(u64, 4), r.consumed); }
/// Whether the application has seen everything there is: the final size /// is known and that much has been consumed. After a reset that only /// happens if the final size was already reached, since nothing more /// will arrive. pub fn finished(r: *const Recv) bool { const size = r.final_size orelse return false; return r.consumed >= size; }
test finished { var window: [64]u8 = undefined; var present: [reassembly.Reassembler.bitmapLen(window.len)]u8 = undefined; var r: Recv = .init(&window, &present, window.len); _ = try r.receive(0, "all", true); // Arrived, but not yet read. try testing.expect(!r.finished()); r.consume(3); try testing.expect(r.finished()); }
/// §3.2: whether this half has reached a terminal state — "Data Read" or /// "Reset Read". /// /// "Data Read" is about the application, not the network: everything has /// arrived *and* been consumed. A reset is taken as terminal the moment /// it arrives, without waiting for the application to hear of it, since /// there is nothing more the stream can deliver. pub fn isTerminal(r: *const Recv) bool { return switch (r.state) { .reset_received => true, .data_received => r.finished(), .receiving, .size_known => false, }; }
test isTerminal { var window: [64]u8 = undefined; var present: [reassembly.Reassembler.bitmapLen(window.len)]u8 = undefined; var r: Recv = .init(&window, &present, window.len); _ = try r.receive(0, "hi", true); try testing.expect(!r.isTerminal()); r.consume(2); try testing.expect(r.isTerminal()); }
/// The limit to advertise in a MAX_STREAM_DATA frame: what has been /// consumed plus a window's worth. /// /// §4.2 leaves the policy open and warns about both ends of it — /// "frequently sending MAX_STREAM_DATA and MAX_DATA frames with small /// changes is undesirable", and updating too rarely blocks the sender. /// A window that slides with consumption is the simple answer: the peer /// is always allowed to have one window of unread data outstanding. /// /// It only computes the number; raising `credit` to match is the /// caller's, once the frame carrying it is written. pub fn limitToAdvertise(r: *const Recv, window: u64) u64 { return r.consumed + window; }
test limitToAdvertise { var buffer: [64]u8 = undefined; var present: [reassembly.Reassembler.bitmapLen(buffer.len)]u8 = undefined; var r: Recv = .init(&buffer, &present, 32); _ = try r.receive(0, "0123456789", false); r.consume(10); // Ten read, so the peer may now reach ten octets further. try testing.expectEqual(@as(u64, 42), r.limitToAdvertise(32)); }};
const testing = std.testing;
test "RFC 9000 3.4: a stream is closed when both halves are terminal" { // "The simplest model presents the stream as 'open' when either sending // or receiving parts are in a non-terminal state and 'closed' when both // sending and receiving streams are in terminal states." Which is the // model here, because the composite states of Table 2 are a presentation // of the same two facts and nothing in this library asks a question they // answer differently. var send_storage: [64]u8 = undefined; var recv_buffer: [64]u8 = undefined; var present: [8]u8 = undefined;
var s: Send = .init(&send_storage, 100); var r: Recv = .init(&recv_buffer, &present, 100); try testing.expect(!s.isTerminal()); try testing.expect(!r.isTerminal());
// Sending everything is not enough; it has to be acknowledged. try s.write("out"); try s.finish(); while (s.next(64)) |chunk| s.advance(chunk); try testing.expectEqual(Send.State.data_sent, s.state); try testing.expect(!s.isTerminal()); s.onAcked(0, 3, true); try testing.expectEqual(Send.State.data_received, s.state); try testing.expect(s.isTerminal());
// Receiving everything is not enough either; the application has to have // read it. §3.2's terminal state is "Data Read", not "Data Recvd". _ = try r.receive(0, "in", true); try testing.expectEqual(Recv.State.data_received, r.state); try testing.expect(!r.isTerminal()); r.consume(2); try testing.expect(r.isTerminal());}
test "RFC 9000 3.1: acknowledging the data is not acknowledging an end sent after it" { var window: [64]u8 = undefined; var s: Send = .init(&window, 100); try s.write("abc"); const data = s.next(64).?; try testing.expect(!data.fin); s.advance(data);
// The end follows on an empty frame of its own. try s.finish(); const end = s.next(64).?; try testing.expect(end.fin); try testing.expectEqual(@as(usize, 0), end.data.len); s.advance(end); try testing.expectEqual(Send.State.data_sent, s.state);
// The data is acknowledged; the end is not, and may yet be lost. s.onAcked(data.offset, data.data.len, false); try testing.expectEqual(Send.State.data_sent, s.state); try testing.expect(!s.isTerminal());
s.onAcked(end.offset, 0, true); try testing.expectEqual(Send.State.data_received, s.state);}
test "RFC 9000 4.5: a reset cannot end a stream behind data already received" { var window: [64]u8 = undefined; var present: [reassembly.Reassembler.bitmapLen(window.len)]u8 = undefined; var r: Recv = .init(&window, &present, window.len); _ = try r.receive(0, "twenty octets arrive", false); // "An endpoint MUST NOT send data on a stream at or beyond the final // size", so a final size of ten says the peer broke that rule. try testing.expectError(error.FinalSizeError, r.reset(0x10c, 10)); try testing.expectEqual(Recv.State.receiving, r.state); // The final size it actually reached is accepted. _ = try r.reset(0x10c, 20);}
test "RFC 9000 4.5: data past the final size is an error after a reset too" { var window: [64]u8 = undefined; var present: [reassembly.Reassembler.bitmapLen(window.len)]u8 = undefined; var r: Recv = .init(&window, &present, window.len); _ = try r.reset(0x10c, 5); // Late data within the final size is ignored, as §4.4 asks... try testing.expectEqual(@as(u64, 0), try r.receive(0, "hello", false)); // ...but "a receiver SHOULD treat receipt of data at or beyond the final // size as an error of type FINAL_SIZE_ERROR, even after a stream is // closed", and a FIN somewhere else is the same contradiction. try testing.expectError(error.FinalSizeError, r.receive(5, "!", false)); try testing.expectError(error.FinalSizeError, r.receive(0, "hel", true));}
test "RFC 9000 3.4: a reset is a terminal state for its own direction only" { // §4.4: "RESET_STREAM terminates one direction of a stream abruptly. For // a bidirectional stream, RESET_STREAM has no effect on data flow in the // opposite direction." var send_storage: [64]u8 = undefined; var recv_buffer: [64]u8 = undefined; var present: [8]u8 = undefined;
var s: Send = .init(&send_storage, 100); var r: Recv = .init(&recv_buffer, &present, 100);
s.reset(7); // §3.5: the direction is abandoned, but not finished with -- the peer has // not been told yet, and the RESET_STREAM carrying that news still has to // go out. A half that reported itself terminal here would have its slot // reclaimed with the frame unsent, which is how a STOP_SENDING comes to // be answered by silence. try testing.expect(s.reset_pending); try testing.expect(!s.isTerminal()); s.resetSent(); // Written, but §13.3 has it repeated until the peer acknowledges it. try testing.expect(!s.isTerminal()); s.resetAcked(); try testing.expect(s.isTerminal()); // And the receiving half is untouched: the peer may still be sending. try testing.expect(!r.isTerminal()); _ = try r.receive(0, "still coming", false); try testing.expect(!r.isTerminal());
_ = try r.reset(9, 12); try testing.expect(r.isTerminal());}
test "RFC 9000 2.1: the low two bits say who opened a stream and which way it runs" { // The table in §2.1, read out of the identifier itself. try testing.expectEqual(Kind.client_bidirectional, (Id{ .value = 0 }).kind()); try testing.expectEqual(Kind.server_bidirectional, (Id{ .value = 1 }).kind()); try testing.expectEqual(Kind.client_unidirectional, (Id{ .value = 2 }).kind()); try testing.expectEqual(Kind.server_unidirectional, (Id{ .value = 3 }).kind());
// Successive streams of a type step by four, because the four types share // one number space. try testing.expectEqual(@as(u64, 0), Id.make(.client_bidirectional, 0).value); try testing.expectEqual(@as(u64, 4), Id.make(.client_bidirectional, 1).value); try testing.expectEqual(@as(u64, 9), Id.make(.server_bidirectional, 2).value); try testing.expectEqual(@as(u64, 2), Id.make(.client_unidirectional, 0).value);
// And the index is what every limit in §4.6 counts. try testing.expectEqual(@as(u64, 25), (Id{ .value = 100 }).index()); try testing.expectEqual(@as(u64, 25), (Id{ .value = 103 }).index());}
test "RFC 9000 3.1: a unidirectional stream has one half at each end" { const client_uni = Id.make(.client_unidirectional, 0); try testing.expect(client_uni.canSend(.client)); try testing.expect(!client_uni.canReceive(.client)); try testing.expect(!client_uni.canSend(.server)); try testing.expect(client_uni.canReceive(.server));
// A bidirectional one has both halves at both ends, whoever opened it. const client_bidi = Id.make(.client_bidirectional, 0); for ([_]Initiator{ .client, .server }) |role| { try testing.expect(client_bidi.canSend(role)); try testing.expect(client_bidi.canReceive(role)); } // But only one end opened it, which is what stream limits count. try testing.expect(client_bidi.isLocal(.client)); try testing.expect(!client_bidi.isLocal(.server));}
test "RFC 9000 4.1: a limit is an offset, so a smaller one has no effect" { var c: Credit = .init(100); try testing.expectEqual(@as(u64, 100), c.available());
try c.spend(60); try testing.expectEqual(@as(u64, 40), c.available());
// "A sender MUST ignore any MAX_STREAM_DATA or MAX_DATA frames that do // not increase flow control limits" -- which is what makes a reordered // or retransmitted one harmless rather than something to sequence. c.grant(50); try testing.expectEqual(@as(u64, 40), c.available()); c.grant(200); try testing.expectEqual(@as(u64, 140), c.available());
// The limit is the largest offset that may be reached, so spending // exactly all of it is allowed and one more octet is not. var exact: Credit = .init(10); try exact.spend(10); try testing.expect(exact.blocked()); try testing.expectError(error.FlowControlError, exact.spend(1));}
test "RFC 9000 2.2: a sender is cut to its peer's limit rather than refused" { var storage: [64]u8 = undefined; var s: Send = .init(&storage, 4); try s.write("abcdefgh"); try s.finish();
// Four octets of credit, and eight to send: what comes out is four. const first = s.next(64).?; try testing.expectEqualStrings("abcd", first.data); // And it does not carry the end, because it no longer reaches it -- a FIN // here would tell the peer the stream was four octets long. try testing.expect(!first.fin); s.advance(first);
// Now it is blocked, which is a different thing from having nothing to // say: §4.1 wants a STREAM_DATA_BLOCKED frame for the one and silence // for the other. try testing.expectEqual(@as(?outgoing.Chunk, null), s.next(64)); try testing.expect(s.blocked());
// The peer raises the limit and the rest follows, end and all. s.grant(8); try testing.expect(!s.blocked()); const rest = s.next(64).?; try testing.expectEqualStrings("efgh", rest.data); try testing.expect(rest.fin); s.advance(rest); try testing.expectEqual(Send.State.data_sent, s.state);}
test "RFC 9000 3.1: nothing may be written after the end" { var storage: [64]u8 = undefined; var s: Send = .init(&storage, 100); try s.write("abc"); try s.finish(); // "An endpoint MUST NOT send data on a stream at or beyond the final // size", and the final size is fixed the moment the stream is finished. try testing.expectError(error.StreamStateError, s.write("d")); try testing.expectError(error.StreamStateError, s.finish());
// Nor after a reset, which abandons the direction entirely. var r: Send = .init(&storage, 100); r.reset(7); try testing.expectEqual(Send.State.reset_sent, r.state); try testing.expectError(error.StreamStateError, r.write("a")); try testing.expectEqual(@as(?outgoing.Chunk, null), r.next(64));}
test "RFC 9000 4.1: what a frame costs is how much further it reaches" { var buffer: [64]u8 = undefined; var present: [8]u8 = undefined; var r: Recv = .init(&buffer, &present, 100);
try testing.expectEqual(@as(u64, 10), try r.receive(0, "0123456789", false)); // A retransmission of what has already arrived costs nothing: the limit // is on the highest offset, not on how many octets crossed the network. try testing.expectEqual(@as(u64, 0), try r.receive(0, "0123456789", false)); // And a frame that overlaps costs only the new part. try testing.expectEqual(@as(u64, 5), try r.receive(5, "5678901234", false)); try testing.expectEqual(@as(u64, 15), r.credit.used);
try testing.expectEqualStrings("012345678901234", r.readable());}
test "RFC 9000 4.1: sending past the limit ends the connection" { var buffer: [64]u8 = undefined; var present: [8]u8 = undefined; var r: Recv = .init(&buffer, &present, 8); _ = try r.receive(0, "abcdefgh", false); // "A receiver MUST close the connection with an error of type // FLOW_CONTROL_ERROR if the sender violates the advertised connection or // stream data limits." try testing.expectError(error.FlowControlError, r.receive(8, "i", false));
// Including by a frame that starts far past it, which is the cheap way // to ask a receiver to allocate. var far: Recv = .init(&buffer, &present, 8); try testing.expectError(error.FlowControlError, far.receive(1 << 40, "x", false));}
test "RFC 9000 4.5: a stream ends in exactly one place" { var buffer: [64]u8 = undefined; var present: [8]u8 = undefined; var r: Recv = .init(&buffer, &present, 100);
_ = try r.receive(0, "abcde", true); try testing.expectEqual(@as(?u64, 5), r.final_size); try testing.expectEqual(Recv.State.data_received, r.state);
// "Once a final size for a stream is known, it cannot change. If a // RESET_STREAM or STREAM frame is received indicating a change in the // final size for the stream, an endpoint SHOULD respond with an error of // type FINAL_SIZE_ERROR." try testing.expectError(error.FinalSizeError, r.receive(5, "f", false)); try testing.expectError(error.FinalSizeError, r.receive(0, "abc", true)); try testing.expectError(error.FinalSizeError, r.reset(0, 9));
// A reset agreeing with what was already known is not a contradiction. _ = try r.reset(0, 5); try testing.expectEqual(Recv.State.reset_received, r.state);}
test "RFC 9000 4.5: an end behind data already received is a contradiction" { // Found by the `streams` fuzz target, which noticed that a receiver was // holding octets past a final size it had just accepted. The check for // data arriving after a known end was there; the mirror -- an end // arriving after the data that outruns it -- was not, and a reordering // path produces the second as readily as the first. var buffer: [64]u8 = undefined; var present: [8]u8 = undefined; var r: Recv = .init(&buffer, &present, 100);
_ = try r.receive(0, "0123456789", false); try testing.expectError(error.FinalSizeError, r.receive(0, "01234", true)); // And an end exactly where the data stops is no contradiction at all. _ = try r.receive(0, "0123456789", true); try testing.expectEqual(@as(?u64, 10), r.final_size);}
test "RFC 9000 4.5: a reset declares what was sent, not what was written" { // Eight octets written against four octets of credit: four go, four wait. var storage: [64]u8 = undefined; var s: Send = .init(&storage, 4); try s.write("abcdefgh"); const first = s.next(64).?; s.advance(first); try testing.expect(s.blocked());
// Abandoned while blocked. The four still waiting never left, so the // stream's final size is four -- which is also all the peer allowed. s.reset(0x10c); try testing.expectEqual(@as(u64, 4), s.finalSize());
// And the peer, having granted four, takes exactly that... var buffer: [64]u8 = undefined; var present: [8]u8 = undefined; var r: Recv = .init(&buffer, &present, 4); _ = try r.receive(0, first.data, false); try testing.expectEqual(@as(u64, 0), try r.reset(0x10c, s.finalSize()));
// ...where the eight that were written would have been more than it ever // permitted, which §4.1 makes FLOW_CONTROL_ERROR and the end of the // connection. var strict: Recv = .init(&buffer, &present, 4); _ = try strict.receive(0, first.data, false); try testing.expectError(error.FlowControlError, strict.reset(0x10c, 8));}
test "RFC 9000 4.5: a stream reset before anything was sent has a final size of zero" { var storage: [64]u8 = undefined; var s: Send = .init(&storage, 0); try s.write("abc"); s.reset(0x10c); try testing.expectEqual(@as(u64, 0), s.finalSize());}
test "RFC 9000 4.4: a reset still accounts for what the stream consumed" { // "Endpoints need to eventually agree on the amount of flow control // credit that has been consumed on every stream, to be able to account // for all bytes for connection-level flow control." So the Final Size // field charges for data that was sent and thrown away, which is the // whole reason RESET_STREAM carries one. var buffer: [64]u8 = undefined; var present: [8]u8 = undefined; var r: Recv = .init(&buffer, &present, 100);
_ = try r.receive(0, "abc", false); try testing.expectEqual(@as(u64, 3), r.credit.used);
// The peer says it had sent 50 octets, 47 of which never arrived. try testing.expectEqual(@as(u64, 47), try r.reset(9, 50)); try testing.expectEqual(@as(u64, 50), r.credit.used); try testing.expectEqual(@as(?u64, 9), r.reset_code);
// And nothing more is taken from it. try testing.expectEqual(@as(u64, 0), try r.receive(3, "d", false));}
test "RFC 9000 4.2: the advertised limit slides with what has been read" { var buffer: [64]u8 = undefined; var present: [8]u8 = undefined; var r: Recv = .init(&buffer, &present, 16);
try testing.expectEqual(@as(u64, 16), r.limitToAdvertise(16)); _ = try r.receive(0, "abcdefgh", false); // Arrival alone does not move it: the peer is entitled to one window of // data this endpoint has not read, and no more. try testing.expectEqual(@as(u64, 16), r.limitToAdvertise(16));
r.consume(8); try testing.expectEqual(@as(u64, 24), r.limitToAdvertise(16));}
test "RFC 9000 3.2: the end is known before it has all arrived" { var buffer: [64]u8 = undefined; var present: [8]u8 = undefined; var r: Recv = .init(&buffer, &present, 100);
// The last frame arrives first, which is ordinary on a reordering path. _ = try r.receive(6, "ghij", true); try testing.expectEqual(Recv.State.size_known, r.state); try testing.expectEqual(@as(?u64, 10), r.final_size); try testing.expectEqual(@as(usize, 0), r.readable().len); try testing.expect(!r.finished());
_ = try r.receive(0, "abcdef", false); try testing.expectEqual(Recv.State.data_received, r.state); try testing.expectEqualStrings("abcdefghij", r.readable()); try testing.expect(!r.finished());
// Finished is about the application, not the network: the octets are // here, but the stream is not done until they have been read. r.consume(10); try testing.expect(r.finished());}