// THE KERNEL'S MONGODB WIRE (`@volter/world-core/mongodb`): MongoDB's client/server message framing as a TwinStream, // so an unmodified MongoDB driver connects to a twin as to a server. The kernel holds the framing, which every // MongoDB-speaking vendor shares; the pack holds what a command means (it answers each command document from its own // engine over the tree) and the document codec (BSON, a library the pack installs). The messages served are what the // vendor's own driver sends, by citation (docs/contributing/architecture.md, "Other wires", the MongoDB wire): OP_MSG // with a body section and document-sequence sections, and the legacy OP_QUERY a driver's first hello may use, answered // with OP_REPLY. Any other message ends the connection. // source: archive:https://registry.npmjs.org/mongodb/-/mongodb-6.20.0.tgz#sha256=a12bd599cb4f39cdf222b32380ea3efd1f60c6d88615e0700632a303a9006b02!/package/src/cmap/commands.ts "moreToCome is an OP_MSG only concept" import type { TwinStream, TwinStreamSink } from '../twin-fetch.ts'; /** A command or reply document as the pack's codec gives it: the pack decides how BSON's types appear in it. */ export type MongoDocument = Record; /** BSON, as the pack supplies it (the `bson` library, installed by the pack's package.json). The kernel frames * documents and never reads inside one but for a command's `$db`. */ export type MongoCodec = { serialize(document: MongoDocument): Uint8Array; deserialize(bytes: Uint8Array): MongoDocument }; /** What a pack's stream reads of the `bson` library its generated fetch's `loadBson` resolves from the pack: the codec, * extended JSON, and the number kinds a reply names. The kernel declares the shape and imports nothing of it. */ export type BsonLibrary = { serialize(document: MongoDocument): Uint8Array; deserialize(bytes: Uint8Array, options?: { promoteValues?: boolean; promoteLongs?: boolean; bsonRegExp?: boolean }): MongoDocument; EJSON: { serialize(value: unknown, options?: { relaxed?: boolean }): MongoDocument; deserialize(value: unknown, options?: { relaxed?: boolean }): MongoDocument }; Double: new (value: number) => unknown; Int32: new (value: number) => unknown; Long: { fromNumber(value: number): unknown }; }; /** What the sender's message said beside its command: whether it will take more than one reply to it (OP_MSG's exhaustAllowed). */ export type MongoAsked = { exhaustAllowed: boolean }; const TIMED = Symbol('mongodb timed reply'); /** * An answer the wire sends LATER, or goes on sending: the vendor's protocol does this in real time (an awaitable * `hello` is held for the sender's maxAwaitTimeMS, and one sent with exhaustAllowed is answered again every such * interval, each reply marked moreToCome). The pack says WHAT and WHEN as data and holds no clock: the same request * gets the same answer every time. The wire does the holding and the repeating on the wall clock, and the delay is * never read back into state (architecture, "The MongoDB wire"). */ export type MongoTimedReply = { readonly [TIMED]: true; reply: MongoDocument; afterMs: number; everyMs?: number }; /** * `reply` after `afterMs` (0: at once); with `everyMs`, again each `everyMs` until the peer closes, where the sender * allowed more than one reply. The two differ in the vendor's own answers: a hello naming the server's current * topology is first answered after the wait, one naming another process at once, and both then repeat at the wait. */ export const timedReply = (reply: MongoDocument, afterMs: number, everyMs?: number): MongoTimedReply => ({ [TIMED]: true, reply, afterMs, ...(everyMs !== undefined ? { everyMs } : {}) }); const isTimed = (answer: MongoDocument | MongoTimedReply): answer is MongoTimedReply => (answer as MongoTimedReply)[TIMED] === true; export type MongoStreamOptions = { codec: MongoCodec; /** A connection opened: what the pack keeps for it (its sessions, an open transaction); never the tree. */ open(peer: string): Session; /** Answer ONE command document sent to `database`. A document sequence (an insert's `documents`, an update's * `updates`) arrives as that field holding the array. The answer is the reply document, `ok: 1` or the vendor's * error document; a command the pack does not serve is the pack's to answer as the vendor answers an unknown one. */ command(session: Session, database: string, command: MongoDocument, asked: MongoAsked): Promise; /** The connection went away: abort what it left open. */ close?(session: Session): void; /** Told why a connection is ended by this stream and not by its peer: the pack threw answering a command, or a * message was one this wire does not serve. Ending the connection is all the wire can say to the client, so the * reason is said here; unset, it is written to the process's error output. A stream that ends connections in * silence leaves its operator with a client that hangs and nothing to read. */ ended?(reason: string, peer: string): void; /** The largest message accepted; the vendor's server names 48,000,000 in its hello (`maxMessageSizeBytes`). */ maxMessageSizeBytes?: number; }; export const MongoOp = { REPLY: 1, QUERY: 2004, MSG: 2013 } as const; /** OP_MSG's flag bits. */ export const MongoMsgFlag = { CHECKSUM_PRESENT: 1 << 0, MORE_TO_COME: 1 << 1, EXHAUST_ALLOWED: 1 << 16 } as const; const HEADER = 16; const dec = new TextDecoder(); const enc = new TextEncoder(); const view = (bytes: Uint8Array): DataView => new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); function concat(parts: Uint8Array[]): Uint8Array { const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)); let at = 0; for (const p of parts) { out.set(p, at); at += p.length; } return out; } function header(length: number, requestId: number, responseTo: number, opcode: number): Uint8Array { const out = new Uint8Array(HEADER), v = view(out); v.setInt32(0, length, true); v.setInt32(4, requestId, true); v.setInt32(8, responseTo, true); v.setInt32(12, opcode, true); return out; } /** An OP_MSG message carrying one document as its body section. */ export function encodeMsg(codec: MongoCodec, document: MongoDocument, requestId: number, responseTo: number, flags = 0): Uint8Array { const body = codec.serialize(document), bits = new Uint8Array(5); view(bits).setUint32(0, flags, true); return concat([header(HEADER + 4 + 1 + body.length, requestId, responseTo, MongoOp.MSG), bits, body]); } /** The command of an OP_MSG message: its body section, with each document sequence as the field it names. */ export function decodeMsg(codec: MongoCodec, message: Uint8Array): { flags: number; document: MongoDocument } { const v = view(message), flags = v.getUint32(HEADER, true), end = message.length - (flags & MongoMsgFlag.CHECKSUM_PRESENT ? 4 : 0); let document: MongoDocument | undefined; const sequences: Record = {}; for (let at = HEADER + 4; at < end;) { const kind = message[at]!; at += 1; if (kind === 0) { const size = v.getInt32(at, true); if (size < 5 || at + size > end) throw new Error('OP_MSG body section runs past the message'); document = codec.deserialize(message.subarray(at, at + size)); at += size; } else if (kind === 1) { const size = v.getInt32(at, true), stop = at + size; if (size < 4 || stop > end) throw new Error('OP_MSG document sequence runs past the message'); const nameEnd = message.indexOf(0, at + 4); if (nameEnd < 0 || nameEnd >= stop) throw new Error('OP_MSG document sequence names no field'); const name = dec.decode(message.subarray(at + 4, nameEnd)), documents: MongoDocument[] = []; for (let cursor = nameEnd + 1; cursor < stop;) { const length = v.getInt32(cursor, true); if (length < 5 || cursor + length > stop) throw new Error('OP_MSG document sequence holds a document that runs past it'); documents.push(codec.deserialize(message.subarray(cursor, cursor + length))); cursor += length; } sequences[name] = documents; at = stop; } else throw new Error(`OP_MSG section kind ${kind} is unknown`); } if (!document) throw new Error('OP_MSG carries no body section'); return { flags, document: { ...document, ...sequences } }; } /** MongoDB's wire, served: each command document answered by the pack, in arrival order, on one connection. */ export function createMongoStream(options: MongoStreamOptions): TwinStream { const limit = options.maxMessageSizeBytes ?? 48_000_000; let nextResponse = 0; return (sink: TwinStreamSink, peer: string) => { const session = options.open(peer); let buffer: Uint8Array = new Uint8Array(0); let closed = false; let chain: Promise = Promise.resolve(); // A reply being held or repeated (a timed reply): its timer, and the messages that arrived meanwhile. A // connection serves one command at a time, so nothing else is answered until a held reply is sent, and nothing // at all while a repeating one runs (recording:hello-awaitable-exhaust-then-command.json: a ping sent into the // stream has no reply). The timer is not work: `settled` does not wait for it, it does not keep the process // alive (unref), and a close from either side clears it at once. let held: ReturnType | undefined; const parked: Uint8Array[] = []; const release = (): void => { if (held !== undefined) { clearTimeout(held); held = undefined; } parked.length = 0; }; const hold = (ms: number, then: () => void): void => { held = setTimeout(() => { held = undefined; if (!closed) then(); }, Math.max(0, ms)); (held as { unref?: () => void }).unref?.(); }; const end = (reason: string): void => { if (closed) return; closed = true; release(); (options.ended ?? ((why, from) => console.error(`mongodb wire: ended the connection from ${from}: ${why}`)))(reason, peer); options.close?.(session); sink.end(); }; const answer = async (message: Uint8Array): Promise => { const v = view(message), requestId = v.getInt32(4, true), opcode = v.getInt32(12, true); if (opcode === MongoOp.MSG) { const { flags, document } = decodeMsg(options.codec, message); const database = typeof document.$db === 'string' ? document.$db : 'admin'; const exhaustAllowed = (flags & MongoMsgFlag.EXHAUST_ALLOWED) !== 0; const answered = await options.command(session, database, document, { exhaustAllowed }); // the sender waits for no reply to a message it marked moreToCome if (flags & MongoMsgFlag.MORE_TO_COME) return; if (!isTimed(answered)) { sink.write(encodeMsg(options.codec, answered, ++nextResponse, requestId)); return; } if (answered.everyMs === undefined || !exhaustAllowed) { // held once: one reply after the wait, with no flag; then what arrived meanwhile is answered in order // source: recording:hello-awaitable-no-exhaust.json "received" hold(answered.afterMs, () => { sink.write(encodeMsg(options.codec, answered.reply, ++nextResponse, requestId)); for (const message of parked.splice(0)) take(message); }); return; } // repeated: each reply marked moreToCome; the first answers the request, each later one answers this // wire's own previous reply, until the peer closes // source: recording:hello-awaitable-exhaust.json "received" let answers = requestId; const again = (): void => { const id = ++nextResponse; sink.write(encodeMsg(options.codec, answered.reply, id, answers, MongoMsgFlag.MORE_TO_COME)); answers = id; hold(answered.everyMs!, again); }; // source: recording:hello-stale-process-exhaust.json "received" (the first at once, the rest at the wait) hold(answered.afterMs, again); return; } if (opcode === MongoOp.QUERY) { // the legacy form a driver's first hello may take: a query on `.$cmd` whose document is the command const nameEnd = message.indexOf(0, HEADER + 4); if (nameEnd < 0) throw new Error('OP_QUERY names no collection'); const namespace = dec.decode(message.subarray(HEADER + 4, nameEnd)); if (!namespace.endsWith('.$cmd')) throw new Error(`OP_QUERY on ${namespace}: only a command on .$cmd is served`); const command = options.codec.deserialize(message.subarray(nameEnd + 1 + 8)); // the legacy form has no flags of OP_MSG's: nothing is held or repeated for it const legacy = await options.command(session, namespace.slice(0, -'.$cmd'.length), command, { exhaustAllowed: false }); const reply = options.codec.serialize(isTimed(legacy) ? legacy.reply : legacy); // OP_REPLY: responseFlags (AwaitCapable), cursorID 0, startingFrom 0, numberReturned 1, then the document const fixed = new Uint8Array(20), f = view(fixed); f.setInt32(0, 8, true); f.setInt32(16, 1, true); sink.write(concat([header(HEADER + 20 + reply.length, ++nextResponse, requestId, MongoOp.REPLY), fixed, reply])); return; } throw new Error(`opcode ${opcode} is not served`); }; // One message, in arrival order: parked while a reply is held, answered otherwise. const take = (message: Uint8Array): void => { chain = chain.then(() => (closed ? undefined : held !== undefined ? void parked.push(message) : answer(message))).catch((error) => end(error instanceof Error ? error.message : String(error))); }; return { data(chunk: Uint8Array): void { if (closed) return; buffer = buffer.length ? concat([buffer, chunk]) : chunk; while (buffer.length >= 4) { const length = view(buffer).getInt32(0, true); // where the citation stops: what the vendor's server does with a malformed or oversized message is not // read; this ends the connection, which no driver's well-formed message reaches if (length < HEADER || length > limit) { end(`a message of ${length} bytes (accepted: ${HEADER} to ${limit})`); return; } if (buffer.length < length) break; const message = buffer.subarray(0, length); buffer = buffer.subarray(length); take(message.slice()); } }, settled: () => chain, close: () => { if (!closed) { closed = true; release(); options.close?.(session); } }, }; }; } /** The bytes of a C string, for a client's OP_QUERY. */ export const cstring = (text: string): Uint8Array => concat([enc.encode(text), new Uint8Array(1)]);