diff --git a/package-lock.json b/package-lock.json index 5c0a5591..d07fbc78 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1202,7 +1202,6 @@ "version": "0.3.0", "license": "MIT", "dependencies": { - "@msgpack/msgpack": "^3.1.3", "cultnet-ts": "^0.2.0" }, "devDependencies": { @@ -1218,7 +1217,6 @@ "license": "MIT", "dependencies": { "@gamecult/cultcache-ts": "^0.14.0", - "@msgpack/msgpack": "^3.1.2", "cultnet-ts": "^0.2.0", "koffi": "3.3.0" }, diff --git a/packages/cultcache-ts/src/document.ts b/packages/cultcache-ts/src/document.ts index a09fec81..e6cd080e 100644 --- a/packages/cultcache-ts/src/document.ts +++ b/packages/cultcache-ts/src/document.ts @@ -82,10 +82,18 @@ export function resolveDocumentFormatter(definition: AnyCultCacheDocumentDefinit if (definition.codec && definition.formatter) { throw new Error(`CultCache document type "${definition.type}" declares both a codec and a formatter.`); } - return definition.formatter ?? (definition.codec ? codecFormatter(definition.codec) : { - encode: (value: unknown) => encode(value), - decode: (payload: Uint8Array) => decode(payload), - }); + return definition.formatter ?? (definition.codec ? codecFormatter(definition.codec) : plainDocumentFormatter); +} + +const plainDocumentFormatter: CultCacheDocumentFormatter = { + encode: (value: unknown) => encode(value), + decode: (payload: Uint8Array) => decode(payload), +}; + +// The one reader of a document payload outside the cache: through the definition's formatter, or as a plain msgpack +// value when the caller holds no definition for the schema. Every package above the cache reads a payload through here. +export function decodeDocumentPayload(definition: AnyCultCacheDocumentDefinition | undefined, payload: Uint8Array): unknown { + return (definition ? resolveDocumentFormatter(definition) : plainDocumentFormatter).decode(payload); } // The schema members of a document: the ones it declares, else those its codec derives, else none. diff --git a/packages/cultcache-ts/src/index.ts b/packages/cultcache-ts/src/index.ts index 75a94f58..8fae6f4c 100644 --- a/packages/cultcache-ts/src/index.ts +++ b/packages/cultcache-ts/src/index.ts @@ -2,7 +2,7 @@ export * as codecs from "./codec"; export type { Codec, SlotsCodec } from "./codec"; export { CultCache, CultCacheBuilder } from "./cult-cache"; export { inspectCultCacheBytes } from "./cult-cache-inspector"; -export { defineDocumentRegistry, defineDocumentType, resolveDocumentFormatter } from "./document"; +export { decodeDocumentPayload, defineDocumentRegistry, defineDocumentType, resolveDocumentFormatter } from "./document"; export { SingleFileMessagePackBackingStore } from "./single-file-messagepack-backing-store"; export type { AnyCultCacheDocumentDefinition, diff --git a/packages/cultcache-ts/test/decode-document-payload.test.ts b/packages/cultcache-ts/test/decode-document-payload.test.ts new file mode 100644 index 00000000..92fd2146 --- /dev/null +++ b/packages/cultcache-ts/test/decode-document-payload.test.ts @@ -0,0 +1,33 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { encode } from "@msgpack/msgpack"; +import { z } from "zod"; + +import { codecs, decodeDocumentPayload, defineDocumentType } from "../src"; + +const note = z.object({ id: z.string(), count: z.number() }); +const plain = defineDocumentType({ type: "t.plain", schemaId: "t.plain.v0", schema: note, name: "id" }); +const codec = defineDocumentType({ + type: "t.codec", + schemaId: "t.codec.v0", + schema: note, + name: "id", + codec: codecs.slots<{ id: string; count: number }>({ 0: ["id", codecs.string], 1: ["count", codecs.int32] }, "T.Note"), +}); +const formatted = defineDocumentType({ + type: "t.formatted", + schemaId: "t.formatted.v0", + schema: note, + name: "id", + formatter: { encode: (value) => encode([(value as { id: string }).id]), decode: () => ({ id: "from-formatter", count: 0 }) }, +}); + +test("a payload is read by its definition's formatter, a codec's, or as a plain value without a definition", () => { + assert.deepEqual(decodeDocumentPayload(undefined, encode({ id: "a", count: 1 })), { id: "a", count: 1 }); + assert.deepEqual(decodeDocumentPayload(plain, encode({ id: "a", count: 1 })), { id: "a", count: 1 }); + assert.deepEqual(decodeDocumentPayload(codec, encode(["a", 1])), { id: "a", count: 1 }); + assert.deepEqual(decodeDocumentPayload(formatted, new Uint8Array([0xc0])), { id: "from-formatter", count: 0 }); + // Without the definition the codec payload is its positional array, which is why a caller that holds one passes it. + assert.deepEqual(decodeDocumentPayload(undefined, encode(["a", 1])), ["a", 1]); +}); diff --git a/packages/cultmesh-browser/package.json b/packages/cultmesh-browser/package.json index 186ab630..e35f143f 100644 --- a/packages/cultmesh-browser/package.json +++ b/packages/cultmesh-browser/package.json @@ -40,7 +40,6 @@ "node": ">=20" }, "dependencies": { - "@msgpack/msgpack": "^3.1.3", "cultnet-ts": "^0.2.0" }, "devDependencies": { diff --git a/packages/cultmesh-browser/src/index.ts b/packages/cultmesh-browser/src/index.ts index ea37c17e..2aaca7bf 100644 --- a/packages/cultmesh-browser/src/index.ts +++ b/packages/cultmesh-browser/src/index.ts @@ -1,4 +1,4 @@ -import { decode, encode } from "@msgpack/msgpack"; +import { decodeWireValue, encodeWireValue } from "cultnet-ts/wire"; import { encodeCultNetMessageForWire, parseCultNetMessage, @@ -387,7 +387,7 @@ export class CultMeshBrowserClient implements AsyncDisposable { operation: options.operation, payloadSchema: options.payloadSchema, payloadEncoding: "messagepack-base64", - payload: bytesToBase64(encode(options.payload)), + payload: bytesToBase64(encodeWireValue(options.payload)), sourceRuntimeId: this.runtimeId, targetRuntimeId: this.identity.authorityRuntimeId, }; @@ -733,7 +733,7 @@ export class CultMeshBrowserClient implements AsyncDisposable { private send(message: CultNetMessage): void { const socket = this.#socket; if (!socket || socket.readyState !== 1) throw new Error("CultMesh browser route is not connected."); - const payload = encode(encodeCultNetMessageForWire(message)); + const payload = encodeWireValue(encodeCultNetMessageForWire(message)); if (payload.byteLength > this.#options.maxFrameBytes) { throw new Error(`CultMesh message exceeds the ${this.#options.maxFrameBytes}-byte limit.`); } @@ -760,11 +760,19 @@ export class CultMeshBrowserClient implements AsyncDisposable { } } -export function decodeCultNetPayload(record: CultNetRawDocumentRecord): T { +/** + * Reads a document record's payload. A document defined with a codec or a formatter is not a plain msgpack map: pass the + * formatter that reads it (a cultcache-ts `resolveDocumentFormatter(definition)`); without one the payload is read as a + * plain value, and a codec document comes back as its positional array. + */ +export function decodeCultNetPayload( + record: CultNetRawDocumentRecord, + formatter?: { decode(payload: Uint8Array): unknown }, +): T { if (record.payloadEncoding !== "messagepack") { throw new Error(`Unsupported CultNet document payload '${record.payloadEncoding}'.`); } - return decode(record.payload) as T; + return (formatter ? formatter.decode(record.payload) : decodeWireValue(record.payload)) as T; } function recordMatchesSchema(record: CultNetRawDocumentRecord, requestedSchema: string): boolean { @@ -777,7 +785,7 @@ export function decodeCultNetOperationPayload(response: CultNetOperationRespo if (response.payloadEncoding !== "messagepack-base64") { throw new Error(`Unsupported CultNet operation payload '${response.payloadEncoding ?? "unspecified"}'.`); } - return decode(base64ToBytes(response.payload)) as T; + return decodeWireValue(base64ToBytes(response.payload)) as T; } function requireWebSocketEndpoint(value: string, field: string): URL { @@ -794,7 +802,7 @@ function requireWebSocketEndpoint(value: string, field: string): URL { } function sendSocketMessage(socket: CultMeshBrowserSocket, message: CultNetMessage, maxFrameBytes: number): void { - const payload = encode(encodeCultNetMessageForWire(message)); + const payload = encodeWireValue(encodeCultNetMessageForWire(message)); if (payload.byteLength > maxFrameBytes) { throw new Error(`CultNet message exceeds the ${maxFrameBytes}-byte limit.`); } @@ -815,7 +823,7 @@ async function decodeSocketMessage(event: MessageEvent, maxFrameBytes: number): if (payload.byteLength > maxFrameBytes) { throw new Error(`CultNet frame exceeds the ${maxFrameBytes}-byte limit.`); } - return parseCultNetMessage(decode(payload)); + return parseCultNetMessage(decodeWireValue(payload)); } async function selectOdinRoute( diff --git a/packages/cultmesh-browser/test/cultmesh-browser.test.ts b/packages/cultmesh-browser/test/cultmesh-browser.test.ts index 59f9fac1..61b560c2 100644 --- a/packages/cultmesh-browser/test/cultmesh-browser.test.ts +++ b/packages/cultmesh-browser/test/cultmesh-browser.test.ts @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { decode, encode } from "@msgpack/msgpack"; +import { decodeWireValue, encodeWireValue } from "cultnet-ts/wire"; import { encodeCultNetMessageForWire, parseCultNetMessage, @@ -372,7 +372,7 @@ test("browser client replays one idempotent operation after route loss without d const open = () => { let socket: FakeSocket; socket = new FakeSocket(wire => { - const message = parseCultNetMessage(decode(wire)); + const message = parseCultNetMessage(decodeWireValue(wire)); if (message.schemaVersion === "cultmesh.session_open.v2") { socket.deliver({ schemaVersion: "cultmesh.session_accepted.v2", @@ -400,7 +400,7 @@ test("browser client replays one idempotent operation after route loss without d status: "accepted", payloadSchema: "sample.increment_receipt.v1", payloadEncoding: "messagepack-base64", - payload: Buffer.from(encode({ count: effectCount })).toString("base64"), + payload: Buffer.from(encodeWireValue({ count: effectCount })).toString("base64"), sourceRuntimeId: "sample.counter-daemon", }; results.set(message.messageId, response!); @@ -600,7 +600,7 @@ class FakeProvider { } private receive(socket: FakeSocket, wire: Uint8Array): void { - const message = parseCultNetMessage(decode(wire)); + const message = parseCultNetMessage(decodeWireValue(wire)); switch (message.schemaVersion) { case "cultmesh.session_open.v2": this.acceptSession(socket, message); @@ -654,7 +654,7 @@ class FakeProvider { status: "invalid", payloadSchema: "gamecult.cultnet.operation_failure.v1", payloadEncoding: "messagepack-base64", - payload: bytesToBase64(encode({ + payload: bytesToBase64(encodeWireValue({ code: "request-schema-mismatch", message: "Expected payload schema 'sample.increment.v1'.", })), @@ -663,7 +663,7 @@ class FakeProvider { }); return; } - const payload = decode(base64ToBytes(message.payload)) as { amount: number }; + const payload = decodeWireValue(base64ToBytes(message.payload)) as { amount: number }; this.#count += payload.amount; for (const [peer, subscriptions] of this.#subscriptions) { for (const subscriptionId of subscriptions.keys()) { @@ -684,7 +684,7 @@ class FakeProvider { status: "accepted", payloadSchema: "sample.increment_receipt.v1", payloadEncoding: "messagepack-base64", - payload: bytesToBase64(encode({ count: this.#count })), + payload: bytesToBase64(encodeWireValue({ count: this.#count })), sourceRuntimeId: this.#responseRuntimeId, }); } @@ -698,7 +698,7 @@ class FakeProvider { recordKey: "counter:main", storedAt: "2026-08-17T00:00:00Z", payloadEncoding: "messagepack", - payload: encode({ count: this.#count }), + payload: encodeWireValue({ count: this.#count }), sourceRuntimeId: this.#runtimeId, }; } @@ -716,7 +716,7 @@ class FakeOdin { open(): FakeSocket { const socket = new FakeSocket(wire => { - const message = parseCultNetMessage(decode(wire)); + const message = parseCultNetMessage(decodeWireValue(wire)); if (message.schemaVersion !== "cultmesh.verse_catalog_request.v0") return; socket.deliver({ schemaVersion: "cultmesh.verse_catalog_response.v0", @@ -785,7 +785,7 @@ function routeForCatalog(route: CultMeshBrowserRoute): NonNullable< function handshakeOnlySocket(route: CultMeshBrowserRoute): FakeSocket { let socket: FakeSocket; socket = new FakeSocket(wire => { - const message = parseCultNetMessage(decode(wire)); + const message = parseCultNetMessage(decodeWireValue(wire)); if (message.schemaVersion !== "cultmesh.session_open.v2") return; socket.deliver({ schemaVersion: "cultmesh.session_accepted.v2", @@ -850,7 +850,7 @@ class FakeSocket implements CultMeshBrowserSocket { } deliver(message: CultNetMessage): void { - const wire = encode(encodeCultNetMessageForWire(message)); + const wire = encodeWireValue(encodeCultNetMessageForWire(message)); queueMicrotask(() => this.onmessage?.({ data: wire.slice().buffer } as MessageEvent)); } } @@ -899,7 +899,7 @@ async function createSignedRoute(endpoint: string): Promise<{ function signedHandshakeSocket(route: CultMeshBrowserRoute, providerPrivate: CryptoKey): FakeSocket { let socket: FakeSocket; socket = new FakeSocket(wire => { - const message = parseCultNetMessage(decode(wire)); + const message = parseCultNetMessage(decodeWireValue(wire)); if (message.schemaVersion !== "cultmesh.session_open.v2") return; void crypto.subtle.sign( { name: "ECDSA", hash: "SHA-256" }, @@ -975,3 +975,10 @@ function base64ToBytes(value: string): Uint8Array { const binary = atob(value); return Uint8Array.from(binary, character => character.charCodeAt(0)); } + +test("decodeCultNetPayload reads a payload through the formatter it is given, and plain without one", () => { + const record = { schemaId: "t.codec.v0", recordKey: "k", payloadEncoding: "messagepack", payload: encodeWireValue([7]) } as unknown as CultNetRawDocumentRecord; + const formatter = { decode: (payload: Uint8Array) => ({ count: (decodeWireValue(payload) as number[])[0] }) }; + assert.deepEqual(decodeCultNetPayload<{ count: number }>(record, formatter), { count: 7 }); + assert.deepEqual(decodeCultNetPayload(record), [7]); +}); diff --git a/packages/cultmesh-browser/test/payload-decode-owner.test.ts b/packages/cultmesh-browser/test/payload-decode-owner.test.ts new file mode 100644 index 00000000..5ed8f915 --- /dev/null +++ b/packages/cultmesh-browser/test/payload-decode-owner.test.ts @@ -0,0 +1,29 @@ +import assert from "node:assert/strict"; +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import test from "node:test"; + +// A document payload is decoded by cultcache-ts alone (decodeDocumentPayload); every other value on a wire goes through +// cultnet-ts's decodeWireValue / encodeWireValue. So no file of this package imports msgpack, and the manifest does not +// list it, which keeps a new direct decode from arriving unnoticed. +// Limits: a text scan. It reads the package's src files for the module specifier and the manifest for the dependency +// name. It does not follow a re-export from another package, a specifier assembled at run time, or a hand-written +// decoder; the dependency absence is what makes the specifier unresolvable here when the workspace does not hoist it. +const root = fileURLToPath(new URL("../../", import.meta.url)); + +function sourceFiles(dir: string): string[] { + return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => + entry.isDirectory() ? sourceFiles(join(dir, entry.name)) : entry.name.endsWith(".ts") ? [join(dir, entry.name)] : []); +} + +test("no source file imports msgpack and the manifest does not list it", () => { + const manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8")) as Record | undefined>; + for (const section of ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]) { + assert.equal(manifest[section]?.["@msgpack/msgpack"], undefined, section); + } + const files = sourceFiles(join(root, "src")); + assert.ok(files.length > 5, "fixture: the scan reads the package's sources"); + const offenders = files.filter((file) => /@msgpack\/msgpack/.test(readFileSync(file, "utf8"))); + assert.deepEqual(offenders, []); +}); diff --git a/packages/cultmesh-ts/package.json b/packages/cultmesh-ts/package.json index 4d59133a..b53555be 100644 --- a/packages/cultmesh-ts/package.json +++ b/packages/cultmesh-ts/package.json @@ -43,7 +43,6 @@ "node": ">=20" }, "dependencies": { - "@msgpack/msgpack": "^3.1.2", "@gamecult/cultcache-ts": "^0.14.0", "cultnet-ts": "^0.2.0", "koffi": "3.3.0" diff --git a/packages/cultmesh-ts/src/index.ts b/packages/cultmesh-ts/src/index.ts index 9c77e586..f738cdcd 100644 --- a/packages/cultmesh-ts/src/index.ts +++ b/packages/cultmesh-ts/src/index.ts @@ -1,5 +1,5 @@ import { createSocket, type Socket } from "node:dgram"; -import { decode, encode } from "@msgpack/msgpack"; +import { decodeWireValue, encodeWireValue } from "cultnet-ts/wire"; import { CultCache, @@ -8,7 +8,7 @@ import { type CacheBackingStore, type CultCacheEnvelope, type CultCacheDocumentValue, - resolveDocumentFormatter, + decodeDocumentPayload, } from "@gamecult/cultcache-ts"; import { CultNetDocumentRegistry, @@ -5957,7 +5957,7 @@ export class CultMesh { payload: Uint8Array, ): Promise { if (record.closed) return; - const message = parseCultNetMessage(decode(payload), wireContract); + const message = parseCultNetMessage(decodeWireValue(payload), wireContract); switch (message.schemaVersion) { case "cultnet.snapshot_request.v0": { if (!options.getCache) { @@ -6000,7 +6000,7 @@ export class CultMesh { sendSchemaMessage(record, { schemaVersion: "cultnet.error.v0", error: unservable.message }); return; } - const receipt = await options.onDocumentPutRaw(normalizeRudpDocumentPut(message, record.remote)); + const receipt = await options.onDocumentPutRaw(normalizeRudpDocumentPut(message, record.remote, options.documents)); if (receipt) { try { sendSchemaMessage(record, receiptMessage(receipt, message.messageId)); @@ -6138,7 +6138,7 @@ export class CultMesh { /** The one reply encoder, shared by sends and by put admission. */ function encodeSchemaMessage(message: CultNetMessage): Uint8Array { - return encode(encodeCultNetMessageForWire(message, wireContract)); + return encodeWireValue(encodeCultNetMessageForWire(message, wireContract)); } /** Builds the receipt `onDocumentPutRaw` returned, under the put's message id by default. */ @@ -6663,6 +6663,7 @@ function requireNonEmpty(value: string, name: string): void { function normalizeRudpDocumentPut( message: CultNetMessage, remote: { address: string; family: string; port: number }, + documents: CultNetDocumentRegistry, ): CultMeshRudpDocumentPut { if (message.schemaVersion !== "cultnet.document_put_raw.v0") { throw new Error(`Expected cultnet.document_put_raw.v0, received ${message.schemaVersion}.`); @@ -6678,7 +6679,7 @@ function normalizeRudpDocumentPut( schemaId: document.schemaId, recordKey: document.recordKey, storedAt: document.storedAt ?? new Date().toISOString(), - payload: decode(document.payload), + payload: decodeDocumentPayload(documents.getBySchemaId(document.schemaId)?.definition, document.payload), sourceRuntimeId: document.sourceRuntimeId ?? null, sourceAgentId: document.sourceAgentId ?? null, sourceRole: document.sourceRole ?? null, @@ -6777,11 +6778,9 @@ async function resolveCultNetPeer( } // A document payload is read the way its definition's cache reads it (a codec or formatter document is not a plain -// msgpack map); a payload with no definition is plain msgpack. +// msgpack map); a payload with no definition is plain msgpack. Both are cultcache-ts's decision. function decodeCultMeshPayload(schemaOrDefinition: string | AnyCultCacheDocumentDefinition, payload: Uint8Array): unknown { - return typeof schemaOrDefinition === "string" - ? decode(payload) - : resolveDocumentFormatter(schemaOrDefinition).decode(payload); + return decodeDocumentPayload(typeof schemaOrDefinition === "string" ? undefined : schemaOrDefinition, payload); } function decodeCultNetRawDocumentPayload( diff --git a/packages/cultmesh-ts/src/provider-rudp-transport.ts b/packages/cultmesh-ts/src/provider-rudp-transport.ts index 0557bf48..7e94df02 100644 --- a/packages/cultmesh-ts/src/provider-rudp-transport.ts +++ b/packages/cultmesh-ts/src/provider-rudp-transport.ts @@ -1,6 +1,6 @@ import { randomUUID } from "node:crypto"; import { createSocket, type Socket } from "node:dgram"; -import { encode } from "@msgpack/msgpack"; +import { encodeWireValue } from "cultnet-ts/wire"; import { CultNetPeer, CultNetRudpSocketTransportConnection, @@ -171,7 +171,7 @@ class RudpProviderConnection implements CultMeshProviderConnection { recordKey: publication.recordKey, storedAt: new Date().toISOString(), payloadEncoding: "messagepack", - payload: encode(publication.value), + payload: encodeWireValue(publication.value), sourceRuntimeId: this.#identity.serviceInstanceId, sourceAgentId: this.#identity.providerId, sourceRole: "provider", diff --git a/packages/cultmesh-ts/src/provider-session-broker.ts b/packages/cultmesh-ts/src/provider-session-broker.ts index eb9e18b5..8f650e36 100644 --- a/packages/cultmesh-ts/src/provider-session-broker.ts +++ b/packages/cultmesh-ts/src/provider-session-broker.ts @@ -1,4 +1,4 @@ -import { encode } from "@msgpack/msgpack"; +import { encodeWireValue } from "cultnet-ts/wire"; import type { CultNetDocumentPutRawMessage, CultNetOperationRequestMessage, @@ -420,7 +420,7 @@ export class CultMeshProviderSessionBroker { recordKey: `${command.providerId}/${command.serviceInstanceId}/${command.commandId}`, storedAt: this.#clock.now().toISOString(), payloadEncoding: "messagepack", - payload: encode(command), + payload: encodeWireValue(command), sourceRuntimeId: this.#options.runtimeId, sourceRole: "provider-session-broker", }, @@ -513,7 +513,7 @@ function documentTuple(document: Pick(payload: string): T { if (typeof payload !== "string" || payload.length === 0) { throw new Error("CultMesh provider-session payload must be non-empty MessagePack base64."); } - return decode(Buffer.from(payload, "base64")) as T; + return decodeWireValue(Buffer.from(payload, "base64")) as T; } export function encodeProviderConnectEvidence( evidence: CultMeshProviderConnectEvidenceWire, ): Uint8Array { assertProviderConnectEvidence(evidence); - return encode(evidence); + return encodeWireValue(evidence); } export function decodeProviderConnectEvidence( payload: Uint8Array, ): CultMeshProviderConnectEvidenceWire { - const evidence = decode(payload) as unknown; + const evidence = decodeWireValue(payload) as unknown; assertProviderConnectEvidence(evidence); return evidence; } @@ -162,7 +162,7 @@ export function decodeProviderCommandDocument(document: CultNetRawDocumentRecord if (document.payloadEncoding !== "messagepack") { throw new Error(`Provider command ${document.recordKey} must use MessagePack.`); } - const command = decode(document.payload) as Partial; + const command = decodeWireValue(document.payload) as Partial; requireText(command.commandId, "commandId"); requireText(command.commandKind, "commandKind"); requireText(command.providerId, "providerId"); diff --git a/packages/cultmesh-ts/test/codec-documents.test.ts b/packages/cultmesh-ts/test/codec-documents.test.ts index 4a0d2494..aeb2a14d 100644 --- a/packages/cultmesh-ts/test/codec-documents.test.ts +++ b/packages/cultmesh-ts/test/codec-documents.test.ts @@ -63,12 +63,16 @@ test("the mesh reads a stored codec document as the cache does, and a plain docu assert.deepEqual(await cultMeshDocumentFromSingleFile(codecPath, codecNote).latest(), { noteId: "n1", body: "positional" }); assert.deepEqual(await cultMeshDocumentFromSingleFile(codecPath, codecNoteAlias).latest(), { noteId: "n1", body: "positional" }); - // A store holding a plain record first and a codec record second: the alias, found by parsing, takes the codec one. - const bothPath = join(dir, "both.ccmp"); - const bothNode = await CultMesh.startNode(bothPath, { documents: [plainNote, codecNote] }); - await bothNode.put(plainNote, "n2", { noteId: "n2", body: "map" }); - await bothNode.put(codecNote, "n1", { noteId: "n1", body: "positional" }); - assert.deepEqual(await cultMeshDocumentFromSingleFile(bothPath, codecNoteAlias).latest(), { noteId: "n1", body: "positional" }); + // A store holding a plain record and a codec record, the alias found by parsing takes the codec one whichever the + // single-file store (which sorts records by key) puts first: the probe has to refuse the plain record, not meet it + // second. + for (const [plainKey, codecKey] of [["a-plain", "z-codec"], ["z-plain", "a-codec"]] as const) { + const bothPath = join(dir, `both-${plainKey}.ccmp`); + const bothNode = await CultMesh.startNode(bothPath, { documents: [plainNote, codecNote] }); + await bothNode.put(plainNote, plainKey, { noteId: plainKey, body: "map" }); + await bothNode.put(codecNote, codecKey, { noteId: codecKey, body: "positional" }); + assert.deepEqual(await cultMeshDocumentFromSingleFile(bothPath, codecNoteAlias).latest(), { noteId: codecKey, body: "positional" }); + } assert.deepEqual(await cultMeshDocumentFromSingleFile(plainPath, plainNote).latest(), { noteId: "n2", body: "map" }); }); @@ -85,11 +89,12 @@ test("the mesh syncs a codec document from a peer snapshot and returns a codec r const commandBinding = defineCultNetDocumentBinding({ definition: codecNote }); const plainBinding = defineCultNetDocumentBinding({ definition: plainNote }); const receiptBinding = defineCultNetDocumentBinding({ definition: codecReceipt }); + const puts: unknown[] = []; const server = CultMesh.createRudpDocumentServer("cultmesh-ts-codec-server", connectionId, { documents: new CultNetDocumentRegistry([commandBinding, plainBinding, receiptBinding]), getCache: () => source.cache, bindHost: "127.0.0.1", bindPort: 0, resendDelayMs: 25, resendPollMs: 5, - onDocumentPutRaw: async (document) => ({ + onDocumentPutRaw: async (document) => (puts.push(document.payload), { binding: receiptBinding, recordKey: document.recordKey, value: { commandId: document.recordKey, body: "applied" }, @@ -119,6 +124,13 @@ test("the mesh syncs a codec document from a peer snapshot and returns a codec r { messageId: "n2", receiptTimeoutMs: 1_000, resendPollMs: 5 }, ); assert.deepEqual(receipt, { commandId: "n2", body: "applied" }); + // The handler is handed the document, not its wire shape: the server reads a put through the registered definition. + await CultMesh.publishRudpDocumentAndWaitForReceipt( + "cultmesh-ts-plain-receipt", connectionId, `rudp://127.0.0.1:${server.bind.port}`, + plainBinding, "n4", { noteId: "n4", body: "plain command" }, receiptBinding, + { messageId: "n4", receiptTimeoutMs: 1_000, resendPollMs: 5 }, + ); + assert.deepEqual(puts, [{ noteId: "n2", body: "command" }, { noteId: "n4", body: "plain command" }]); } finally { peer?.close(); server.close(); diff --git a/packages/cultmesh-ts/test/cultmesh.test.ts b/packages/cultmesh-ts/test/cultmesh.test.ts index 5ec961a5..4cdce8df 100644 --- a/packages/cultmesh-ts/test/cultmesh.test.ts +++ b/packages/cultmesh-ts/test/cultmesh.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; import assert from "node:assert/strict"; -import { decode, encode } from "@msgpack/msgpack"; +import { decodeWireValue, encodeWireValue } from "cultnet-ts/wire"; import { z } from "zod"; import { defineDocumentType } from "@gamecult/cultcache-ts"; import { @@ -268,7 +268,7 @@ test("CultMesh TS store document handles choose compatible foreign schema payloa type: "runtime.generated.incompatible-note", schemaId: "runtime.generated.incompatible-note.v1", storedAt: "2026-06-27T00:00:00Z", - payload: encode({ nope: "not the requested shape" }), + payload: encodeWireValue({ nope: "not the requested shape" }), catalogEntry: { schemaId: "runtime.generated.incompatible-note.v1", schemaName: "runtime.generated.incompatible-note", @@ -283,7 +283,7 @@ test("CultMesh TS store document handles choose compatible foreign schema payloa type: "runtime.generated.cultmesh.note", schemaId: "runtime.generated.cultmesh.note.ui.42", storedAt: "2026-06-27T00:00:01Z", - payload: encode({ + payload: encodeWireValue({ noteId: "note:foreign", body: "foreign schema id, local store shape", }), @@ -2820,7 +2820,7 @@ test("CultMesh TS RUDP document server accepts raw document puts from multiple p recordKey: "note:a", storedAt: new Date().toISOString(), payloadEncoding: "messagepack", - payload: encode("first"), + payload: encodeWireValue("first"), sourceRuntimeId: "client-a", }, }); @@ -2832,7 +2832,7 @@ test("CultMesh TS RUDP document server accepts raw document puts from multiple p recordKey: "note:b", storedAt: new Date().toISOString(), payloadEncoding: "messagepack", - payload: encode("second"), + payload: encodeWireValue("second"), sourceRuntimeId: "client-b", }, }); @@ -3311,7 +3311,7 @@ function notePut( recordKey, storedAt, payloadEncoding: "messagepack", - payload: encode({ noteId: recordKey, body: "x".repeat(bodyLength) }), + payload: encodeWireValue({ noteId: recordKey, body: "x".repeat(bodyLength) }), ...(sourceRuntimeId ? { sourceRuntimeId } : {}), }, }; @@ -3324,7 +3324,7 @@ function notePut( */ function servedAloneBytes(put: CultNetDocumentPutRawMessage): number { const { schemaId, recordKey, storedAt, payloadEncoding, payload } = put.document; - return encode({ + return encodeWireValue({ schemaVersion: "cultnet.snapshot_response_raw.v0", messageId: "0", documents: [{ schemaId, recordKey, storedAt, payloadEncoding, payload }], @@ -3337,7 +3337,7 @@ function servedAloneBytes(put: CultNetDocumentPutRawMessage): number { * asked of the server, so a server that sized another receipt is caught. */ function echoReceiptBytes(put: CultNetDocumentPutRawMessage): number { - return encode({ + return encodeWireValue({ schemaVersion: "cultnet.document_put_raw.v0", messageId: put.messageId, document: { @@ -3345,7 +3345,7 @@ function echoReceiptBytes(put: CultNetDocumentPutRawMessage): number { recordKey: put.document.recordKey, storedAt: new Date().toISOString(), payloadEncoding: "messagepack", - payload: encode(decode(put.document.payload)), + payload: encodeWireValue(decodeWireValue(put.document.payload)), sourceRuntimeId: SERVED_BOUND_SERVER, sourceAgentId: undefined, sourceRole: "provider", @@ -3397,7 +3397,7 @@ async function withServedBoundRig( recordKey: document.recordKey, storedAt: document.storedAt, payloadEncoding: "messagepack", - payload: encode(document.payload), + payload: encodeWireValue(document.payload), }, }); if (!handler.receipt) return undefined; @@ -3448,7 +3448,7 @@ function servedBodies(reply: CultNetMessage): Array<[string, number]> { assert.equal(reply.schemaVersion, "cultnet.snapshot_response_raw.v0"); return (reply as CultNetSnapshotResponseRawMessage).documents.map((document) => [ document.recordKey, - (decode(document.payload) as { body: string }).body.length, + (decodeWireValue(document.payload) as { body: string }).body.length, ]); } @@ -3567,7 +3567,7 @@ async function withRawPeerRig( const request = (messageId: string, recordKeys: string[]): number[] => { const packets = session.sendMany( "schema", - encode({ schemaVersion: "cultnet.snapshot_request.v0", messageId, recordKeys }), + encodeWireValue({ schemaVersion: "cultnet.snapshot_request.v0", messageId, recordKeys }), { reliable: true, ordered: true, nowMs: 2, maxFragmentBytes: 1200 }, ); packets.forEach(send); @@ -3586,7 +3586,7 @@ function refusalIn(packets: CultNetRudpPacket[]): { message: Record packet.packetType === "data" && packet.channelId === "schema" && !packet.reliable) .sort((a, b) => (a.fragmentIndex ?? 0) - (b.fragmentIndex ?? 0)); if (parts.length === 0) return undefined; - const message = decode(Buffer.concat(parts.map((part) => Buffer.from(part.payload ?? new Uint8Array())))) as Record; + const message = decodeWireValue(Buffer.concat(parts.map((part) => Buffer.from(part.payload ?? new Uint8Array())))) as Record; return { message, parts }; } @@ -3655,7 +3655,7 @@ test("CultMesh TS RUDP document server honours maxPayloadBytes for replies and j // A put whose own frame is over the limit only by the provenance it carries is served at the // bound, so it is admitted and served. const carried = notePut("put-at", "note:at", atBound, `runtime-${"r".repeat(200)}`); - assert.ok(encode(carried).byteLength > limit, "fixture: the put's frame is over the limit"); + assert.ok(encodeWireValue(carried).byteLength > limit, "fixture: the put's frame is over the limit"); rig.peer.send(carried); await waitForAdmission(rig, "note:at"); assert.deepEqual(servedBodies(await snapshotUnderShortestId(rig, "note:at")), [["note:at", atBound]]); diff --git a/packages/cultmesh-ts/test/payload-decode-owner.test.ts b/packages/cultmesh-ts/test/payload-decode-owner.test.ts new file mode 100644 index 00000000..e267a9c2 --- /dev/null +++ b/packages/cultmesh-ts/test/payload-decode-owner.test.ts @@ -0,0 +1,28 @@ +import assert from "node:assert/strict"; +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import test from "node:test"; + +// A document payload is decoded by cultcache-ts alone (decodeDocumentPayload); every other value on a wire goes through +// cultnet-ts's decodeWireValue / encodeWireValue. So no file of this package imports msgpack, and the manifest does not +// list it, which keeps a new direct decode from arriving unnoticed. +// Limits: a text scan. It reads the package's src files for the module specifier and the manifest for the dependency +// name. It does not follow a re-export from another package, a specifier assembled at run time, or a hand-written +// decoder; the dependency absence is what makes the specifier unresolvable here when the workspace does not hoist it. +const root = join(__dirname, "..", ".."); + +function sourceFiles(dir: string): string[] { + return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => + entry.isDirectory() ? sourceFiles(join(dir, entry.name)) : entry.name.endsWith(".ts") ? [join(dir, entry.name)] : []); +} + +test("no source file imports msgpack and the manifest does not list it", () => { + const manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8")) as Record | undefined>; + for (const section of ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]) { + assert.equal(manifest[section]?.["@msgpack/msgpack"], undefined, section); + } + const files = sourceFiles(join(root, "src")); + assert.ok(files.length > 5, "fixture: the scan reads the package's sources"); + const offenders = files.filter((file) => /@msgpack\/msgpack/.test(readFileSync(file, "utf8"))); + assert.deepEqual(offenders, []); +}); diff --git a/packages/cultmesh-ts/test/provider-rudp-transport.test.ts b/packages/cultmesh-ts/test/provider-rudp-transport.test.ts index f1dd5d2d..abb8f010 100644 --- a/packages/cultmesh-ts/test/provider-rudp-transport.test.ts +++ b/packages/cultmesh-ts/test/provider-rudp-transport.test.ts @@ -1,7 +1,7 @@ import test from "node:test"; import assert from "node:assert/strict"; import { createSocket } from "node:dgram"; -import { decode } from "@msgpack/msgpack"; +import { decodeWireValue } from "cultnet-ts/wire"; import { CultNetDocumentRegistry, CultNetRudpSession, @@ -46,7 +46,7 @@ test("RUDP provider transport requires broker acceptance for the full lifecycle" session.connectPayload !== undefined && decodeProviderConnectEvidence(session.connectPayload).sessionToken === "signed-provider-token", acceptPublication: (_identity, publicationId, document) => { - accepted.set(publicationId, decode(document.payload)); + accepted.set(publicationId, decodeWireValue(document.payload)); acceptedProvenance.set(publicationId, { runtime: document.sourceRuntimeId, agent: document.sourceAgentId, diff --git a/packages/cultmesh-ts/test/rudp-document-server-send-failure.test.ts b/packages/cultmesh-ts/test/rudp-document-server-send-failure.test.ts index 64f19111..8d0425e4 100644 --- a/packages/cultmesh-ts/test/rudp-document-server-send-failure.test.ts +++ b/packages/cultmesh-ts/test/rudp-document-server-send-failure.test.ts @@ -5,7 +5,7 @@ import assert from "node:assert/strict"; import { createSocket, type RemoteInfo, type Socket } from "node:dgram"; import test from "node:test"; -import { encode } from "@msgpack/msgpack"; +import { encodeWireValue } from "cultnet-ts/wire"; import { CultNetDocumentRegistry, CultNetRudpSession, @@ -43,7 +43,7 @@ function put(recordKey: string) { recordKey, storedAt: new Date().toISOString(), payloadEncoding: "messagepack" as const, - payload: encode(recordKey), + payload: encodeWireValue(recordKey), }, }; } diff --git a/packages/cultnet-ts/package.json b/packages/cultnet-ts/package.json index e72a10aa..9147d4ea 100644 --- a/packages/cultnet-ts/package.json +++ b/packages/cultnet-ts/package.json @@ -15,6 +15,11 @@ "require": "./dist/contracts.js", "default": "./dist/contracts.js" }, + "./wire": { + "types": "./dist/wire-value.d.ts", + "require": "./dist/wire-value.js", + "default": "./dist/wire-value.js" + }, "./idunn-runtime": { "types": "./dist/idunn-runtime-authority.d.ts", "require": "./dist/idunn-runtime-authority.js", diff --git a/packages/cultnet-ts/src/wire-value.ts b/packages/cultnet-ts/src/wire-value.ts new file mode 100644 index 00000000..43a5e029 --- /dev/null +++ b/packages/cultnet-ts/src/wire-value.ts @@ -0,0 +1,11 @@ +import { decode, encode } from "@msgpack/msgpack"; + +// The one msgpack entry point above the wire for packages that do not own it: a frame, an envelope, a command, any +// value that is not a document payload. A document payload is read through cultcache-ts's decodeDocumentPayload. +export function encodeWireValue(value: unknown): Uint8Array { + return encode(value); +} + +export function decodeWireValue(bytes: ArrayLike | ArrayBufferView | ArrayBuffer): unknown { + return decode(bytes); +}