Merge C1 shapes (d7911589) into C2 provider

This commit is contained in:
Meta Vens 2026-10-19 18:20:23 +02:00
commit 196222962f
10 changed files with 2736 additions and 90 deletions

View file

@ -156,8 +156,8 @@
46,
48
],
"contentHash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"recordKey": "mesh:cdn:artifact:smile:1.0.0:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
"contentHash": "\u017Fha256:abc",
"recordKey": "mesh:cdn:artifact:smile:1.0.0:\u017Fha256:abc"
},
{
"artifactIdUnits": [
@ -174,7 +174,7 @@
116,
97
],
"contentHash": "SHA256:E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855",
"contentHash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"recordKey": "mesh:cdn:artifact:cb3f91d54eee30e53e35b2b99905f70f169ed549fd78909d3dac2defc9ed8d3b:v2-beta:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
{
@ -186,7 +186,7 @@
"versionUnits": [
252
],
"contentHash": " e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 ",
"contentHash": "SHA256:E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855",
"recordKey": "mesh:cdn:artifact:a-b:\u00FC:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
{
@ -194,8 +194,8 @@
55296
],
"versionUnits": [],
"contentHash": " sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"recordKey": "mesh:cdn:artifact:83d544ccc223c057d2bf80d3f2a32982c32c3c0db8e2674820da5064783fb097:unversioned:sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
"contentHash": " e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 ",
"recordKey": "mesh:cdn:artifact:83d544ccc223c057d2bf80d3f2a32982c32c3c0db8e2674820da5064783fb097:unversioned:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
{
"artifactIdUnits": [
@ -208,7 +208,7 @@
32,
32
],
"contentHash": "sha256:sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"contentHash": " sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"recordKey": "mesh:cdn:artifact:x-y:unversioned:sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
{
@ -223,8 +223,8 @@
46,
48
],
"contentHash": "Sha256:\u0130\u03A3\uD801\uDC00",
"recordKey": "mesh:cdn:artifact:\u0663d:1.0.0:\u0130\u03C3\uD801\uDC28"
"contentHash": "sha256:sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"recordKey": "mesh:cdn:artifact:\u0663d:1.0.0:sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
{
"artifactIdUnits": [
@ -241,8 +241,44 @@
116,
97
],
"contentHash": "Sha256:\u0130\u03A3\uD801\uDC00",
"recordKey": "mesh:cdn:artifact:a:v2-beta:\u0130\u03C3\uD801\uDC28"
},
{
"artifactIdUnits": [
32,
32,
45,
45,
45,
32,
32
],
"versionUnits": [
252
],
"contentHash": "sha256:",
"recordKey": "mesh:cdn:artifact:a:v2-beta:"
"recordKey": "mesh:cdn:artifact:fcd2a2fb27957aa9a10d2d9eca16ccbc9c35a76933b03f470211d327f6946c3f:\u00FC:"
},
{
"artifactIdUnits": [
9398
],
"versionUnits": [],
"contentHash": "\u017Fha256:abc",
"recordKey": "mesh:cdn:artifact:7d9633ae307dae04a8b362df41dca4b38a653823d69f27a259e7b6928508d3a6:unversioned:\u017Fha256:abc"
},
{
"artifactIdUnits": [
8555
],
"versionUnits": [
32,
32,
32
],
"contentHash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"recordKey": "mesh:cdn:artifact:8c0e55c55f47de02406174ec976279a977e2e73ea5aec8ab90f94c40a6ab2d60:unversioned:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
{
"artifactIdUnits": [
@ -403,6 +439,230 @@
],
"contentHash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"recordKey": "mesh:cdn:artifact:eureka-content-vector:\u00FC:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
{
"artifactIdUnits": [
101,
117,
114,
101,
107,
97,
47,
99,
111,
110,
116,
101,
110,
116,
45,
118,
101,
99,
116,
111,
114
],
"versionUnits": [],
"contentHash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"recordKey": "mesh:cdn:artifact:eureka-content-vector:unversioned:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
{
"artifactIdUnits": [
101,
117,
114,
101,
107,
97,
47,
99,
111,
110,
116,
101,
110,
116,
45,
118,
101,
99,
116,
111,
114
],
"versionUnits": [],
"contentHash": "SHA256:E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855",
"recordKey": "mesh:cdn:artifact:eureka-content-vector:unversioned:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
{
"artifactIdUnits": [
101,
117,
114,
101,
107,
97,
47,
99,
111,
110,
116,
101,
110,
116,
45,
118,
101,
99,
116,
111,
114
],
"versionUnits": [],
"contentHash": " e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 ",
"recordKey": "mesh:cdn:artifact:eureka-content-vector:unversioned:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
{
"artifactIdUnits": [
101,
117,
114,
101,
107,
97,
47,
99,
111,
110,
116,
101,
110,
116,
45,
118,
101,
99,
116,
111,
114
],
"versionUnits": [],
"contentHash": " sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"recordKey": "mesh:cdn:artifact:eureka-content-vector:unversioned:sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
{
"artifactIdUnits": [
101,
117,
114,
101,
107,
97,
47,
99,
111,
110,
116,
101,
110,
116,
45,
118,
101,
99,
116,
111,
114
],
"versionUnits": [],
"contentHash": "sha256:sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"recordKey": "mesh:cdn:artifact:eureka-content-vector:unversioned:sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
{
"artifactIdUnits": [
101,
117,
114,
101,
107,
97,
47,
99,
111,
110,
116,
101,
110,
116,
45,
118,
101,
99,
116,
111,
114
],
"versionUnits": [],
"contentHash": "Sha256:\u0130\u03A3\uD801\uDC00",
"recordKey": "mesh:cdn:artifact:eureka-content-vector:unversioned:\u0130\u03C3\uD801\uDC28"
},
{
"artifactIdUnits": [
101,
117,
114,
101,
107,
97,
47,
99,
111,
110,
116,
101,
110,
116,
45,
118,
101,
99,
116,
111,
114
],
"versionUnits": [],
"contentHash": "sha256:",
"recordKey": "mesh:cdn:artifact:eureka-content-vector:unversioned:"
},
{
"artifactIdUnits": [
101,
117,
114,
101,
107,
97,
47,
99,
111,
110,
116,
101,
110,
116,
45,
118,
101,
99,
116,
111,
114
],
"versionUnits": [],
"contentHash": "\u017Fha256:abc",
"recordKey": "mesh:cdn:artifact:eureka-content-vector:unversioned:\u017Fha256:abc"
}
],
"chunks": [
@ -433,6 +693,10 @@
{
"chunkHash": "sha256:",
"recordKey": "mesh:cdn:chunk:"
},
{
"chunkHash": "\u017Fha256:abc",
"recordKey": "mesh:cdn:chunk:\u017Fha256:abc"
}
]
}
}

File diff suppressed because it is too large Load diff

View file

@ -94,6 +94,27 @@
},
"recordKey": "mesh:cdn:artifact:pixel-heroes-hüt:v1-beta:89f4ff56a25dd1db06a4ce6033603775d705fb96f30f8693733fef602a1ca532",
"messagePackBase64": "mrVQaXhlbCBIZXJvZXMvSMO8dCDimIOlYXNzZXSnVjEgQmV0YdlAODlmNGZmNTZhMjVkZDFkYjA2YTRjZTYwMzM2MDM3NzVkNzA1ZmI5NmYzMGY4NjkzNzMzZmVmNjAyYTFjYTUzMs0D6L9hcHBsaWNhdGlvbi94LWN1bHRuZXQtdHMtdmVjdG9y2SEyMDI2LTEwLTE5VDAwOjAwOjAwLjAwMDAwMDArMDA6MDCRlNlAODlmNGZmNTZhMjVkZDFkYjA2YTRjZTYwMzM2MDM3NzVkNzA1ZmI5NmYzMGY4NjkzNzMzZmVmNjAyYTFjYTUzMgDNA+jZT21lc2g6Y2RuOmNodW5rOjg5ZjRmZjU2YTI1ZGQxZGIwNmE0Y2U2MDMzNjAzNzc1ZDcwNWZiOTZmMzBmODY5MzczM2ZlZjYwMmExY2E1MzKQgA=="
},
{
"label": "ts whitespace version, padded kind and mime",
"kind": "manifest",
"input": {
"artifactId": "Pixel Heroes/Hüt ☃",
"kind": " build ",
"version": " ",
"mimeType": " text/plain; charset=utf-8 ",
"createdAtUtc": "2026-10-19T00:00:00.0000000+00:00",
"chunkSizeBytes": 4194304,
"tags": [],
"metadata": [],
"body": {
"length": 1000,
"multiplier": 7,
"modulus": 256
}
},
"recordKey": "mesh:cdn:artifact:pixel-heroes-hüt:unversioned:89f4ff56a25dd1db06a4ce6033603775d705fb96f30f8693733fef602a1ca532",
"messagePackBase64": "mrVQaXhlbCBIZXJvZXMvSMO8dCDimIOnIGJ1aWxkIKIgINlAODlmNGZmNTZhMjVkZDFkYjA2YTRjZTYwMzM2MDM3NzVkNzA1ZmI5NmYzMGY4NjkzNzMzZmVmNjAyYTFjYTUzMs0D6L0gIHRleHQvcGxhaW47IGNoYXJzZXQ9dXRmLTggINkhMjAyNi0xMC0xOVQwMDowMDowMC4wMDAwMDAwKzAwOjAwkZTZQDg5ZjRmZjU2YTI1ZGQxZGIwNmE0Y2U2MDMzNjAzNzc1ZDcwNWZiOTZmMzBmODY5MzczM2ZlZjYwMmExY2E1MzIAzQPo2U9tZXNoOmNkbjpjaHVuazo4OWY0ZmY1NmEyNWRkMWRiMDZhNGNlNjAzMzYwMzc3NWQ3MDVmYjk2ZjMwZjg2OTM3MzNmZWY2MDJhMWNhNTMykIA="
}
]
}

View file

@ -140,9 +140,16 @@ imports no `node:` module, so a browser bundle can take it.
object reorders integer-like keys, and the entry order is the wire bytes.
Duplicate keys, integers a JS number cannot hold exactly, and payloads nested
past the shared depth limit are refused.
- The decoder reads what MessagePack-CSharp reads and refuses what it refuses:
nil in a string, tag or metadata slot is `null` and is written back as nil,
a missing trailing slot takes the reference's default, extra slots and trailing
bytes are skipped, a float-encoded integer is refused, and invalid UTF-8
decodes to U+FFFD. A nil `chunks` is refused, as the reference's
`ValidateManifest` refuses it. `content-acceptance-vectors.json` is the
reference's own verdict on each of those shapes.
- Bytes and keys are held to files the C# reference writes
(`contracts/cultmesh/content-vectors.cs-written.json`,
`cdn-record-key-vectors.json`) and to `content-vectors.rs-written.json`.
`cdn-record-key-vectors.json`, `content-acceptance-vectors.json`) and to `content-vectors.rs-written.json`.
The TypeScript-written `content-vectors.ts-written.json` is judged by the C#
reference. Regenerate it with `npm run build --workspace packages/cultnet-ts`
and `node scripts/write-cultmesh-content-vectors.mjs`; never edit it by hand.

View file

@ -7,33 +7,36 @@
// No `node:` import. A manifest names its chunks by hash and carries no address: where bytes are fetched from is the
// caller's to resolve through CultMesh.
import { Decoder, encode } from "@msgpack/msgpack";
import { encode } from "@msgpack/msgpack";
import { checkPayloadDepth } from "@gamecult/cultcache-ts/document";
import { isNullOrWhiteSpaceCSharp, trimCSharp } from "./cultmesh-authority";
import { wellFormed } from "./utf8-bound";
export const CULTMESH_CDN_MANIFEST_SCHEMA = "gamecult.mesh.cdn_artifact_manifest.v1";
export const DEFAULT_CHUNK_SIZE_BYTES = 4 * 1024 * 1024;
export const EMPTY_SHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
// The reference's value model: a string, the tag array and the metadata map are reference types there, so MessagePack
// nil reads as null and writes back as nil. `chunks` is the exception: `ValidateManifest` refuses a nil one.
export interface CultMeshCdnChunkRef {
readonly chunkHash: string;
readonly chunkHash: string | null;
readonly offset: number;
readonly sizeBytes: number;
readonly recordKey: string;
readonly recordKey: string | null;
}
// Metadata is ordered entries, never an object: a JS object reorders integer-like keys, and the entry order is wire bytes.
export interface CultMeshCdnArtifactManifest {
readonly artifactId: string;
readonly kind: string;
readonly version: string;
readonly contentHash: string;
readonly artifactId: string | null;
readonly kind: string | null;
readonly version: string | null;
readonly contentHash: string | null;
readonly sizeBytes: number;
readonly mimeType: string;
readonly createdAtUtc: string;
readonly mimeType: string | null;
readonly createdAtUtc: string | null;
readonly chunks: readonly CultMeshCdnChunkRef[];
readonly tags: readonly string[];
readonly metadata: readonly (readonly [string, string])[];
readonly tags: readonly (string | null)[] | null;
readonly metadata: readonly (readonly [string, string | null])[] | null;
}
export interface CultMeshCdnPackOptions {
@ -59,13 +62,13 @@ const lowerInvariant = (text: string): string =>
Array.from(text, character => { const lower = character.toLowerCase(); return Array.from(lower).length === 1 ? lower : character; }).join("");
/** `CultMeshCdn.NormalizeHash`: a case-insensitive `sha256:` prefix is stripped before the trim, and nothing checks for hex. */
export function normalizeHash(hash: string, parameterName = "hash"): string {
export function normalizeHash(hash: string | null | undefined, parameterName = "hash"): string {
if (isNullOrWhiteSpaceCSharp(hash)) throw new Error(`Hash must be non-empty. (Parameter '${parameterName}')`);
return lowerInvariant(trimCSharp(hash.slice(0, 7).toLowerCase() === "sha256:" ? hash.slice(7) : hash));
return lowerInvariant(trimCSharp(hash!.slice(0, 7).toLowerCase() === "sha256:" ? hash!.slice(7) : hash!));
}
/** The hash a file name or a fetch may rest on: `normalizeHash`, then exactly 64 lowercase hexadecimal digits. */
export function parseSha256Hex(hash: string, parameterName = "hash"): string {
export function parseSha256Hex(hash: string | null | undefined, parameterName = "hash"): string {
const hex = normalizeHash(hash, parameterName);
if (!/^[0-9a-f]{64}$/.test(hex)) throw new Error(`Hash must be 64 hexadecimal digits. (Parameter '${parameterName}')`);
return hex;
@ -77,7 +80,7 @@ export async function sha256Hex(bytes: Uint8Array): Promise<string> {
return Array.from(new Uint8Array(await subtle.digest("SHA-256", bytes as BufferSource)), byte => byte.toString(16).padStart(2, "0")).join("");
}
export const chunkRecordKey = (chunkHash: string): string => `mesh:cdn:chunk:${normalizeHash(chunkHash, "chunkHash")}`;
export const chunkRecordKey = (chunkHash: string | null | undefined): string => `mesh:cdn:chunk:${normalizeHash(chunkHash, "chunkHash")}`;
// `CultMeshCdn.StableToken`, unit by unit: a letter or decimal digit, `-`, `_` and `.` survive, anything else (a lone
// surrogate included) becomes `-`, and a token that is empty after the trim falls back to the hash of the original.
@ -86,10 +89,10 @@ async function stableToken(value: string): Promise<string> {
return token || sha256Hex(new TextEncoder().encode(value));
}
export async function artifactRecordKey(artifactId: string, version: string, contentHash: string): Promise<string> {
export async function artifactRecordKey(artifactId: string | null, version: string | null, contentHash: string | null): Promise<string> {
if (isNullOrWhiteSpaceCSharp(artifactId)) throw new Error("Value must be non-empty. (Parameter 'artifactId')");
const versioned = isNullOrWhiteSpaceCSharp(version) ? "unversioned" : await stableToken(version);
return `mesh:cdn:artifact:${await stableToken(artifactId)}:${versioned}:${normalizeHash(contentHash, "contentHash")}`;
const versioned = isNullOrWhiteSpaceCSharp(version) ? "unversioned" : await stableToken(version!);
return `mesh:cdn:artifact:${await stableToken(artifactId!)}:${versioned}:${normalizeHash(contentHash, "contentHash")}`;
}
// ---- validation ------------------------------------------------------------------------------------------------------
@ -104,7 +107,8 @@ export function validateManifest(manifest: CultMeshCdnArtifactManifest): void {
expectedOffset += reference.sizeBytes;
}
if (expectedOffset !== manifest.sizeBytes) throw new Error("CDN artifact chunk sizes do not sum to the manifest size.");
if (new Set(manifest.metadata.map(([key]) => key)).size !== manifest.metadata.length) {
const metadata = manifest.metadata ?? [];
if (new Set(metadata.map(([key]) => key)).size !== metadata.length) {
throw new Error("CDN artifact manifest metadata has a duplicate key.");
}
}
@ -122,59 +126,151 @@ const mapHeader = (count: number): Uint8Array =>
: count < 0x10000 ? Uint8Array.of(0xde, count >> 8, count & 0xff)
: Uint8Array.of(0xdf, count >>> 24, (count >> 16) & 0xff, (count >> 8) & 0xff, count & 0xff);
/** A string slot is written as C# writes it: a lone surrogate has no UTF-8 encoding and becomes U+FFFD at every length. */
const text = <T>(field: T): T => (typeof field === "string" ? wellFormed(field) : field) as T;
/** The positional ten-array of the C# `[MessagePackObject]`: chunk references are four-arrays, metadata a map in entry order. */
export function encodeManifest(manifest: CultMeshCdnArtifactManifest): Uint8Array {
const { artifactId, kind, version, contentHash, sizeBytes, mimeType, createdAtUtc, chunks, tags, metadata } = manifest;
return concat([
Uint8Array.of(0x9a),
...[artifactId, kind, version, contentHash, sizeBytes, mimeType, createdAtUtc].map(field => encode(field)),
encode(chunks.map(c => [c.chunkHash, c.offset, c.sizeBytes, c.recordKey])),
encode(tags),
mapHeader(metadata.length),
...metadata.flatMap(([key, value]) => [encode(key), encode(value)]),
...[artifactId, kind, version, contentHash, sizeBytes, mimeType, createdAtUtc].map(field => encode(text(field))),
encode(chunks.map(c => [text(c.chunkHash), c.offset, c.sizeBytes, text(c.recordKey)])),
encode(tags === null ? null : tags.map(text)),
...(metadata === null ? [encode(null)] : [mapHeader(metadata.length), ...metadata.flatMap(([key, value]) => [encode(text(key)), encode(text(value))])]),
]);
}
const wrongType = (field: string): never => { throw new Error(`CDN artifact manifest field '${field}' has the wrong type.`); };
const text = (value: unknown, field: string): string => typeof value === "string" ? value : wrongType(field);
const list = (value: unknown, field: string): unknown[] => Array.isArray(value) ? value : wrongType(field);
const record = (value: unknown, field: string): Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Uint8Array) ? value as Record<string, unknown> : wrongType(field);
// Any integer width, as the reference reads. A 64-bit value a JS number cannot hold exactly rounds to 2^53 or beyond, which is
// never a safe integer: it is refused, never silently rounded.
const integer = (value: unknown, field: string): number => Number.isSafeInteger(value) ? value as number : wrongType(field);
/** The reference's reader: depth first, exact types, then `validateManifest`. */
// MessagePack-CSharp's reader for the manifest, family by family: the integer rule must see the wire family (a float
// encoding of 0 is not an integer there), a string is `str` or nil, an array header is an array, and the invalid UTF-8
// of a string decodes to U+FFFD as .NET decodes it. `ignoreBOM` keeps a leading U+FEFF, as `Encoding.GetString` does.
const utf8 = new TextDecoder("utf-8", { ignoreBOM: true });
const SAFE = BigInt(Number.MAX_SAFE_INTEGER);
// Payload size after the code byte, or the width of the length that precedes a variable payload.
const FIXED: Readonly<Record<number, number>> = { 0xca: 4, 0xcb: 8, 0xcc: 1, 0xcd: 2, 0xce: 4, 0xcf: 8, 0xd0: 1, 0xd1: 2, 0xd2: 4, 0xd3: 8, 0xd4: 2, 0xd5: 3, 0xd6: 5, 0xd7: 9, 0xd8: 17 };
const BYTES: Readonly<Record<number, number>> = { 0xc4: 1, 0xc5: 2, 0xc6: 4, 0xd9: 1, 0xda: 2, 0xdb: 4 };
const EXT: Readonly<Record<number, number>> = { 0xc7: 1, 0xc8: 2, 0xc9: 4 };
const ARRAY: Readonly<Record<number, number>> = { 0xdc: 2, 0xdd: 4 };
const MAP: Readonly<Record<number, number>> = { 0xde: 2, 0xdf: 4 };
class Reader {
position = 0;
private readonly view: DataView;
constructor(private readonly bytes: Uint8Array) {
this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
}
private take(count: number): number {
const start = this.position;
if (count > this.bytes.length - start) throw new Error("CDN artifact manifest ends before its last field.");
this.position += count;
return start;
}
private code(): number { return this.bytes[this.take(1)]!; }
private width(size: number): number {
const at = this.take(size);
return size === 1 ? this.view.getUint8(at) : size === 2 ? this.view.getUint16(at) : this.view.getUint32(at);
}
nil(): boolean {
if (this.bytes[this.position] !== 0xc0) return false;
this.position += 1;
return true;
}
array(field: string): number {
const code = this.code();
return code >= 0x90 && code <= 0x9f ? code & 0x0f : ARRAY[code] ? this.width(ARRAY[code]!) : wrongType(field);
}
map(field: string): number {
const code = this.code();
return code >= 0x80 && code <= 0x8f ? code & 0x0f : MAP[code] ? this.width(MAP[code]!) : wrongType(field);
}
string(field: string): string | null {
if (this.nil()) return null;
const code = this.code();
const length = code >= 0xa0 && code <= 0xbf ? code & 0x1f : code === 0xd9 || code === 0xda || code === 0xdb ? this.width(BYTES[code]!) : wrongType(field);
const start = this.take(length);
return utf8.decode(this.bytes.subarray(start, start + length));
}
// Any integer family; a 64-bit value a JS number cannot hold exactly is refused, never silently rounded.
integer(field: string): number {
const code = this.code();
if (code <= 0x7f) return code;
if (code >= 0xe0) return code - 0x100;
const at = (code >= 0xcc && code <= 0xd3) ? this.take(FIXED[code]!) : wrongType(field);
const big = code === 0xcf ? this.view.getBigUint64(at) : code === 0xd3 ? this.view.getBigInt64(at) : undefined;
if (big !== undefined) return big >= -SAFE && big <= SAFE ? Number(big) : wrongType(field);
return code === 0xcc ? this.view.getUint8(at) : code === 0xcd ? this.view.getUint16(at) : code === 0xce ? this.view.getUint32(at)
: code === 0xd0 ? this.view.getInt8(at) : code === 0xd1 ? this.view.getInt16(at) : this.view.getInt32(at);
}
// `MessagePackReader.Skip`: one value of any family, nested containers included (the depth rule has already bounded them).
skip(): void {
for (let pending = 1; pending > 0; pending -= 1) {
const code = this.code();
if (code <= 0x7f || code >= 0xe0 || code === 0xc0 || code === 0xc2 || code === 0xc3) continue;
if (code <= 0x8f) pending += 2 * (code & 0x0f);
else if (code <= 0x9f) pending += code & 0x0f;
else if (code <= 0xbf) this.take(code & 0x1f);
else if (FIXED[code]) this.take(FIXED[code]!);
else if (BYTES[code]) this.take(this.width(BYTES[code]!));
else if (EXT[code]) this.take(this.width(EXT[code]!) + 1);
else if (ARRAY[code]) pending += this.width(ARRAY[code]!);
else if (MAP[code]) pending += 2 * this.width(MAP[code]!);
else wrongType("manifest");
}
}
}
/** The reference's reader then `validateManifest`: depth first, then the positional array as MessagePack-CSharp reads it. */
export function decodeManifest(bytes: Uint8Array): CultMeshCdnArtifactManifest {
checkPayloadDepth(bytes, "CDN artifact manifest");
// The decoder builds a JS object, which reorders integer-like keys; the converter sees the keys in wire order.
const keys: string[] = [];
const decoder = new Decoder({ mapKeyConverter: key => { keys.push(text(key, "metadata")); return key as string; } });
const fields = list(decoder.decode(bytes), "manifest");
if (fields.length !== 10) wrongType("manifest");
const map = record(fields[9], "metadata");
const reader = new Reader(bytes);
// A slot the array does not reach keeps the property initialiser; a slot past the tenth is skipped. Trailing bytes are not read.
const count = reader.array("manifest");
let index = 0;
const slot = <T>(read: () => T, initial: T): T => index++ < count ? read() : initial;
const manifest: CultMeshCdnArtifactManifest = {
artifactId: text(fields[0], "artifactId"),
kind: text(fields[1], "kind"),
version: text(fields[2], "version"),
contentHash: text(fields[3], "contentHash"),
sizeBytes: integer(fields[4], "sizeBytes"),
mimeType: text(fields[5], "mimeType"),
createdAtUtc: text(fields[6], "createdAtUtc"),
chunks: list(fields[7], "chunks").map(item => {
const chunk = list(item, "chunks");
if (chunk.length !== 4) wrongType("chunks");
const sizeBytes = integer(chunk[2], "chunks.sizeBytes");
return { chunkHash: text(chunk[0], "chunks.chunkHash"), offset: integer(chunk[1], "chunks.offset"),
sizeBytes: sizeBytes >= -(2 ** 31) && sizeBytes < 2 ** 31 ? sizeBytes : wrongType("chunks.sizeBytes"), recordKey: text(chunk[3], "chunks.recordKey") };
}),
tags: list(fields[8], "tags").map(tag => text(tag, "tags")),
metadata: keys.map(key => [key, text(map[key], "metadata")] as const),
artifactId: slot(() => reader.string("artifactId"), ""),
kind: slot(() => reader.string("kind"), "asset"),
version: slot(() => reader.string("version"), ""),
contentHash: slot(() => reader.string("contentHash"), ""),
sizeBytes: slot(() => reader.integer("sizeBytes"), 0),
mimeType: slot(() => reader.string("mimeType"), "application/octet-stream"),
createdAtUtc: slot(() => reader.string("createdAtUtc"), ""),
chunks: slot(() => Array.from({ length: reader.array("chunks") }, () => readChunkRef(reader)), []),
tags: slot(() => reader.nil() ? null : Array.from({ length: reader.array("tags") }, () => reader.string("tags")), []),
metadata: slot(() => reader.nil() ? null : Array.from({ length: reader.map("metadata") }, () =>
[reader.string("metadata") ?? wrongType("metadata"), reader.string("metadata")] as const), []),
};
for (; index < count; index += 1) reader.skip();
validateManifest(manifest);
return manifest;
}
function readChunkRef(reader: Reader): CultMeshCdnChunkRef {
const count = reader.array("chunks");
let index = 0;
const slot = <T>(read: () => T, initial: T): T => index++ < count ? read() : initial;
const chunk = {
chunkHash: slot(() => reader.string("chunks.chunkHash"), ""),
offset: slot(() => reader.integer("chunks.offset"), 0),
// The reference's `int`.
sizeBytes: slot(() => { const size = reader.integer("chunks.sizeBytes"); return size >= -(2 ** 31) && size < 2 ** 31 ? size : wrongType("chunks.sizeBytes"); }, 0),
recordKey: slot(() => reader.string("chunks.recordKey"), ""),
};
for (; index < count; index += 1) reader.skip();
return chunk;
}
// ---- packing ---------------------------------------------------------------------------------------------------------
/** `CultMeshCdn.PackArtifact`: content-addressed chunks and the manifest that names them. An empty body is one empty chunk. */

View file

@ -8,13 +8,18 @@
* A value is therefore in bounds exactly when this returns it unchanged.
*/
export function truncateUtf8Bytes(value: string, maxBytes: number): string {
const wellFormed = (value as string & { toWellFormed(): string }).toWellFormed();
const text = wellFormed(value);
let bytes = 0;
let end = 0;
for (const char of wellFormed) {
for (const char of text) {
bytes += Buffer.byteLength(char, "utf8");
if (bytes > maxBytes) break;
end += char.length;
}
return wellFormed.slice(0, end);
return text.slice(0, end);
}
/** `value` with every lone surrogate replaced by U+FFFD: the one spelling every TypeScript writer puts on a wire. */
export function wellFormed(value: string): string {
return (value as string & { toWellFormed(): string }).toWellFormed();
}

View file

@ -120,8 +120,8 @@ test("packContent refuses a blank artifact id, a chunk size outside 1..214748364
test("default createdAtUtc matches the C# round-trip 'O' format", async () => {
const { manifest } = await packContent("x", new Uint8Array(1));
assert.match(manifest.createdAtUtc, /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{7}\+00:00$/);
assert.ok(Math.abs(Date.parse(manifest.createdAtUtc.replace(/(\.\d{3})\d{4}\+00:00$/, "$1Z")) - Date.now()) < 60_000);
assert.match(manifest.createdAtUtc!, /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{7}\+00:00$/);
assert.ok(Math.abs(Date.parse(manifest.createdAtUtc!.replace(/(\.\d{3})\d{4}\+00:00$/, "$1Z")) - Date.now()) < 60_000);
});
test("manifest_out_of_order decodes and validates, and its chunks keep wire order", () => {
@ -144,18 +144,16 @@ test("a manifest with a duplicated metadata key is refused, in decode and in val
validateManifest(manifestOf({ metadata: [["a", "1"], ["b", "1"]] }));
});
test("a metadata key that is not a string, and a __proto__ key, are refused", () => {
test("a metadata key that is not a string is refused", () => {
const withMap = (...entry: Uint8Array[]) => Uint8Array.from([...wire().slice(0, -5), 0x81, ...entry.flatMap(part => Array.from(part))]);
decodeManifest(withMap(encode("k"), encode("v")));
refusal(withMap(encode(5), encode("v")));
refusal(withMap(encode(new Uint8Array(2)), encode("v")));
refusal(withMap(encode("__proto__"), encode("v")));
});
test("an integer field accepts any width and refuses what a JS number cannot hold exactly", () => {
const empty = { 4: 0, 7: [] as unknown[] };
// Past the integer rule, a size nothing sums to fails the sum check; a refused integer fails the type check first.
assert.throws(() => decodeManifest(wire({ ...empty, 4: 2 ** 53 - 1 })), /do not sum/);
assert.throws(() => decodeManifest(wire({ ...empty, 4: 2n ** 53n - 1n })), /do not sum/);
assert.throws(() => decodeManifest(wire({ ...empty, 4: 2n ** 53n })), /wrong type/);
assert.throws(() => decodeManifest(wire({ ...empty, 4: 2n ** 53n + 1n })), /wrong type/);
@ -173,7 +171,7 @@ test("a chunk size outside int32 is refused as the reference's int cannot hold i
const chunk = (size: number) => decodeManifest(wire({ 4: size, 7: [[HASH, 0, size, "k"]] }));
assert.equal(chunk(2 ** 31 - 1).chunks[0]!.sizeBytes, 2 ** 31 - 1);
assert.throws(() => chunk(2 ** 31), /chunks\.sizeBytes.*wrong type/);
assert.throws(() => decodeManifest(wire({ 4: -(2 ** 31) - 1, 7: [[HASH, 0, -(2 ** 31) - 1, "k"]] })), /chunks\.sizeBytes.*wrong type/);
assert.throws(() => decodeManifest(wire({ 4: -(2n ** 31n) - 1n, 7: [[HASH, 0, -(2n ** 31n) - 1n, "k"]] })), /chunks\.sizeBytes.*wrong type/);
assert.throws(() => decodeManifest(wire({ 4: 0, 7: [[HASH, 0, -(2 ** 31), "k"]] })), /chunk has a negative size/);
});
@ -192,25 +190,23 @@ test("a manifest of the wrong shape is refused naming the field and never the va
const canary = "CANARY-7f3a91";
const chunk = (...parts: unknown[]) => wire({ 7: [parts] });
const cases: [Uint8Array, string][] = [
[wire({ 0: 5 }), "artifactId"], [wire({ 0: null }), "artifactId"], [wire({ 1: 5 }), "kind"], [wire({ 2: 5 }), "version"],
[wire({ 0: 5 }), "artifactId"], [wire({ 1: 5 }), "kind"], [wire({ 2: 5 }), "version"],
[wire({ 3: 5 }), "contentHash"], [wire({ 5: 5 }), "mimeType"], [wire({ 6: 5 }), "createdAtUtc"],
[wire({ 4: canary }), "sizeBytes"], [wire({ 4: "4" }), "sizeBytes"], [wire({ 4: null }), "sizeBytes"], [wire({ 4: 0.5 }), "sizeBytes"],
[wire({ 7: canary }), "chunks"], [wire({ 7: [canary] }), "chunks"], [chunk(HASH, 0, 4), "chunks"], [chunk(HASH, 0, 4, "k", canary), "chunks"],
[wire({ 7: canary }), "chunks"], [wire({ 7: [canary] }), "chunks"],
[chunk(5, 0, 4, "k"), "chunks.chunkHash"], [chunk(HASH, canary, 4, "k"), "chunks.offset"], [chunk(HASH, 0, canary, "k"), "chunks.sizeBytes"],
[chunk(HASH, 0, 4, 5), "chunks.recordKey"],
[wire({ 8: canary }), "tags"], [wire({ 8: [5] }), "tags"],
[wire({ 9: canary }), "metadata"], [wire({ 9: { k: 5 } }), "metadata"], [wire({ 9: null }), "metadata"], [wire({ 9: [] }), "metadata"],
[wire({ 9: canary }), "metadata"], [wire({ 9: { k: 5 } }), "metadata"], [wire({ 9: [] }), "metadata"],
[wire({ 9: new Uint8Array(2) }), "metadata"],
[encode(fieldsOf().slice(0, 9)), "manifest"], [wire({ 10: canary }), "manifest"], [encode([canary]), "manifest"], [encode(canary), "manifest"],
[encode(canary), "manifest"], [encode({ [canary]: canary }), "manifest"],
];
for (const [bytes, field] of cases) {
assert.throws(() => decodeManifest(bytes), (error: unknown) =>
error instanceof Error && error.message.includes(`'${field}'`) && !error.message.includes(canary), field);
}
// Refusals that are not shape: truncated, trailing bytes. Neither echoes the value.
for (const bytes of [encode(canary).slice(0, 4), Uint8Array.from([...wire(), 0xc0])]) {
assert.throws(() => decodeManifest(bytes), (error: unknown) => error instanceof Error && !error.message.includes(canary));
}
// A payload that ends early is not a shape; it does not echo the value either.
assert.throws(() => decodeManifest(encode([canary]).slice(0, 4)), (error: unknown) => error instanceof Error && !error.message.includes(canary));
assert.equal(decodeManifest(wire()).chunks.length, 1, "the unmodified fixture decodes");
});
@ -338,6 +334,83 @@ test("the metadata map header is the minimal MessagePack header at every size bo
const expected = encode(Object.fromEntries(entries));
const bytes = encodeManifest(manifestOf({ metadata: entries }));
assert.deepEqual(bytes.slice(bytes.length - expected.length), expected, `${count} entries`);
assert.equal(decodeManifest(bytes).metadata.length, count);
assert.equal(decodeManifest(bytes).metadata!.length, count);
}
});
// The reference's acceptance, case by case: `contracts/cultmesh/content-acceptance-vectors.json` is written by the C# test
// from `MessagePackSerializer.Deserialize` plus `ValidateManifest`; an accepted case carries the bytes the reference
// writes back and the key it derives. Nothing in the file is authored on this side.
test("decodeManifest accepts and refuses exactly what the reference does, and re-encodes what it re-encodes", async () => {
const file = JSON.parse(readFileSync(join(CONTRACTS, "content-acceptance-vectors.json"), "utf8")) as {
cases: { label: string; inputBase64: string; accepted: boolean; reencodedBase64: string | null; recordKey: string | null }[];
};
const bytes = (base64: string) => new Uint8Array(Buffer.from(base64, "base64"));
assert.ok(file.cases.filter(c => c.accepted).length > 30 && file.cases.filter(c => !c.accepted).length > 30, "the file holds both verdicts in quantity");
assert.equal(new Set(file.cases.map(c => c.label)).size, file.cases.length);
for (const c of file.cases) {
if (!c.accepted) {
assert.throws(() => decodeManifest(bytes(c.inputBase64)), /./, `${c.label}: the reference refuses`);
continue;
}
const manifest = decodeManifest(bytes(c.inputBase64));
assert.deepEqual(encodeManifest(manifest), bytes(c.reencodedBase64!), `${c.label}: the reference's bytes`);
if (c.recordKey === null) await assert.rejects(artifactRecordKey(manifest.artifactId, manifest.version, manifest.contentHash), /./, `${c.label}: no key`);
else assert.equal(await artifactRecordKey(manifest.artifactId, manifest.version, manifest.contentHash), c.recordKey, `${c.label}: key`);
}
});
test("a manifest written as a map names the manifest, not a field inside it", () => {
assert.throws(() => decodeManifest(encode({ 0: "a", 9: { k: "v" } })), /field 'manifest' has the wrong type/);
});
test("nil in a reference slot reads as null and writes back as nil; a missing trailing slot takes the initialiser", () => {
const nils = wire({ 0: null, 2: null, 8: null, 9: null });
const manifest = decodeManifest(nils);
assert.deepEqual([manifest.artifactId, manifest.version, manifest.tags, manifest.metadata], [null, null, null, null]);
assert.deepEqual(encodeManifest(manifest), nils);
const short = decodeManifest(encode(["id"]));
assert.deepEqual(short, { artifactId: "id", kind: "asset", version: "", contentHash: "", sizeBytes: 0, mimeType: "application/octet-stream", createdAtUtc: "", chunks: [], tags: [], metadata: [] });
});
// Refusals that are the same refusal in the reference but would read differently if the wrong rule fired: the message
// names the true cause (the sign, the nil chunk, the reserved code, the early end), never a neighbouring field.
test("a refusal names its true cause", () => {
const refuses = (bytes: Uint8Array, message: RegExp) => assert.throws(() => decodeManifest(bytes), message);
refuses(wire({ 4: -1, 7: [] }), /negative size/);
refuses(wire({ 4: -32, 7: [] }), /negative size/);
refuses(wire({ 4: -(2n ** 53n - 1n), 7: [] }), /negative size/);
refuses(wire({ 4: -(2n ** 53n), 7: [] }), /field 'sizeBytes' has the wrong type/);
refuses(wire({ 4: 0, 7: [[HASH, 0, -32, "k"]] }), /chunk has a negative size/);
refuses(wire({ 7: null }), /field 'chunks' has the wrong type/);
refuses(wire({ 7: [null] }), /field 'chunks' has the wrong type/);
refuses(Uint8Array.of(0xc0), /field 'manifest' has the wrong type/);
refuses(wire().slice(0, 8), /ends before its last field/);
refuses(Uint8Array.of(0x91, 0xa3, 0x41), /ends before its last field/);
refuses(Uint8Array.from([0x9b, ...wire().slice(1), 0xc1]), /field 'manifest' has the wrong type/);
});
test("a lone surrogate is written as U+FFFD at every string length, short and long alike, in every string slot", async () => {
const base = (await packContent("x", Uint8Array.of(1, 2, 3), { createdAtUtc: "2026-09-22T00:00:00.0000000+00:00" })).manifest;
// @msgpack/msgpack switches encoders past 50 UTF-16 units; the reference writes U+FFFD on both sides of that line.
for (const length of [1, 2, 16, 31, 32, 49, 50, 51, 52, 64, 200]) {
for (const [lone, replaced] of [["\ud800", "\ufffd"], ["\udfff", "\ufffd"]]) {
const filler = "a".repeat(length - 1);
const bad = `${filler}${lone}`;
const good = `${filler}${replaced}`;
const withText = (value: string): CultMeshCdnArtifactManifest => ({
...base,
artifactId: value, kind: value, version: value, mimeType: value, createdAtUtc: value,
chunks: [{ ...base.chunks[0]!, recordKey: value }],
tags: [value],
metadata: [[value, value]],
});
const bytes = encodeManifest(withText(bad));
assert.deepEqual(bytes, encodeManifest(withText(good)), `length ${length}`);
assert.ok(!bytes.some((b, i) => b === 0xed && bytes[i + 1]! >= 0xa0 && bytes[i + 1]! <= 0xbf), `no CESU surrogate bytes at length ${length}`);
assert.equal(decodeManifest(bytes).artifactId, good, `length ${length} reads back as written`);
}
}
const packed = await packContent(`a${"b".repeat(60)}\ud800`, Uint8Array.of(1), { kind: "k\udc00", createdAtUtc: "2026-09-22T00:00:00.0000000+00:00" });
assert.equal(decodeManifest(encodeManifest(packed.manifest)).kind, "k\ufffd");
});

View file

@ -41,6 +41,9 @@ const inputs = [
["ts multi-chunk body", { ...common, body: { length: 777777, multiplier: 7, modulus: 256 } }],
["ts empty body", { ...common, body: { length: 0, multiplier: 7, modulus: 256 } }],
["ts single chunk, versioned", { ...common, version: "V1 Beta", chunkSizeBytes: 4194304, tags: [], metadata: [], body: { length: 1000, multiplier: 7, modulus: 256 } }],
// Padding the reference keeps: a whitespace version stays as written (the key reads it as unversioned), kind and MIME are
// only replaced when blank.
["ts whitespace version, padded kind and mime", { ...common, kind: " build ", version: " ", mimeType: " text/plain; charset=utf-8 ", chunkSizeBytes: 4194304, tags: [], metadata: [], body: { length: 1000, multiplier: 7, modulus: 256 } }],
];
const vectors = [];

View file

@ -13,6 +13,10 @@
<ProjectReference Include="..\GameCult.Networking\GameCult.Networking.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="GameCult.Mesh.Tests" />
</ItemGroup>
<ItemGroup>
<None Include="README.md" Pack="true" PackagePath="\" />
<None Include="docs\**\*.md" Pack="true" PackagePath="docs\" />

View file

@ -2,10 +2,12 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using FluentAssertions;
using GameCult.Caching;
using GameCult.Caching.MessagePack;
using GameCult.Networking;
using MessagePack;
using NUnit.Framework;
@ -35,6 +37,7 @@ public sealed class CultMeshContentVectorTests
Assert.Ignore("Set CULTNET_WRITE_VECTORS=1 to (re)write the committed vector file.");
File.WriteAllText(VectorPath("content-vectors.cs-written.json"), ToJson(BuildVectors(out _, out _)));
File.WriteAllText(VectorPath("cdn-record-key-vectors.json"), RecordKeyVectorsToJson(BuildRecordKeyVectors()));
File.WriteAllText(VectorPath("content-acceptance-vectors.json"), AcceptanceVectorsToJson(BuildAcceptanceVectors()));
}
[Test]
@ -70,7 +73,7 @@ public sealed class CultMeshContentVectorTests
Reencode(response).Should().Equal(vector.Bytes, vector.Label);
break;
case "manifest":
var manifest = MessagePackSerializer.Deserialize<CultMeshCdnArtifactManifest>(vector.Bytes, CultNetSchemaMessageSerialization.Options);
var manifest = ReadManifest(vector.Bytes);
manifest.Should().BeEquivalentTo((CultMeshCdnArtifactManifest)expected);
Reencode(manifest).Should().Equal(vector.Bytes, vector.Label);
break;
@ -119,7 +122,7 @@ public sealed class CultMeshContentVectorTests
{
var label = vector.GetProperty("label").GetString()!;
var bytes = Convert.FromBase64String(vector.GetProperty("messagePackBase64").GetString()!);
var manifest = MessagePackSerializer.Deserialize<CultMeshCdnArtifactManifest>(bytes, CultNetSchemaMessageSerialization.Options);
var manifest = ReadManifest(bytes);
Reencode(manifest).Should().Equal(bytes, $"{label}: the reference reads and rewrites the TypeScript bytes unchanged");
CultMeshCdnArtifactManifest.CreateRecordKey(manifest).Value.Should().Be(vector.GetProperty("recordKey").GetString(), label);
@ -149,6 +152,294 @@ public sealed class CultMeshContentVectorTests
}
}
[Test]
public void CommittedAcceptanceVectorsEqualAFreshRun()
{
var path = VectorPath("content-acceptance-vectors.json");
File.Exists(path).Should().BeTrue($"{path} is written by this fixture under CULTNET_WRITE_VECTORS=1");
var fresh = BuildAcceptanceVectors();
fresh.Select(c => c.Label).Should().OnlyHaveUniqueItems();
fresh.Count(c => c.Accepted).Should().BeGreaterThan(30);
fresh.Count(c => !c.Accepted).Should().BeGreaterThan(30);
Lines(File.ReadAllText(path)).Should().Be(Lines(AcceptanceVectorsToJson(fresh)), "the reference's acceptance drifted from the committed vectors");
}
private sealed record Acceptance(string Label, byte[] Input, bool Accepted, byte[]? Reencoded, string? RecordKey);
/// <summary>What the reference does with these bytes: deserialise, then <c>ValidateManifest</c>; accepted bytes are rewritten and keyed.</summary>
private static Acceptance Judge(string label, byte[] input)
{
CultMeshCdnArtifactManifest manifest;
try
{
manifest = ReadManifest(input);
CultMeshCdn.ValidateManifest(manifest);
}
catch (Exception)
{
return new Acceptance(label, input, false, null, null);
}
string? key = null;
try { key = CultMeshCdnArtifactManifest.CreateRecordKey(manifest).Value; }
catch (ArgumentException) { }
return new Acceptance(label, input, true, Reencode(manifest), key);
}
private static byte[] Deep(int depth) => Cat(Enumerable.Repeat((byte)0x91, depth).ToArray(), Nil);
private static byte[] Cat(params byte[][] parts) => parts.SelectMany(p => p).ToArray();
private static byte[] Raw(params byte[] bytes) => bytes;
private static readonly byte[] Nil = { 0xc0 };
private static byte[] Str(string text)
{
var bytes = Encoding.UTF8.GetBytes(text);
return Cat(bytes.Length < 32 ? Raw((byte)(0xa0 | bytes.Length)) : Raw(0xd9, (byte)bytes.Length), bytes);
}
private static byte[] StrRaw(params byte[] bytes) => Cat(Raw((byte)(0xa0 | bytes.Length)), bytes);
private static byte[] Arr(params byte[][] items) => Cat(Raw((byte)(0x90 | items.Length)), Cat(items));
private static byte[] MapOf(params byte[][] pairs) => Cat(Raw((byte)(0x80 | (pairs.Length / 2))), Cat(pairs));
private static byte[] Be(byte code, long value, int width)
{
var bytes = new byte[width];
for (var i = 0; i < width; i++) bytes[width - 1 - i] = (byte)(value >> (8 * i));
return Cat(Raw(code), bytes);
}
private static byte[] F64(long bits) => Be(0xcb, bits, 8);
private static byte[] F32(int bits) => Be(0xca, bits, 4);
private static byte[][] BaseFields() => new[]
{
Str("a/b"), Str("asset"), Str("1"), Str(EmptyHash), Raw(0x00), Str("application/x-t"), Str("t"),
Arr(Chunk(Raw(0x00), Raw(0x00))), Arr(Str("x")), MapOf(Str("k"), Str("v"))
};
private const string EmptyHash = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
private static byte[] Chunk(byte[] offset, byte[] size) => Arr(Str(EmptyHash), offset, size, Str("k"));
private static byte[] Doc(IEnumerable<byte[]> fields)
{
var list = fields.ToArray();
return Cat(Raw((byte)(0x90 | list.Length)), Cat(list));
}
private static byte[][] With(params (int Index, byte[] Value)[] edits)
{
var fields = BaseFields();
foreach (var (index, value) in edits) fields[index] = value;
return fields;
}
/// <summary>
/// Byte shapes at the edge of what MessagePack-CSharp reads: nil in reference slots, missing and extra slots,
/// trailing bytes, integer and float families, string families and invalid UTF-8. The reference judges each one;
/// the TypeScript decoder is held to the verdict and to the bytes the reference writes back.
/// </summary>
private static List<Acceptance> BuildAcceptanceVectors()
{
var cases = new List<Acceptance>();
void Add(string label, byte[] input) => cases.Add(Judge(label, input));
void AddFields(string label, params (int Index, byte[] Value)[] edits) => Add(label, Doc(With(edits)));
var fields = BaseFields();
Add("base", Doc(fields));
for (var count = 0; count <= 9; count++) Add($"short_{count}", Doc(fields.Take(count)));
Add("array16_header", Cat(Raw(0xdc, 0, 10), Cat(fields)));
Add("array32_header", Cat(Raw(0xdd, 0, 0, 0, 10), Cat(fields)));
Add("extra_11_nil", Doc(fields.Append(Nil)));
Add("extra_11_str", Doc(fields.Append(Str("x"))));
Add("extra_11_nested", Doc(fields.Append(Arr(Arr(Str("x")), MapOf(Str("a"), F64(0))))));
Add("extra_11_ext", Doc(fields.Append(Raw(0xd4, 1, 2))));
Add("extra_11_ext8", Doc(fields.Append(Raw(0xc7, 2, 1, 7, 7))));
Add("extra_11_bin", Doc(fields.Append(Raw(0xc4, 2, 1, 2))));
Add("extra_11_float", Doc(fields.Append(F32(0))));
Add("extra_11_uint64", Doc(fields.Append(Be(0xcf, 7, 8))));
Add("extra_11_array16", Doc(fields.Append(Cat(Raw(0xdc, 0, 2), Raw(1), Raw(2)))));
Add("extra_11_map16", Doc(fields.Append(Cat(Raw(0xde, 0, 1), Raw(1), Raw(2)))));
Add("extra_11_str8", Doc(fields.Append(Raw(0xd9, 1, 0x41))));
Add("extra_12", Doc(fields.Append(Nil).Append(Str("y"))));
Add("extra_11_reserved_code", Doc(fields.Append(Raw(0xc1))));
Add("extra_11_truncated", Doc(fields.Append(Raw(0x92, 1))));
// The production reader refuses payloads nested past CultPayloadDepth (256); the extra slot is skipped, so only that rule can refuse it.
foreach (var depth in new[] { 250, 253, 254, 255, 256, 257, 300 })
{
Add($"deep_extra_{depth}", Doc(fields.Append(Deep(depth))));
AddFields($"deep_chunkextra_{depth}", (7, Arr(Arr(Str(EmptyHash), Raw(0), Raw(0), Str("k"), Deep(depth)))));
}
AddFields("chunk_3", (7, Arr(Arr(Str(EmptyHash), Raw(0), Raw(0)))));
AddFields("chunk_5", (7, Arr(Arr(Str(EmptyHash), Raw(0), Raw(0), Str("k"), Nil))));
AddFields("chunk_5_nested", (7, Arr(Arr(Str(EmptyHash), Raw(0), Raw(0), Str("k"), Arr(Raw(1), Raw(2))))));
// An extra slot inside a chunk reference is followed by more bytes, so a skip that stops short shows.
var extras = new (string Name, byte[] Value)[]
{
("map", MapOf(Str("a"), Str("b"), Str("c"), Str("d"))), ("map16", Cat(Raw(0xde, 0, 2), Raw(1), Raw(2), Raw(3), Raw(4))),
("map32", Cat(Raw(0xdf, 0, 0, 0, 1), Raw(1), Raw(2))), ("array", Arr(Raw(1), Raw(2), Raw(3))),
("array16", Cat(Raw(0xdc, 0, 2), Raw(1), Raw(2))), ("array32", Cat(Raw(0xdd, 0, 0, 0, 1), Raw(1))),
("fixext1", Raw(0xd4, 1, 2)), ("fixext2", Raw(0xd5, 1, 2, 3)), ("fixext4", Raw(0xd6, 1, 2, 3, 4, 5)),
("fixext8", Raw(0xd7, 1, 2, 3, 4, 5, 6, 7, 8, 9)), ("fixext16", Cat(Raw(0xd8, 1), new byte[16])),
("ext8", Raw(0xc7, 2, 1, 7, 7)), ("ext16", Raw(0xc8, 0, 2, 1, 7, 7)), ("ext32", Raw(0xc9, 0, 0, 0, 2, 1, 7, 7)),
("bin8", Raw(0xc4, 2, 1, 2)), ("bin16", Raw(0xc5, 0, 2, 1, 2)), ("bin32", Raw(0xc6, 0, 0, 0, 2, 1, 2)),
("str8", Raw(0xd9, 2, 0x41, 0x42)), ("str16", Raw(0xda, 0, 2, 0x41, 0x42)), ("str32", Raw(0xdb, 0, 0, 0, 2, 0x41, 0x42)),
("fixstr", Str("ab")), ("f32", F32(1)), ("f64", F64(1)), ("u8", Raw(0xcc, 1)), ("u16", Be(0xcd, 1, 2)), ("u32", Be(0xce, 1, 4)),
("u64", Be(0xcf, 1, 8)), ("i8", Raw(0xd0, 1)), ("i16", Be(0xd1, 1, 2)), ("i32", Be(0xd2, 1, 4)), ("i64", Be(0xd3, 1, 8)),
("true", Raw(0xc3)), ("false", Raw(0xc2)), ("nil", Nil), ("negfixint", Raw(0xff)), ("reserved", Raw(0xc1)),
("fixint_max", Raw(0x7f)), ("negfixint_min", Raw(0xe0)), ("fixstr_31", Cat(Raw(0xbf), new byte[31])),
("fixmap_15", Cat(Raw(0x8f), Cat(Enumerable.Range(0, 15).Select(_ => Raw(1, 2)).ToArray()))), ("fixarray_15", Cat(Raw(0x9f), new byte[15])),
("nested", Arr(MapOf(Str("a"), Arr(Raw(1), Raw(2))), Arr()))
};
foreach (var (name, value) in extras)
AddFields($"chunk_extra_{name}", (7, Arr(Arr(Str(EmptyHash), Raw(0), Raw(0), Str("k"), value))));
AddFields("chunk_1", (7, Arr(Arr(Str(EmptyHash)))));
AddFields("chunk_0", (7, Arr(Arr())));
AddFields("chunk_is_map", (7, Arr(MapOf(Str("a"), Str("b")))));
AddFields("chunk_is_str", (7, Arr(Str("a"))));
AddFields("chunks_empty_with_size", (7, Arr()));
AddFields("chunks_empty_size_zero", (7, Arr()), (4, Raw(0)));
AddFields("chunks_is_str", (7, Str("a")));
AddFields("chunks_is_map", (7, MapOf()));
AddFields("chunks_gap", (7, Arr(Chunk(Raw(1), Raw(0)))));
foreach (var (index, name) in new[] { (0, "artifactId"), (1, "kind"), (2, "version"), (3, "contentHash"), (5, "mimeType"), (6, "createdAtUtc") })
AddFields($"nil_{name}", (index, Nil));
AddFields("nil_chunks", (7, Nil));
AddFields("nil_chunk_element", (7, Arr(Nil)));
AddFields("nil_chunk_hash", (7, Arr(Arr(Nil, Raw(0), Raw(0), Str("k")))));
AddFields("nil_chunk_recordKey", (7, Arr(Arr(Str(EmptyHash), Raw(0), Raw(0), Nil))));
AddFields("nil_tags", (8, Nil));
AddFields("nil_tag_element", (8, Arr(Nil, Str("x"))));
AddFields("nil_metadata", (9, Nil));
AddFields("nil_metadata_value", (9, MapOf(Str("k"), Nil)));
AddFields("nil_metadata_key", (9, MapOf(Nil, Str("v"))));
AddFields("nil_size", (4, Nil));
AddFields("metadata_duplicate_key", (9, MapOf(Str("k"), Str("1"), Str("k"), Str("2"))));
AddFields("metadata_integer_like_keys", (9, MapOf(Str("10"), Str("a"), Str("alpha"), Str("b"), Str("2"), Str("c"))));
AddFields("metadata_int_key", (9, MapOf(Raw(5), Str("v"))));
AddFields("metadata_int_value", (9, MapOf(Str("k"), Raw(5))));
AddFields("metadata_empty_key", (9, MapOf(Str(""), Str("v"))));
AddFields("metadata_proto_key", (9, MapOf(Str("__proto__"), Str("v"))));
AddFields("metadata_map16", (9, Cat(Raw(0xde, 0, 1), Str("k"), Str("v"))));
AddFields("metadata_map32", (9, Cat(Raw(0xdf, 0, 0, 0, 1), Str("k"), Str("v"))));
AddFields("metadata_is_array", (9, Arr()));
AddFields("metadata_is_str", (9, Str("k")));
AddFields("tags_is_map", (8, MapOf()));
AddFields("tags_int_element", (8, Arr(Raw(5))));
AddFields("tags_array16", (8, Cat(Raw(0xdc, 0, 1), Str("x"))));
Add("trailing_nil", Cat(Doc(fields), Nil));
Add("trailing_reserved_code", Cat(Doc(fields), Raw(0xc1)));
Add("trailing_truncated_array", Cat(Doc(fields), Raw(0x92)));
Add("top_nil", Nil);
Add("top_empty", Array.Empty<byte>());
Add("top_map", MapOf(Str("a"), Str("b")));
Add("top_str", Str("a"));
Add("top_int", Raw(5));
Add("top_truncated", Doc(fields)[..^3]);
foreach (var (name, zero) in new (string, byte[])[]
{
("u8", Raw(0xcc, 0)), ("u16", Be(0xcd, 0, 2)), ("u32", Be(0xce, 0, 4)), ("u64", Be(0xcf, 0, 8)),
("i8", Raw(0xd0, 0)), ("i16", Be(0xd1, 0, 2)), ("i32", Be(0xd2, 0, 4)), ("i64", Be(0xd3, 0, 8)),
("f32", F32(0)), ("f32_negzero", F32(int.MinValue)), ("f64", F64(0)), ("f64_negzero", F64(long.MinValue)),
("f64_one", F64(0x3FF0000000000000)),
("true", Raw(0xc3)), ("false", Raw(0xc2)), ("str", Str("0")), ("bin", Raw(0xc4, 1, 0)), ("array", Arr()), ("ext", Raw(0xd4, 1, 0)),
// Zero-filled so that a reader which took them for an int32 would read 0.
("fixext4", Cat(Raw(0xd6), new byte[5])), ("fixext8", Cat(Raw(0xd7), new byte[9])), ("fixext16", Cat(Raw(0xd8), new byte[17]))
})
{
AddFields($"size_{name}", (4, zero));
AddFields($"offset_{name}", (7, Arr(Chunk(zero, Raw(0)))));
AddFields($"chunksize_{name}", (7, Arr(Chunk(Raw(0), zero))));
}
AddFields("size_negative", (4, Raw(0xff)), (7, Arr()));
AddFields("size_u64_over_long", (4, Be(0xcf, -1, 8)), (7, Arr()));
AddFields("size_i64_min", (4, Be(0xd3, long.MinValue, 8)), (7, Arr()));
AddFields("size_2p53_minus_1", (4, Be(0xcf, (1L << 53) - 1, 8)), (7, Arr()));
AddFields("chunksize_int_max", (4, Be(0xce, int.MaxValue, 4)), (7, Arr(Chunk(Raw(0), Be(0xce, int.MaxValue, 4)))));
AddFields("chunksize_2p31", (4, Be(0xce, 1L << 31, 4)), (7, Arr(Chunk(Raw(0), Be(0xce, 1L << 31, 4)))));
AddFields("chunksize_i32_min", (4, Raw(0)), (7, Arr(Chunk(Raw(0), Be(0xd2, int.MinValue, 4)))));
AddFields("chunksize_i64_below_i32", (4, Raw(0)), (7, Arr(Chunk(Raw(0), Be(0xd3, (long)int.MinValue - 1, 8)))));
AddFields("offset_beyond_int32",
(4, Be(0xcf, 3L * int.MaxValue, 8)),
(7, Arr(Chunk(Raw(0), Be(0xce, int.MaxValue, 4)), Chunk(Be(0xce, int.MaxValue, 4), Be(0xce, int.MaxValue, 4)),
Chunk(Be(0xce, 2L * int.MaxValue, 4), Be(0xce, int.MaxValue, 4)))));
AddFields("chunks_out_of_order",
(4, Raw(2)), (7, Arr(Chunk(Raw(1), Raw(1)), Chunk(Raw(0), Raw(1)))));
AddFields("chunks_overlap", (4, Raw(2)), (7, Arr(Chunk(Raw(0), Raw(2)), Chunk(Raw(1), Raw(1)))));
AddFields("chunk_negative_size", (4, Raw(0)), (7, Arr(Chunk(Raw(0), Raw(0xff)))));
AddFields("str_bin", (1, Raw(0xc4, 1, 0x41)));
AddFields("str_ext", (1, Raw(0xd4, 1, 0x41)));
AddFields("str_int", (1, Raw(0x41)));
AddFields("str_str16", (1, Raw(0xda, 0, 1, 0x41)));
AddFields("str_str32", (1, Raw(0xdb, 0, 0, 0, 1, 0x41)));
AddFields("str_empty", (1, Str("")));
AddFields("str_invalid_utf8", (1, StrRaw(0xFF, 0xFE)));
AddFields("str_lone_surrogate_cesu", (1, StrRaw(0xED, 0xA0, 0x80)));
AddFields("str_overlong", (1, StrRaw(0xC0, 0xAF)));
AddFields("str_truncated_sequence", (1, StrRaw(0xE2, 0x82)));
AddFields("str_bom", (0, Str("bom")));
AddFields("str_nul", (0, StrRaw(0x61, 0x00, 0x62)));
AddFields("id_invalid_utf8", (0, StrRaw(0xFF)));
AddFields("hash_invalid_utf8", (3, StrRaw(0xFF)));
AddFields("version_invalid_utf8", (2, StrRaw(0xFF, 0xFE)));
AddFields("id_blank", (0, Str(" ")));
AddFields("hash_blank", (3, Str(" ")));
AddFields("hash_prefix_upper_long_s", (3, Str("ſha256:abc")));
// Shapes that end early, and header families a lenient reader would take for another.
var whole = Doc(fields);
Add("truncated_string_body", whole[..^1]);
Add("truncated_str8_length", Raw(0x91, 0xd9));
Add("truncated_u16", Cat(Raw(0x95), Str("a"), Str("k"), Str("v"), Str(EmptyHash), Raw(0xcd, 0)));
Add("truncated_u64", Cat(Raw(0x95), Str("a"), Str("k"), Str("v"), Str(EmptyHash), Raw(0xcf, 0, 0, 0)));
Add("truncated_array16", Raw(0xdc, 0));
Add("extra_11_truncated_string", Doc(fields.Append(Raw(0xa5, 0x41))));
Add("extra_11_truncated_str8_length", Doc(fields.Append(Raw(0xd9))));
Add("array_15", Doc(fields.Concat(Enumerable.Repeat(Nil, 5))));
AddFields("metadata_15_entries", (9, Cat(Raw(0x8f), Cat(Enumerable.Range(0, 15).Select(i => Cat(Str($"k{i}"), Str("v"))).ToArray()))));
Add("tags_fixint_then_trailing", Cat(Raw(0x99), Cat(fields[..8]), Raw(1), Str("a")));
Add("tags_fixmap", Cat(Raw(0x99), Cat(fields[..8]), MapOf(Str("a"), Str("b"))));
Add("metadata_fixint_then_trailing", Cat(Raw(0x9a), Cat(fields[..9]), Raw(1), Str("a"), Str("b")));
Add("metadata_array_then_trailing", Cat(Raw(0x9a), Cat(fields[..9]), Arr(Str("a"), Str("b")), Str("c"), Str("d")));
// Every integer family at a value that needs its full width and its own signedness: as the sizes, then as an offset.
foreach (var (name, value, n) in new (string, byte[], long)[]
{
("u8_200", Raw(0xcc, 200), 200), ("u16_258", Be(0xcd, 258, 2), 258), ("u16_40000", Be(0xcd, 40000, 2), 40000),
("u32_258", Be(0xce, 258, 4), 258), ("u64_258", Be(0xcf, 258, 8), 258), ("i8_100", Raw(0xd0, 100), 100),
("i16_258", Be(0xd1, 258, 2), 258), ("i32_258", Be(0xd2, 258, 4), 258), ("i64_258", Be(0xd3, 258, 8), 258),
("fixint_127", Raw(0x7f), 127)
})
{
AddFields($"width_{name}", (4, value), (7, Arr(Chunk(Raw(0), value))));
AddFields($"width_{name}_offset", (4, Be(0xcd, n + 1, 2)), (7, Arr(Chunk(Raw(0), Be(0xcd, n, 2)), Chunk(value, Raw(1)))));
}
AddFields("width_u32_over_int32", (4, Be(0xce, 3_000_000_000, 4)),
(7, Arr(Chunk(Raw(0), Be(0xce, int.MaxValue, 4)), Chunk(Be(0xce, int.MaxValue, 4), Be(0xce, 3_000_000_000 - int.MaxValue, 4)))));
AddFields("width_negative_fixint", (4, Raw(0xff)));
AddFields("width_negative_fixint_min", (4, Raw(0xe0)));
AddFields("width_negative_i64_safe", (4, Be(0xd3, -((1L << 53) - 1), 8)));
AddFields("width_negative_i64_unsafe", (4, Be(0xd3, -(1L << 53), 8)));
return cases;
}
private static string AcceptanceVectorsToJson(List<Acceptance> cases) =>
JsonSerializer.Serialize(
new
{
cases = cases.Select(c => new
{
label = c.Label,
inputBase64 = Convert.ToBase64String(c.Input),
accepted = c.Accepted,
reencodedBase64 = c.Reencoded == null ? null : Convert.ToBase64String(c.Reencoded),
recordKey = c.RecordKey
})
},
new JsonSerializerOptions { WriteIndented = true });
private static byte[] Body() =>
Enumerable.Range(0, BodyLength).Select(i => (byte)(i % 251)).ToArray();
@ -166,8 +457,12 @@ public sealed class CultMeshContentVectorTests
private static byte[] Reencode(CultMeshContentChunkResponseMessage message) =>
CultNetSchemaMessageSerialization.Serialize(message);
/// <summary>The one reader of manifest bytes: the document reader production stores and reads manifests with (CultPayloadDepth 256 included).</summary>
private static CultMeshCdnArtifactManifest ReadManifest(byte[] bytes) =>
(CultMeshCdnArtifactManifest)CultDocumentMessagePackSerialization.DeserializeUntyped(typeof(CultMeshCdnArtifactManifest), bytes);
private static byte[] Reencode(CultMeshCdnArtifactManifest manifest) =>
MessagePackSerializer.Serialize(manifest, CultNetSchemaMessageSerialization.Options);
CultDocumentMessagePackSerialization.SerializeUntyped(manifest, typeof(CultMeshCdnArtifactManifest));
private static CultMeshContentChunkRequestMessage Request(string id, string hash, string key, int size) => new()
{
@ -331,7 +626,9 @@ public sealed class CultMeshContentVectorTests
return new[]
{
empty, "SHA256:" + empty.ToUpperInvariant(), " " + empty + " ", " sha256:" + empty,
"sha256:sha256:" + empty, "Sha256:\u0130\u03A3\U00010400", "sha256:"
"sha256:sha256:" + empty, "Sha256:\u0130\u03A3\U00010400", "sha256:",
// U+017F uppercases to 'S': a prefix fold by upper case would strip it, the reference's ordinal-ignore-case does not.
"\u017Fha256:abc"
};
}
@ -345,12 +642,15 @@ public sealed class CultMeshContentVectorTests
var ids = new[]
{
"eureka/content-vector", " Mixed Case/Path ", "\u0130stanbul", "\u0391\u03A3", "\uFEFFbom", "\u0085nel\u0085",
"\u65E5\u672C\u8A9E/\u8CC7\u7523", "\U0001F642 smile", "---", "a\uD800b", "\uD800", "x\u00B2y", "\u0663d", "\U00010400A"
"\u65E5\u672C\u8A9E/\u8CC7\u7523", "\U0001F642 smile", "---", "a\uD800b", "\uD800", "x\u00B2y", "\u0663d", "\U00010400A",
// Tokens that are empty after the trim: the fallback hashes the original, neither trimmed nor lower-cased.
" --- ", "\u24B6", "\u216B"
};
var versions = new[] { string.Empty, " ", "1.0.0", "V2 Beta", "\u00FC" };
var hashes = KeyHashes();
var artifacts = ids.Select((id, i) => (id, versions[i % versions.Length], hashes[i % hashes.Length]))
.Concat(versions.Select(version => (ids[0], version, hashes[0])))
.Concat(hashes.Select(hash => (ids[0], versions[0], hash)))
.Select(t => (t.Item1, t.Item2, t.Item3, CultMeshCdnArtifactManifest.CreateRecordKey(t.Item1, t.Item2, t.Item3).Value))
.ToList();
var chunks = hashes.Select(hash => (hash, CultMeshCdnArtifactChunk.CreateRecordKey(hash).Value)).ToList();