From 6cbc73fb17bfe08259a0b61f658a1e324c56b665 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 16 Sep 2026 19:20:41 +0200 Subject: [PATCH] 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 --- .../cultmesh/realtime-frame-vectors.json | 177 +++++++++ .../realtime-frame-vectors.ts-written.json | 177 +++++++++ packages/cultmesh-ts/src/index.ts | 1 + packages/cultmesh-ts/src/realtime-wire.ts | 178 +++++++++ .../cultmesh-ts/test/realtime-wire.test.ts | 344 +++++++++++++++++ .../write-cultmesh-realtime-frame-vectors.mjs | 177 +++++++++ .../CultMeshRealtimeWireProtocolTests.cs | 361 ++++++++++++++++++ 7 files changed, 1415 insertions(+) create mode 100644 contracts/cultmesh/realtime-frame-vectors.json create mode 100644 contracts/cultmesh/realtime-frame-vectors.ts-written.json create mode 100644 packages/cultmesh-ts/src/realtime-wire.ts create mode 100644 packages/cultmesh-ts/test/realtime-wire.test.ts create mode 100644 scripts/write-cultmesh-realtime-frame-vectors.mjs create mode 100644 tests/GameCult.Mesh.Tests/CultMeshRealtimeWireProtocolTests.cs diff --git a/contracts/cultmesh/realtime-frame-vectors.json b/contracts/cultmesh/realtime-frame-vectors.json new file mode 100644 index 00000000..467c784d --- /dev/null +++ b/contracts/cultmesh/realtime-frame-vectors.json @@ -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." + } + ] +} diff --git a/contracts/cultmesh/realtime-frame-vectors.ts-written.json b/contracts/cultmesh/realtime-frame-vectors.ts-written.json new file mode 100644 index 00000000..0b987722 --- /dev/null +++ b/contracts/cultmesh/realtime-frame-vectors.ts-written.json @@ -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." + } + ] +} diff --git a/packages/cultmesh-ts/src/index.ts b/packages/cultmesh-ts/src/index.ts index e9fbb8be..ef532359 100644 --- a/packages/cultmesh-ts/src/index.ts +++ b/packages/cultmesh-ts/src/index.ts @@ -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"; diff --git a/packages/cultmesh-ts/src/realtime-wire.ts b/packages/cultmesh-ts/src/realtime-wire.ts new file mode 100644 index 00000000..091faf08 --- /dev/null +++ b/packages/cultmesh-ts/src/realtime-wire.ts @@ -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), + }; +} diff --git a/packages/cultmesh-ts/test/realtime-wire.test.ts b/packages/cultmesh-ts/test/realtime-wire.test.ts new file mode 100644 index 00000000..6a3c1a19 --- /dev/null +++ b/packages/cultmesh-ts/test/realtime-wire.test.ts @@ -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 } { + const text = readFileSync(path, "utf8"); + const int64s = new Map(); + const pattern = /"label": "(?