Payload decode has one owner: cultcache-ts decodeDocumentPayload; wire values go through cultnet-ts/wire
The RUDP put handler and the browser payload reader decoded a codec document with plain msgpack. cultcache-ts now exports decodeDocumentPayload (definition or plain), the RUDP server reads a put through the registry's definition, and decodeCultNetPayload takes the formatter. cultmesh-ts and cultmesh-browser no longer depend on @msgpack/msgpack: frames and commands use cultnet-ts/wire, and a test per package scans src and the manifest. The envelope probe fixture now runs the plain record first and last. Not yet built or tested on this commit; the verify job follows. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
8fa2d11042
commit
f1e7b36a39
20 changed files with 211 additions and 75 deletions
2
package-lock.json
generated
2
package-lock.json
generated
|
|
@ -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"
|
||||
},
|
||||
|
|
|
|||
|
|
@ -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<unknown> = {
|
||||
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.
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
33
packages/cultcache-ts/test/decode-document-payload.test.ts
Normal file
33
packages/cultcache-ts/test/decode-document-payload.test.ts
Normal file
|
|
@ -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]);
|
||||
});
|
||||
|
|
@ -40,7 +40,6 @@
|
|||
"node": ">=20"
|
||||
},
|
||||
"dependencies": {
|
||||
"@msgpack/msgpack": "^3.1.3",
|
||||
"cultnet-ts": "^0.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
|
|
|||
|
|
@ -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<T>(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<T>(
|
||||
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<T>(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(
|
||||
|
|
|
|||
|
|
@ -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<number[]>(record), [7]);
|
||||
});
|
||||
|
|
|
|||
29
packages/cultmesh-browser/test/payload-decode-owner.test.ts
Normal file
29
packages/cultmesh-browser/test/payload-decode-owner.test.ts
Normal file
|
|
@ -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<string, Record<string, string> | 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, []);
|
||||
});
|
||||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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<void> {
|
||||
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(
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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<CultNetRawDocumentRecord, "schemaId" | "re
|
|||
}
|
||||
|
||||
function wireEquivalent(left: unknown, right: unknown): boolean {
|
||||
return Buffer.from(encode(left)).equals(Buffer.from(encode(right)));
|
||||
return Buffer.from(encodeWireValue(left)).equals(Buffer.from(encodeWireValue(right)));
|
||||
}
|
||||
|
||||
function publicationEntries(record: LeaseRecord): readonly {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { decode, encode } from "@msgpack/msgpack";
|
||||
import { decodeWireValue, encodeWireValue } from "cultnet-ts/wire";
|
||||
import type { CultNetRawDocumentRecord } from "cultnet-ts";
|
||||
|
||||
export const CULTMESH_PROVIDER_SESSION_SERVICE_ID = "gamecult.mesh.provider_session";
|
||||
|
|
@ -120,27 +120,27 @@ export interface CultMeshProviderMutationAcceptanceWire {
|
|||
}
|
||||
|
||||
export function encodeProviderSessionPayload(value: unknown): string {
|
||||
return Buffer.from(encode(value)).toString("base64");
|
||||
return Buffer.from(encodeWireValue(value)).toString("base64");
|
||||
}
|
||||
|
||||
export function decodeProviderSessionPayload<T>(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<CultMeshProviderCommandWire>;
|
||||
const command = decodeWireValue(document.payload) as Partial<CultMeshProviderCommandWire>;
|
||||
requireText(command.commandId, "commandId");
|
||||
requireText(command.commandKind, "commandKind");
|
||||
requireText(command.providerId, "providerId");
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
|
|
|
|||
|
|
@ -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<string, unkn
|
|||
.filter((packet) => 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<string, unknown>;
|
||||
const message = decodeWireValue(Buffer.concat(parts.map((part) => Buffer.from(part.payload ?? new Uint8Array())))) as Record<string, unknown>;
|
||||
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]]);
|
||||
|
|
|
|||
28
packages/cultmesh-ts/test/payload-decode-owner.test.ts
Normal file
28
packages/cultmesh-ts/test/payload-decode-owner.test.ts
Normal file
|
|
@ -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<string, Record<string, string> | 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, []);
|
||||
});
|
||||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
11
packages/cultnet-ts/src/wire-value.ts
Normal file
11
packages/cultnet-ts/src/wire-value.ts
Normal file
|
|
@ -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<number> | ArrayBufferView | ArrayBuffer): unknown {
|
||||
return decode(bytes);
|
||||
}
|
||||
Loading…
Reference in a new issue