Encode a CultMesh realtime frame in TypeScript

One codec, `packages/cultmesh-ts/src/realtime-wire.ts`, rule for rule what
`CultMeshRealtimeWireProtocol` does: the 37-byte little-endian fixed header
with magic 0x31545343, the delivery byte as the C# enum ordinal, the i64
epoch and sequence, three u16 identity lengths, the i32 payload length, the
stamped header size and wire version, then UTF-8 identities and the payload.
It touches no socket; QUIC stream framing stays transport-owned. The blank
reading in `Validate` is `IsNullOrWhiteSpace`, whose whitespace set is not
`String.prototype.trim`'s, so it borrows `isNullOrWhiteSpaceCSharp` from
`cultnet-ts` rather than growing a second reading of the same rule.

Byte parity is proven in both directions and in two processes, which is what
the authority vectors cost us to learn. `contracts/cultmesh/realtime-frame-vectors.json`
is written by the new C# test under CULTMESH_WRITE_VECTORS=1 and decoded and
re-encoded here; `realtime-frame-vectors.ts-written.json` is written by
`scripts/write-cultmesh-realtime-frame-vectors.mjs` with this codec, over
different identities and epochs, and decoded by the same C# test with the
reference implementation alone. Both files share one field shape, so each
side reads both with one reader. The two cases that would put megabytes into
a committed contract file, identities at exactly 65,535 UTF-8 bytes and a
64 MiB payload, are recorded as a build rule plus the digest of the whole
encoding; both sides build them the same way.

Three things the C# reference gets from its type system and TypeScript does
not, each refused rather than left to surface as a stray runtime error: a
`bigint` outside the i64 range, a delivery string the union cannot spell, and
a leading U+FEFF, which `TextDecoder` deletes by default and
`Encoding.UTF8.GetString` keeps. The last one is a real divergence the test
caught; the decoder now sets `ignoreBOM`. U+FEFF is not whitespace to .NET,
so such an identity passes the transport contract and reaches the wire.

There was no C# test for this codec before; this is also its first.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-16 19:20:41 +02:00
commit 6cbc73fb17
7 changed files with 1415 additions and 0 deletions

View file

@ -0,0 +1,177 @@
{
"frames": [
{
"label": "reliable-ordered, small payload",
"fields": {
"channelId": "aetheria.zone-1",
"schemaId": "cultmesh.realtime.v1",
"bodyId": "body-7",
"producerEpoch": 1,
"sequence": 2,
"delivery": "reliable-ordered",
"payload": "AH+A/yo="
},
"encoding": "Q1NUMQABAAAAAAAAAAIAAAAAAAAADwAUAAYABQAAACUAAAABAGFldGhlcmlhLnpvbmUtMWN1bHRtZXNoLnJlYWx0aW1lLnYxYm9keS03AH+A/yo=",
"encodedLength": 83,
"sha256OfEncoding": "d04539b99790560e5e570208d92d3ac25f85909a36bfeb190c2080288cc9f1d4"
},
{
"label": "latest-only, small payload",
"fields": {
"channelId": "aetheria.zone-1",
"schemaId": "cultmesh.realtime.v1",
"bodyId": "body-7",
"producerEpoch": 3,
"sequence": 4,
"delivery": "latest-only",
"payload": "AQID"
},
"encoding": "Q1NUMQEDAAAAAAAAAAQAAAAAAAAADwAUAAYAAwAAACUAAAABAGFldGhlcmlhLnpvbmUtMWN1bHRtZXNoLnJlYWx0aW1lLnYxYm9keS03AQID",
"encodedLength": 81,
"sha256OfEncoding": "2c875718cf4968979f3cd4083ba2b279e8c03815ad3447c66037ee4530b2814a"
},
{
"label": "unreliable, small payload",
"fields": {
"channelId": "aetheria.zone-1",
"schemaId": "cultmesh.realtime.v1",
"bodyId": "body-7",
"producerEpoch": 5,
"sequence": 6,
"delivery": "unreliable",
"payload": "/g=="
},
"encoding": "Q1NUMQIFAAAAAAAAAAYAAAAAAAAADwAUAAYAAQAAACUAAAABAGFldGhlcmlhLnpvbmUtMWN1bHRtZXNoLnJlYWx0aW1lLnYxYm9keS03/g==",
"encodedLength": 79,
"sha256OfEncoding": "b932adf333a0ca73d3a9077e15cf9062070a3084a50a3a30c3baa53312d864b1"
},
{
"label": "empty payload",
"fields": {
"channelId": "aetheria.zone-1",
"schemaId": "cultmesh.realtime.v1",
"bodyId": "body-7",
"producerEpoch": 0,
"sequence": 0,
"delivery": "reliable-ordered",
"payload": ""
},
"encoding": "Q1NUMQAAAAAAAAAAAAAAAAAAAAAADwAUAAYAAAAAACUAAAABAGFldGhlcmlhLnpvbmUtMWN1bHRtZXNoLnJlYWx0aW1lLnYxYm9keS03",
"encodedLength": 78,
"sha256OfEncoding": "06c0362f2b395bf7855522190f6a59c45c46947ce7a9a4b8be115cf54a48f419"
},
{
"label": "multi-byte identities",
"fields": {
"channelId": "aetheria.zöne-∞",
"schemaId": "cultmesh.realtime.€1",
"bodyId": "bødy-\uD83D\uDD25",
"producerEpoch": 11,
"sequence": 12,
"delivery": "latest-only",
"payload": "cGF5bG9hZC3iiJ4="
},
"encoding": "Q1NUMQELAAAAAAAAAAwAAAAAAAAAEgAWAAoACwAAACUAAAABAGFldGhlcmlhLnrDtm5lLeKInmN1bHRtZXNoLnJlYWx0aW1lLuKCrDFiw7hkeS3wn5SlcGF5bG9hZC3iiJ4=",
"encodedLength": 98,
"sha256OfEncoding": "90c6ae8f1362d9e000aa57682612bb1d7606cabe2cd0c0969fdd07b816f44b1c"
},
{
"label": "epoch and sequence at long.MaxValue",
"fields": {
"channelId": "aetheria.zone-1",
"schemaId": "cultmesh.realtime.v1",
"bodyId": "body-7",
"producerEpoch": 9223372036854775807,
"sequence": 9223372036854775807,
"delivery": "unreliable",
"payload": "Wg=="
},
"encoding": "Q1NUMQL/////////f/////////9/DwAUAAYAAQAAACUAAAABAGFldGhlcmlhLnpvbmUtMWN1bHRtZXNoLnJlYWx0aW1lLnYxYm9keS03Wg==",
"encodedLength": 79,
"sha256OfEncoding": "208068a668b48dc1abde9b3d7f025e7f7b6de6c480faea25c1383b6de9fd37ca"
},
{
"label": "identities at exactly 65535 UTF-8 bytes",
"fields": {
"channelId": {
"repeat": "ä€",
"byteLength": 65535
},
"schemaId": {
"repeat": "ۊ",
"byteLength": 65535
},
"bodyId": {
"repeat": "ñ€",
"byteLength": 65535
},
"producerEpoch": 13,
"sequence": 14,
"delivery": "reliable-ordered",
"payload": "ESI="
},
"encoding": null,
"encodedLength": 196644,
"sha256OfEncoding": "e3c1a353b606e86b35169efb875e76349dcfcb2d036973ee3bbe3c601fbda3e1"
},
{
"label": "64 MiB payload",
"fields": {
"channelId": "aetheria.zone-1",
"schemaId": "cultmesh.realtime.v1",
"bodyId": "body-7",
"producerEpoch": 15,
"sequence": 16,
"delivery": "reliable-ordered",
"payload": {
"ramp": 67108864
}
},
"encoding": null,
"encodedLength": 67108942,
"sha256OfEncoding": "4d99183bdb450af854d87a81ba86a3a4c92ecc1b208675d916f1b75a9f1e7928"
}
],
"malformed": [
{
"label": "truncated header",
"encoding": "Q1NUMQABAAAAAAAAAAIAAAAAAAAADwAUAAYAAwAAACUAAAAB",
"message": "Realtime frame header is truncated."
},
{
"label": "wrong magic",
"encoding": "vFNUMQABAAAAAAAAAAIAAAAAAAAADwAUAAYAAwAAACUAAAABAGFldGhlcmlhLnpvbmUtMWN1bHRtZXNoLnJlYWx0aW1lLnYxYm9keS03CQkJ",
"message": "Realtime frame magic is invalid."
},
{
"label": "wire version 2",
"encoding": "Q1NUMQABAAAAAAAAAAIAAAAAAAAADwAUAAYAAwAAACUAAAACAGFldGhlcmlhLnpvbmUtMWN1bHRtZXNoLnJlYWx0aW1lLnYxYm9keS03CQkJ",
"message": "Realtime frame wire version is unsupported."
},
{
"label": "header size 36",
"encoding": "Q1NUMQABAAAAAAAAAAIAAAAAAAAADwAUAAYAAwAAACQAAAABAGFldGhlcmlhLnpvbmUtMWN1bHRtZXNoLnJlYWx0aW1lLnYxYm9keS03CQkJ",
"message": "Realtime frame wire version is unsupported."
},
{
"label": "delivery 3",
"encoding": "Q1NUMQMBAAAAAAAAAAIAAAAAAAAADwAUAAYAAwAAACUAAAABAGFldGhlcmlhLnpvbmUtMWN1bHRtZXNoLnJlYWx0aW1lLnYxYm9keS03CQkJ",
"message": "Realtime frame delivery mode is invalid."
},
{
"label": "delivery 255",
"encoding": "Q1NUMf8BAAAAAAAAAAIAAAAAAAAADwAUAAYAAwAAACUAAAABAGFldGhlcmlhLnpvbmUtMWN1bHRtZXNoLnJlYWx0aW1lLnYxYm9keS03CQkJ",
"message": "Realtime frame delivery mode is invalid."
},
{
"label": "payload length -1",
"encoding": "Q1NUMQABAAAAAAAAAAIAAAAAAAAADwAUAAYAAwAAgCUAAAABAGFldGhlcmlhLnpvbmUtMWN1bHRtZXNoLnJlYWx0aW1lLnYxYm9keS03CQkJ",
"message": "Realtime frame length is invalid."
},
{
"label": "length sum off by one",
"encoding": "Q1NUMQABAAAAAAAAAAIAAAAAAAAADwAUAAYAAwAAACUAAAABAGFldGhlcmlhLnpvbmUtMWN1bHRtZXNoLnJlYWx0aW1lLnYxYm9keS03CQkJAA==",
"message": "Realtime frame length is invalid."
}
]
}

View file

@ -0,0 +1,177 @@
{
"frames": [
{
"label": "ts reliable-ordered, small payload",
"fields": {
"channelId": "ts.zone-a",
"schemaId": "cultmesh.realtime.v1",
"bodyId": "ts-body-1",
"producerEpoch": 21,
"sequence": 22,
"delivery": "reliable-ordered",
"payload": "AAH+/w=="
},
"encoding": "Q1NUMQAVAAAAAAAAABYAAAAAAAAACQAUAAkABAAAACUAAAABAHRzLnpvbmUtYWN1bHRtZXNoLnJlYWx0aW1lLnYxdHMtYm9keS0xAAH+/w==",
"encodedLength": 79,
"sha256OfEncoding": "68c264a42ce34e540e9dbee31dab5b73dec98c767f0b44591ce6a477cd17fc04"
},
{
"label": "ts latest-only, small payload",
"fields": {
"channelId": "ts.zone-a",
"schemaId": "cultmesh.realtime.v1",
"bodyId": "ts-body-1",
"producerEpoch": 23,
"sequence": 24,
"delivery": "latest-only",
"payload": "f4A="
},
"encoding": "Q1NUMQEXAAAAAAAAABgAAAAAAAAACQAUAAkAAgAAACUAAAABAHRzLnpvbmUtYWN1bHRtZXNoLnJlYWx0aW1lLnYxdHMtYm9keS0xf4A=",
"encodedLength": 77,
"sha256OfEncoding": "3d4f49f4aa2c1f132c3a09ee83555c13e0bc036d636524a972e2829cf417b959"
},
{
"label": "ts unreliable, small payload",
"fields": {
"channelId": "ts.zone-a",
"schemaId": "cultmesh.realtime.v1",
"bodyId": "ts-body-1",
"producerEpoch": 25,
"sequence": 26,
"delivery": "unreliable",
"payload": "pQ=="
},
"encoding": "Q1NUMQIZAAAAAAAAABoAAAAAAAAACQAUAAkAAQAAACUAAAABAHRzLnpvbmUtYWN1bHRtZXNoLnJlYWx0aW1lLnYxdHMtYm9keS0xpQ==",
"encodedLength": 76,
"sha256OfEncoding": "2c2faec604850959d44ee65d87d2ea59462b667c5d0db8565a8c159d75301851"
},
{
"label": "ts empty payload",
"fields": {
"channelId": "ts.zone-a",
"schemaId": "cultmesh.realtime.v1",
"bodyId": "ts-body-1",
"producerEpoch": 0,
"sequence": 0,
"delivery": "latest-only",
"payload": ""
},
"encoding": "Q1NUMQEAAAAAAAAAAAAAAAAAAAAACQAUAAkAAAAAACUAAAABAHRzLnpvbmUtYWN1bHRtZXNoLnJlYWx0aW1lLnYxdHMtYm9keS0x",
"encodedLength": 75,
"sha256OfEncoding": "6d2a04b399f32db4086e728194249b0279330ffa5517cdd82228f691a0f10708"
},
{
"label": "ts multi-byte identities",
"fields": {
"channelId": "ts.zøne-∂",
"schemaId": "cultmesh.realtime.µ1",
"bodyId": "ts-bödy-🧊",
"producerEpoch": 27,
"sequence": 28,
"delivery": "unreliable",
"payload": "dHMtcGF5bG9hZC3iiII="
},
"encoding": "Q1NUMQIbAAAAAAAAABwAAAAAAAAADAAVAA0ADgAAACUAAAABAHRzLnrDuG5lLeKIgmN1bHRtZXNoLnJlYWx0aW1lLsK1MXRzLWLDtmR5LfCfp4p0cy1wYXlsb2FkLeKIgg==",
"encodedLength": 97,
"sha256OfEncoding": "d5d22458bd50a446c7bdce4e2598fe8e5e7bfac3646d8fcd7215363c7c5c8ca1"
},
{
"label": "ts epoch and sequence at long.MaxValue",
"fields": {
"channelId": "ts.zone-a",
"schemaId": "cultmesh.realtime.v1",
"bodyId": "ts-body-1",
"producerEpoch": 9223372036854775807,
"sequence": 9223372036854775807,
"delivery": "reliable-ordered",
"payload": "Bw=="
},
"encoding": "Q1NUMQD/////////f/////////9/CQAUAAkAAQAAACUAAAABAHRzLnpvbmUtYWN1bHRtZXNoLnJlYWx0aW1lLnYxdHMtYm9keS0xBw==",
"encodedLength": 76,
"sha256OfEncoding": "2abb67a876dc4ed006f33708b4c4dda55a90a6f95da7352749225195b10d45ba"
},
{
"label": "ts identities at exactly 65535 UTF-8 bytes",
"fields": {
"channelId": {
"repeat": "ü☃",
"byteLength": 65535
},
"schemaId": {
"repeat": "☃ü",
"byteLength": 65535
},
"bodyId": {
"repeat": "ç☃",
"byteLength": 65535
},
"producerEpoch": 29,
"sequence": 30,
"delivery": "latest-only",
"payload": "M0Q="
},
"encoding": null,
"encodedLength": 196644,
"sha256OfEncoding": "8bd4cd4c5232339f76b8e394eb93b66e8d14302398ecce2ae5bdb78070ef783a"
},
{
"label": "ts 64 MiB payload",
"fields": {
"channelId": "ts.zone-a",
"schemaId": "cultmesh.realtime.v1",
"bodyId": "ts-body-1",
"producerEpoch": 31,
"sequence": 32,
"delivery": "unreliable",
"payload": {
"ramp": 67108864
}
},
"encoding": null,
"encodedLength": 67108939,
"sha256OfEncoding": "f2c20e0b47a7681fbaeff6fcba024363542805de4cd95eeb7fa9f125ba646af0"
}
],
"malformed": [
{
"label": "ts truncated header",
"encoding": "Q1NUMQAVAAAAAAAAABYAAAAAAAAACQAUAAkABAAAACUAAAAB",
"message": "Realtime frame header is truncated."
},
{
"label": "ts wrong magic",
"encoding": "Q1OrMQAVAAAAAAAAABYAAAAAAAAACQAUAAkABAAAACUAAAABAHRzLnpvbmUtYWN1bHRtZXNoLnJlYWx0aW1lLnYxdHMtYm9keS0xAAH+/w==",
"message": "Realtime frame magic is invalid."
},
{
"label": "ts wire version 2",
"encoding": "Q1NUMQAVAAAAAAAAABYAAAAAAAAACQAUAAkABAAAACUAAAACAHRzLnpvbmUtYWN1bHRtZXNoLnJlYWx0aW1lLnYxdHMtYm9keS0xAAH+/w==",
"message": "Realtime frame wire version is unsupported."
},
{
"label": "ts header size 38",
"encoding": "Q1NUMQAVAAAAAAAAABYAAAAAAAAACQAUAAkABAAAACYAAAABAHRzLnpvbmUtYWN1bHRtZXNoLnJlYWx0aW1lLnYxdHMtYm9keS0xAAH+/w==",
"message": "Realtime frame wire version is unsupported."
},
{
"label": "ts delivery 3",
"encoding": "Q1NUMQMVAAAAAAAAABYAAAAAAAAACQAUAAkABAAAACUAAAABAHRzLnpvbmUtYWN1bHRtZXNoLnJlYWx0aW1lLnYxdHMtYm9keS0xAAH+/w==",
"message": "Realtime frame delivery mode is invalid."
},
{
"label": "ts delivery 128",
"encoding": "Q1NUMYAVAAAAAAAAABYAAAAAAAAACQAUAAkABAAAACUAAAABAHRzLnpvbmUtYWN1bHRtZXNoLnJlYWx0aW1lLnYxdHMtYm9keS0xAAH+/w==",
"message": "Realtime frame delivery mode is invalid."
},
{
"label": "ts payload length -1",
"encoding": "Q1NUMQAVAAAAAAAAABYAAAAAAAAACQAUAAkABAAAgCUAAAABAHRzLnpvbmUtYWN1bHRtZXNoLnJlYWx0aW1lLnYxdHMtYm9keS0xAAH+/w==",
"message": "Realtime frame length is invalid."
},
{
"label": "ts length sum off by one",
"encoding": "Q1NUMQAVAAAAAAAAABYAAAAAAAAACQAUAAkABAAAACUAAAABAHRzLnpvbmUtYWN1bHRtZXNoLnJlYWx0aW1lLnYxdHMtYm9keS0xAAH+/wA=",
"message": "Realtime frame length is invalid."
}
]
}

View file

@ -34,6 +34,7 @@ import {
type CultNetWireContract,
} from "cultnet-ts";
export * from "./realtime-wire";
export * from "./provider-session";
export * from "./provider-session-wire";
export * from "./provider-rudp-transport";

View file

@ -0,0 +1,178 @@
// The one TypeScript encoding of a CultMesh realtime frame.
//
// Rule for rule, this is `CultMeshRealtimeWireProtocol` in the C# reference
// (`src/GameCult.Mesh/CultMeshRealtimeWireProtocol.cs`), over the frame shape
// `CultMeshRealtimeTransports.cs` defines. QUIC stream framing stays
// transport-owned; this file owns only the typed frame bytes and never touches
// a socket.
//
// Byte parity is proven both ways, cross-process, by two committed vector files
// under `contracts/cultmesh/`: `realtime-frame-vectors.json`, which the C# test
// `CultMeshRealtimeWireProtocolTests` writes under CULTMESH_WRITE_VECTORS=1 and
// this package's test decodes and re-encodes, and
// `realtime-frame-vectors.ts-written.json`, which
// `scripts/write-cultmesh-realtime-frame-vectors.mjs` writes with this codec and
// the same C# test decodes. A fixture authored on one side alone would only
// agree with itself.
import { isNullOrWhiteSpaceCSharp } from "cultnet-ts";
/** `CultMeshRealtimeWireProtocol.ApplicationProtocolName`: the QUIC ALPN. */
export const CULTMESH_REALTIME_ALPN = "cultmesh-state-v1";
/** `ConnectionCloseCode`: ASCII "CULT". A QUIC error code is 62-bit, so bigint. */
export const CULTMESH_REALTIME_CONNECTION_CLOSE_CODE = 0x43554c54n;
/** `StreamAbortCode`: ASCII "STAT". */
export const CULTMESH_REALTIME_STREAM_ABORT_CODE = 0x53544154n;
/** `ReliableStream`: the stream kind carrying `reliable-ordered`. */
export const CULTMESH_REALTIME_RELIABLE_STREAM = 1;
/** `LatestOnlyStream`: the stream kind carrying `latest-only`. */
export const CULTMESH_REALTIME_LATEST_ONLY_STREAM = 2;
/** `MaximumFrameBytes`: the payload ceiling, 64 MiB. */
export const CULTMESH_REALTIME_MAX_PAYLOAD_BYTES = 64 * 1024 * 1024;
/** `MaximumEncodedFrameBytes`: the payload ceiling plus the header and three maximal identities. */
export const CULTMESH_REALTIME_MAX_ENCODED_FRAME_BYTES =
CULTMESH_REALTIME_MAX_PAYLOAD_BYTES + 37 + 3 * 0xffff;
/**
* `CultMeshRealtimeDelivery`. The wire byte is the C# enum's ordinal, so the
* order of these three is the wire contract, not a naming choice.
*/
export type CultMeshRealtimeDelivery = "reliable-ordered" | "latest-only" | "unreliable";
const DELIVERY_BYTES: readonly CultMeshRealtimeDelivery[] = ["reliable-ordered", "latest-only", "unreliable"];
/** `CultMeshRealtimeFrame`. `producerEpoch` and `sequence` are `long` in C#, which exceeds `Number.MAX_SAFE_INTEGER`. */
export interface CultMeshRealtimeFrame {
channelId: string;
schemaId: string;
bodyId: string;
producerEpoch: bigint;
sequence: bigint;
delivery: CultMeshRealtimeDelivery;
payload: Uint8Array;
}
const MAGIC = 0x31545343;
const FIXED_HEADER_BYTES = 37;
const WIRE_VERSION = 1;
const MAX_IDENTITY_BYTES = 0xffff;
const INT64_MIN = -(2n ** 63n);
const INT64_MAX = 2n ** 63n - 1n;
/**
* `CultMeshRealtimeFrame.Validate`. The C# reading of "non-empty" is
* `string.IsNullOrWhiteSpace`, whose whitespace set is not
* `String.prototype.trim`'s, so this borrows the one TypeScript implementation
* of that set from `cultnet-ts` rather than keeping a second reading here.
*
* The range check has no C# counterpart because `long` gives it for free; a
* `bigint` does not, and a `DataView` would otherwise throw a bare `RangeError`
* from inside the encoder.
*/
function validateFrame(frame: CultMeshRealtimeFrame): void {
if (isNullOrWhiteSpaceCSharp(frame.channelId)) throw new Error("Realtime channel identity is required.");
if (isNullOrWhiteSpaceCSharp(frame.schemaId)) throw new Error("Realtime schema identity is required.");
if (isNullOrWhiteSpaceCSharp(frame.bodyId)) throw new Error("Realtime body identity is required.");
if (frame.producerEpoch < 0n || frame.sequence < 0n) {
throw new Error("Realtime epoch and sequence must be non-negative.");
}
if (frame.producerEpoch > INT64_MAX || frame.sequence > INT64_MAX || frame.producerEpoch < INT64_MIN || frame.sequence < INT64_MIN) {
throw new Error("Realtime epoch and sequence must fit a 64-bit signed integer.");
}
}
/** `CultMeshRealtimeWireProtocol.EncodeFrame`. */
export function encodeRealtimeFrame(frame: CultMeshRealtimeFrame): Uint8Array {
validateFrame(frame);
const deliveryByte = DELIVERY_BYTES.indexOf(frame.delivery);
// C# reads an enum, which holds any byte; a TypeScript union does not, so the
// unspellable value is refused here with the message decode gives it.
if (deliveryByte < 0) throw new Error("Realtime frame delivery mode is invalid.");
const encoder = new TextEncoder();
const channel = encoder.encode(frame.channelId);
const schema = encoder.encode(frame.schemaId);
const body = encoder.encode(frame.bodyId);
if (channel.byteLength > MAX_IDENTITY_BYTES || schema.byteLength > MAX_IDENTITY_BYTES || body.byteLength > MAX_IDENTITY_BYTES) {
throw new Error("Realtime frame identity exceeds the QUIC wire limit.");
}
if (frame.payload.byteLength > CULTMESH_REALTIME_MAX_PAYLOAD_BYTES) {
throw new Error("Realtime frame payload exceeds the QUIC wire limit.");
}
const result = new Uint8Array(
FIXED_HEADER_BYTES + channel.byteLength + schema.byteLength + body.byteLength + frame.payload.byteLength,
);
const view = new DataView(result.buffer);
view.setUint32(0, MAGIC, true);
result[4] = deliveryByte;
view.setBigInt64(5, frame.producerEpoch, true);
view.setBigInt64(13, frame.sequence, true);
view.setUint16(21, channel.byteLength, true);
view.setUint16(23, schema.byteLength, true);
view.setUint16(25, body.byteLength, true);
view.setInt32(27, frame.payload.byteLength, true);
view.setInt32(31, FIXED_HEADER_BYTES, true);
view.setUint16(35, WIRE_VERSION, true);
let offset = FIXED_HEADER_BYTES;
result.set(channel, offset); offset += channel.byteLength;
result.set(schema, offset); offset += schema.byteLength;
result.set(body, offset); offset += body.byteLength;
result.set(frame.payload, offset);
return result;
}
/**
* `CultMeshRealtimeWireProtocol.DecodeFrame`, refusal for refusal and in the
* same order. Like the reference, it does not call `validateFrame`: a frame
* whose identities are blank decodes here exactly as it does in C#, and only
* encoding refuses it.
*
* One corner has no C# counterpart. The reference sums the lengths under
* `checked`, so a payload length near `int.MaxValue` throws `OverflowException`
* there rather than its length refusal; JavaScript numbers do not overflow, so
* the sum simply fails to match and the length refusal covers that case too.
* No encoder on either side can produce such a frame.
*/
export function decodeRealtimeFrame(bytes: Uint8Array): CultMeshRealtimeFrame {
if (bytes.byteLength < FIXED_HEADER_BYTES) throw new Error("Realtime frame header is truncated.");
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
if (view.getUint32(0, true) !== MAGIC) throw new Error("Realtime frame magic is invalid.");
if (view.getUint16(35, true) !== WIRE_VERSION || view.getInt32(31, true) !== FIXED_HEADER_BYTES) {
throw new Error("Realtime frame wire version is unsupported.");
}
const delivery = DELIVERY_BYTES[bytes[4]!];
if (delivery === undefined) throw new Error("Realtime frame delivery mode is invalid.");
const channelLength = view.getUint16(21, true);
const schemaLength = view.getUint16(23, true);
const bodyLength = view.getUint16(25, true);
const payloadLength = view.getInt32(27, true);
const expected = FIXED_HEADER_BYTES + channelLength + schemaLength + bodyLength + payloadLength;
if (payloadLength < 0 || expected !== bytes.byteLength) throw new Error("Realtime frame length is invalid.");
// `Encoding.UTF8.GetString` substitutes U+FFFD for invalid bytes rather than
// throwing, which is what a non-fatal `TextDecoder` does. `ignoreBOM` is not
// cosmetic: by default `TextDecoder` *deletes* a leading U+FEFF, and
// `GetString` keeps it, so an identity starting with a byte-order mark would
// decode to a different string on the two sides. U+FEFF is not whitespace to
// .NET either, so such an identity passes the transport contract and reaches
// the wire.
const decoder = new TextDecoder("utf-8", { ignoreBOM: true });
let offset = FIXED_HEADER_BYTES;
const channelId = decoder.decode(bytes.subarray(offset, offset + channelLength)); offset += channelLength;
const schemaId = decoder.decode(bytes.subarray(offset, offset + schemaLength)); offset += schemaLength;
const bodyId = decoder.decode(bytes.subarray(offset, offset + bodyLength)); offset += bodyLength;
return {
channelId,
schemaId,
bodyId,
producerEpoch: view.getBigInt64(5, true),
sequence: view.getBigInt64(13, true),
delivery,
payload: bytes.slice(offset, offset + payloadLength),
};
}

View file

@ -0,0 +1,344 @@
// The realtime frame codec, pinned rule by rule against the C# reference.
//
// The bytes themselves are pinned by two committed files under
// `contracts/cultmesh/`. `realtime-frame-vectors.json` is written by
// `CultMeshRealtimeWireProtocolTests.RealtimeFrameVectorsAreSharedWithTypeScript`
// under CULTMESH_WRITE_VECTORS=1: this side decodes it and re-encodes to the
// same bytes. `realtime-frame-vectors.ts-written.json` is written by
// `scripts/write-cultmesh-realtime-frame-vectors.mjs` with this codec and
// decoded by the C# reference, so parity is proven in both directions and in
// two processes. A fixture authored on one side alone would only agree with
// itself, which is what the authority vectors already taught.
import test from "node:test";
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import {
CULTMESH_REALTIME_ALPN,
CULTMESH_REALTIME_CONNECTION_CLOSE_CODE,
CULTMESH_REALTIME_LATEST_ONLY_STREAM,
CULTMESH_REALTIME_MAX_ENCODED_FRAME_BYTES,
CULTMESH_REALTIME_MAX_PAYLOAD_BYTES,
CULTMESH_REALTIME_RELIABLE_STREAM,
CULTMESH_REALTIME_STREAM_ABORT_CODE,
decodeRealtimeFrame,
encodeRealtimeFrame,
type CultMeshRealtimeDelivery,
type CultMeshRealtimeFrame,
} from "../src/realtime-wire";
const CONTRACTS = join(__dirname, "..", "..", "..", "..", "contracts", "cultmesh");
const CSHARP_VECTORS = join(CONTRACTS, "realtime-frame-vectors.json");
const TS_VECTORS = join(CONTRACTS, "realtime-frame-vectors.ts-written.json");
interface IdentityRule { repeat: string; byteLength: number }
interface RampRule { ramp: number }
interface VectorFields {
channelId: string | IdentityRule;
schemaId: string | IdentityRule;
bodyId: string | IdentityRule;
producerEpoch: number;
sequence: number;
delivery: CultMeshRealtimeDelivery;
payload: string | RampRule;
}
interface Vectors {
frames: {
label: string;
fields: VectorFields;
encoding: string | null;
encodedLength: number;
sha256OfEncoding: string;
}[];
malformed: { label: string; encoding: string; message: string }[];
}
/** The repeat unit written whole until the UTF-8 byte length is exactly `byteLength`. */
function repeatToByteLength(unit: string, byteLength: number): string {
const unitBytes = Buffer.byteLength(unit, "utf8");
assert.equal(byteLength % unitBytes, 0, `'${unit}' is ${unitBytes} UTF-8 bytes and does not divide ${byteLength}`);
return unit.repeat(byteLength / unitBytes);
}
/** The deterministic payload both runtimes build the same way. */
function ramp(length: number): Uint8Array {
const bytes = new Uint8Array(length);
for (let index = 0; index < length; index += 1) bytes[index] = index % 251;
return bytes;
}
function identity(value: string | IdentityRule): string {
return typeof value === "string" ? value : repeatToByteLength(value.repeat, value.byteLength);
}
function payload(value: string | RampRule): Uint8Array {
return typeof value === "string" ? new Uint8Array(Buffer.from(value, "base64")) : ramp(value.ramp);
}
function frameOf(fields: VectorFields): CultMeshRealtimeFrame {
return {
channelId: identity(fields.channelId),
schemaId: identity(fields.schemaId),
bodyId: identity(fields.bodyId),
// The C# `long` fields are written as JSON integers and can exceed the safe
// integer range, so they are read from the raw text, never through
// `JSON.parse`'s number.
producerEpoch: 0n,
sequence: 0n,
delivery: fields.delivery,
payload: payload(fields.payload),
};
}
// `JSON.parse` would round `long.MaxValue` to 9223372036854775808, which is not
// a valid i64 and not what either side encoded. The two i64 fields are lifted
// out of the raw text as bigints before the document is parsed.
function readVectors(path: string): { doc: Vectors; int64s: Map<string, { producerEpoch: bigint; sequence: bigint }> } {
const text = readFileSync(path, "utf8");
const int64s = new Map<string, { producerEpoch: bigint; sequence: bigint }>();
const pattern = /"label": "(?<label>(?:[^"\\]|\\.)*)"[\s\S]*?"producerEpoch": (?<epoch>-?\d+),\s*"sequence": (?<sequence>-?\d+),/g;
for (const match of text.matchAll(pattern)) {
const groups = match.groups!;
int64s.set(JSON.parse(`"${groups["label"]!}"`) as string, {
producerEpoch: BigInt(groups["epoch"]!),
sequence: BigInt(groups["sequence"]!),
});
}
return { doc: JSON.parse(text) as Vectors, int64s };
}
const sha256 = (bytes: Uint8Array) => createHash("sha256").update(bytes).digest("hex");
for (const [label, path] of [["C# reference", CSHARP_VECTORS], ["TypeScript-written", TS_VECTORS]] as const) {
test(`every ${label} frame vector decodes to its recorded fields and re-encodes to its recorded bytes`, () => {
const { doc, int64s } = readVectors(path);
assert.ok(doc.frames.length >= 8, `${label} carries ${doc.frames.length} frames`);
const seen = new Set<CultMeshRealtimeDelivery>();
for (const vector of doc.frames) {
const int64 = int64s.get(vector.label);
assert.ok(int64, `${vector.label}: no i64 pair was lifted from the text`);
const frame = { ...frameOf(vector.fields), ...int64 };
seen.add(frame.delivery);
// This side encodes the recorded fields to the recorded bytes.
const encoded = encodeRealtimeFrame(frame);
assert.equal(encoded.byteLength, vector.encodedLength, vector.label);
assert.equal(sha256(encoded), vector.sha256OfEncoding, vector.label);
// The two oversized cases carry no literal encoding; the digest above is
// the whole of their parity.
const recorded = vector.encoding === null ? encoded : new Uint8Array(Buffer.from(vector.encoding, "base64"));
assert.deepEqual(recorded, encoded, vector.label);
// And decodes those bytes back to the recorded fields.
const decoded = decodeRealtimeFrame(recorded);
assert.equal(decoded.channelId, frame.channelId, vector.label);
assert.equal(decoded.schemaId, frame.schemaId, vector.label);
assert.equal(decoded.bodyId, frame.bodyId, vector.label);
assert.equal(decoded.producerEpoch, frame.producerEpoch, vector.label);
assert.equal(decoded.sequence, frame.sequence, vector.label);
assert.equal(decoded.delivery, frame.delivery, vector.label);
assert.deepEqual(decoded.payload, frame.payload, vector.label);
}
// One vector per delivery mode, or a mode is unpinned.
assert.deepEqual([...seen].sort(), ["latest-only", "reliable-ordered", "unreliable"]);
});
test(`every ${label} malformed vector is refused with the C# reference's exact message`, () => {
const { doc } = readVectors(path);
assert.ok(doc.malformed.length >= 8, `${label} carries ${doc.malformed.length} malformed frames`);
for (const vector of doc.malformed) {
const bytes = new Uint8Array(Buffer.from(vector.encoding, "base64"));
assert.throws(
() => decodeRealtimeFrame(bytes),
(error: Error) => error.message === vector.message,
`${vector.label}: expected ${JSON.stringify(vector.message)}`,
);
}
// Every refusal the C# decoder can give is exercised by the file.
assert.deepEqual([...new Set(doc.malformed.map(vector => vector.message))].sort(), [
"Realtime frame delivery mode is invalid.",
"Realtime frame header is truncated.",
"Realtime frame length is invalid.",
"Realtime frame magic is invalid.",
"Realtime frame wire version is unsupported.",
]);
});
}
const sample = (overrides: Partial<CultMeshRealtimeFrame> = {}): CultMeshRealtimeFrame => ({
channelId: "aetheria.zone-1",
schemaId: "cultmesh.realtime.v1",
bodyId: "body-7",
producerEpoch: 1n,
sequence: 2n,
delivery: "reliable-ordered",
payload: Uint8Array.from([1, 2, 3]),
...overrides,
});
test("the wire constants are the C# reference's, including the ALPN and the two QUIC error codes", () => {
assert.equal(CULTMESH_REALTIME_ALPN, "cultmesh-state-v1");
assert.equal(CULTMESH_REALTIME_CONNECTION_CLOSE_CODE, 0x43554c54n);
assert.equal(CULTMESH_REALTIME_STREAM_ABORT_CODE, 0x53544154n);
assert.equal(CULTMESH_REALTIME_RELIABLE_STREAM, 1);
assert.equal(CULTMESH_REALTIME_LATEST_ONLY_STREAM, 2);
assert.equal(CULTMESH_REALTIME_MAX_PAYLOAD_BYTES, 64 * 1024 * 1024);
assert.equal(CULTMESH_REALTIME_MAX_ENCODED_FRAME_BYTES, 64 * 1024 * 1024 + 37 + 3 * 65535);
// The ALPN and the close codes are ASCII the C# side spells as numbers.
assert.equal(Buffer.from("CULT", "ascii").readUInt32BE(0), Number(CULTMESH_REALTIME_CONNECTION_CLOSE_CODE));
assert.equal(Buffer.from("STAT", "ascii").readUInt32BE(0), Number(CULTMESH_REALTIME_STREAM_ABORT_CODE));
});
// `CultMeshRealtimeWireProtocol.cs:37-54`, offset by offset. A vector proves the
// whole layout at once; this says which byte carries which field, so a swap of
// two same-width fields names itself.
test("the fixed header is 37 little-endian bytes in the reference's order", () => {
const encoded = encodeRealtimeFrame(sample({
channelId: "ch", schemaId: "sch", bodyId: "bdy",
producerEpoch: 0x0102030405060708n, sequence: 0x1112131415161718n,
delivery: "unreliable", payload: Uint8Array.from([0xaa]),
}));
const view = new DataView(encoded.buffer, encoded.byteOffset, encoded.byteLength);
assert.equal(view.getUint32(0, true), 0x31545343, "magic, little-endian");
assert.deepEqual([...encoded.subarray(0, 4)], [0x43, 0x53, 0x54, 0x31], "magic bytes as written");
assert.equal(encoded[4], 2, "delivery");
assert.equal(view.getBigInt64(5, true), 0x0102030405060708n, "producer epoch");
assert.equal(view.getBigInt64(13, true), 0x1112131415161718n, "sequence");
assert.equal(view.getUint16(21, true), 2, "channel length");
assert.equal(view.getUint16(23, true), 3, "schema length");
assert.equal(view.getUint16(25, true), 3, "body length");
assert.equal(view.getInt32(27, true), 1, "payload length");
assert.equal(view.getInt32(31, true), 37, "header size");
assert.equal(view.getUint16(35, true), 1, "wire version");
assert.equal(Buffer.from(encoded.subarray(37, 37 + 2 + 3 + 3)).toString("utf8"), "chschbdy", "identities in order");
assert.deepEqual([...encoded.subarray(45)], [0xaa], "payload last");
assert.equal(encoded.byteLength, 37 + 2 + 3 + 3 + 1);
});
test("the delivery byte is the C# enum ordinal: 0, 1, 2 in that order", () => {
const bytes: Record<CultMeshRealtimeDelivery, number> = { "reliable-ordered": 0, "latest-only": 1, "unreliable": 2 };
for (const [delivery, byte] of Object.entries(bytes) as [CultMeshRealtimeDelivery, number][]) {
const encoded = encodeRealtimeFrame(sample({ delivery }));
assert.equal(encoded[4], byte, delivery);
assert.equal(decodeRealtimeFrame(encoded).delivery, delivery, delivery);
}
assert.throws(
() => encodeRealtimeFrame(sample({ delivery: "at-most-once" as CultMeshRealtimeDelivery })),
/delivery mode is invalid/,
);
});
test("identities are UTF-8 and their length prefixes count bytes, not characters", () => {
const frame = sample({ channelId: "z\u00f6ne-\u221e", schemaId: "s", bodyId: "b" });
const encoded = encodeRealtimeFrame(frame);
const view = new DataView(encoded.buffer, encoded.byteOffset, encoded.byteLength);
assert.equal(frame.channelId.length, 6);
assert.equal(view.getUint16(21, true), Buffer.byteLength(frame.channelId, "utf8"));
assert.equal(view.getUint16(21, true), 9);
assert.equal(decodeRealtimeFrame(encoded).channelId, frame.channelId);
});
test("an identity of exactly 65535 UTF-8 bytes encodes and one byte more is refused", () => {
const wide = repeatToByteLength("\u00e4\u20ac", 65535);
assert.equal(Buffer.byteLength(wide, "utf8"), 65535);
assert.notEqual(wide.length, 65535);
const encoded = encodeRealtimeFrame(sample({ channelId: wide }));
assert.equal(new DataView(encoded.buffer, encoded.byteOffset).getUint16(21, true), 65535);
assert.equal(decodeRealtimeFrame(encoded).channelId, wide);
for (const field of ["channelId", "schemaId", "bodyId"] as const) {
assert.throws(
() => encodeRealtimeFrame(sample({ [field]: `${wide}a` })),
/identity exceeds the QUIC wire limit/,
field,
);
}
});
test("a payload at the 64 MiB ceiling encodes and one byte more is refused", () => {
const encoded = encodeRealtimeFrame(sample({ payload: ramp(CULTMESH_REALTIME_MAX_PAYLOAD_BYTES) }));
assert.equal(encoded.byteLength, 37 + 15 + 20 + 6 + CULTMESH_REALTIME_MAX_PAYLOAD_BYTES);
assert.equal(decodeRealtimeFrame(encoded).payload.byteLength, CULTMESH_REALTIME_MAX_PAYLOAD_BYTES);
assert.throws(
() => encodeRealtimeFrame(sample({ payload: new Uint8Array(CULTMESH_REALTIME_MAX_PAYLOAD_BYTES + 1) })),
/payload exceeds the QUIC wire limit/,
);
});
// `CultMeshRealtimeTransports.cs:29-39`, message for message. The blank strings
// are C#'s `IsNullOrWhiteSpace` set, not `String.prototype.trim`'s: U+0085 is
// whitespace to .NET and not to JavaScript, and U+FEFF the other way round.
test("encode refuses what the transport contract forbids, in the reference's words", () => {
for (const blank of ["", " ", "\t", "\u0085", "\u3000"]) {
assert.throws(() => encodeRealtimeFrame(sample({ channelId: blank })), /^Error: Realtime channel identity is required\.$/);
assert.throws(() => encodeRealtimeFrame(sample({ schemaId: blank })), /^Error: Realtime schema identity is required\.$/);
assert.throws(() => encodeRealtimeFrame(sample({ bodyId: blank })), /^Error: Realtime body identity is required\.$/);
}
// U+FEFF is not whitespace to .NET, so it is a legal one-character identity.
assert.equal(decodeRealtimeFrame(encodeRealtimeFrame(sample({ channelId: "\ufeff" }))).channelId, "\ufeff");
assert.throws(() => encodeRealtimeFrame(sample({ producerEpoch: -1n })), /epoch and sequence must be non-negative/);
assert.throws(() => encodeRealtimeFrame(sample({ sequence: -1n })), /epoch and sequence must be non-negative/);
// C# gets this bound from `long`; a bigint does not.
assert.throws(() => encodeRealtimeFrame(sample({ sequence: 2n ** 63n })), /must fit a 64-bit signed integer/);
assert.equal(encodeRealtimeFrame(sample({ sequence: 2n ** 63n - 1n })).byteLength, 37 + 15 + 20 + 6 + 3);
});
// `CultMeshRealtimeWireProtocol.cs:60-76`, refusal for refusal and in the same
// order: a frame that breaks two rules names the earlier one.
test("decode refuses every malformed frame the reference refuses, in the reference's order", () => {
const good = encodeRealtimeFrame(sample());
const spoil = (mutate: (bytes: Uint8Array) => void) => { const copy = Uint8Array.from(good); mutate(copy); return copy; };
const cases: readonly (readonly [string, Uint8Array, string])[] = [
["a header one byte short", good.subarray(0, 36), "Realtime frame header is truncated."],
["an empty buffer", new Uint8Array(0), "Realtime frame header is truncated."],
["a wrong magic", spoil(bytes => { bytes[3] = 0x32; }), "Realtime frame magic is invalid."],
["a big-endian magic", spoil(bytes => bytes.set([0x31, 0x54, 0x53, 0x43], 0)), "Realtime frame magic is invalid."],
["wire version 0", spoil(bytes => { bytes[35] = 0; }), "Realtime frame wire version is unsupported."],
["wire version 2", spoil(bytes => { bytes[35] = 2; }), "Realtime frame wire version is unsupported."],
["header size 36", spoil(bytes => { bytes[31] = 36; }), "Realtime frame wire version is unsupported."],
["header size 38", spoil(bytes => { bytes[31] = 38; }), "Realtime frame wire version is unsupported."],
["delivery 3", spoil(bytes => { bytes[4] = 3; }), "Realtime frame delivery mode is invalid."],
["delivery 255", spoil(bytes => { bytes[4] = 255; }), "Realtime frame delivery mode is invalid."],
["a negative payload length", spoil(bytes => { bytes[30] = 0x80; }), "Realtime frame length is invalid."],
["one byte too many", Uint8Array.from([...good, 0]), "Realtime frame length is invalid."],
["one byte too few", good.subarray(0, good.byteLength - 1), "Realtime frame length is invalid."],
["a channel length one too long", spoil(bytes => { bytes[21] += 1; }), "Realtime frame length is invalid."],
];
for (const [label, bytes, message] of cases) {
assert.throws(() => decodeRealtimeFrame(bytes), (error: Error) => error.message === message, label);
}
// Order: a frame whose magic and delivery are both wrong is refused for the
// magic, and one whose version and delivery are both wrong for the version.
assert.throws(
() => decodeRealtimeFrame(spoil(bytes => { bytes[3] = 0x32; bytes[4] = 9; })),
(error: Error) => error.message === "Realtime frame magic is invalid.",
);
assert.throws(
() => decodeRealtimeFrame(spoil(bytes => { bytes[35] = 3; bytes[4] = 9; })),
(error: Error) => error.message === "Realtime frame wire version is unsupported.",
);
// Like the reference, decode does not re-run the transport contract: a frame
// with a blank identity decodes rather than being refused.
const blank = spoil(bytes => bytes.set(new Uint8Array(15).fill(0x20), 37));
assert.equal(decodeRealtimeFrame(blank).channelId, " ".repeat(15));
});
test("decode reads exactly the viewed bytes of an offset view, not the buffer behind it", () => {
const good = encodeRealtimeFrame(sample({ payload: Uint8Array.from([9, 8, 7]) }));
const pool = new Uint8Array(good.byteLength + 64).fill(0xa5);
pool.set(good, 17);
const view = pool.subarray(17, 17 + good.byteLength);
assert.deepEqual(decodeRealtimeFrame(view).payload, Uint8Array.from([9, 8, 7]));
assert.equal(decodeRealtimeFrame(view).channelId, "aetheria.zone-1");
// And the decoded payload does not alias the frame it came from.
const decoded = decodeRealtimeFrame(good);
good[good.byteLength - 1] = 0;
assert.deepEqual(decoded.payload, Uint8Array.from([9, 8, 7]));
});
test("the codec touches no socket: no node: import in the source", () => {
const source = readFileSync(join(__dirname, "..", "..", "src", "realtime-wire.ts"), "utf8");
assert.doesNotMatch(source, /from "node:|require\("node:/);
});

View file

@ -0,0 +1,177 @@
// The TypeScript -> C# direction of the CultMesh realtime frame parity check.
//
// `contracts/cultmesh/realtime-frame-vectors.json` is written by the C#
// reference and decoded by TypeScript. This script writes the mirror file,
// `contracts/cultmesh/realtime-frame-vectors.ts-written.json`: the TypeScript
// codec (`packages/cultmesh-ts/src/realtime-wire.ts`) encodes the frames and
// builds the malformed bytes, and the C# test
// `CultMeshRealtimeWireProtocolTests.RealtimeFrameVectorsWrittenByTypeScriptDecodeHere`
// judges the committed file with the reference implementation only.
//
// The two files share one field shape, so each side reads both with one reader:
// an identity is a string or `{ repeat, byteLength }`, a payload is base64 or
// `{ ramp }`, and `encoding` is null when the frame is too large to sit in a
// committed contract file, where the digest carries the parity instead.
//
// npm run build --workspace packages/cultmesh-ts
// node scripts/write-cultmesh-realtime-frame-vectors.mjs
//
// Unlike the authority vectors, nothing here is randomised: rerunning on an
// unchanged codec rewrites the same bytes.
import { createHash } from "node:crypto";
import { existsSync, writeFileSync } from "node:fs";
import { createRequire } from "node:module";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const modulePath = join(repoRoot, "packages", "cultmesh-ts", "dist", "realtime-wire.js");
const outputPath = join(repoRoot, "contracts", "cultmesh", "realtime-frame-vectors.ts-written.json");
if (!existsSync(modulePath)) {
throw new Error(`${modulePath} is missing; run 'npm run build --workspace packages/cultmesh-ts' first.`);
}
const { encodeRealtimeFrame, decodeRealtimeFrame, CULTMESH_REALTIME_MAX_PAYLOAD_BYTES } =
createRequire(import.meta.url)(modulePath);
// Deliberately not the C# file's frames: different identities, different
// epochs, a different ramp length. Agreeing on a copy of the other side's
// inputs would prove less.
const WIDE_CHANNEL_UNIT = "\u00fc\u2603";
const WIDE_SCHEMA_UNIT = "\u2603\u00fc";
const WIDE_BODY_UNIT = "\u00e7\u2603";
const WIDE_IDENTITY_BYTES = 65535;
const INLINE_LIMIT = 4096;
const sha256 = bytes => createHash("sha256").update(bytes).digest("hex");
const base64 = bytes => Buffer.from(bytes).toString("base64");
function repeat(unit, byteLength) {
const unitBytes = Buffer.byteLength(unit, "utf8");
if (byteLength % unitBytes !== 0) {
throw new Error(`'${unit}' is ${unitBytes} UTF-8 bytes and does not divide ${byteLength}.`);
}
return unit.repeat(byteLength / unitBytes);
}
function ramp(length) {
const bytes = new Uint8Array(length);
for (let index = 0; index < length; index += 1) bytes[index] = index % 251;
return bytes;
}
const frames = [
{
label: "ts reliable-ordered, small payload",
frame: frame("ts.zone-a", "cultmesh.realtime.v1", "ts-body-1", 21n, 22n, "reliable-ordered", Uint8Array.from([0, 1, 254, 255])),
},
{
label: "ts latest-only, small payload",
frame: frame("ts.zone-a", "cultmesh.realtime.v1", "ts-body-1", 23n, 24n, "latest-only", Uint8Array.from([0x7f, 0x80])),
},
{
label: "ts unreliable, small payload",
frame: frame("ts.zone-a", "cultmesh.realtime.v1", "ts-body-1", 25n, 26n, "unreliable", Uint8Array.from([0xa5])),
},
{
label: "ts empty payload",
frame: frame("ts.zone-a", "cultmesh.realtime.v1", "ts-body-1", 0n, 0n, "latest-only", new Uint8Array(0)),
},
{
label: "ts multi-byte identities",
frame: frame(
"ts.z\u00f8ne-\u2202", "cultmesh.realtime.\u00b51", "ts-b\u00f6dy-\ud83e\uddca", 27n, 28n, "unreliable",
new TextEncoder().encode("ts-payload-\u2202"),
),
},
{
label: "ts epoch and sequence at long.MaxValue",
frame: frame("ts.zone-a", "cultmesh.realtime.v1", "ts-body-1", 2n ** 63n - 1n, 2n ** 63n - 1n, "reliable-ordered", Uint8Array.from([7])),
},
{
label: "ts identities at exactly 65535 UTF-8 bytes",
frame: frame(
repeat(WIDE_CHANNEL_UNIT, WIDE_IDENTITY_BYTES), repeat(WIDE_SCHEMA_UNIT, WIDE_IDENTITY_BYTES),
repeat(WIDE_BODY_UNIT, WIDE_IDENTITY_BYTES), 29n, 30n, "latest-only", Uint8Array.from([0x33, 0x44]),
),
identityRepeats: [WIDE_CHANNEL_UNIT, WIDE_SCHEMA_UNIT, WIDE_BODY_UNIT],
},
{
label: "ts 64 MiB payload",
frame: frame("ts.zone-a", "cultmesh.realtime.v1", "ts-body-1", 31n, 32n, "unreliable", ramp(CULTMESH_REALTIME_MAX_PAYLOAD_BYTES)),
rampPayload: true,
},
];
function frame(channelId, schemaId, bodyId, producerEpoch, sequence, delivery, payload) {
return { channelId, schemaId, bodyId, producerEpoch, sequence, delivery, payload };
}
const good = encodeRealtimeFrame(frames[0].frame);
const spoil = mutate => { const copy = Uint8Array.from(good); mutate(copy); return copy; };
const malformed = [
{ label: "ts truncated header", bytes: good.subarray(0, 36) },
{ label: "ts wrong magic", bytes: spoil(bytes => { bytes[2] ^= 0xff; }) },
{ label: "ts wire version 2", bytes: spoil(bytes => { bytes[35] = 2; }) },
{ label: "ts header size 38", bytes: spoil(bytes => { bytes[31] = 38; }) },
{ label: "ts delivery 3", bytes: spoil(bytes => { bytes[4] = 3; }) },
{ label: "ts delivery 128", bytes: spoil(bytes => { bytes[4] = 128; }) },
{ label: "ts payload length -1", bytes: spoil(bytes => { bytes[30] = 0x80; }) },
{ label: "ts length sum off by one", bytes: Uint8Array.from([...good, 0]) },
];
const recorded = frames.map(entry => {
const encoded = encodeRealtimeFrame(entry.frame);
// A file the TypeScript codec cannot read back is not evidence of anything.
const roundTrip = decodeRealtimeFrame(encoded);
for (const key of ["channelId", "schemaId", "bodyId", "producerEpoch", "sequence", "delivery"]) {
if (roundTrip[key] !== entry.frame[key]) throw new Error(`${entry.label}: ${key} did not round-trip`);
}
if (Buffer.compare(Buffer.from(roundTrip.payload), Buffer.from(entry.frame.payload)) !== 0) {
throw new Error(`${entry.label}: payload did not round-trip`);
}
const identity = (value, unit) =>
(unit === undefined ? value : { repeat: unit, byteLength: WIDE_IDENTITY_BYTES });
const [channelUnit, schemaUnit, bodyUnit] = entry.identityRepeats ?? [];
return {
label: entry.label,
fields: {
channelId: identity(entry.frame.channelId, channelUnit),
schemaId: identity(entry.frame.schemaId, schemaUnit),
bodyId: identity(entry.frame.bodyId, bodyUnit),
// JSON has one number type and these do not fit it; the C# reader takes
// them as `long`, so they are written as JSON integers, not strings.
producerEpoch: entry.frame.producerEpoch,
sequence: entry.frame.sequence,
delivery: entry.frame.delivery,
payload: entry.rampPayload ? { ramp: entry.frame.payload.byteLength } : base64(entry.frame.payload),
},
encoding: encoded.byteLength > INLINE_LIMIT ? null : base64(encoded),
encodedLength: encoded.byteLength,
sha256OfEncoding: sha256(encoded),
};
});
const refusals = malformed.map(entry => {
let message = "<no refusal>";
try {
decodeRealtimeFrame(entry.bytes);
} catch (error) {
message = error.message;
}
if (message === "<no refusal>") throw new Error(`${entry.label} was not refused`);
return { label: entry.label, encoding: base64(entry.bytes), message };
});
// `JSON.stringify` refuses a bigint, and the two i64 fields must land in the
// file as JSON integers for the C# reader. They are written through a placeholder
// and spliced back, rather than quoted as strings.
const bigints = new Map();
const text = JSON.stringify({ frames: recorded, malformed: refusals }, (_key, value) => {
if (typeof value !== "bigint") return value;
const token = `@@bigint:${bigints.size}@@`;
bigints.set(token, value.toString());
return token;
}, 2);
writeFileSync(outputPath, `${[...bigints].reduce((carry, [token, digits]) => carry.replace(`"${token}"`, digits), text)}\n`);
console.log(`wrote ${outputPath}`);

View file

@ -0,0 +1,361 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using FluentAssertions;
using NUnit.Framework;
namespace GameCult.Mesh.Tests
{
/// <summary>
/// The realtime frame codec, rule by rule, and the C# half of the
/// cross-runtime byte parity. <c>contracts/cultmesh/realtime-frame-vectors.json</c>
/// is written here under CULTMESH_WRITE_VECTORS=1 and decoded by
/// <c>packages/cultmesh-ts/test/realtime-wire.test.ts</c>;
/// <c>realtime-frame-vectors.ts-written.json</c> is written by
/// <c>scripts/write-cultmesh-realtime-frame-vectors.mjs</c> with the
/// TypeScript codec and judged here by the reference only. Both files carry
/// the same field shape: an identity is a string or a repeat rule, a payload
/// is base64 or a ramp rule, so one reader on each side serves both.
/// </summary>
[TestFixture]
public class CultMeshRealtimeWireProtocolTests
{
// The three identities that sit exactly on the u16 length prefix. Each
// repeat unit is five UTF-8 bytes over two characters, so 13,107 repeats
// are 65,535 bytes and 26,214 characters: byte length and character
// length differ, which is the point of the case. The vector records the
// rule and the digest of the whole encoding instead of 200 KB of literal
// identity text.
private const string WideChannelUnit = "\u00e4\u20ac";
private const string WideSchemaUnit = "\u20ac\u00e4";
private const string WideBodyUnit = "\u00f1\u20ac";
private const int WideIdentityBytes = 65535;
[Test]
public void RealtimeFrameVectorsAreSharedWithTypeScript()
{
var path = VectorPath("realtime-frame-vectors.json");
if (Environment.GetEnvironmentVariable("CULTMESH_WRITE_VECTORS") == "1")
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path, JsonSerializer.Serialize(new
{
frames = Frames().Select(Recorded).ToArray(),
malformed = Malformed().Select(entry => new
{
label = entry.Label,
encoding = Convert.ToBase64String(entry.Bytes),
message = Refusal(entry.Bytes)
}).ToArray()
}, new JsonSerializerOptions
{
WriteIndented = true,
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
}) + "\n");
}
using var vectors = JsonDocument.Parse(File.ReadAllText(path));
var root = vectors.RootElement;
var expected = Frames().ToDictionary(entry => entry.Label);
root.GetProperty("frames").GetArrayLength().Should().Be(expected.Count);
foreach (var element in root.GetProperty("frames").EnumerateArray())
{
var label = element.GetProperty("label").GetString()!;
expected.Should().ContainKey(label);
var frame = expected[label].Frame;
var encoded = CultMeshRealtimeWireProtocol.EncodeFrame(frame);
element.GetProperty("encodedLength").GetInt32().Should().Be(encoded.Length, label);
element.GetProperty("sha256OfEncoding").GetString().Should().Be(Sha256(encoded), label);
if (element.TryGetProperty("encoding", out var encoding) && encoding.ValueKind == JsonValueKind.String)
Convert.FromBase64String(encoding.GetString()!).Should().Equal(encoded, label);
// The recorded fields rebuild the frame, and it round-trips.
Same(Read(element.GetProperty("fields")), frame, label);
var decoded = CultMeshRealtimeWireProtocol.DecodeFrame(encoded);
Same(decoded, frame, label);
CultMeshRealtimeWireProtocol.EncodeFrame(decoded).Should().Equal(encoded, label);
}
var malformed = Malformed().ToDictionary(entry => entry.Label);
root.GetProperty("malformed").GetArrayLength().Should().Be(malformed.Count);
foreach (var element in root.GetProperty("malformed").EnumerateArray())
{
var label = element.GetProperty("label").GetString()!;
malformed.Should().ContainKey(label);
var bytes = Convert.FromBase64String(element.GetProperty("encoding").GetString()!);
bytes.Should().Equal(malformed[label].Bytes, label);
Refusal(bytes).Should().Be(element.GetProperty("message").GetString(), label);
}
}
// The other direction, cross-process: the TypeScript codec wrote these
// bytes and only the reference implementation judges them here.
[Test]
public void RealtimeFrameVectorsWrittenByTypeScriptDecodeHere()
{
var path = VectorPath("realtime-frame-vectors.ts-written.json");
using var vectors = JsonDocument.Parse(File.ReadAllText(path));
var frames = vectors.RootElement.GetProperty("frames");
frames.GetArrayLength().Should().BeGreaterThan(0);
foreach (var element in frames.EnumerateArray())
{
var label = element.GetProperty("label").GetString()!;
var frame = Read(element.GetProperty("fields"));
var mine = CultMeshRealtimeWireProtocol.EncodeFrame(frame);
// What TypeScript wrote is what this side writes, byte for byte.
element.GetProperty("encodedLength").GetInt32().Should().Be(mine.Length, label);
element.GetProperty("sha256OfEncoding").GetString().Should().Be(Sha256(mine), label);
var theirs = element.TryGetProperty("encoding", out var encoding) && encoding.ValueKind == JsonValueKind.String
? Convert.FromBase64String(encoding.GetString()!)
: mine;
theirs.Should().Equal(mine, label);
// And it decodes here to the fields TypeScript claims it encoded.
Same(CultMeshRealtimeWireProtocol.DecodeFrame(theirs), frame, label);
}
foreach (var element in vectors.RootElement.GetProperty("malformed").EnumerateArray())
{
var label = element.GetProperty("label").GetString()!;
var bytes = Convert.FromBase64String(element.GetProperty("encoding").GetString()!);
Refusal(bytes).Should().Be(element.GetProperty("message").GetString(), label);
}
}
[Test]
public void EncodeRefusesWhatTheTransportContractForbids()
{
Spoiled(frame => frame.ChannelId = " ").Should().Be("Realtime channel identity is required.");
Spoiled(frame => frame.SchemaId = "\t").Should().Be("Realtime schema identity is required.");
Spoiled(frame => frame.BodyId = "").Should().Be("Realtime body identity is required.");
Spoiled(frame => frame.ProducerEpoch = -1).Should().Be("Realtime epoch and sequence must be non-negative.");
Spoiled(frame => frame.Sequence = -1).Should().Be("Realtime epoch and sequence must be non-negative.");
Spoiled(frame => frame.ChannelId = new string('a', ushort.MaxValue + 1))
.Should().Be("Realtime frame identity exceeds the QUIC wire limit.");
Spoiled(frame => frame.Payload = new byte[CultMeshRealtimeWireProtocol.MaximumFrameBytes + 1])
.Should().Be("Realtime frame payload exceeds the QUIC wire limit.");
}
[Test]
public void TheWireConstantsAreTheOnesTypeScriptMirrors()
{
CultMeshRealtimeWireProtocol.ApplicationProtocolName.Should().Be("cultmesh-state-v1");
CultMeshRealtimeWireProtocol.ConnectionCloseCode.Should().Be(0x43554c54);
CultMeshRealtimeWireProtocol.StreamAbortCode.Should().Be(0x53544154);
CultMeshRealtimeWireProtocol.ReliableStream.Should().Be(1);
CultMeshRealtimeWireProtocol.LatestOnlyStream.Should().Be(2);
CultMeshRealtimeWireProtocol.MaximumFrameBytes.Should().Be(64 * 1024 * 1024);
CultMeshRealtimeWireProtocol.MaximumEncodedFrameBytes.Should().Be(
CultMeshRealtimeWireProtocol.MaximumFrameBytes + 37 + 3 * ushort.MaxValue);
((int)CultMeshRealtimeDelivery.ReliableOrdered).Should().Be(0);
((int)CultMeshRealtimeDelivery.LatestOnly).Should().Be(1);
((int)CultMeshRealtimeDelivery.Unreliable).Should().Be(2);
}
private static IEnumerable<(string Label, CultMeshRealtimeFrame Frame, bool Wide)> Frames()
{
yield return ("reliable-ordered, small payload", Frame(
"aetheria.zone-1", "cultmesh.realtime.v1", "body-7", 1, 2,
CultMeshRealtimeDelivery.ReliableOrdered, new byte[] { 0x00, 0x7f, 0x80, 0xff, 0x2a }), false);
yield return ("latest-only, small payload", Frame(
"aetheria.zone-1", "cultmesh.realtime.v1", "body-7", 3, 4,
CultMeshRealtimeDelivery.LatestOnly, new byte[] { 0x01, 0x02, 0x03 }), false);
yield return ("unreliable, small payload", Frame(
"aetheria.zone-1", "cultmesh.realtime.v1", "body-7", 5, 6,
CultMeshRealtimeDelivery.Unreliable, new byte[] { 0xfe }), false);
yield return ("empty payload", Frame(
"aetheria.zone-1", "cultmesh.realtime.v1", "body-7", 0, 0,
CultMeshRealtimeDelivery.ReliableOrdered, Array.Empty<byte>()), false);
yield return ("multi-byte identities", Frame(
"aetheria.z\u00f6ne-\u221e", "cultmesh.realtime.\u20ac1", "b\u00f8dy-\ud83d\udd25", 11, 12,
CultMeshRealtimeDelivery.LatestOnly, Encoding.UTF8.GetBytes("payload-\u221e")), false);
yield return ("epoch and sequence at long.MaxValue", Frame(
"aetheria.zone-1", "cultmesh.realtime.v1", "body-7", long.MaxValue, long.MaxValue,
CultMeshRealtimeDelivery.Unreliable, new byte[] { 0x5a }), false);
yield return ("identities at exactly 65535 UTF-8 bytes", Frame(
Repeat(WideChannelUnit, WideIdentityBytes), Repeat(WideSchemaUnit, WideIdentityBytes),
Repeat(WideBodyUnit, WideIdentityBytes), 13, 14,
CultMeshRealtimeDelivery.ReliableOrdered, new byte[] { 0x11, 0x22 }), true);
yield return ("64 MiB payload", Frame(
"aetheria.zone-1", "cultmesh.realtime.v1", "body-7", 15, 16,
CultMeshRealtimeDelivery.ReliableOrdered, Ramp(CultMeshRealtimeWireProtocol.MaximumFrameBytes)), false);
}
private static IEnumerable<(string Label, byte[] Bytes)> Malformed()
{
var good = CultMeshRealtimeWireProtocol.EncodeFrame(Frame(
"aetheria.zone-1", "cultmesh.realtime.v1", "body-7", 1, 2,
CultMeshRealtimeDelivery.ReliableOrdered, new byte[] { 9, 9, 9 }));
yield return ("truncated header", good.Take(36).ToArray());
yield return ("wrong magic", Spoil(good, bytes => bytes[0] ^= 0xff));
yield return ("wire version 2", Spoil(good, bytes => bytes[35] = 2));
yield return ("header size 36", Spoil(good, bytes => bytes[31] = 36));
yield return ("delivery 3", Spoil(good, bytes => bytes[4] = 3));
yield return ("delivery 255", Spoil(good, bytes => bytes[4] = 255));
yield return ("payload length -1", Spoil(good, bytes => bytes[30] = 0x80));
yield return ("length sum off by one", good.Concat(new byte[] { 0 }).ToArray());
}
private static object Recorded((string Label, CultMeshRealtimeFrame Frame, bool Wide) entry)
{
var encoded = CultMeshRealtimeWireProtocol.EncodeFrame(entry.Frame);
var frame = entry.Frame;
return new
{
label = entry.Label,
fields = new
{
channelId = entry.Wide ? Rule(WideChannelUnit, WideIdentityBytes) : frame.ChannelId,
schemaId = entry.Wide ? Rule(WideSchemaUnit, WideIdentityBytes) : frame.SchemaId,
bodyId = entry.Wide ? Rule(WideBodyUnit, WideIdentityBytes) : frame.BodyId,
producerEpoch = frame.ProducerEpoch,
sequence = frame.Sequence,
delivery = Name(frame.Delivery),
payload = frame.Payload.Length > 4096
? (object)new { ramp = frame.Payload.Length }
: Convert.ToBase64String(frame.Payload.ToArray())
},
// The two oversized cases would put megabytes into a committed
// contract file; both sides build them from the rules above and
// compare the digest of the whole encoding.
encoding = encoded.Length > 4096 ? null : Convert.ToBase64String(encoded),
encodedLength = encoded.Length,
sha256OfEncoding = Sha256(encoded)
};
}
private static object Rule(string unit, int byteLength) => new { repeat = unit, byteLength };
private static void Same(CultMeshRealtimeFrame actual, CultMeshRealtimeFrame expected, string label)
{
actual.ChannelId.Should().Be(expected.ChannelId, label);
actual.SchemaId.Should().Be(expected.SchemaId, label);
actual.BodyId.Should().Be(expected.BodyId, label);
actual.ProducerEpoch.Should().Be(expected.ProducerEpoch, label);
actual.Sequence.Should().Be(expected.Sequence, label);
actual.Delivery.Should().Be(expected.Delivery, label);
actual.Payload.Length.Should().Be(expected.Payload.Length, label);
actual.Payload.Span.SequenceEqual(expected.Payload.Span).Should().BeTrue(label);
}
private static CultMeshRealtimeFrame Read(JsonElement fields) => new()
{
ChannelId = Identity(fields.GetProperty("channelId")),
SchemaId = Identity(fields.GetProperty("schemaId")),
BodyId = Identity(fields.GetProperty("bodyId")),
ProducerEpoch = fields.GetProperty("producerEpoch").GetInt64(),
Sequence = fields.GetProperty("sequence").GetInt64(),
Delivery = Delivery(fields.GetProperty("delivery").GetString()!),
Payload = Payload(fields.GetProperty("payload"))
};
private static string Identity(JsonElement element) =>
element.ValueKind == JsonValueKind.String
? element.GetString()!
: Repeat(element.GetProperty("repeat").GetString()!, element.GetProperty("byteLength").GetInt32());
private static byte[] Payload(JsonElement element) =>
element.ValueKind == JsonValueKind.String
? Convert.FromBase64String(element.GetString()!)
: Ramp(element.GetProperty("ramp").GetInt32());
/// <summary>The repeat unit written whole until the UTF-8 byte length is exactly <paramref name="byteLength"/>.</summary>
private static string Repeat(string unit, int byteLength)
{
var unitBytes = Encoding.UTF8.GetByteCount(unit);
if (byteLength % unitBytes != 0)
throw new ArgumentException($"'{unit}' is {unitBytes} UTF-8 bytes and does not divide {byteLength}.");
return string.Concat(Enumerable.Repeat(unit, byteLength / unitBytes));
}
/// <summary>A deterministic payload both runtimes build the same way.</summary>
private static byte[] Ramp(int length)
{
var bytes = new byte[length];
for (var index = 0; index < length; index++) bytes[index] = (byte)(index % 251);
return bytes;
}
private static string Spoiled(Action<CultMeshRealtimeFrame> spoil)
{
var frame = Frame("c", "s", "b", 1, 2, CultMeshRealtimeDelivery.ReliableOrdered, new byte[] { 1 });
spoil(frame);
try
{
CultMeshRealtimeWireProtocol.EncodeFrame(frame);
return "<no refusal>";
}
catch (Exception error)
{
return error.Message;
}
}
private static string Refusal(byte[] bytes)
{
try
{
CultMeshRealtimeWireProtocol.DecodeFrame(bytes);
return "<no refusal>";
}
catch (Exception error)
{
return error.Message;
}
}
private static byte[] Spoil(byte[] bytes, Action<byte[]> spoil)
{
var copy = bytes.ToArray();
spoil(copy);
return copy;
}
private static CultMeshRealtimeFrame Frame(
string channelId, string schemaId, string bodyId, long producerEpoch, long sequence,
CultMeshRealtimeDelivery delivery, byte[] payload) =>
new()
{
ChannelId = channelId,
SchemaId = schemaId,
BodyId = bodyId,
ProducerEpoch = producerEpoch,
Sequence = sequence,
Delivery = delivery,
Payload = payload
};
private static string Name(CultMeshRealtimeDelivery delivery) => delivery switch
{
CultMeshRealtimeDelivery.ReliableOrdered => "reliable-ordered",
CultMeshRealtimeDelivery.LatestOnly => "latest-only",
CultMeshRealtimeDelivery.Unreliable => "unreliable",
_ => throw new ArgumentOutOfRangeException(nameof(delivery))
};
private static CultMeshRealtimeDelivery Delivery(string name) => name switch
{
"reliable-ordered" => CultMeshRealtimeDelivery.ReliableOrdered,
"latest-only" => CultMeshRealtimeDelivery.LatestOnly,
"unreliable" => CultMeshRealtimeDelivery.Unreliable,
_ => throw new ArgumentOutOfRangeException(nameof(name), name, "unknown delivery")
};
private static string Sha256(byte[] bytes) => Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
private static string VectorPath(string name) => Path.Combine(RepoRoot(), "contracts", "cultmesh", name);
private static string RepoRoot()
{
var directory = new DirectoryInfo(TestContext.CurrentContext.TestDirectory);
while (directory != null && !File.Exists(Path.Combine(directory.FullName, "CultLib.sln")))
directory = directory.Parent;
return directory?.FullName ?? throw new InvalidOperationException("CultLib.sln was not found above the test directory.");
}
}
}