// HTTP/2 over a plain TCP socket (h2c with prior knowledge, RFC 9113 §3.3) — the transport gRPC rides on (the kernel's // gRPC wire, ./grpc-wire.ts; architecture, "Other wires": gRPC), with its HPACK tables (./hpack.json) derived from the // vendored RFC 7541. Written on a socket because the runtime this repo develops under cannot serve it: Bun 1.3's // `node:http2` server writes frames nghttp2 rejects at the connection preface (a node client gets // ERR_HTTP2_ERROR before the first SETTINGS; measured 2026-09-27, Bun 1.3.11, Node 22.23.2, the // probe is temporal-h2.test.ts's "node:http2 client" case). A socket works under both runtimes. // // Scope, stated: a SERVER for request/response exchanges. It frames HEADERS/CONTINUATION, DATA, // SETTINGS, PING, WINDOW_UPDATE, RST_STREAM, GOAWAY and PRIORITY (ignored), decodes HPACK (RFC 7541, // the tables derived from the vendored RFC into ./hpack.json), honours both directions of // flow control, and never pushes. The encoder emits literals without indexing, which RFC 7541 §6.2.2 // allows for any header, so the peer's dynamic table is never touched. import type { Socket } from 'node:net'; import hpack from './hpack.json' with { type: 'json' }; const PREFACE = 'PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n'; const FRAME = { DATA: 0, HEADERS: 1, PRIORITY: 2, RST_STREAM: 3, SETTINGS: 4, PUSH_PROMISE: 5, PING: 6, GOAWAY: 7, WINDOW_UPDATE: 8, CONTINUATION: 9 } as const; const FLAG = { END_STREAM: 0x1, ACK: 0x1, END_HEADERS: 0x4, PADDED: 0x8, PRIORITY: 0x20 } as const; const ERROR = { NO_ERROR: 0, PROTOCOL_ERROR: 1, INTERNAL_ERROR: 2, FLOW_CONTROL_ERROR: 3, STREAM_CLOSED: 5, FRAME_SIZE_ERROR: 6, REFUSED_STREAM: 7, CANCEL: 8, COMPRESSION_ERROR: 9 } as const; const DEFAULT_WINDOW = 65_535; /** what this server grants each stream and the connection to receive */ const RECEIVE_WINDOW = 16 * 1024 * 1024; const MAX_CONCURRENT_STREAMS = 1000; /** a request body larger than this resets its stream: a memory bound, not Temporal's message limit (the * SDKs' gRPC default is 4 MiB; this server does not enforce that one) */ const MAX_REQUEST_BYTES = 64 * 1024 * 1024; /** A chunked body (RFC 9112 §7.1) from `from`: its bytes once the last chunk and the trailer section have arrived, * 'incomplete' before, 'bad' for a malformed size line or one past MAX_REQUEST_BYTES. Extensions and trailers are * read past and not kept. */ function chunkedBody(buffer: Buffer, from: number): Uint8Array | 'incomplete' | 'bad' { const parts: Buffer[] = []; let at = from, total = 0; for (;;) { const line = buffer.indexOf('\r\n', at); if (line < 0) return buffer.length - at > 4096 ? 'bad' : 'incomplete'; const size = /^([0-9A-Fa-f]{1,8})[ \t]*(?:;.*)?$/su.exec(buffer.subarray(at, line).toString('latin1')); if (!size) return 'bad'; const length = parseInt(size[1]!, 16); at = line + 2; if (length === 0) break; total += length; if (total > MAX_REQUEST_BYTES) return 'bad'; if (buffer.length < at + length + 2) return 'incomplete'; if (buffer[at + length] !== 0x0d || buffer[at + length + 1] !== 0x0a) return 'bad'; parts.push(buffer.subarray(at, at + length)); at += length + 2; } // The trailer section: field lines up to an empty line. for (;;) { const line = buffer.indexOf('\r\n', at); if (line < 0) return buffer.length - at > 64 * 1024 ? 'bad' : 'incomplete'; if (line === at) return Buffer.concat(parts); at = line + 2; } } /** a header block (HEADERS + CONTINUATION) larger than this closes the connection */ const MAX_HEADER_BLOCK = 256 * 1024; // ---- HPACK ------------------------------------------------------------------------------------ const STATIC_TABLE = hpack.staticTable as Array<[string, string]>; type HuffmanNode = { symbol?: number; zero?: HuffmanNode; one?: HuffmanNode }; const HUFFMAN_ROOT: HuffmanNode = (() => { const root: HuffmanNode = {}; (hpack.huffman as Array<[number, number]>).forEach(([code, length], symbol) => { let node = root; for (let bit = length - 1; bit >= 0; bit -= 1) { const key = (code >>> bit) & 1 ? 'one' : 'zero'; node = node[key] ??= {}; } node.symbol = symbol; }); return root; })(); export class HpackError extends Error {} export function huffmanDecode(bytes: Uint8Array): string { const out: number[] = []; let node = HUFFMAN_ROOT; let pending = 0; // bits consumed since the last symbol let allOnes = true; for (const byte of bytes) { for (let bit = 7; bit >= 0; bit -= 1) { const one = (byte >> bit) & 1; const next = one ? node.one : node.zero; if (!next) throw new HpackError('invalid huffman code'); pending += 1; allOnes &&= one === 1; if (next.symbol !== undefined) { if (next.symbol === 256) throw new HpackError('EOS symbol inside a huffman string'); // §5.2 out.push(next.symbol); node = HUFFMAN_ROOT; pending = 0; allOnes = true; } else { node = next; } } } // §5.2: padding is at most 7 bits and is the most significant bits of EOS (all ones) if (pending > 7 || !allOnes) throw new HpackError('invalid huffman padding'); return Buffer.from(out).toString('latin1'); } export class HpackDecoder { private table: Array<[string, string]> = []; private size = 0; private maxSize: number; /** the SETTINGS_HEADER_TABLE_SIZE this endpoint advertised (the decoder's ceiling; 4096 is the * protocol default, which this server never changes) */ private readonly limit: number; constructor(headerTableSize = 4096) { this.maxSize = headerTableSize; this.limit = headerTableSize; } decode(block: Uint8Array): Array<[string, string]> { const headers: Array<[string, string]> = []; let offset = 0; const integer = (prefixBits: number): number => { const mask = (1 << prefixBits) - 1; let value = block[offset]! & mask; offset += 1; if (value < mask) return value; let shift = 0; for (;;) { if (offset >= block.length) throw new HpackError('truncated integer'); const byte = block[offset]!; offset += 1; value += (byte & 0x7f) * 2 ** shift; shift += 7; if ((byte & 0x80) === 0) return value; if (shift > 28) throw new HpackError('integer overflow'); } }; const string = (): string => { if (offset >= block.length) throw new HpackError('truncated string'); const huffman = (block[offset]! & 0x80) !== 0; const length = integer(7); if (offset + length > block.length) throw new HpackError('truncated string'); const bytes = block.subarray(offset, offset + length); offset += length; return huffman ? huffmanDecode(bytes) : Buffer.from(bytes).toString('latin1'); }; const entry = (index: number): [string, string] => { if (index <= 0) throw new HpackError('index 0'); if (index <= STATIC_TABLE.length) return STATIC_TABLE[index - 1]!; const dynamic = this.table[index - STATIC_TABLE.length - 1]; if (!dynamic) throw new HpackError(`index ${index} is beyond the dynamic table`); return dynamic; }; while (offset < block.length) { const byte = block[offset]!; if (byte & 0x80) { // §6.1 indexed headers.push(entry(integer(7))); } else if (byte & 0x40) { // §6.2.1 literal with incremental indexing const index = integer(6); const name = index === 0 ? string() : entry(index)[0]; const value = string(); headers.push([name, value]); this.insert(name, value); } else if (byte & 0x20) { // §6.3 dynamic table size update const size = integer(5); if (size > this.limit) throw new HpackError('table size update above the advertised limit'); this.maxSize = size; this.evict(); } else { // §6.2.2 without indexing / §6.2.3 never indexed const index = integer(4); const name = index === 0 ? string() : entry(index)[0]; headers.push([name, string()]); } } return headers; } private insert(name: string, value: string): void { this.table.unshift([name, value]); this.size += name.length + value.length + 32; this.evict(); } private evict(): void { while (this.size > this.maxSize && this.table.length > 0) { const [name, value] = this.table.pop()!; this.size -= name.length + value.length + 32; } } } function hpackInteger(value: number, prefixBits: number, firstByte: number): number[] { const mask = (1 << prefixBits) - 1; if (value < mask) return [firstByte | value]; const out = [firstByte | mask]; let rest = value - mask; while (rest >= 128) { out.push((rest % 128) + 128); rest = Math.floor(rest / 128); } out.push(rest); return out; } /** Every header as a literal without indexing, new name, no huffman (RFC 7541 §6.2.2). */ export function hpackEncode(headers: Array<[string, string]>): Uint8Array { const out: number[] = []; for (const [name, value] of headers) { const nameBytes = Buffer.from(name.toLowerCase(), 'latin1'); const valueBytes = Buffer.from(value, 'latin1'); out.push(0x00, ...hpackInteger(nameBytes.length, 7, 0), ...nameBytes, ...hpackInteger(valueBytes.length, 7, 0), ...valueBytes); } return Uint8Array.from(out); } // ---- framing ---------------------------------------------------------------------------------- export type H2Request = { headers: Record; body: Uint8Array; /** aborted when the peer resets the stream or the connection goes away */ signal: AbortSignal; }; export type H2Response = { /** send response headers; `end` closes the stream with them (a trailers-only answer) */ headers(headers: Array<[string, string]>, end?: boolean): void; data(bytes: Uint8Array): void; /** close the stream with trailing headers */ trailers(headers: Array<[string, string]>): void; readonly closed: boolean; }; export type H2Handler = (request: H2Request, response: H2Response) => void; type Outbound = { kind: 'headers'; block: Uint8Array; end: boolean } | { kind: 'data'; bytes: Uint8Array; offset: number }; type StreamState = { id: number; headerBlock: Uint8Array[] | null; headers: Record; body: Uint8Array[]; bodyBytes: number; remoteClosed: boolean; localClosed: boolean; sendWindow: number; outbound: Outbound[]; abort: AbortController; /** handed to the handler: a stream is dispatched at most once */ dispatched?: boolean; /** a header block arrived after dispatch */ late?: boolean; }; function frameHeader(length: number, type: number, flags: number, streamId: number): Buffer { const header = Buffer.alloc(9); header.writeUIntBE(length, 0, 3); header[3] = type; header[4] = flags; header.writeUInt32BE(streamId & 0x7fffffff, 5); return header; } class H2Connection { // Node-only bytes belong to a live socket, never the browser-importable kernel's module initialization. private readonly preface = Buffer.from(PREFACE, 'latin1'); private buffer: Buffer = Buffer.alloc(0); private prefaceSeen = false; private readonly decoder = new HpackDecoder(); private readonly streams = new Map(); /** the peer sent GOAWAY: it opens no more streams, and the connection ends once the open ones are answered (RFC 9113 §6.8) */ private peerGone = false; private continuing: StreamState | null = null; private lastStreamId = 0; private peerInitialWindow = DEFAULT_WINDOW; private peerMaxFrame = 16_384; private connectionSendWindow = DEFAULT_WINDOW; private dead = false; private readonly socket: Socket; private readonly handler: H2Handler; private readonly http1: Http1Handler | undefined; private http1Mode = false; constructor(socket: Socket, handler: H2Handler, http1?: Http1Handler) { this.socket = socket; this.handler = handler; this.http1 = http1; socket.on('data', (chunk: Buffer) => this.receive(chunk)); socket.on('close', () => this.teardown()); socket.on('error', () => this.teardown()); } /** The server's connection preface (§3.4), sent once the client's has arrived: no push, a stream * ceiling and a large receive window. Waiting for the client's is what lets an HTTP/1 request on * the same port be answered as one instead of receiving binary frames first. */ private sendPreface(): void { const settings = Buffer.alloc(18); settings.writeUInt16BE(0x2, 0); settings.writeUInt32BE(0, 2); // ENABLE_PUSH settings.writeUInt16BE(0x3, 6); settings.writeUInt32BE(MAX_CONCURRENT_STREAMS, 8); settings.writeUInt16BE(0x4, 12); settings.writeUInt32BE(RECEIVE_WINDOW, 14); this.write(FRAME.SETTINGS, 0, 0, settings); this.windowUpdate(0, RECEIVE_WINDOW - DEFAULT_WINDOW); } /** An HTTP/1.1 request on this port (a World's door probe, a curl of the HTTP API): read one * request, answer it through the fetch handler, close. */ private receiveHttp1(): void { const end = this.buffer.indexOf('\r\n\r\n'); if (end < 0) { if (this.buffer.length > 64 * 1024) this.teardown(); return; } const head = this.buffer.subarray(0, end).toString('latin1').split('\r\n'); const [method, target] = head[0]!.split(' '); const headers = new Headers(); try { for (const line of head.slice(1)) { const colon = line.indexOf(':'); if (colon > 0) headers.append(line.slice(0, colon).trim(), line.slice(colon + 1).trim()); } } catch { this.respondHttp1(new Response('bad header', { status: 400 })); return; } // A request with a Transfer-Encoding has a body framed by it, and its Content-Length is not read (RFC 9112 §6.3): // undici sends a streamed body (a World's fetch forwarding a request's own body, duplex 'half') chunked. const coding = headers.get('transfer-encoding'); let body: Uint8Array; if (coding !== null) { if (coding.split(',').map((each) => each.trim().toLowerCase()).at(-1) !== 'chunked') { this.respondHttp1(new Response('a transfer coding other than chunked is not read', { status: 400 })); return; } const read = chunkedBody(this.buffer, end + 4); if (read === 'bad') { this.respondHttp1(new Response('bad chunked body', { status: 400 })); return; } if (read === 'incomplete') return; body = read; } else { const length = Number(headers.get('content-length') ?? 0); if (!Number.isFinite(length) || length < 0 || length > MAX_REQUEST_BYTES) { this.respondHttp1(new Response('bad content-length', { status: 400 })); return; } if (this.buffer.length < end + 4 + length) return; body = this.buffer.subarray(end + 4, end + 4 + length); } this.buffer = Buffer.alloc(0); this.socket.removeAllListeners('data'); let request: Request; try { // the URL is built on loopback, never on the client's Host header if (!target?.startsWith('/')) throw new Error('request target must be origin-form'); request = new Request(`http://127.0.0.1${target}`, { method: method!, headers, ...(method === 'GET' || method === 'HEAD' ? {} : { body: new Uint8Array(body) }), }); } catch { this.respondHttp1(new Response('bad request', { status: 400 })); return; } void Promise.resolve().then(() => this.http1!(request)).then((response) => this.respondHttp1(response), () => this.respondHttp1(new Response('internal error', { status: 500 }))); } private respondHttp1(response: Response): void { void response.arrayBuffer().then((bytes) => { if (this.dead) return; const lines = [`HTTP/1.1 ${response.status} ${response.statusText || 'OK'}`]; response.headers.forEach((value, key) => { if (key !== 'content-length' && key !== 'connection') lines.push(`${key}: ${value}`); }); lines.push(`content-length: ${bytes.byteLength}`, 'connection: close', '', ''); this.socket.end(Buffer.concat([Buffer.from(lines.join('\r\n'), 'latin1'), Buffer.from(bytes)])); }); } private write(type: number, flags: number, streamId: number, payload: Uint8Array = new Uint8Array(0)): void { if (this.dead) return; this.socket.write(Buffer.concat([frameHeader(payload.length, type, flags, streamId), payload])); } private windowUpdate(streamId: number, increment: number): void { if (increment <= 0) return; const payload = Buffer.alloc(4); payload.writeUInt32BE(increment & 0x7fffffff, 0); this.write(FRAME.WINDOW_UPDATE, 0, streamId, payload); } private goaway(code: number, message: string): void { const payload = Buffer.concat([Buffer.alloc(8), Buffer.from(message, 'utf8')]); payload.writeUInt32BE(this.lastStreamId & 0x7fffffff, 0); payload.writeUInt32BE(code, 4); this.write(FRAME.GOAWAY, 0, 0, payload); // end, not destroy: the GOAWAY frame is flushed before the socket closes this.dead = true; for (const stream of this.streams.values()) stream.abort.abort(); this.streams.clear(); this.socket.end(); // a peer that never closes its half is cut off after a grace setTimeout(() => this.socket.destroy(), 1000).unref?.(); } private resetStream(stream: StreamState, code: number): void { const payload = Buffer.alloc(4); payload.writeUInt32BE(code, 0); this.write(FRAME.RST_STREAM, 0, stream.id, payload); this.closeStream(stream); } private closeStream(stream: StreamState): void { stream.localClosed = true; stream.remoteClosed = true; stream.outbound = []; stream.abort.abort(); this.streams.delete(stream.id); this.endIfDone(); } private endIfDone(): void { if (!this.peerGone || this.streams.size > 0) return; this.socket.end(); this.teardown(); } teardown(): void { if (this.dead) { this.socket.destroy(); return; } this.dead = true; for (const stream of this.streams.values()) stream.abort.abort(); this.streams.clear(); this.socket.destroy(); } private receive(chunk: Buffer): void { if (this.dead) return; this.buffer = this.buffer.length ? Buffer.concat([this.buffer, chunk]) : chunk; if (this.http1Mode) { this.receiveHttp1(); return; } if (!this.prefaceSeen) { const seen = this.buffer.subarray(0, Math.min(this.buffer.length, this.preface.length)); if (!this.preface.subarray(0, seen.length).equals(seen)) { // not HTTP/2: an HTTP/1 request line is answered by the fetch handler, anything else refused const start = this.buffer.subarray(0, 8).toString('latin1'); if (this.http1 && this.buffer.length < 8 && /^[A-Z]+$/.test(start)) return; // a method still arriving if (this.http1 && /^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS) /.test(start)) { this.http1Mode = true; this.receiveHttp1(); return; } this.socket.end(); this.teardown(); return; } if (this.buffer.length < this.preface.length) return; this.prefaceSeen = true; this.buffer = this.buffer.subarray(this.preface.length); this.sendPreface(); } while (!this.dead && this.buffer.length >= 9) { const length = this.buffer.readUIntBE(0, 3); if (length > 16_384) { this.goaway(ERROR.FRAME_SIZE_ERROR, 'frame larger than SETTINGS_MAX_FRAME_SIZE'); return; } if (this.buffer.length < 9 + length) return; const type = this.buffer[3]!; const flags = this.buffer[4]!; const streamId = this.buffer.readUInt32BE(5) & 0x7fffffff; const payload = this.buffer.subarray(9, 9 + length); this.buffer = this.buffer.subarray(9 + length); try { this.frame(type, flags, streamId, payload); } catch (error) { this.goaway(error instanceof HpackError ? ERROR.COMPRESSION_ERROR : ERROR.PROTOCOL_ERROR, (error as Error).message); return; } } } private frame(type: number, flags: number, streamId: number, payload: Buffer): void { if (this.continuing && type !== FRAME.CONTINUATION) throw new Error('expected CONTINUATION'); // §6.10 switch (type) { case FRAME.SETTINGS: { if (streamId !== 0) throw new Error('SETTINGS on a stream'); if (flags & FLAG.ACK) return; if (payload.length % 6 !== 0) throw new Error('SETTINGS length'); for (let i = 0; i < payload.length; i += 6) { const id = payload.readUInt16BE(i); const value = payload.readUInt32BE(i + 2); if (id === 0x4) { if (value > 0x7fffffff) throw new Error('SETTINGS_INITIAL_WINDOW_SIZE too large'); const delta = value - this.peerInitialWindow; this.peerInitialWindow = value; for (const stream of this.streams.values()) stream.sendWindow += delta; } else if (id === 0x5) { if (value < 16_384 || value > 16_777_215) throw new Error('SETTINGS_MAX_FRAME_SIZE out of range'); this.peerMaxFrame = value; } // HEADER_TABLE_SIZE governs the peer's decoder of OUR blocks, which never index; the // rest (push, concurrency, header list size) bound what this server already never does } this.write(FRAME.SETTINGS, FLAG.ACK, 0); this.flush(); return; } case FRAME.PING: { if (payload.length !== 8) throw new Error('PING length'); if (!(flags & FLAG.ACK)) this.write(FRAME.PING, FLAG.ACK, 0, payload); return; } case FRAME.GOAWAY: { this.peerGone = true; this.endIfDone(); return; } case FRAME.WINDOW_UPDATE: { if (payload.length !== 4) throw new Error('WINDOW_UPDATE length'); const increment = payload.readUInt32BE(0) & 0x7fffffff; if (streamId === 0) { if (increment === 0) throw new Error('WINDOW_UPDATE of 0'); this.connectionSendWindow += increment; } else { const stream = this.streams.get(streamId); if (stream) stream.sendWindow += increment; } this.flush(); return; } case FRAME.RST_STREAM: { const stream = this.streams.get(streamId); if (stream) this.closeStream(stream); return; } case FRAME.PRIORITY: return; case FRAME.PUSH_PROMISE: throw new Error('a client never sends PUSH_PROMISE'); case FRAME.HEADERS: { if (streamId === 0 || streamId % 2 === 0) throw new Error('HEADERS on an invalid stream id'); let body = payload; let pad = 0; if (flags & FLAG.PADDED) { pad = body[0]!; body = body.subarray(1); } if (flags & FLAG.PRIORITY) body = body.subarray(5); if (pad > body.length) throw new Error('padding exceeds HEADERS payload'); body = body.subarray(0, body.length - pad); let stream = this.streams.get(streamId); if (!stream) { if (streamId <= this.lastStreamId) throw new Error('stream id reused'); // §5.1.1 this.lastStreamId = streamId; stream = { id: streamId, headerBlock: [], headers: {}, body: [], bodyBytes: 0, remoteClosed: false, localClosed: false, sendWindow: this.peerInitialWindow, outbound: [], abort: new AbortController(), }; this.streams.set(streamId, stream); } else { // trailers from the client: this server's methods carry none, but the block must still // be decoded to keep the HPACK table in step stream.headerBlock = []; } stream.headerBlock!.push(body); if (stream.dispatched) stream.late = true; // decoded for the HPACK table, then refused if (flags & FLAG.END_STREAM) stream.remoteClosed = true; if (flags & FLAG.END_HEADERS) this.headersDone(stream); else this.continuing = stream; return; } case FRAME.CONTINUATION: { const stream = this.continuing; if (!stream || stream.id !== streamId) throw new Error('CONTINUATION without HEADERS'); stream.headerBlock!.push(payload); if (stream.headerBlock!.reduce((n, part) => n + part.length, 0) > MAX_HEADER_BLOCK) throw new Error('header block too large'); if (flags & FLAG.END_HEADERS) { this.continuing = null; this.headersDone(stream); } return; } case FRAME.DATA: { let body = payload; if (flags & FLAG.PADDED) { const pad = body[0]!; if (pad >= body.length) throw new Error('padding exceeds DATA payload'); body = body.subarray(1, body.length - pad); } // replenish what the frame consumed (padding included), connection and stream this.windowUpdate(0, payload.length); const stream = this.streams.get(streamId); if (!stream || stream.remoteClosed) { if (streamId > this.lastStreamId) throw new Error('DATA on an idle stream'); return; // a stream this server already closed or reset } if (!(flags & FLAG.END_STREAM)) this.windowUpdate(streamId, payload.length); stream.body.push(Buffer.from(body)); stream.bodyBytes += body.length; if (stream.bodyBytes > MAX_REQUEST_BYTES) { this.resetStream(stream, ERROR.REFUSED_STREAM); return; } if (flags & FLAG.END_STREAM) { stream.remoteClosed = true; this.dispatch(stream); } return; } default: return; // §4.1: unknown frame types are ignored } } private headersDone(stream: StreamState): void { const block = Buffer.concat(stream.headerBlock!); stream.headerBlock = null; const decoded = this.decoder.decode(block); // the decoded list is bounded too: indexed references re-emit dynamic entries, so a small block // can decode to far more than it carries (SETTINGS_MAX_HEADER_LIST_SIZE's concern, RFC 9113 §6.5.2) if (decoded.reduce((n, [name, value]) => n + name.length + value.length + 32, 0) > MAX_HEADER_BLOCK) throw new HpackError('decoded header list too large'); // a header block on a stream this server already answers is a stream error (RFC 9113 §5.1, // half-closed (remote)): it is never dispatched a second time if (stream.late) { this.resetStream(stream, ERROR.STREAM_CLOSED); return; } const first = Object.keys(stream.headers).length === 0; if (first) for (const [name, value] of decoded) stream.headers[name] = stream.headers[name] === undefined ? value : `${stream.headers[name]}, ${value}`; if (this.streams.size > MAX_CONCURRENT_STREAMS) { this.resetStream(stream, ERROR.REFUSED_STREAM); return; } if (stream.remoteClosed) this.dispatch(stream); } private dispatch(stream: StreamState): void { if (stream.dispatched) return; stream.dispatched = true; const response: H2Response = { headers: (headers, end = false) => this.enqueue(stream, { kind: 'headers', block: hpackEncode(headers), end }), data: (bytes) => this.enqueue(stream, { kind: 'data', bytes, offset: 0 }), trailers: (headers) => this.enqueue(stream, { kind: 'headers', block: hpackEncode(headers), end: true }), get closed() { return stream.localClosed; }, }; try { this.handler({ headers: stream.headers, body: Buffer.concat(stream.body), signal: stream.abort.signal }, response); } catch { this.resetStream(stream, ERROR.INTERNAL_ERROR); } } private enqueue(stream: StreamState, item: Outbound): void { if (stream.localClosed || this.dead) return; stream.outbound.push(item); if (item.kind === 'headers' && item.end) stream.localClosed = true; this.flush(); } private flush(): void { for (const stream of [...this.streams.values()]) { while (stream.outbound.length > 0 && !this.dead) { const item = stream.outbound[0]!; if (item.kind === 'headers') { // one HEADERS frame, CONTINUATION for a block larger than the peer's frame size let offset = 0; const block = item.block; const firstLength = Math.min(block.length, this.peerMaxFrame); const last = firstLength === block.length; this.write(FRAME.HEADERS, (item.end ? FLAG.END_STREAM : 0) | (last ? FLAG.END_HEADERS : 0), stream.id, block.subarray(0, firstLength)); offset = firstLength; while (offset < block.length) { const length = Math.min(block.length - offset, this.peerMaxFrame); this.write(FRAME.CONTINUATION, offset + length === block.length ? FLAG.END_HEADERS : 0, stream.id, block.subarray(offset, offset + length)); offset += length; } stream.outbound.shift(); if (item.end) { this.streams.delete(stream.id); this.endIfDone(); break; } continue; } const remaining = item.bytes.length - item.offset; const allowance = Math.min(remaining, this.peerMaxFrame, this.connectionSendWindow, stream.sendWindow); if (remaining > 0 && allowance <= 0) break; // wait for WINDOW_UPDATE const chunk = item.bytes.subarray(item.offset, item.offset + allowance); this.write(FRAME.DATA, 0, stream.id, chunk); item.offset += allowance; this.connectionSendWindow -= allowance; stream.sendWindow -= allowance; if (item.offset >= item.bytes.length) stream.outbound.shift(); } } } } /** An HTTP/1 request arriving on the same port, answered by a fetch handler. */ export type Http1Handler = (request: Request) => Response | Promise; /** Speak HTTP/2 (h2c with prior knowledge) on an accepted socket; an HTTP/1 request line is handed to * `http1` when given. The listener that accepts sockets is the pack's server module's. */ export function acceptH2Connection(socket: Socket, handler: H2Handler, http1?: Http1Handler): { teardown(): void } { socket.setNoDelay(true); return new H2Connection(socket, handler, http1); }