/** * The protocol's base layer: each message is a block of headers, a * blank line, and a body of `Content-Length` bytes. The headers are * written the way HTTP writes them, one `Name: value` per line. */ import { StringReader } from 'zena:core'; /** The value of the `Content-Length` header in a header block, or -1. */ function contentLength(headers: String): i32 { for (let line in headers.split('\r\n')) { let reader = new StringReader(line); let name = reader.readUntil(':'); if (name != null && name.trim().asciiLowerCase() == 'content-length') { return parseI32(reader.readToEnd().trim()) ?? -1; } } return -1; } /** * Takes a byte stream apart into messages, each a block of headers, a * blank line, and `Content-Length` bytes of body. */ export final class MessageReader { /** Reads what the input has next; '' at the end of it. */ #read: () => Future; var #buffer = ''; new(read: () => Future) : #read = read; /** The next message's body, or null at the end of the input. */ async next(): Future { while (true) { let body = this.#take(); if (body != null) { return body; } let read = this.#read; let chunk = await read(); if (chunk == '') { return null; } this.#buffer = this.#buffer + chunk; } return null; } /** A whole message's body from the front of the buffer, if it has one. */ #take(): String | null { let reader = new StringReader(this.#buffer); let headers = reader.readUntil('\r\n\r\n'); if (headers == null) { return null; } let length = contentLength(headers); if (length < 0) { throw new Error('A message has no Content-Length header'); } // The length counts bytes, the way the protocol counts it. if (reader.remaining < length) { return null; } let bodyStart = reader.mark(); reader.skipBytes(length); let body = reader.sliceFrom(bodyStart); this.#buffer = reader.readToEnd(); return body; } } /** A message with its `Content-Length` header, ready to write. */ export function frame(body: String): String { return `Content-Length: ${body.length}\r\n\r\n${body}`; }