diff --git a/.changeset/smart-sheep-repair.md b/.changeset/smart-sheep-repair.md new file mode 100644 index 0000000..602fcca --- /dev/null +++ b/.changeset/smart-sheep-repair.md @@ -0,0 +1,5 @@ +--- +"@cutils/mongo": minor +--- + +elf consumer entry: ./elf export + createConnection options form + JSDoc contract for npm-static builds diff --git a/packages/mongo/AGENTS.md b/packages/mongo/AGENTS.md index 7c99a0d..e89edf1 100644 --- a/packages/mongo/AGENTS.md +++ b/packages/mongo/AGENTS.md @@ -87,3 +87,19 @@ not reselect after a primary step-down. Connection pool, async iterators, exhaust cursors, change streams, decimal128/timestamp/DbRef encode, `for await`, FFI. + +## Consumer compile contract (`--npm-static`) + +- `./elf` (→ `./dist/esm/index.js`) is the consumer entry — conditional + `exports` objects resolve to nothing under `--npm-static`, so it stays + a plain string, like postgres/cache/cli. +- The `.d.ts` is hidden in that mode; signatures whose params would + infer `unknown` need `@param {T}` JSDoc that survives tsc (see + `connectTcp` in `src/internal/socket.ts` — an `unknown` `port` hit the + unlowered `createConnection` overload, SC2020). +- Use `createConnection({ host, port })` (options-object form), never + positional `connect(port, host)` — under JS inference the positional + form binds `host` into a listener slot ("expected function, got + string" at runtime). +- `test/consumer-elf.test.sh` packs → installs → `--npm-static` compiles + `test/consumer-elf-app.ts` → runs the ELF vs `test/mock-server.mjs`. diff --git a/packages/mongo/package.json b/packages/mongo/package.json index 71f1c60..6371c67 100644 --- a/packages/mongo/package.json +++ b/packages/mongo/package.json @@ -20,12 +20,13 @@ "types": "./dist/esm/index.d.ts", "import": "./dist/esm/index.js" }, - "./package.json": "./package.json" + "./package.json": "./package.json", + "./elf": "./dist/esm/index.js" }, "scripts": { "build": "tsc -p tsconfig.json", "typecheck": "tsc -p tsconfig.json --noEmit", - "test": "npm run build && node --test test/*.test.js test/*.test.mjs && bash test/elf.test.sh" + "test": "npm run build && node --test test/*.test.js test/*.test.mjs && bash test/elf.test.sh && bash test/consumer-elf.test.sh" }, "devDependencies": { "@chttp/val": "^0.2.1", diff --git a/packages/mongo/src/internal/socket.ts b/packages/mongo/src/internal/socket.ts index a57dfcd..1a8f2ac 100644 --- a/packages/mongo/src/internal/socket.ts +++ b/packages/mongo/src/internal/socket.ts @@ -3,7 +3,7 @@ // commands sequentially on the owned socket. A response read gathers the // 4-byte length prefix then exactly messageLength bytes. -import { connect as netConnect, Socket } from "node:net"; +import { createConnection, Socket } from "node:net"; import { connect as tlsConnectRaw } from "node:tls"; import { mongoError } from "../errors.ts"; @@ -144,12 +144,17 @@ export class SocketChannel { } } -/** Connect a plain TCP channel. */ +/** + * Connect a plain TCP channel. + * @param {string} host + * @param {number} port + * @param {number} timeoutMs + */ export function connectTcp(host: string, port: number, timeoutMs: number): Promise { return new Promise((resolve, reject) => { const ch = new SocketChannel(); let settled = false; - const sock = netConnect(port, host); + const sock = createConnection({ host: host, port: port }); sock.setTimeout(timeoutMs); sock.once("connect", () => { settled = true; diff --git a/packages/mongo/test/consumer-elf-app.ts b/packages/mongo/test/consumer-elf-app.ts new file mode 100644 index 0000000..5788d02 --- /dev/null +++ b/packages/mongo/test/consumer-elf-app.ts @@ -0,0 +1,19 @@ +// Consumer-side ELF program for @cutils/mongo: exercises the published +// "./elf" entry exactly as a consumer's `scriptc build --npm-static` +// would — connect to the canned wire server, run a find, print a row. +import { MongoClient } from "@cutils/mongo/elf"; + +const port = Number(process.argv[2] || "0"); +const client = await MongoClient.connect({ + uri: "mongodb://127.0.0.1:" + port, + dbName: "smoke", + appName: "consumer-elf", + connectTimeoutMs: 5000, +}); +const coll = client.database().collection("todos"); +const doc = await coll.findOne({}); +if (doc === null) { + throw new Error("findOne returned null"); +} +console.log("consumer OK", doc.title); +await client.close(); diff --git a/packages/mongo/test/consumer-elf.test.sh b/packages/mongo/test/consumer-elf.test.sh new file mode 100755 index 0000000..133a1a3 --- /dev/null +++ b/packages/mongo/test/consumer-elf.test.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +# Consumer-side ELF smoke for @cutils/mongo: packs the package, installs +# the tarball into a scratch app under build/, and compiles a small +# consumer program against the published "./elf" entry via --npm-static — +# the same path a real consumer's `scriptc build` takes from node_modules. +# Runs the ELF against test/mock-server.mjs (canned OP_MSG wire server). +set -euo pipefail + +cd "$(dirname "$0")/.." +PKG="$PWD" + +fail() { + echo "consumer-elf.test.sh FAIL: $*" >&2 + exit 1 +} + +BIN="scriptc" +if [ -x ../../node_modules/.bin/scriptc ]; then + BIN="$PKG/../../node_modules/.bin/scriptc" +fi + +WORK="$PKG/build/consumer-smoke" +rm -rf "$WORK" +mkdir -p "$WORK" + +corepack pnpm pack --pack-destination "$WORK" >/dev/null || fail "pnpm pack" +TARBALL=$(find "$WORK" -maxdepth 1 -name '*.tgz' | head -1) +[ -n "$TARBALL" ] || fail "pnpm pack produced no tarball" + +cd "$WORK" +cat > package.json <<'JSON' +{ "name": "consumer-smoke", "private": true, "type": "module" } +JSON + +corepack pnpm add --ignore-workspace "$TARBALL" >/dev/null || fail "pnpm add tarball" +[ -f "$WORK/node_modules/@cutils/mongo/dist/esm/index.js" ] || fail "dist/esm/index.js missing" + +cp "$PKG/test/consumer-elf-app.ts" app.ts + +"$BIN" build app.ts --npm-static @cutils/mongo -o app-elf \ + || fail "scriptc build" + +node "$PKG/test/mock-server.mjs" 0 > "$WORK/srv.out" & +SRV_PID=$! +trap '[ -n "${SRV_PID:-}" ] && kill "$SRV_PID" 2>/dev/null || true' EXIT +for _ in $(seq 1 50); do + [ -s "$WORK/srv.out" ] && break + sleep 0.1 +done +PORT="$(awk '/READY/{print $2}' "$WORK/srv.out")" +[ -n "$PORT" ] || fail "mock server did not start" + +out="$(timeout 30 ./app-elf "$PORT")" || fail "app-elf exited nonzero" +printf '%s\n' "$out" | grep -q "consumer OK" || fail "expected 'consumer OK', got: $out" +echo "consumer-elf.test.sh OK" diff --git a/packages/mongo/test/mock-server.mjs b/packages/mongo/test/mock-server.mjs new file mode 100644 index 0000000..9a36634 --- /dev/null +++ b/packages/mongo/test/mock-server.mjs @@ -0,0 +1,129 @@ +// mock-server.mjs — canned OP_MSG wire server (plain Node, not subset). +// Powers wire smoke tests + the consumer ELF smoke. Canned mongod: replies +// to `hello` with version/maxWireVersion, to `find`/`aggregate` with a +// single-document firstBatch and cursor id 0 (so no getMore), to +// `killCursors` and `endSessions` with ok:1. Auth is scriptable the same +// way as postgres's mock (createMockServer) but the ELF smoke runs +// unauthenticated. +// +// Usage: node test/mock-server.mjs (port 0 = ephemeral) +// Prints "READY " once listening; logs each $db-qualified command. + +import { createServer } from "node:net"; +import { decodeDoc, encodeDoc } from "../dist/esm/internal/bson.js"; +import { decodeMsg, encodeMsg, DocSeq } from "../dist/esm/internal/opmsg.js"; +import { vI32, vI64Raw, vStr, vArr, vObj, vBool } from "../dist/esm/bson/value.js"; + +/** Reply body for one command, or null to fall through to ok:1. */ +function replyFor(cmd) { + if (cmd.hello !== undefined || cmd.ismaster !== undefined) { + return { + ok: vI32(1), + helloOk: vBool(true), + isWritablePrimary: vBool(true), + primary: vStr("mock:27017"), + maxBsonObjectSize: vI32(16777216), + maxMessageSizeBytes: vI32(48000000), + maxWriteBatchSize: vI32(100000), + version: vStr("8.0.0"), + maxWireVersion: vI32(25), + minWireVersion: vI32(0), + }; + } + if (cmd.find !== undefined || cmd.aggregate !== undefined) { + const doc = { + _id: vStr("mock-1"), + title: vStr("from-mock"), + done: vBool(false), + n: vI32(5), + }; + return { + ok: vI32(1), + cursor: vObj({ + id: vI64Raw(BigInt(0)), + ns: vStr(cmd.$db + "." + (cmd.find ?? cmd.aggregate)), + firstBatch: vArr([vObj(doc)]), + }), + }; + } + return null; +} + +let nextId = 100; + +export function createMockServer(onCommand) { + const server = createServer((sock) => { + let buf = Buffer.alloc(0); + sock.on("data", (chunk) => { + buf = Buffer.concat([buf, chunk]); + while (buf.length >= 16) { + const len = buf.readInt32LE(0); + if (buf.length < len) break; + const frame = buf.subarray(0, len); + buf = buf.subarray(len); + const msg = decodeMsg(new Uint8Array(frame)); + const cmd = {}; + for (const k of Object.keys(msg.body)) cmd[k] = plain(msg.body[k]); + for (const s of msg.seqs) cmd[s.name] = s.docs.map((d) => plain(vObj(d))); + let body = replyFor(cmd); + if (body === null) { + if (onCommand) onCommand(cmd); + body = { ok: vI32(1) }; + } + // encodeMsg emits the complete frame (header included); patch its + // requestId/responseTo in place rather than wrapping again. + const resp = encodeMsg(0, body, []); + nextId = nextId + 1; + resp[4] = nextId & 0xff; + resp[5] = (nextId >> 8) & 0xff; + resp[6] = (nextId >> 16) & 0xff; + resp[7] = (nextId >> 24) & 0xff; + resp[8] = msg.requestId & 0xff; + resp[9] = (msg.requestId >> 8) & 0xff; + resp[10] = (msg.requestId >> 16) & 0xff; + resp[11] = (msg.requestId >> 24) & 0xff; + sock.write(Buffer.from(resp)); + } + }); + sock.on("error", () => {}); + }); + return server; +} + +// BsonValue -> plain JS for the canned matcher. Only what the mock matches +// on; unknown arms come back as null. +function plain(v) { + if (v === null || v === undefined) return null; + switch (v.kind) { + case "object": + return docPlain(v.v); + case "array": + return v.v.map(plain); + case "string": + return v.v; + case "int32": + return v.v; + case "int64": + return v.raw ?? BigInt(v.v); + case "boolean": + return v.v; + case "double": + return v.v; + default: + return null; + } +} + +function docPlain(doc) { + const out = {}; + for (const k of Object.keys(doc)) out[k] = plain(doc[k]); + return out; +} + +const port = Number(process.argv[2] ?? "0"); +if (process.argv[1] && process.argv[1].endsWith("mock-server.mjs")) { + const srv = createMockServer(); + srv.listen(port, "127.0.0.1", () => { + console.log("READY", srv.address().port); + }); +}