@browsercore/quic 0.1.3 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +122 -0
- package/dist/connection.d.ts +13 -13
- package/dist/connection.d.ts.map +1 -1
- package/dist/connection.js +119 -73
- package/dist/connection.js.map +1 -1
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js.map +1 -1
- package/dist/frame/frame.d.ts +1 -2
- package/dist/frame/frame.d.ts.map +1 -1
- package/dist/frame/frame.js +19 -8
- package/dist/frame/frame.js.map +1 -1
- package/dist/frame/varint.d.ts +10 -0
- package/dist/frame/varint.d.ts.map +1 -1
- package/dist/frame/varint.js +38 -14
- package/dist/frame/varint.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/packet/packet.d.ts +1 -2
- package/dist/packet/packet.d.ts.map +1 -1
- package/dist/packet/packet.js +19 -4
- package/dist/packet/packet.js.map +1 -1
- package/dist/stream/stream.d.ts +1 -1
- package/dist/stream/stream.d.ts.map +1 -1
- package/dist/stream/stream.js +124 -84
- package/dist/stream/stream.js.map +1 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/utils.d.ts.map +1 -1
- package/dist/utils.js +2 -1
- package/dist/utils.js.map +1 -1
- package/package.json +22 -9
- package/.github/workflows/ci.yml +0 -17
- package/.github/workflows/publish.yml +0 -49
- package/CODING_STANDARDS.md +0 -205
- package/src/connection.ts +0 -374
- package/src/errors.ts +0 -153
- package/src/frame/frame.ts +0 -423
- package/src/frame/varint.ts +0 -124
- package/src/index.ts +0 -70
- package/src/packet/packet.ts +0 -210
- package/src/stream/stream.ts +0 -746
- package/src/types.ts +0 -441
- package/src/utils.ts +0 -38
- package/tests/connection.test.ts +0 -106
- package/tests/fake-transport.ts +0 -107
- package/tests/stream.test.ts +0 -152
- package/tests/wire.test.ts +0 -342
- package/tsconfig.json +0 -30
package/src/stream/stream.ts
DELETED
|
@@ -1,746 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* QUIC stream state machine + flow control + receive reassembly (RFC 9000 §2, §4).
|
|
3
|
-
*
|
|
4
|
-
* Each QUIC stream is a reliable, ordered byte stream. The connection receives
|
|
5
|
-
* STREAM frames (offset, data, fin) out of order — datagrams are not ordered —
|
|
6
|
-
* so a stream reassembles by offset into the byte stream `read()` consumes.
|
|
7
|
-
* Flow control is enforced on both sides: we never send more than the peer's
|
|
8
|
-
* MAX_STREAM_DATA / MAX_DATA windows allow, and we replenish the peer's send
|
|
9
|
-
* credit with MAX_STREAM_DATA / MAX_DATA frames as we consume.
|
|
10
|
-
*
|
|
11
|
-
* Honest limitations:
|
|
12
|
-
* - Send-side backpressure is real: `write()` resolves once bytes are buffered
|
|
13
|
-
* at the QUIC layer, and the connection drains the send queue only as far as
|
|
14
|
-
* the peer's flow-control window allows, queueing the rest. When the window
|
|
15
|
-
* is exhausted we tell the peer with DATA_BLOCKED / STREAM_DATA_BLOCKED.
|
|
16
|
-
* - There is no congestion controller and no liveness ping in this layer —
|
|
17
|
-
* ACK frames are relayed but not paced. Connection establishment (the TLS
|
|
18
|
-
* handshake) and packet protection are out of scope; `connectQuic()` returns
|
|
19
|
-
* a connection that moves frames over the transport directly.
|
|
20
|
-
*/
|
|
21
|
-
|
|
22
|
-
import { EventEmitter } from "node:events";
|
|
23
|
-
import type {
|
|
24
|
-
MaxStreamsFrame,
|
|
25
|
-
QuicFrame,
|
|
26
|
-
QuicStream,
|
|
27
|
-
QuicTransportParameters,
|
|
28
|
-
StreamId,
|
|
29
|
-
StreamState,
|
|
30
|
-
StreamCloseReason,
|
|
31
|
-
} from "../types.js";
|
|
32
|
-
import { QuicFrameType } from "../types.js";
|
|
33
|
-
import {
|
|
34
|
-
firstStreamId,
|
|
35
|
-
makeStreamId,
|
|
36
|
-
nextStreamId,
|
|
37
|
-
streamIdIsBidirectional,
|
|
38
|
-
streamIdIsClientInitiated,
|
|
39
|
-
} from "../types.js";
|
|
40
|
-
import { ResetStreamError, StopSendingError } from "../errors.js";
|
|
41
|
-
import { concat } from "../utils.js";
|
|
42
|
-
|
|
43
|
-
/** Byte type alias matching the `Uint8Array<ArrayBufferLike>` wire signatures. */
|
|
44
|
-
type Bytes = Uint8Array<ArrayBufferLike>;
|
|
45
|
-
|
|
46
|
-
/** Empty byte array constant. */
|
|
47
|
-
const EMPTY: Bytes = new Uint8Array(0);
|
|
48
|
-
|
|
49
|
-
// ---------------------------------------------------------------------------
|
|
50
|
-
// Defaults (RFC 9000 §18.2 has no mandated initial windows; these are sane)
|
|
51
|
-
// ---------------------------------------------------------------------------
|
|
52
|
-
|
|
53
|
-
const DEFAULT_INITIAL_MAX_DATA = 1_048_576n; // 1 MiB
|
|
54
|
-
const DEFAULT_INITIAL_MAX_STREAM_DATA = 262_144n; // 256 KiB
|
|
55
|
-
const DEFAULT_INITIAL_MAX_STREAMS_BIDI = 100n;
|
|
56
|
-
const DEFAULT_INITIAL_MAX_STREAMS_UNI = 100n;
|
|
57
|
-
|
|
58
|
-
/**
|
|
59
|
-
* Replenish the peer's send credit once we have consumed this fraction of the
|
|
60
|
-
* current window. Sending an update per byte would flood the connection; waiting
|
|
61
|
-
* for the full window would stall the peer. Half is the usual trade-off.
|
|
62
|
-
*/
|
|
63
|
-
const REPLENISH_FRACTION = 2;
|
|
64
|
-
|
|
65
|
-
// ---------------------------------------------------------------------------
|
|
66
|
-
// Internal stream record
|
|
67
|
-
// ---------------------------------------------------------------------------
|
|
68
|
-
|
|
69
|
-
/**
|
|
70
|
-
* A single QUIC stream. Externally we hand out the `QuicStream` view; this adds
|
|
71
|
-
* the bookkeeping the state machine needs (send queue, reassembly buffer,
|
|
72
|
-
* flow-control windows, waiters) without polluting the public interface.
|
|
73
|
-
*/
|
|
74
|
-
class ManagedStream implements QuicStream {
|
|
75
|
-
public readonly id: StreamId;
|
|
76
|
-
public state: StreamState = { state: "open" };
|
|
77
|
-
|
|
78
|
-
// --- send side -------------------------------------------------------------
|
|
79
|
-
/** Bytes buffered waiting for flow-control window / connection drain. */
|
|
80
|
-
public sendQueue: Bytes = EMPTY;
|
|
81
|
-
/** True once the local side requested FIN (via close()). */
|
|
82
|
-
public sendFinPending = false;
|
|
83
|
-
/** True once the FIN bit has been sent on a STREAM frame. */
|
|
84
|
-
public finSent = false;
|
|
85
|
-
/** Total stream bytes sent so far (for flow-control accounting). */
|
|
86
|
-
public dataSent = 0n;
|
|
87
|
-
/** The peer's current per-stream send limit (grown via MAX_STREAM_DATA). */
|
|
88
|
-
public maxStreamData: bigint;
|
|
89
|
-
|
|
90
|
-
// --- receive side ----------------------------------------------------------
|
|
91
|
-
/** Out-of-order STREAM data waiting to be reassembled, sorted by offset. */
|
|
92
|
-
private readonly reassembly: Array<{ readonly offset: bigint; readonly data: Bytes }> = [];
|
|
93
|
-
/** Next byte offset to deliver to a reader. */
|
|
94
|
-
private recvOffset = 0n;
|
|
95
|
-
/** Offset at which the FIN arrived, if any. */
|
|
96
|
-
private recvFinOffset: bigint | undefined;
|
|
97
|
-
/** Bytes ready to read, buffered when no reader is waiting. */
|
|
98
|
-
private readBuffer: Bytes = EMPTY;
|
|
99
|
-
/** True once the FIN has been delivered to a reader. */
|
|
100
|
-
private finDelivered = false;
|
|
101
|
-
/** Total stream bytes received so far (for flow-control accounting). */
|
|
102
|
-
private dataReceived = 0n;
|
|
103
|
-
/** The local per-stream receive limit we have advertised to the peer. */
|
|
104
|
-
private maxStreamDataAdvertised: bigint;
|
|
105
|
-
|
|
106
|
-
// --- waiters ---------------------------------------------------------------
|
|
107
|
-
/** Readers waiting for data / fin. */
|
|
108
|
-
private readonly readWaiters: Array<{
|
|
109
|
-
resolve: (bytes: Bytes) => void;
|
|
110
|
-
reject: (err: Error) => void;
|
|
111
|
-
}> = [];
|
|
112
|
-
/** Writers waiting for flow-control window to open. */
|
|
113
|
-
private readonly sendWaiters: Array<{
|
|
114
|
-
resolve: () => void;
|
|
115
|
-
reject: (err: Error) => void;
|
|
116
|
-
}> = [];
|
|
117
|
-
|
|
118
|
-
public constructor(id: StreamId, initialMaxStreamData: bigint) {
|
|
119
|
-
this.id = id;
|
|
120
|
-
this.maxStreamData = initialMaxStreamData;
|
|
121
|
-
this.maxStreamDataAdvertised = initialMaxStreamData;
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
// --- public QuicStream surface ---------------------------------------------
|
|
125
|
-
|
|
126
|
-
public async write(data: Uint8Array): Promise<void> {
|
|
127
|
-
if (this.state.state === "closed" || this.state.state === "half_closed_local") {
|
|
128
|
-
throw new ResetStreamError(this.id, 0x05n /* STREAM_STATE_ERROR */, this.dataSent);
|
|
129
|
-
}
|
|
130
|
-
if (data.length === 0) return;
|
|
131
|
-
this.sendQueue = concat(this.sendQueue, data as Bytes);
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
public read(): Promise<Bytes> {
|
|
135
|
-
// Data already buffered: hand back the next contiguous chunk.
|
|
136
|
-
if (this.readBuffer.length > 0) {
|
|
137
|
-
const out = this.readBuffer;
|
|
138
|
-
this.readBuffer = EMPTY;
|
|
139
|
-
return Promise.resolve(out);
|
|
140
|
-
}
|
|
141
|
-
// EOF already reached: signal end-of-stream with an empty chunk.
|
|
142
|
-
if (this.finDelivered) {
|
|
143
|
-
return Promise.resolve(EMPTY);
|
|
144
|
-
}
|
|
145
|
-
// Otherwise block until data / fin / reset arrives.
|
|
146
|
-
return new Promise<Bytes>((resolve, reject) => {
|
|
147
|
-
this.readWaiters.push({ resolve, reject });
|
|
148
|
-
});
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
public close(): Promise<void> {
|
|
152
|
-
if (this.state.state === "closed") return Promise.resolve();
|
|
153
|
-
this.sendFinPending = true;
|
|
154
|
-
return Promise.resolve();
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
// --- send-side drain (called by the connection) ----------------------------
|
|
158
|
-
|
|
159
|
-
/**
|
|
160
|
-
* Pull up to `maxBytes` from the send queue for transmission. Returns the
|
|
161
|
-
* bytes to put on a STREAM frame (caller adds offset + fin). Does not mutate
|
|
162
|
-
* the queue; call `commitSend()` once the frame is actually sent.
|
|
163
|
-
*/
|
|
164
|
-
public peekSend(maxBytes: number): Bytes {
|
|
165
|
-
if (this.sendQueue.length === 0) return EMPTY;
|
|
166
|
-
const len = Math.min(maxBytes, this.sendQueue.length);
|
|
167
|
-
return this.sendQueue.subarray(0, len) as Bytes;
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
/** Record that `count` bytes starting at `offset` were sent. */
|
|
171
|
-
public commitSend(offset: bigint, count: number, fin: boolean): void {
|
|
172
|
-
this.sendQueue = this.sendQueue.subarray(count) as Bytes;
|
|
173
|
-
this.dataSent += BigInt(count);
|
|
174
|
-
if (offset + BigInt(count) > this.sendFinOffset) {
|
|
175
|
-
this.sendFinOffset = offset + BigInt(count);
|
|
176
|
-
}
|
|
177
|
-
if (fin) {
|
|
178
|
-
this.finSent = true;
|
|
179
|
-
this.transitionOnLocalFin();
|
|
180
|
-
}
|
|
181
|
-
// The send queue may have drained below the window — wake waiters.
|
|
182
|
-
this.drainSendWaiters();
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
/** The offset at which the next byte should be sent. */
|
|
186
|
-
public get sendOffset(): bigint {
|
|
187
|
-
return this.dataSent;
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
/** True if there is data or a FIN left to send. */
|
|
191
|
-
public get hasPendingSend(): boolean {
|
|
192
|
-
return this.sendQueue.length > 0 || (this.sendFinPending && !this.finSent);
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
// --- receive-side reassembly (called by the manager) ------------------------
|
|
196
|
-
|
|
197
|
-
/**
|
|
198
|
-
* Ingest a STREAM frame's payload at `offset`. Reassembles contiguous bytes
|
|
199
|
-
* into the read buffer / resolves a waiting reader, and updates flow-control
|
|
200
|
-
* accounting. Returns true if a MAX_STREAM_DATA update should be sent.
|
|
201
|
-
*/
|
|
202
|
-
public ingest(offset: bigint, data: Bytes, fin: boolean): boolean {
|
|
203
|
-
const end = offset + BigInt(data.length);
|
|
204
|
-
if (fin) {
|
|
205
|
-
this.recvFinOffset = end;
|
|
206
|
-
}
|
|
207
|
-
this.dataReceived += BigInt(data.length);
|
|
208
|
-
|
|
209
|
-
// Drop bytes we have already delivered (retransmissions / overlaps).
|
|
210
|
-
if (end <= this.recvOffset) {
|
|
211
|
-
if (offset < this.recvOffset) return this.replenishNeeded();
|
|
212
|
-
return this.replenishNeeded();
|
|
213
|
-
}
|
|
214
|
-
// Clip the front if part of this frame is below recvOffset.
|
|
215
|
-
let payload = data;
|
|
216
|
-
let payloadOffset = offset;
|
|
217
|
-
if (offset < this.recvOffset) {
|
|
218
|
-
const drop = Number(this.recvOffset - offset);
|
|
219
|
-
payload = payload.subarray(drop) as Bytes;
|
|
220
|
-
payloadOffset = this.recvOffset;
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
// Contiguous: deliver immediately. Else buffer for later.
|
|
224
|
-
if (payloadOffset === this.recvOffset) {
|
|
225
|
-
this.recvOffset += BigInt(payload.length);
|
|
226
|
-
this.deliver(payload);
|
|
227
|
-
// The new recvOffset may now bridge buffered gaps — drain them.
|
|
228
|
-
this.drainReassembly();
|
|
229
|
-
} else {
|
|
230
|
-
this.insertReassembly(payloadOffset, payload);
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
// FIN and all bytes delivered: signal EOF.
|
|
234
|
-
if (this.recvFinOffset !== undefined && this.recvOffset >= this.recvFinOffset) {
|
|
235
|
-
this.signalFin();
|
|
236
|
-
}
|
|
237
|
-
return this.replenishNeeded();
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
/** True if we should send a MAX_STREAM_DATA to replenish the peer's credit. */
|
|
241
|
-
private replenishNeeded(): boolean {
|
|
242
|
-
const consumed = this.dataReceived;
|
|
243
|
-
const threshold = this.maxStreamDataAdvertised / BigInt(REPLENISH_FRACTION);
|
|
244
|
-
return consumed >= threshold;
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
/** Advertise additional receive credit to the peer (call after sending MAX_STREAM_DATA). */
|
|
248
|
-
public advertiseStreamDataCredit(additional: bigint): void {
|
|
249
|
-
this.maxStreamDataAdvertised += additional;
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
/** The current per-stream receive limit we have advertised to the peer. */
|
|
253
|
-
public get streamMaxDataAdvertised(): bigint {
|
|
254
|
-
return this.maxStreamDataAdvertised;
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
private insertReassembly(offset: bigint, data: Bytes): void {
|
|
258
|
-
this.reassembly.push({ offset, data });
|
|
259
|
-
this.reassembly.sort((a, b) => (a.offset < b.offset ? -1 : a.offset > b.offset ? 1 : 0));
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
/** Deliver any buffered reassembly chunks that now bridge recvOffset. */
|
|
263
|
-
private drainReassembly(): void {
|
|
264
|
-
while (this.reassembly.length > 0) {
|
|
265
|
-
const head = this.reassembly[0]!;
|
|
266
|
-
if (head.offset > this.recvOffset) break;
|
|
267
|
-
this.reassembly.shift();
|
|
268
|
-
// head.offset <= recvOffset (it was inserted above recvOffset, so equal).
|
|
269
|
-
this.recvOffset += BigInt(head.data.length);
|
|
270
|
-
this.deliver(head.data);
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
/** Hand bytes to a waiting reader or buffer them. */
|
|
275
|
-
private deliver(bytes: Bytes): void {
|
|
276
|
-
if (this.readWaiters.length > 0) {
|
|
277
|
-
const waiter = this.readWaiters.shift()!;
|
|
278
|
-
waiter.resolve(bytes);
|
|
279
|
-
} else {
|
|
280
|
-
this.readBuffer = concat(this.readBuffer, bytes);
|
|
281
|
-
}
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
private signalFin(): void {
|
|
285
|
-
if (this.finDelivered) return;
|
|
286
|
-
this.finDelivered = true;
|
|
287
|
-
if (this.readWaiters.length > 0) {
|
|
288
|
-
const waiter = this.readWaiters.shift()!;
|
|
289
|
-
waiter.resolve(EMPTY);
|
|
290
|
-
}
|
|
291
|
-
this.transitionOnRemoteFin();
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
// --- peer control frames ---------------------------------------------------
|
|
295
|
-
|
|
296
|
-
/** Peer reset the stream: reject every waiter and close. */
|
|
297
|
-
public resetPeer(errorCode: bigint, finalSize: bigint): void {
|
|
298
|
-
this.state = { state: "closed", reason: { kind: "reset", errorCode } };
|
|
299
|
-
this.rejectReaders(new ResetStreamError(this.id, errorCode, finalSize));
|
|
300
|
-
this.rejectWriters(new ResetStreamError(this.id, errorCode, finalSize));
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
/** Peer asked us to stop sending. */
|
|
304
|
-
public stopSending(errorCode: bigint): void {
|
|
305
|
-
// Discard the send queue — the peer does not want more data.
|
|
306
|
-
this.sendQueue = EMPTY;
|
|
307
|
-
this.sendFinPending = false;
|
|
308
|
-
this.rejectWriters(new StopSendingError(this.id, errorCode));
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
/** Grow the peer's per-stream send limit (MAX_STREAM_DATA arrived). */
|
|
312
|
-
public growSendWindow(maximum: bigint): void {
|
|
313
|
-
if (maximum <= this.maxStreamData) return;
|
|
314
|
-
this.maxStreamData = maximum;
|
|
315
|
-
this.drainSendWaiters();
|
|
316
|
-
}
|
|
317
|
-
|
|
318
|
-
// --- waiter management -----------------------------------------------------
|
|
319
|
-
|
|
320
|
-
private drainSendWaiters(): void {
|
|
321
|
-
if (this.sendQueue.length === 0) {
|
|
322
|
-
while (this.sendWaiters.length > 0) this.sendWaiters.shift()!.resolve();
|
|
323
|
-
}
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
private rejectReaders(err: Error): void {
|
|
327
|
-
while (this.readWaiters.length > 0) this.readWaiters.shift()!.reject(err);
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
private rejectWriters(err: Error): void {
|
|
331
|
-
while (this.sendWaiters.length > 0) this.sendWaiters.shift()!.reject(err);
|
|
332
|
-
}
|
|
333
|
-
|
|
334
|
-
// --- state machine ----------------------------------------------------------
|
|
335
|
-
|
|
336
|
-
private transitionOnLocalFin(): void {
|
|
337
|
-
const s = this.state;
|
|
338
|
-
if (s.state === "open") {
|
|
339
|
-
this.state = { state: "half_closed_local" };
|
|
340
|
-
} else if (s.state === "half_closed_remote") {
|
|
341
|
-
this.state = { state: "closed", reason: { kind: "normal" } };
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
private transitionOnRemoteFin(): void {
|
|
346
|
-
const s = this.state;
|
|
347
|
-
if (s.state === "open") {
|
|
348
|
-
this.state = { state: "half_closed_remote" };
|
|
349
|
-
} else if (s.state === "half_closed_local") {
|
|
350
|
-
this.state = { state: "closed", reason: { kind: "normal" } };
|
|
351
|
-
}
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
/** Force-close (connection teardown). */
|
|
355
|
-
public forceClose(reason: StreamCloseReason): void {
|
|
356
|
-
this.state = { state: "closed", reason };
|
|
357
|
-
this.rejectReaders(new Error("connection closed"));
|
|
358
|
-
this.rejectWriters(new Error("connection closed"));
|
|
359
|
-
}
|
|
360
|
-
|
|
361
|
-
/** The offset up to which we have sent (for STREAM frame offset + final size). */
|
|
362
|
-
public sendFinOffset = 0n;
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
// ---------------------------------------------------------------------------
|
|
366
|
-
// Stream manager
|
|
367
|
-
// ---------------------------------------------------------------------------
|
|
368
|
-
|
|
369
|
-
/** A handle the stream manager exposes to the connection for sending + dispatch. */
|
|
370
|
-
export interface StreamManager {
|
|
371
|
-
/** Open a new locally-initiated stream of the given type. */
|
|
372
|
-
openStream(bidirectional: boolean): QuicStream;
|
|
373
|
-
/** Wait for the next peer-initiated stream of the given type. */
|
|
374
|
-
acceptStream(bidirectional: boolean): Promise<QuicStream>;
|
|
375
|
-
/** Dispatch a decoded frame to the relevant stream / connection. */
|
|
376
|
-
dispatch(frame: QuicFrame): void;
|
|
377
|
-
/**
|
|
378
|
-
* Drain pending sends into STREAM frames, respecting flow control. Calls
|
|
379
|
-
* `emit` for each frame that should be packed into an outbound packet.
|
|
380
|
-
* `maxPayload` bounds the total bytes of STREAM data to emit this pass.
|
|
381
|
-
*/
|
|
382
|
-
flushSends(maxPayload: number, emit: (frame: QuicFrame) => void): void;
|
|
383
|
-
/** True if there are streams with data/FIN pending to send. */
|
|
384
|
-
readonly hasPendingSends: boolean;
|
|
385
|
-
/** Reject every in-flight reader/writer and close all streams. */
|
|
386
|
-
abortAll(error: Error): void;
|
|
387
|
-
/** Begin connection close: emit a CONNECTION_CLOSE and stop accepting. */
|
|
388
|
-
close(errorCode: bigint, reason: string): void;
|
|
389
|
-
/** The local transport parameters we advertise. */
|
|
390
|
-
readonly localParameters: QuicTransportParameters;
|
|
391
|
-
}
|
|
392
|
-
|
|
393
|
-
/** Dependencies the stream manager needs from the connection. */
|
|
394
|
-
export interface StreamManagerDeps {
|
|
395
|
-
/** Send a frame to be packed into an outbound packet. */
|
|
396
|
-
sendFrame: (frame: QuicFrame) => void;
|
|
397
|
-
/** Local transport parameters to advertise. */
|
|
398
|
-
localParameters: QuicTransportParameters;
|
|
399
|
-
/** Peer transport parameters (for their receive windows). */
|
|
400
|
-
peerParameters: QuicTransportParameters;
|
|
401
|
-
}
|
|
402
|
-
|
|
403
|
-
/**
|
|
404
|
-
* Create a stream manager. `deps.sendFrame` is the callback for frame I/O — the
|
|
405
|
-
* manager never touches the transport directly.
|
|
406
|
-
*
|
|
407
|
-
* The returned object is also an {@link EventEmitter} emitting connection-level
|
|
408
|
-
* signals the connection layer reacts to:
|
|
409
|
-
* - "incomingStream", stream — a peer-initiated stream the app can accept
|
|
410
|
-
* - "connectionClose", {errorCode, reason} — peer sent CONNECTION_CLOSE
|
|
411
|
-
* - "maxData", maximum — peer grew our connection send window
|
|
412
|
-
*/
|
|
413
|
-
export function createStreamManager(deps: StreamManagerDeps): StreamManager & EventEmitter {
|
|
414
|
-
const streams = new Map<StreamId, ManagedStream>();
|
|
415
|
-
const emitter = new EventEmitter();
|
|
416
|
-
|
|
417
|
-
// Next locally-initiated stream ids, per type (RFC 9000 §2.1).
|
|
418
|
-
let nextBidi = firstStreamId(true, true); // client-initiated bidirectional = 0
|
|
419
|
-
let nextUni = firstStreamId(false, true); // client-initiated unidirectional = 2
|
|
420
|
-
|
|
421
|
-
// Peer stream-id limits (how many streams the peer will accept).
|
|
422
|
-
let peerMaxBidi = DEFAULT_INITIAL_MAX_STREAMS_BIDI;
|
|
423
|
-
let peerMaxUni = DEFAULT_INITIAL_MAX_STREAMS_UNI;
|
|
424
|
-
|
|
425
|
-
// Connection-level flow control (send side).
|
|
426
|
-
let connectionMaxData = DEFAULT_INITIAL_MAX_DATA;
|
|
427
|
-
let connectionDataSent = 0n;
|
|
428
|
-
|
|
429
|
-
// Connection-level flow control (receive side) + accounting.
|
|
430
|
-
let connectionMaxDataAdvertised = resolveLocalMaxData(deps.localParameters);
|
|
431
|
-
let connectionDataReceived = 0n;
|
|
432
|
-
|
|
433
|
-
let closing = false;
|
|
434
|
-
let closed = false;
|
|
435
|
-
|
|
436
|
-
function resolveLocalMaxData(params: QuicTransportParameters): bigint {
|
|
437
|
-
return params.initialMaxData ?? DEFAULT_INITIAL_MAX_DATA;
|
|
438
|
-
}
|
|
439
|
-
|
|
440
|
-
function resolvePeerMaxStreamData(bidirectional: boolean): bigint {
|
|
441
|
-
// The peer's limit on how much *we* may send per stream. We do not know
|
|
442
|
-
// the peer's per-stream value until the handshake, so fall back to the
|
|
443
|
-
// default; a real implementation reads INITIAL_MAX_STREAM_DATA_*.
|
|
444
|
-
if (bidirectional) {
|
|
445
|
-
return (
|
|
446
|
-
deps.peerParameters.initialMaxStreamDataBidiRemote ??
|
|
447
|
-
deps.peerParameters.initialMaxStreamDataBidiLocal ??
|
|
448
|
-
DEFAULT_INITIAL_MAX_STREAM_DATA
|
|
449
|
-
);
|
|
450
|
-
}
|
|
451
|
-
return deps.peerParameters.initialMaxStreamDataUni ?? DEFAULT_INITIAL_MAX_STREAM_DATA;
|
|
452
|
-
}
|
|
453
|
-
|
|
454
|
-
// --- frame I/O helpers -----------------------------------------------------
|
|
455
|
-
|
|
456
|
-
function sendMaxStreamData(stream: ManagedStream): void {
|
|
457
|
-
// Grant the peer another full window of credit on this stream.
|
|
458
|
-
const additional = resolvePeerMaxStreamData(streamIdIsBidirectional(stream.id));
|
|
459
|
-
stream.advertiseStreamDataCredit(additional);
|
|
460
|
-
deps.sendFrame({
|
|
461
|
-
type: QuicFrameType.MAX_STREAM_DATA,
|
|
462
|
-
streamId: stream.id,
|
|
463
|
-
maximum: stream.streamMaxDataAdvertised,
|
|
464
|
-
});
|
|
465
|
-
}
|
|
466
|
-
|
|
467
|
-
function sendMaxData(): void {
|
|
468
|
-
const additional = connectionMaxDataAdvertised;
|
|
469
|
-
connectionMaxDataAdvertised += additional;
|
|
470
|
-
deps.sendFrame({ type: QuicFrameType.MAX_DATA, maximum: connectionMaxDataAdvertised });
|
|
471
|
-
}
|
|
472
|
-
|
|
473
|
-
// --- stream lifecycle ------------------------------------------------------
|
|
474
|
-
|
|
475
|
-
function openStream(bidirectional: boolean): QuicStream {
|
|
476
|
-
if (closing || closed) throw new Error("connection is closing");
|
|
477
|
-
const id = bidirectional ? nextBidi : nextUni;
|
|
478
|
-
if (bidirectional) {
|
|
479
|
-
nextBidi = nextStreamId(nextBidi);
|
|
480
|
-
} else {
|
|
481
|
-
nextUni = nextStreamId(nextUni);
|
|
482
|
-
}
|
|
483
|
-
const stream = new ManagedStream(id, resolvePeerMaxStreamData(bidirectional));
|
|
484
|
-
streams.set(id, stream);
|
|
485
|
-
return stream;
|
|
486
|
-
}
|
|
487
|
-
|
|
488
|
-
function acceptStream(bidirectional: boolean): Promise<QuicStream> {
|
|
489
|
-
if (closing || closed) return Promise.reject(new Error("connection is closing"));
|
|
490
|
-
// Already have an incoming stream of this type waiting?
|
|
491
|
-
for (const stream of streams.values()) {
|
|
492
|
-
const matchesType = streamIdIsBidirectional(stream.id) === bidirectional;
|
|
493
|
-
const peerInitiated = !streamIdIsClientInitiated(stream.id);
|
|
494
|
-
if (matchesType && peerInitiated) {
|
|
495
|
-
// Only surface it once: mark as accepted by flipping to a synthetic
|
|
496
|
-
// client-initiated id is wrong — instead, track acceptance. We use a
|
|
497
|
-
// simple "accepted" flag on a wrapper; here we just return it once.
|
|
498
|
-
if (!acceptedStreams.has(stream.id)) {
|
|
499
|
-
acceptedStreams.add(stream.id);
|
|
500
|
-
return Promise.resolve(stream);
|
|
501
|
-
}
|
|
502
|
-
}
|
|
503
|
-
}
|
|
504
|
-
return new Promise<QuicStream>((resolve, reject) => {
|
|
505
|
-
acceptWaiters.push({ bidirectional, resolve, reject });
|
|
506
|
-
});
|
|
507
|
-
}
|
|
508
|
-
|
|
509
|
-
const acceptedStreams = new Set<StreamId>();
|
|
510
|
-
const acceptWaiters: Array<{
|
|
511
|
-
bidirectional: boolean;
|
|
512
|
-
resolve: (s: QuicStream) => void;
|
|
513
|
-
reject: (e: Error) => void;
|
|
514
|
-
}> = [];
|
|
515
|
-
|
|
516
|
-
function registerIncomingStream(id: StreamId): ManagedStream {
|
|
517
|
-
const bidirectional = streamIdIsBidirectional(id);
|
|
518
|
-
const stream = new ManagedStream(id, resolvePeerMaxStreamData(bidirectional));
|
|
519
|
-
streams.set(id, stream);
|
|
520
|
-
// Wake a matching accept waiter if one is waiting.
|
|
521
|
-
const waiterIdx = acceptWaiters.findIndex((w) => w.bidirectional === bidirectional);
|
|
522
|
-
if (waiterIdx >= 0) {
|
|
523
|
-
const waiter = acceptWaiters.splice(waiterIdx, 1)[0]!;
|
|
524
|
-
acceptedStreams.add(id);
|
|
525
|
-
waiter.resolve(stream);
|
|
526
|
-
} else {
|
|
527
|
-
emitter.emit("incomingStream", stream);
|
|
528
|
-
}
|
|
529
|
-
return stream;
|
|
530
|
-
}
|
|
531
|
-
|
|
532
|
-
// --- send drain ------------------------------------------------------------
|
|
533
|
-
|
|
534
|
-
function flushSends(maxPayload: number, emit: (frame: QuicFrame) => void): void {
|
|
535
|
-
let budget = maxPayload;
|
|
536
|
-
for (const stream of streams.values()) {
|
|
537
|
-
if (budget <= 0) break;
|
|
538
|
-
if (!stream.hasPendingSend) continue;
|
|
539
|
-
// Respect both the connection and per-stream send windows.
|
|
540
|
-
const streamWindow = stream.maxStreamData - stream.dataSent;
|
|
541
|
-
const connWindow = connectionMaxData - connectionDataSent;
|
|
542
|
-
let allow = Math.min(Number(streamWindow), Number(connWindow), budget);
|
|
543
|
-
if (allow <= 0) {
|
|
544
|
-
if (streamWindow <= 0n) {
|
|
545
|
-
emit({
|
|
546
|
-
type: QuicFrameType.STREAM_DATA_BLOCKED,
|
|
547
|
-
streamId: stream.id,
|
|
548
|
-
limit: stream.maxStreamData,
|
|
549
|
-
});
|
|
550
|
-
}
|
|
551
|
-
continue;
|
|
552
|
-
}
|
|
553
|
-
let payload = stream.peekSend(allow);
|
|
554
|
-
if (payload.length > allow) payload = payload.subarray(0, allow) as Bytes;
|
|
555
|
-
const isLastOfStream =
|
|
556
|
-
stream.sendFinPending && stream.sendQueue.length <= payload.length;
|
|
557
|
-
if (isLastOfStream) {
|
|
558
|
-
allow = payload.length; // FIN frame may be shorter than the window
|
|
559
|
-
}
|
|
560
|
-
const offset = stream.sendOffset;
|
|
561
|
-
emit({
|
|
562
|
-
type: QuicFrameType.STREAM,
|
|
563
|
-
streamId: stream.id,
|
|
564
|
-
offset,
|
|
565
|
-
data: payload,
|
|
566
|
-
fin: isLastOfStream,
|
|
567
|
-
});
|
|
568
|
-
stream.commitSend(offset, payload.length, isLastOfStream);
|
|
569
|
-
connectionDataSent += BigInt(payload.length);
|
|
570
|
-
budget -= payload.length;
|
|
571
|
-
}
|
|
572
|
-
if (budget <= 0 && connWindowTooSmall()) {
|
|
573
|
-
emit({ type: QuicFrameType.DATA_BLOCKED, limit: connectionMaxData });
|
|
574
|
-
}
|
|
575
|
-
}
|
|
576
|
-
|
|
577
|
-
function connWindowTooSmall(): boolean {
|
|
578
|
-
return connectionMaxData - connectionDataSent <= 0n;
|
|
579
|
-
}
|
|
580
|
-
|
|
581
|
-
// --- dispatch --------------------------------------------------------------
|
|
582
|
-
|
|
583
|
-
function dispatch(frame: QuicFrame): void {
|
|
584
|
-
switch (frame.type) {
|
|
585
|
-
case QuicFrameType.STREAM:
|
|
586
|
-
return handleStream(frame);
|
|
587
|
-
case QuicFrameType.RESET_STREAM:
|
|
588
|
-
return handleResetStream(frame);
|
|
589
|
-
case QuicFrameType.STOP_SENDING:
|
|
590
|
-
return handleStopSending(frame);
|
|
591
|
-
case QuicFrameType.MAX_DATA:
|
|
592
|
-
return handleMaxData(frame);
|
|
593
|
-
case QuicFrameType.MAX_STREAM_DATA:
|
|
594
|
-
return handleMaxStreamData(frame);
|
|
595
|
-
case QuicFrameType.MAX_STREAMS_BIDI:
|
|
596
|
-
case QuicFrameType.MAX_STREAMS_UNI:
|
|
597
|
-
return handleMaxStreams(frame);
|
|
598
|
-
case QuicFrameType.DATA_BLOCKED:
|
|
599
|
-
case QuicFrameType.STREAM_DATA_BLOCKED:
|
|
600
|
-
case QuicFrameType.STREAMS_BLOCKED_BIDI:
|
|
601
|
-
case QuicFrameType.STREAMS_BLOCKED_UNI:
|
|
602
|
-
// Peer is blocked on a window we control — informational; a full
|
|
603
|
-
// implementation would pace. We surface nothing here.
|
|
604
|
-
return;
|
|
605
|
-
case QuicFrameType.CONNECTION_CLOSE:
|
|
606
|
-
case QuicFrameType.CONNECTION_CLOSE_APP:
|
|
607
|
-
return handleConnectionClose(frame);
|
|
608
|
-
case QuicFrameType.PING:
|
|
609
|
-
// Liveness probe: the connection layer handles ACKs; nothing to do.
|
|
610
|
-
return;
|
|
611
|
-
default:
|
|
612
|
-
// ACK, CRYPTO, NEW_TOKEN, NEW_CONNECTION_ID, RETIRE_CONNECTION_ID,
|
|
613
|
-
// PATH_CHALLENGE, PATH_RESPONSE, HANDSHAKE_DONE, PADDING are handled
|
|
614
|
-
// by the connection / handshake layers, not the data plane.
|
|
615
|
-
return;
|
|
616
|
-
}
|
|
617
|
-
}
|
|
618
|
-
|
|
619
|
-
function handleStream(frame: Extract<QuicFrame, { type: typeof QuicFrameType.STREAM }>): void {
|
|
620
|
-
let stream = streams.get(makeStreamId(frame.streamId));
|
|
621
|
-
if (stream === undefined) {
|
|
622
|
-
// Peer opened a new stream.
|
|
623
|
-
if (!streamIdIsClientInitiated(makeStreamId(frame.streamId))) {
|
|
624
|
-
stream = registerIncomingStream(makeStreamId(frame.streamId));
|
|
625
|
-
} else {
|
|
626
|
-
return; // unknown local stream; ignore
|
|
627
|
-
}
|
|
628
|
-
}
|
|
629
|
-
const replenish = stream.ingest(frame.offset, frame.data as Bytes, frame.fin);
|
|
630
|
-
connectionDataReceived += BigInt(frame.data.length);
|
|
631
|
-
if (replenish) sendMaxStreamData(stream);
|
|
632
|
-
// Receiving data grows the connection receive window accounting.
|
|
633
|
-
if (connectionDataReceived >= connectionMaxDataAdvertised / BigInt(REPLENISH_FRACTION)) {
|
|
634
|
-
connectionDataReceived = 0n;
|
|
635
|
-
sendMaxData();
|
|
636
|
-
}
|
|
637
|
-
}
|
|
638
|
-
|
|
639
|
-
function handleResetStream(
|
|
640
|
-
frame: Extract<QuicFrame, { type: typeof QuicFrameType.RESET_STREAM }>,
|
|
641
|
-
): void {
|
|
642
|
-
const stream = streams.get(makeStreamId(frame.streamId));
|
|
643
|
-
if (stream === undefined) return;
|
|
644
|
-
stream.resetPeer(frame.errorCode, frame.finalSize);
|
|
645
|
-
streams.delete(makeStreamId(frame.streamId));
|
|
646
|
-
}
|
|
647
|
-
|
|
648
|
-
function handleStopSending(
|
|
649
|
-
frame: Extract<QuicFrame, { type: typeof QuicFrameType.STOP_SENDING }>,
|
|
650
|
-
): void {
|
|
651
|
-
const stream = streams.get(makeStreamId(frame.streamId));
|
|
652
|
-
if (stream === undefined) return;
|
|
653
|
-
stream.stopSending(frame.errorCode);
|
|
654
|
-
}
|
|
655
|
-
|
|
656
|
-
function handleMaxData(frame: Extract<QuicFrame, { type: typeof QuicFrameType.MAX_DATA }>): void {
|
|
657
|
-
if (frame.maximum <= connectionMaxData) return;
|
|
658
|
-
connectionMaxData = frame.maximum;
|
|
659
|
-
emitter.emit("maxData", frame.maximum);
|
|
660
|
-
}
|
|
661
|
-
|
|
662
|
-
function handleMaxStreamData(
|
|
663
|
-
frame: Extract<QuicFrame, { type: typeof QuicFrameType.MAX_STREAM_DATA }>,
|
|
664
|
-
): void {
|
|
665
|
-
const stream = streams.get(makeStreamId(frame.streamId));
|
|
666
|
-
if (stream === undefined) return;
|
|
667
|
-
stream.growSendWindow(frame.maximum);
|
|
668
|
-
}
|
|
669
|
-
|
|
670
|
-
function handleMaxStreams(frame: MaxStreamsFrame): void {
|
|
671
|
-
switch (frame.type) {
|
|
672
|
-
case QuicFrameType.MAX_STREAMS_BIDI:
|
|
673
|
-
if (frame.maximum > peerMaxBidi) peerMaxBidi = frame.maximum;
|
|
674
|
-
return;
|
|
675
|
-
case QuicFrameType.MAX_STREAMS_UNI:
|
|
676
|
-
if (frame.maximum > peerMaxUni) peerMaxUni = frame.maximum;
|
|
677
|
-
return;
|
|
678
|
-
}
|
|
679
|
-
}
|
|
680
|
-
|
|
681
|
-
function handleConnectionClose(
|
|
682
|
-
frame: Extract<
|
|
683
|
-
QuicFrame,
|
|
684
|
-
{ type: typeof QuicFrameType.CONNECTION_CLOSE | typeof QuicFrameType.CONNECTION_CLOSE_APP }
|
|
685
|
-
>,
|
|
686
|
-
): void {
|
|
687
|
-
closing = true;
|
|
688
|
-
emitter.emit("connectionClose", { errorCode: frame.errorCode, reason: frame.reason });
|
|
689
|
-
}
|
|
690
|
-
|
|
691
|
-
// --- teardown --------------------------------------------------------------
|
|
692
|
-
|
|
693
|
-
function abortAll(error: Error): void {
|
|
694
|
-
for (const stream of [...streams.values()]) stream.forceClose({ kind: "connection_close" });
|
|
695
|
-
streams.clear();
|
|
696
|
-
for (const waiter of acceptWaiters) waiter.reject(error);
|
|
697
|
-
acceptWaiters.length = 0;
|
|
698
|
-
}
|
|
699
|
-
|
|
700
|
-
function close(errorCode: bigint, reason: string): void {
|
|
701
|
-
if (closed) return;
|
|
702
|
-
closing = true;
|
|
703
|
-
deps.sendFrame({
|
|
704
|
-
type: QuicFrameType.CONNECTION_CLOSE,
|
|
705
|
-
errorCode,
|
|
706
|
-
frameType: undefined,
|
|
707
|
-
reason,
|
|
708
|
-
});
|
|
709
|
-
}
|
|
710
|
-
|
|
711
|
-
const localParameters = deps.localParameters;
|
|
712
|
-
|
|
713
|
-
const manager: StreamManager = {
|
|
714
|
-
openStream,
|
|
715
|
-
acceptStream,
|
|
716
|
-
dispatch,
|
|
717
|
-
flushSends,
|
|
718
|
-
abortAll,
|
|
719
|
-
close,
|
|
720
|
-
get hasPendingSends(): boolean {
|
|
721
|
-
for (const s of streams.values()) if (s.hasPendingSend) return true;
|
|
722
|
-
return false;
|
|
723
|
-
},
|
|
724
|
-
get localParameters(): QuicTransportParameters {
|
|
725
|
-
return localParameters;
|
|
726
|
-
},
|
|
727
|
-
};
|
|
728
|
-
|
|
729
|
-
// Mirror EventEmitter's core methods onto the manager so the returned object
|
|
730
|
-
// satisfies the `StreamManager & EventEmitter` intersection type and callers
|
|
731
|
-
// can subscribe through a single handle.
|
|
732
|
-
Object.assign(manager, {
|
|
733
|
-
on: (event: string | symbol, listener: (...args: unknown[]) => void) =>
|
|
734
|
-
emitter.on(event, listener),
|
|
735
|
-
once: (event: string | symbol, listener: (...args: unknown[]) => void) =>
|
|
736
|
-
emitter.once(event, listener),
|
|
737
|
-
off: (event: string | symbol, listener: (...args: unknown[]) => void) =>
|
|
738
|
-
emitter.off(event, listener),
|
|
739
|
-
removeListener: (event: string | symbol, listener: (...args: unknown[]) => void) =>
|
|
740
|
-
emitter.removeListener(event, listener),
|
|
741
|
-
removeAllListeners: (event?: string | symbol) => emitter.removeAllListeners(event),
|
|
742
|
-
emit: (event: string | symbol, ...args: unknown[]) => emitter.emit(event, ...args),
|
|
743
|
-
});
|
|
744
|
-
|
|
745
|
-
return manager as StreamManager & EventEmitter;
|
|
746
|
-
}
|