Discover browser providers through Odin

This commit is contained in:
Meta Vens 2026-08-18 00:34:44 +02:00
commit d563a1ac64
15 changed files with 567 additions and 75 deletions

View file

@ -10,13 +10,16 @@ writes. A renderer watches provider-owned records and invokes provider-owned
operations.
```ts
const odin = new CultMeshBrowserOdinRendezvous({
endpoints: ["wss://odin.example/verse"],
runtimeId: "counter-browser.discovery",
});
const mesh = await CultMeshBrowserClient.connect({
verseId: "sample.counter",
providerId: "sample.counter-provider",
runtimeId: "counter-browser",
rendezvous: {
resolve: async identity => discoverWebSocketRoute(identity),
},
rendezvous: odin,
});
const counter = await mesh.leaseRawDocument({
@ -27,8 +30,10 @@ const counter = await mesh.leaseRawDocument({
counter.watch(record => renderCounter(decodeCultNetPayload(record)));
```
The rendezvous port may call Odin, but application code does not own reconnect
or resubscription. The physical socket endpoint is a replaceable route, not the
`CultMeshBrowserOdinRendezvous` speaks the canonical CultNet Verse-catalog
messages to one or more configured Odin WebSocket endpoints. Application code
supplies stable identity; it does not own endpoint selection, reconnect, or
resubscription. The physical provider socket is a replaceable route, not the
provider identity.
The browser handshake carries authentication through the host application's

View file

@ -10,6 +10,8 @@ import {
type CultNetOperationResponseMessage,
type CultNetRawDocumentRecord,
type CultNetSnapshotResponseRawMessage,
type CultMeshVerseCatalogRequestMessage,
type CultMeshVerseCatalogResponseMessage,
} from "cultnet-ts/contracts";
export interface CultMeshBrowserIdentity {
@ -26,6 +28,16 @@ export interface CultMeshBrowserRendezvous {
resolve(identity: CultMeshBrowserIdentity): Promise<CultMeshBrowserRoute>;
}
export interface CultMeshBrowserOdinRendezvousOptions {
endpoints: readonly string[];
runtimeId: string;
transportVersion?: string;
timeoutMs?: number;
maxFrameBytes?: number;
createId?: () => string;
socketFactory?: (endpoint: string) => CultMeshBrowserSocket;
}
export interface CultMeshBrowserSocket {
binaryType: BinaryType;
readonly readyState: number;
@ -37,6 +49,107 @@ export interface CultMeshBrowserSocket {
close(code?: number, reason?: string): void;
}
/** Resolves stable Verse/provider identity through Odin's canonical CultNet Verse catalog. */
export class CultMeshBrowserOdinRendezvous implements CultMeshBrowserRendezvous {
#options: Required<Omit<CultMeshBrowserOdinRendezvousOptions, "transportVersion" | "socketFactory">> & {
transportVersion?: string;
socketFactory: (endpoint: string) => CultMeshBrowserSocket;
};
constructor(options: CultMeshBrowserOdinRendezvousOptions) {
requireText(options.runtimeId, "runtimeId");
const endpoints = [...new Set(options.endpoints.map(value => value.trim()).filter(Boolean))];
if (endpoints.length === 0) throw new Error("At least one Odin WebSocket endpoint is required.");
for (const endpoint of endpoints) requireWebSocketEndpoint(endpoint, "Odin rendezvous endpoint");
this.#options = {
...options,
endpoints,
timeoutMs: options.timeoutMs ?? 10_000,
maxFrameBytes: options.maxFrameBytes ?? 4 * 1024 * 1024,
createId: options.createId ?? (() => crypto.randomUUID()),
socketFactory: options.socketFactory ?? (endpoint => new WebSocket(endpoint)),
};
if (this.#options.timeoutMs <= 0) throw new Error("Odin rendezvous timeoutMs must be positive.");
if (this.#options.maxFrameBytes <= 0) throw new Error("Odin rendezvous maxFrameBytes must be positive.");
}
async resolve(identity: CultMeshBrowserIdentity): Promise<CultMeshBrowserRoute> {
requireText(identity.verseId, "verseId");
requireText(identity.providerId, "providerId");
const failures: Error[] = [];
for (const endpoint of this.#options.endpoints) {
try {
return await this.resolveFrom(endpoint, identity);
} catch (error) {
failures.push(error instanceof Error ? error : new Error(String(error)));
}
}
throw new AggregateError(
failures,
`Odin could not resolve Verse '${identity.verseId}' provider '${identity.providerId}'.`,
);
}
private resolveFrom(endpoint: string, identity: CultMeshBrowserIdentity): Promise<CultMeshBrowserRoute> {
const socket = this.#options.socketFactory(endpoint);
socket.binaryType = "arraybuffer";
const messageId = this.#options.createId();
const request: CultMeshVerseCatalogRequestMessage = {
schemaVersion: "cultmesh.verse_catalog_request.v0",
messageId,
verseIds: [identity.verseId],
...(this.#options.transportVersion ? { transportVersion: this.#options.transportVersion } : {}),
};
return new Promise<CultMeshBrowserRoute>((resolve, reject) => {
let settled = false;
const finish = (error?: Error, route?: CultMeshBrowserRoute) => {
if (settled) return;
settled = true;
clearTimeout(timer);
socket.onopen = null;
socket.onmessage = null;
socket.onerror = null;
socket.onclose = null;
socket.close(1000, error ? "Odin resolution failed" : "Odin resolution complete");
if (error) reject(error);
else resolve(route!);
};
const timer = setTimeout(
() => finish(new Error(`Odin resolution timed out at '${endpoint}'.`)),
this.#options.timeoutMs,
);
socket.onopen = () => {
try {
sendSocketMessage(socket, {
schemaVersion: "cultnet.hello.v0",
runtimeId: this.#options.runtimeId,
runtimeKind: "browser",
supportedMessageVersions: [
"cultmesh.verse_catalog_request.v0",
"cultmesh.verse_catalog_response.v0",
],
}, this.#options.maxFrameBytes);
sendSocketMessage(socket, request, this.#options.maxFrameBytes);
} catch (error) {
finish(error instanceof Error ? error : new Error(String(error)));
}
};
socket.onmessage = event => {
void decodeSocketMessage(event, this.#options.maxFrameBytes).then(message => {
if (message.schemaVersion === "cultnet.error.v0") {
finish(new Error(message.error));
return;
}
if (message.schemaVersion !== "cultmesh.verse_catalog_response.v0" || message.messageId !== messageId) return;
finish(undefined, selectOdinRoute(message, identity));
}).catch(error => finish(error instanceof Error ? error : new Error(String(error))));
};
socket.onerror = () => finish(new Error(`Odin WebSocket could not open '${endpoint}'.`));
socket.onclose = () => finish(new Error(`Odin WebSocket closed before resolving '${identity.verseId}'.`));
});
}
}
export interface CultMeshBrowserClientOptions extends CultMeshBrowserIdentity {
runtimeId: string;
rendezvous: CultMeshBrowserRendezvous;
@ -418,22 +531,17 @@ export class CultMeshBrowserClient implements AsyncDisposable {
private async receive(event: MessageEvent, generation: number): Promise<void> {
if (this.#disposed || generation !== this.#socketGeneration) return;
let payload: Uint8Array;
if (event.data instanceof ArrayBuffer) {
payload = new Uint8Array(event.data);
} else if (ArrayBuffer.isView(event.data)) {
payload = new Uint8Array(event.data.buffer, event.data.byteOffset, event.data.byteLength);
} else if (event.data instanceof Blob) {
payload = new Uint8Array(await event.data.arrayBuffer());
} else {
this.#socket?.close(1003, "CultNet requires binary WebSocket frames");
let message: CultNetMessage;
try {
message = await decodeSocketMessage(event, this.#options.maxFrameBytes);
} catch (error) {
const oversized = error instanceof Error && error.message.includes("exceeds");
this.#socket?.close(
oversized ? 1009 : 1003,
oversized ? "CultNet frame exceeds configured maximum" : "CultNet requires binary WebSocket frames",
);
return;
}
if (payload.byteLength > this.#options.maxFrameBytes) {
this.#socket?.close(1009, "CultNet frame exceeds configured maximum");
return;
}
const message = parseCultNetMessage(decode(payload));
switch (message.schemaVersion) {
case "cultnet.snapshot_response_raw.v0":
this.applySnapshot(message);
@ -540,6 +648,74 @@ function base64ToBytes(value: string): Uint8Array {
return Uint8Array.from(binary, character => character.charCodeAt(0));
}
function requireWebSocketEndpoint(value: string, field: string): URL {
let endpoint: URL;
try {
endpoint = new URL(value);
} catch {
throw new Error(`${field} '${value}' is not a valid URL.`);
}
if (endpoint.protocol !== "ws:" && endpoint.protocol !== "wss:") {
throw new Error(`${field} must use ws:// or wss://, got '${value}'.`);
}
return endpoint;
}
function sendSocketMessage(socket: CultMeshBrowserSocket, message: CultNetMessage, maxFrameBytes: number): void {
const payload = encode(encodeCultNetMessageForWire(message));
if (payload.byteLength > maxFrameBytes) {
throw new Error(`CultNet message exceeds the ${maxFrameBytes}-byte limit.`);
}
socket.send(payload);
}
async function decodeSocketMessage(event: MessageEvent, maxFrameBytes: number): Promise<CultNetMessage> {
let payload: Uint8Array;
if (event.data instanceof ArrayBuffer) {
payload = new Uint8Array(event.data);
} else if (ArrayBuffer.isView(event.data)) {
payload = new Uint8Array(event.data.buffer, event.data.byteOffset, event.data.byteLength);
} else if (event.data instanceof Blob) {
payload = new Uint8Array(await event.data.arrayBuffer());
} else {
throw new Error("CultNet requires binary WebSocket frames.");
}
if (payload.byteLength > maxFrameBytes) {
throw new Error(`CultNet frame exceeds the ${maxFrameBytes}-byte limit.`);
}
return parseCultNetMessage(decode(payload));
}
function selectOdinRoute(
response: CultMeshVerseCatalogResponseMessage,
identity: CultMeshBrowserIdentity,
): CultMeshBrowserRoute {
const matchingVerses = response.verses.filter(verse =>
verse.verseId === identity.verseId && verse.authorityRuntimeIds.includes(identity.providerId));
if (matchingVerses.length !== 1) {
throw new Error(
`Odin returned ${matchingVerses.length} routes for Verse '${identity.verseId}' provider '${identity.providerId}'.`,
);
}
const verse = matchingVerses[0];
const endpoints = verse.discoveryEndpoints.filter(endpoint => {
try {
requireWebSocketEndpoint(endpoint, "Odin provider route");
return true;
} catch {
return false;
}
});
if (endpoints.length === 0) {
throw new Error(`Odin advertised no browser-compatible route for '${identity.providerId}'.`);
}
return {
...identity,
endpoint: endpoints[0],
generation: [verse.compatibility.transportVersion, verse.compatibility.rulesHash, endpoints[0]].join(":"),
};
}
function requireText(value: string, field: string): void {
if (!value || value.trim().length === 0) throw new Error(`CultMesh browser ${field} is required.`);
}

View file

@ -13,12 +13,40 @@ import {
import {
CultMeshBrowserClient,
CultMeshBrowserOdinRendezvous,
decodeCultNetOperationPayload,
decodeCultNetPayload,
type CultMeshBrowserRoute,
type CultMeshBrowserSocket,
} from "../src/index.js";
test("Odin rendezvous resolves stable provider identity and observes route rotation", async () => {
const odin = new FakeOdin("ws://127.0.0.1:4050/mesh");
let id = 0;
const rendezvous = new CultMeshBrowserOdinRendezvous({
endpoints: ["ws://127.0.0.1:4040/odin"],
runtimeId: "browser-odin-test",
createId: () => `odin-${++id}`,
socketFactory: () => odin.open(),
});
assert.equal((await rendezvous.resolve({
verseId: "sample.counter",
providerId: "sample.counter-provider",
})).endpoint, "ws://127.0.0.1:4050/mesh");
odin.providerEndpoint = "ws://127.0.0.1:4060/mesh";
assert.equal((await rendezvous.resolve({
verseId: "sample.counter",
providerId: "sample.counter-provider",
})).endpoint, "ws://127.0.0.1:4060/mesh");
await assert.rejects(
rendezvous.resolve({ verseId: "sample.counter", providerId: "other-provider" }),
/could not resolve/,
);
});
test("browser client leases provider state, invokes an operation, and follows route replacement", async () => {
const first = new FakeProvider("ws://127.0.0.1:4101/mesh", 4);
const second = new FakeProvider("ws://127.0.0.1:4102/mesh", 9);
@ -252,6 +280,40 @@ class FakeProvider {
}
}
class FakeOdin {
providerEndpoint: string;
constructor(providerEndpoint: string) {
this.providerEndpoint = providerEndpoint;
}
open(): FakeSocket {
const socket = new FakeSocket(wire => {
const message = parseCultNetMessage(decode(wire));
if (message.schemaVersion !== "cultmesh.verse_catalog_request.v0") return;
socket.deliver({
schemaVersion: "cultmesh.verse_catalog_response.v0",
messageId: message.messageId,
verses: [{
verseId: "sample.counter",
displayName: "Counter",
authorityModel: "ServerAuthoritative",
compatibility: {
transportVersion: "cultmesh.v1",
rulesHash: "counter-v1",
compatibleVerseIds: [],
requiredPluginIds: [],
optionalPluginIds: [],
},
discoveryEndpoints: [this.providerEndpoint],
authorityRuntimeIds: ["sample.counter-provider"],
}],
});
}, () => undefined);
return socket;
}
}
class FakeSocket implements CultMeshBrowserSocket {
binaryType: BinaryType = "arraybuffer";
readyState = 0;

View file

@ -0,0 +1,14 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultmesh.verse-catalog-request.schema.json",
"title": "CultMesh Verse Catalog Request",
"type": "object",
"required": ["schemaVersion", "messageId"],
"additionalProperties": false,
"properties": {
"schemaVersion": { "const": "cultmesh.verse_catalog_request.v0" },
"messageId": { "type": "string", "minLength": 1 },
"verseIds": { "type": "array", "items": { "type": "string", "minLength": 1 }, "uniqueItems": true },
"transportVersion": { "type": "string", "minLength": 1 }
}
}

View file

@ -0,0 +1,42 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultmesh.verse-catalog-response.schema.json",
"title": "CultMesh Verse Catalog Response",
"type": "object",
"required": ["schemaVersion", "messageId", "verses"],
"additionalProperties": false,
"$defs": {
"compatibility": {
"type": "object",
"required": ["transportVersion", "rulesHash", "compatibleVerseIds", "requiredPluginIds", "optionalPluginIds"],
"additionalProperties": false,
"properties": {
"transportVersion": { "type": "string", "minLength": 1 },
"rulesHash": { "type": "string", "minLength": 1 },
"compatibleVerseIds": { "type": "array", "items": { "type": "string", "minLength": 1 }, "uniqueItems": true },
"requiredPluginIds": { "type": "array", "items": { "type": "string", "minLength": 1 }, "uniqueItems": true },
"optionalPluginIds": { "type": "array", "items": { "type": "string", "minLength": 1 }, "uniqueItems": true }
}
},
"verse": {
"type": "object",
"required": ["verseId", "displayName", "authorityModel", "compatibility", "discoveryEndpoints", "authorityRuntimeIds"],
"additionalProperties": false,
"properties": {
"verseId": { "type": "string", "minLength": 1 },
"displayName": { "type": "string", "minLength": 1 },
"authorityModel": { "type": "string", "minLength": 1 },
"compatibility": { "$ref": "#/$defs/compatibility" },
"discoveryEndpoints": { "type": "array", "items": { "type": "string", "minLength": 1 }, "uniqueItems": true },
"authorityRuntimeIds": { "type": "array", "items": { "type": "string", "minLength": 1 }, "uniqueItems": true },
"parentVerseId": { "type": "string", "minLength": 1 },
"description": { "type": "string" }
}
}
},
"properties": {
"schemaVersion": { "const": "cultmesh.verse_catalog_response.v0" },
"messageId": { "type": "string", "minLength": 1 },
"verses": { "type": "array", "items": { "$ref": "#/$defs/verse" } }
}
}

View file

@ -28,6 +28,8 @@ import shardCatalogRequestSchema from "../contracts/cultnet.shard-catalog-reques
import shardCatalogResponseSchema from "../contracts/cultnet.shard-catalog-response.schema.json";
import operationRequestSchema from "../contracts/cultnet.operation-request.schema.json";
import operationResponseSchema from "../contracts/cultnet.operation-response.schema.json";
import verseCatalogRequestSchema from "../contracts/cultmesh.verse-catalog-request.schema.json";
import verseCatalogResponseSchema from "../contracts/cultmesh.verse-catalog-response.schema.json";
import ghostlightAgentStateSchema from "../contracts/ghostlight.agent-state.schema.json";
export type CultNetWireContract = "cultnet.schema.v0" | "gamecult.networking.v0";
@ -55,7 +57,9 @@ export type CultNetSchemaVersion =
| "cultnet.shard_catalog_request.v0"
| "cultnet.shard_catalog_response.v0"
| "cultnet.operation_request.v0"
| "cultnet.operation_response.v0";
| "cultnet.operation_response.v0"
| "cultmesh.verse_catalog_request.v0"
| "cultmesh.verse_catalog_response.v0";
export type CultNetSchemaKind = "wire_message" | "document_payload" | "shared_contract";
export type CultNetRawPayloadEncoding = "messagepack";
@ -328,6 +332,38 @@ export interface CultNetOperationResponseMessage {
sourceRuntimeId?: string;
}
export interface CultMeshVerseCompatibilityMessage {
transportVersion: string;
rulesHash: string;
compatibleVerseIds: string[];
requiredPluginIds: string[];
optionalPluginIds: string[];
}
export interface CultMeshVerseDescriptorMessage {
verseId: string;
displayName: string;
authorityModel: string;
compatibility: CultMeshVerseCompatibilityMessage;
discoveryEndpoints: string[];
authorityRuntimeIds: string[];
parentVerseId?: string;
description?: string;
}
export interface CultMeshVerseCatalogRequestMessage {
schemaVersion: "cultmesh.verse_catalog_request.v0";
messageId: string;
verseIds?: string[];
transportVersion?: string;
}
export interface CultMeshVerseCatalogResponseMessage {
schemaVersion: "cultmesh.verse_catalog_response.v0";
messageId: string;
verses: CultMeshVerseDescriptorMessage[];
}
export interface GhostlightPressure {
pressure_id: string;
label: string;
@ -577,7 +613,9 @@ export type CultNetMessage =
| CultNetShardCatalogRequestMessage
| CultNetShardCatalogResponseMessage
| CultNetOperationRequestMessage
| CultNetOperationResponseMessage;
| CultNetOperationResponseMessage
| CultMeshVerseCatalogRequestMessage
| CultMeshVerseCatalogResponseMessage;
const ajv = new Ajv2020({
allErrors: true,
@ -608,6 +646,8 @@ const CULTNET_MESSAGE_SCHEMAS = [
shardCatalogResponseSchema,
operationRequestSchema,
operationResponseSchema,
verseCatalogRequestSchema,
verseCatalogResponseSchema,
] as const;
const cultNetValidators = new Map<CultNetSchemaVersion, ValidateFunction>();
@ -1142,6 +1182,16 @@ function normalizeCultNetOptionalNulls(
case "cultnet.operation_response.v0":
stripNullProperties(candidate, ["payloadEncoding", "diagnostics", "sourceRuntimeId"]);
return;
case "cultmesh.verse_catalog_request.v0":
stripNullProperties(candidate, ["verseIds", "transportVersion"]);
return;
case "cultmesh.verse_catalog_response.v0":
for (const verse of Array.isArray(candidate.verses) ? candidate.verses : []) {
if (verse && typeof verse === "object") {
stripNullProperties(verse as Record<string, unknown>, ["parentVerseId", "description"]);
}
}
return;
case "cultnet.schema_catalog_request.v0":
stripNullProperties(candidate, ["schemaIds", "kinds"]);
return;

View file

@ -58,6 +58,42 @@ import {
type InteropNote,
} from "./interop/cultnet-interop-shared";
test("CultNet validates the canonical CultMesh Verse catalog messages", () => {
const request = parseCultNetMessage({
schemaVersion: "cultmesh.verse_catalog_request.v0",
messageId: "catalog-1",
verseIds: ["sample.counter"],
transportVersion: "cultmesh.v1",
});
assert.equal(request.schemaVersion, "cultmesh.verse_catalog_request.v0");
const response = parseCultNetMessage({
schemaVersion: "cultmesh.verse_catalog_response.v0",
messageId: "catalog-1",
verses: [{
verseId: "sample.counter",
displayName: "Counter",
authorityModel: "OperatorCluster",
compatibility: {
transportVersion: "cultmesh.v1",
rulesHash: "counter-v1",
compatibleVerseIds: [],
requiredPluginIds: [],
optionalPluginIds: [],
},
discoveryEndpoints: ["wss://provider.example/cultmesh"],
authorityRuntimeIds: ["sample.counter-provider"],
}],
});
assert.equal(response.schemaVersion, "cultmesh.verse_catalog_response.v0");
assert.equal(response.verses[0].authorityRuntimeIds[0], "sample.counter-provider");
assert.throws(() => parseCultNetMessage({
...response,
verses: [{ ...response.verses[0], compatibility: { ...response.verses[0].compatibility, rulesHash: "" } }],
}), /rulesHash/);
});
class FakeRudpReconnectTransport extends EventEmitter {
public connectCalls = 0;
public closeCalls = 0;