// A MongoDB client over any byte exchange: the other side of ./stream.ts, so a journey speaks the wire as an // application's driver does. It sends one command document as an OP_MSG and returns the document the server // answered; it reads what the protocol answers and decides nothing. // 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 { MongoOp, decodeMsg, encodeMsg, type MongoCodec, type MongoDocument } from './stream.ts'; /** Sends bytes and returns every byte the server answered to them. */ export type MongoExchange = (bytes: Uint8Array) => Promise; /** A client on one connection: `command` sends a document to `database` and resolves with the reply document, * whatever its `ok`. A reply that is not one whole OP_MSG answering this request is an error. */ export function mongoClient(exchange: MongoExchange, codec: MongoCodec): { command(database: string, command: MongoDocument): Promise } { let nextRequest = 0; return { async command(database, command) { const requestId = ++nextRequest; const answered = await exchange(encodeMsg(codec, { ...command, $db: database }, requestId, 0)); if (answered.length < 16) throw new Error('the server answered no message'); const view = new DataView(answered.buffer, answered.byteOffset, answered.byteLength); const length = view.getInt32(0, true), responseTo = view.getInt32(8, true), opcode = view.getInt32(12, true); if (length !== answered.length) throw new Error(`the server answered ${answered.length} bytes, and its message says ${length}`); if (opcode !== MongoOp.MSG) throw new Error(`the server answered opcode ${opcode}, not OP_MSG`); if (responseTo !== requestId) throw new Error(`the server answered request ${responseTo}, not ${requestId}`); return decodeMsg(codec, answered).document; }, }; }