diff --git a/src/hermodr-daemon.cjs b/src/hermodr-daemon.cjs index 21c1164..3efed86 100644 --- a/src/hermodr-daemon.cjs +++ b/src/hermodr-daemon.cjs @@ -9,8 +9,7 @@ const path = require("path"); const { defineOdinDocuments } = require("./odin/documents.cjs"); const { createIdunnRudpHealthPublisher, publishIdunnRudpHealth } = require("./odin/idunn-rudp.cjs"); const { parseArgs } = require("./odin/utils.cjs"); -const { OdinLivePublicationSource } = require("./odin/live-publication-source.cjs"); -const { createProviderSessionIngress } = require("./odin/provider-session-ingress.cjs"); +const { ProviderSubscriptionSource } = require("./hermodr-provider-subscription.cjs"); const { HermodrStateStreamRegistry } = require("./hermodr-state-stream.cjs"); const repoRoot = path.resolve(__dirname, ".."); @@ -28,9 +27,8 @@ const cultCacheRequire = createRequire(resolveCultCachePackagePath()); const cultMeshRequire = createRequire(resolveCultMeshPackagePath()); const { defineDocumentType } = cultCacheRequire(resolveCultCacheRuntimePath()); const cultMeshRuntime = cultMeshRequire(resolveCultMeshRuntimePath()); -const { CultMesh, CultMeshProviderSessionBroker, decodeProviderConnectEvidence } = cultMeshRuntime; +const { CultMesh } = cultMeshRuntime; const { decode: decodeMessagePack } = cultMeshRequire("@msgpack/msgpack"); -const { CultNetDocumentRegistry } = cultMeshRequire("cultnet-ts"); const documents = defineOdinDocuments(defineDocumentType); const odinDocumentDefinitions = Object.values(documents).filter(Boolean); @@ -61,18 +59,19 @@ async function main() { return; } - const livePublicationSource = new OdinLivePublicationSource(payload => decodeMessagePack(bufferFromPayload(payload))); - const providerIngress = options.providerSessionBind ? createProviderSessionIngress({ - runtime: { CultMesh, CultMeshProviderSessionBroker, decodeProviderConnectEvidence }, - CultNetDocumentRegistry, - source: livePublicationSource, - runtimeId: "hermodr-provider-session-ingress", - ...parseBind(options.providerSessionBind), - sessionToken: options.providerSessionToken, - onError: error => console.error(`Hermodr provider-session ingress failed: ${error.message}`), - }) : null; - if (providerIngress) await providerIngress.start(); - const bridge = createHermodrBridge(options, providerIngress ? livePublicationSource : null); + // Providers own their state. Odin says where it lives. Hermodr resolves the + // provider through the catalog and reads that provider directly, the same way + // the command path already routes intent to a provider-advertised endpoint. + const livePublicationSource = new ProviderSubscriptionSource( + (providerId, schemaId, recordKey) => readProviderStateDocument(options, providerId, schemaId, recordKey), + { + pollIntervalMs: options.providerPollIntervalMs, + onError: (error, selection) => console.error( + `Hermodr provider read failed for ${selection.providerId} ${selection.schemaId}:${selection.recordKey}: ${error.message}`, + ), + }, + ); + const bridge = createHermodrBridge(options, livePublicationSource); const server = http.createServer((request, response) => { bridge.handle(request, response).catch((error) => { writeJson(response, error?.statusCode || 500, { @@ -112,7 +111,6 @@ async function main() { const shutdown = () => { if (healthTimer) clearInterval(healthTimer); server.close(() => {}); - providerIngress?.close(); closeProviderRudpPeers(); }; process.once("SIGINT", shutdown); @@ -141,8 +139,10 @@ function parseOptions(argv) { process.env.HERMODR_PROVIDER_CATALOG_KEYS, defaultProviderCatalogKeys, ), - providerSessionBind: stringOption(parsed.providerSessionBind || parsed["provider-session-bind"], process.env.HERMODR_PROVIDER_SESSION_BIND || ""), - providerSessionToken: stringOption(parsed.providerSessionToken || parsed["provider-session-token"], process.env.HERMODR_PROVIDER_SESSION_TOKEN || ""), + providerPollIntervalMs: Math.max(250, numberOption( + parsed.providerPollIntervalMs || parsed["provider-poll-interval-ms"], + process.env.HERMODR_PROVIDER_POLL_INTERVAL_MS || 2_000, + )), sleipnirProviderId: stringOption(parsed.sleipnirProviderId, process.env.HERMODR_SLEIPNIR_PROVIDER_ID || "sleipnir.input-mirror.starfire"), idunnRudpHealth: idunnRudpHealthOptions(parsed), idunnHealthIntervalMs: Math.max(1_000, numberOption( @@ -182,6 +182,13 @@ function rejectRemovedOptions(options) { "aetheriaCommandRudp", "hermodrCommandStorePath", "odinCachePath", + // parseArgs keys options exactly as typed, so both spellings are reachable + // and both must fail. Hermodr no longer accepts provider publications; it + // reads providers through the routes Odin advertises. + "providerSessionBind", + "provider-session-bind", + "providerSessionToken", + "provider-session-token", ]; for (const option of removed) { if (Object.hasOwn(options.raw, option)) { @@ -201,6 +208,8 @@ function rejectRemovedOptions(options) { "HERMODR_AETHERIA_COMMAND_RUDP", "HERMODR_ODIN_CULTMESH_STORE", "ODIN_CULTMESH_STORE", + "HERMODR_PROVIDER_SESSION_BIND", + "HERMODR_PROVIDER_SESSION_TOKEN", ]; for (const name of removedEnv) { if (process.env[name]) { @@ -354,11 +363,6 @@ function openStateEventStream(request, response, registry, selection) { response.once("close", release); } -function parseBind(value) { - const parsed = new URL(String(value).includes("://") ? value : `rudp://${value}`); - return { bindHost: parsed.hostname, bindPort: Number(parsed.port) }; -} - async function readCatalog(options) { const providerSnapshots = []; for (let attempt = 0; attempt < 3; attempt += 1) { @@ -933,6 +937,70 @@ function findProviderCommandRoute(catalog, providerId) { return ""; } +// Provider state routes change far more slowly than state does, and resolving +// one costs a round of Odin catalog reads. Cache the route, not the state. +const providerStateRoutes = new Map(); +const PROVIDER_ROUTE_TTL_MS = 30_000; + +async function resolveProviderStateEndpoint(options, providerId) { + const cached = providerStateRoutes.get(providerId); + if (cached && cached.expiresAt > Date.now()) return cached.endpoint; + + const catalog = await readCatalog(options); + const endpoint = findProviderStateEndpoint(catalog, providerId); + if (!endpoint) { + throw new Error(`Odin advertises no reachable state route for provider ${providerId}.`); + } + providerStateRoutes.set(providerId, { endpoint, expiresAt: Date.now() + PROVIDER_ROUTE_TTL_MS }); + return endpoint; +} + +function findProviderStateEndpoint(catalog, providerId) { + const normalized = String(providerId || "").trim(); + const provider = (catalog.providers || []).find((candidate) => candidate.id === normalized) + || (catalog.providers || []).find((candidate) => candidate.id.includes(normalized) || normalized.includes(candidate.id)); + if (!provider) return ""; + + const endpoints = [...(provider.endpoints || []), ...(provider.routes || [])]; + const stateEndpoint = endpoints.find((endpoint) => { + const role = [endpoint.id, endpoint.role, ...(endpoint.tags || [])].join(" ").toLowerCase(); + return Boolean(endpoint.address) && /state|document|surface/.test(role); + }); + const anyEndpoint = endpoints.find((endpoint) => Boolean(endpoint.address)); + const address = stateEndpoint?.address || anyEndpoint?.address || provider.cultMeshAddress; + if (!address) return ""; + return String(address).startsWith("rudp://") ? String(address) : `rudp://${address}`; +} + +// The read behind the provider subscription. Odin says where; the provider +// answers with what. Hermodr does not cache the answer as truth: the +// subscription source owns lifecycle, and this returns null for absence rather +// than throwing, so a missing document reads as withdrawal while a transport +// failure propagates as an error and is not mistaken for one. +async function readProviderStateDocument(options, providerId, schemaId, recordKey) { + const endpoint = await resolveProviderStateEndpoint(options, providerId); + const peer = await getProviderRudpPeer(endpoint); + try { + const document = await requestCultNetRawSnapshotDocument(peer, schemaId, recordKey, { + timeoutMs: 4_000, + messageIdPrefix: "hermodr-provider-state", + }); + if (!document) return null; + return decodeMessagePack(bufferFromPayload(document.payload)); + } catch (error) { + if (/did not return/.test(String(error?.message || ""))) { + // The provider answered and does not hold this document. That is absence, + // not failure. + return null; + } + // The peer may be wedged. Drop it so the next poll reconnects, and let the + // subscription source treat this as a failed read rather than a withdrawal. + await dropProviderRudpPeer(endpoint); + providerStateRoutes.delete(providerId); + throw error; + } +} + function normalizeProviderAdvertisement(value, recordKey) { const providerId = value?.providerId || value?.provider?.id || value?.id || recordKey; if (!providerId) { @@ -1435,10 +1503,14 @@ function printUsage() { console.log(`Usage: node src/hermodr-daemon.cjs [--host 127.0.0.1] [--port 8798] [--odin-cultmesh-uri cultmesh://odin/rendezvous/provider-catalog] -Hermodr is a browser lowering adapter over Odin/CultMesh state. It does not own -provider discovery or daemon state. Live Eve state requires ---provider-session-bind plus HERMODR_PROVIDER_SESSION_TOKEN and a CULTLIB_ROOT -pointing at the CultLib reliability branch. +Hermodr is a browser lowering adapter. It owns no provider discovery and no +daemon state. Odin advertises where a provider's state lives; Hermodr resolves +that route and reads the provider directly, then lowers the surface to browsers +and relays operator intent back as typed CultMesh command documents. + +Live Eve state needs a reachable Odin catalog and a CULTLIB_ROOT pointing at the +CultLib reliability branch. Poll cadence is --provider-poll-interval-ms +(default 2000). `); } diff --git a/src/hermodr-provider-subscription.cjs b/src/hermodr-provider-subscription.cjs new file mode 100644 index 0000000..9fe43f7 --- /dev/null +++ b/src/hermodr-provider-subscription.cjs @@ -0,0 +1,154 @@ +"use strict"; + +// Provider state subscription for the browser lowering. +// +// Hermodr previously ran its own provider-session ingress and accepted +// publications into a private store, which made it a required ingress rather +// than a bridge: a surface reached a browser only if its provider bound to +// Hermodr specifically. Providers own their state. Odin publishes where to find +// it. This source resolves a provider through the catalog and reads that +// provider directly, exactly as the command path already routes intent. +// +// It presents the same narrow port the previous store did - +// forProvider(id) -> { latest, watch, watchLifecycle } - so +// HermodrStateStreamRegistry, its sequence numbers, and its stale/reconnected +// transitions are untouched. +// +// readDocument is injected. That keeps the polling and lifecycle semantics +// testable without a live Verse, and keeps CultMesh transport out of this file. + +const DEFAULT_POLL_INTERVAL_MS = 2_000; + +class ProviderSubscriptionSource { + constructor(readDocument, options = {}) { + if (typeof readDocument !== "function") { + throw new Error("Provider subscription source requires a readDocument(providerId, schemaId, recordKey) function."); + } + this.readDocument = readDocument; + this.pollIntervalMs = Number.isFinite(options.pollIntervalMs) && options.pollIntervalMs > 0 + ? options.pollIntervalMs + : DEFAULT_POLL_INTERVAL_MS; + this.setInterval = options.setInterval || setInterval; + this.clearInterval = options.clearInterval || clearInterval; + this.onError = options.onError || (() => {}); + this.entries = new Map(); + this.sequence = 0; + } + + forProvider(providerId) { + return { + latest: (schemaId, recordKey) => this.latest(providerId, schemaId, recordKey), + watch: (schemaId, recordKey, callback) => this.watch(providerId, schemaId, recordKey, callback), + watchLifecycle: (schemaId, recordKey, callback) => this.watchLifecycle(providerId, schemaId, recordKey, callback), + }; + } + + async latest(providerId, schemaId, recordKey) { + const value = await this.readDocument(providerId, schemaId, recordKey); + if (value === undefined || value === null) { + throw new Error(`Provider ${providerId} published no ${schemaId}:${recordKey}.`); + } + return value; + } + + watch(providerId, schemaId, recordKey, callback) { + return this.watchLifecycle(providerId, schemaId, recordKey, (event) => { + if (event.kind !== "withdrawn") callback(event.value); + }); + } + + watchLifecycle(providerId, schemaId, recordKey, callback) { + const key = keyOf(providerId, schemaId, recordKey); + let entry = this.entries.get(key); + if (!entry) { + entry = { + providerId, + schemaId, + recordKey, + listeners: new Set(), + value: undefined, + present: false, + timer: null, + polling: false, + }; + this.entries.set(key, entry); + entry.timer = this.setInterval(() => { this.poll(key); }, this.pollIntervalMs); + if (typeof entry.timer?.unref === "function") entry.timer.unref(); + } + + entry.listeners.add(callback); + if (entry.present) { + callback({ kind: "snapshot", sequence: ++this.sequence, value: entry.value }); + } + // First listener on a cold entry still needs a value without waiting a full + // interval. Subsequent listeners piggyback on the shared poll. + this.poll(key); + + let released = false; + return () => { + if (released) return; + released = true; + entry.listeners.delete(callback); + if (entry.listeners.size === 0) { + this.clearInterval(entry.timer); + this.entries.delete(key); + } + }; + } + + async poll(key) { + const entry = this.entries.get(key); + if (!entry || entry.polling) return; + entry.polling = true; + try { + let value; + try { + value = await this.readDocument(entry.providerId, entry.schemaId, entry.recordKey); + } catch (error) { + // A read failure is not a withdrawal. The provider may be restarting, + // and claiming withdrawal would let a transport hiccup look like the + // provider retracting state it still holds. + this.onError(error, { providerId: entry.providerId, schemaId: entry.schemaId, recordKey: entry.recordKey }); + return; + } + + if (!this.entries.has(key)) return; + + const missing = value === undefined || value === null; + if (missing) { + if (entry.present) { + entry.present = false; + entry.value = undefined; + this.emit(entry, { kind: "withdrawn", sequence: ++this.sequence, reason: "withdrawn" }); + } + return; + } + + if (entry.present && equivalent(entry.value, value)) return; + + const kind = entry.present ? "update" : "snapshot"; + entry.present = true; + entry.value = value; + this.emit(entry, { kind, sequence: ++this.sequence, value }); + } finally { + entry.polling = false; + } + } + + emit(entry, event) { + for (const listener of entry.listeners) listener(event); + } +} + +function keyOf(providerId, schemaId, recordKey) { + if (!String(providerId || "").trim() || !String(schemaId || "").trim() || !String(recordKey || "").trim()) { + throw new Error("Provider subscription requires providerId, schemaId, and recordKey."); + } + return `${providerId}\u001f${schemaId}\u001f${recordKey}`; +} + +function equivalent(left, right) { + return JSON.stringify(left) === JSON.stringify(right); +} + +module.exports = { ProviderSubscriptionSource, DEFAULT_POLL_INTERVAL_MS }; diff --git a/src/odin/live-publication-source.cjs b/src/odin/live-publication-source.cjs deleted file mode 100644 index 73fecdb..0000000 --- a/src/odin/live-publication-source.cjs +++ /dev/null @@ -1,76 +0,0 @@ -"use strict"; - -class OdinLivePublicationSource { - constructor(decode) { - this.decode = decode; - this.values = new Map(); - this.listeners = new Map(); - this.sequence = 0; - } - - forProvider(providerId) { - return { - latest: (schemaId, recordKey) => this.latest(providerId, schemaId, recordKey), - watch: (schemaId, recordKey, callback) => this.watch(providerId, schemaId, recordKey, callback), - watchLifecycle: (schemaId, recordKey, callback) => this.watchLifecycle(providerId, schemaId, recordKey, callback), - }; - } - - async latest(providerId, schemaId, recordKey) { - const entry = this.values.get(keyOf(providerId, schemaId, recordKey)); - if (!entry) throw new Error(`No accepted live publication ${schemaId}:${recordKey}.`); - return entry.value; - } - - watch(providerId, schemaId, recordKey, callback) { - return this.watchLifecycle(providerId, schemaId, recordKey, event => { - if (event.kind !== "withdrawn") callback(event.value); - }); - } - - watchLifecycle(providerId, schemaId, recordKey, callback) { - const key = keyOf(providerId, schemaId, recordKey); - let listeners = this.listeners.get(key); - if (!listeners) this.listeners.set(key, listeners = new Set()); - listeners.add(callback); - const current = this.values.get(key); - if (current) callback({ kind: "snapshot", sequence: current.sequence, value: current.value }); - return () => { - listeners.delete(callback); - if (listeners.size === 0) this.listeners.delete(key); - }; - } - - accept(identity, document) { - const key = keyOf(identity.providerId, document.schemaId, document.recordKey); - const value = this.decode(document.payload); - const previous = this.values.get(key); - if (previous && equivalent(previous.value, value)) return; - const entry = { sequence: ++this.sequence, value }; - this.values.set(key, entry); - this.emit(key, { kind: previous ? "update" : "snapshot", ...entry }); - } - - withdraw(identity, document, reason = "withdrawn") { - const key = keyOf(identity.providerId, document.schemaId, document.recordKey); - if (!this.values.delete(key)) return; - this.emit(key, { kind: "withdrawn", sequence: ++this.sequence, reason }); - } - - emit(key, event) { - for (const listener of this.listeners.get(key) ?? []) listener(event); - } -} - -function keyOf(providerId, schemaId, recordKey) { - if (!String(providerId || "").trim() || !String(schemaId || "").trim() || !String(recordKey || "").trim()) { - throw new Error("Live publication source requires providerId, schemaId, and recordKey."); - } - return `${providerId}\u001f${schemaId}\u001f${recordKey}`; -} - -function equivalent(left, right) { - return JSON.stringify(left) === JSON.stringify(right); -} - -module.exports = { OdinLivePublicationSource }; diff --git a/src/odin/provider-session-ingress.cjs b/src/odin/provider-session-ingress.cjs deleted file mode 100644 index 21766fa..0000000 --- a/src/odin/provider-session-ingress.cjs +++ /dev/null @@ -1,38 +0,0 @@ -"use strict"; - -function createProviderSessionIngress(options) { - const { CultMesh, CultMeshProviderSessionBroker, decodeProviderConnectEvidence } = options.runtime; - const broker = new CultMeshProviderSessionBroker({ - runtimeId: options.runtimeId, - expiryPollMs: options.expiryPollMs, - authorizeRegistration: (_identity, session) => { - if (!options.sessionToken) return false; - try { - return decodeProviderConnectEvidence(session.connectPayload).sessionToken === options.sessionToken; - } catch { - return false; - } - }, - acceptPublication: (identity, _publicationId, document) => options.source.accept(identity, document), - deletePublications: (identity, publications) => { - for (const publication of publications) options.source.withdraw(identity, publication.document, "provider-session-ended"); - }, - acceptReceipt: options.acceptReceipt ?? (() => {}), - onError: options.onError, - }); - const server = CultMesh.createRudpDocumentServer(options.runtimeId, options.connectionId ?? 0x43554c54, { - bindHost: options.bindHost, - bindPort: options.bindPort, - documents: new options.CultNetDocumentRegistry(), - onOperationRequest: (request, session) => broker.handle(request, session), - onSessionClosed: session => broker.sessionClosed(session), - onError: options.onError, - }); - return { - get bind() { return server.bind; }, - start: () => server.start(), - close: () => { broker.close(); server.close(); }, - }; -} - -module.exports = { createProviderSessionIngress }; diff --git a/test/hermodr-live-publication.test.cjs b/test/hermodr-live-publication.test.cjs deleted file mode 100644 index 4ace9c2..0000000 --- a/test/hermodr-live-publication.test.cjs +++ /dev/null @@ -1,121 +0,0 @@ -"use strict"; - -const assert = require("node:assert/strict"); -const test = require("node:test"); -const path = require("node:path"); -const { createRequire } = require("node:module"); -const { OdinLivePublicationSource } = require("../src/odin/live-publication-source.cjs"); -const { createProviderSessionIngress } = require("../src/odin/provider-session-ingress.cjs"); -const { HermodrStateStreamRegistry } = require("../src/hermodr-state-stream.cjs"); -const { normalizeStateBindingSource } = require("../src/hermodr-daemon.cjs"); - -const selection = { - providerId: "voidbot.swarm", - sourceId: "voidbot.swarm_state_snapshot:voidbot-swarm", - schemaId: "voidbot.swarm_state_snapshot.v1", - recordKey: "voidbot-swarm", -}; -const identity = { providerId: selection.providerId }; - -test("accepted provider publications drive ordered SSE state without polling", async () => { - const source = new OdinLivePublicationSource(value => value); - const streams = new HermodrStateStreamRegistry(source); - const events = []; - streams.acquire(selection, event => events.push(event)); - - source.accept(identity, { schemaId: selection.schemaId, recordKey: selection.recordKey, payload: { summary: { globalHeat: 1.2 } } }); - source.accept(identity, { schemaId: selection.schemaId, recordKey: selection.recordKey, payload: { summary: { globalHeat: 0.15 } } }); - source.withdraw(identity, { schemaId: selection.schemaId, recordKey: selection.recordKey }, "lease-expired"); - source.accept(identity, { schemaId: selection.schemaId, recordKey: selection.recordKey, payload: { summary: { globalHeat: 0.2 } } }); - - assert.deepEqual(events.map(event => [event.type, event.sequence]), [["snapshot", 1], ["update", 2], ["stale", 3], ["reconnected", 4]]); - assert.equal(events[1].value.summary.globalHeat, 0.15); - assert.equal((await source.forProvider(selection.providerId).latest(selection.schemaId, selection.recordKey)).summary.globalHeat, 0.2); -}); - -test("replayed accepted state is delivered immediately to a new typed source subscriber", () => { - const source = new OdinLivePublicationSource(value => value); - source.accept(identity, { schemaId: selection.schemaId, recordKey: selection.recordKey, payload: { heat: 1.2 } }); - const events = []; - new HermodrStateStreamRegistry(source).acquire(selection, event => events.push(event)); - assert.deepEqual(events.map(event => event.type), ["snapshot"]); - assert.deepEqual(events[0].value, { heat: 1.2 }); -}); - -test("Eve source ids select record keys while pointer paths remain client-owned", () => { - assert.deepEqual(normalizeStateBindingSource({ ...selection, pointerId: "summary.globalHeat" }), selection); - assert.equal(normalizeStateBindingSource({ providerId: "voidbot.swarm", sourceId: "", schemaId: selection.schemaId }), null); -}); - -test("CultLib provider-session acceptance and withdrawal drive the live source", async () => { - const cultLibRoot = process.env.CULTLIB_ROOT; - assert.ok(cultLibRoot, "CULTLIB_ROOT must identify the CultLib reliability branch worktree"); - const requireCultMesh = createRequire(path.join(cultLibRoot, "packages", "cultmesh-ts", "package.json")); - const runtime = requireCultMesh("./dist/index.js"); - const { CultNetDocumentRegistry } = requireCultMesh("cultnet-ts"); - const { decode } = requireCultMesh("@msgpack/msgpack"); - const source = new OdinLivePublicationSource(payload => decode(payload)); - const ingress = createProviderSessionIngress({ - runtime, - CultNetDocumentRegistry, - source, - runtimeId: "odin-live-source-test", - bindHost: "127.0.0.1", - bindPort: 0, - sessionToken: "test-provider-authority", - }); - await ingress.start(); - const transport = new runtime.CultMeshProviderRudpTransport({ - endpoint: `rudp://127.0.0.1:${ingress.bind.port}`, - runtimeId: "voidbot-worker-test", - connectionId: 0x43554c54, - sessionToken: "test-provider-authority", - }); - const providerIdentity = { - providerId: selection.providerId, - serviceInstanceId: "voidbot-worker-test", - endpointId: "voidbot-worker-test.rudp", - verseId: "voidbot.local", - }; - const connection = await transport.connect(providerIdentity, new AbortController().signal); - try { - const lease = await connection.register({ identity: providerIdentity, requestedLeaseDurationMs: 5_000 }, new AbortController().signal); - await connection.publish({ publicationId: "swarm", schemaId: selection.schemaId, recordKey: selection.recordKey, value: { heat: 0.15 } }, lease); - assert.deepEqual(await source.forProvider(selection.providerId).latest(selection.schemaId, selection.recordKey), { heat: 0.15 }); - await connection.withdrawPublication("swarm", lease); - await assert.rejects(source.forProvider(selection.providerId).latest(selection.schemaId, selection.recordKey)); - } finally { - connection.close(); - ingress.close(); - } -}); - -test("provider lease expiry withdraws accepted state and emits stale", async () => { - const cultLibRoot = process.env.CULTLIB_ROOT; - const requireCultMesh = createRequire(path.join(cultLibRoot, "packages", "cultmesh-ts", "package.json")); - const runtime = requireCultMesh("./dist/index.js"); - const { CultNetDocumentRegistry } = requireCultMesh("cultnet-ts"); - const { decode } = requireCultMesh("@msgpack/msgpack"); - const source = new OdinLivePublicationSource(payload => decode(payload)); - const ingress = createProviderSessionIngress({ - runtime, CultNetDocumentRegistry, source, - runtimeId: "odin-expiry-test", bindHost: "127.0.0.1", bindPort: 0, - sessionToken: "expiry-token", expiryPollMs: 10, - }); - await ingress.start(); - const identity = { providerId: selection.providerId, serviceInstanceId: "expiry-worker", endpointId: "expiry.rudp", verseId: "voidbot.local" }; - const connection = await new runtime.CultMeshProviderRudpTransport({ - endpoint: `rudp://127.0.0.1:${ingress.bind.port}`, runtimeId: "expiry-worker", - connectionId: 0x43554c54, sessionToken: "expiry-token", - }).connect(identity, new AbortController().signal); - const events = []; - const release = new HermodrStateStreamRegistry(source).acquire(selection, event => events.push(event)); - try { - const lease = await connection.register({ identity, requestedLeaseDurationMs: 30 }, new AbortController().signal); - await connection.publish({ publicationId: "swarm", schemaId: selection.schemaId, recordKey: selection.recordKey, value: { heat: 1.2 } }, lease); - await new Promise(resolve => setTimeout(resolve, 80)); - assert.deepEqual(events.map(event => event.type), ["snapshot", "stale"]); - } finally { - release(); connection.close(); ingress.close(); - } -}); diff --git a/test/hermodr-provider-subscription.test.cjs b/test/hermodr-provider-subscription.test.cjs new file mode 100644 index 0000000..99e4c27 --- /dev/null +++ b/test/hermodr-provider-subscription.test.cjs @@ -0,0 +1,188 @@ +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { ProviderSubscriptionSource } = require("../src/hermodr-provider-subscription.cjs"); + +function harness(reads) { + const state = { value: reads.shift(), calls: 0, cleared: 0 }; + let tick = null; + const source = new ProviderSubscriptionSource( + async () => { + state.calls += 1; + if (state.value instanceof Error) throw state.value; + return state.value; + }, + { + setInterval: (fn) => { tick = fn; return { unref() {} }; }, + clearInterval: () => { state.cleared += 1; tick = null; }, + onError: () => {}, + }, + ); + return { + source, + state, + set: (value) => { state.value = value; }, + poll: async () => { if (tick) tick(); await flush(); }, + hasTimer: () => tick !== null, + }; +} + +async function flush() { + for (let i = 0; i < 4; i += 1) await new Promise((resolve) => setImmediate(resolve)); +} + +function collect(source, providerId = "erycina", schemaId = "gamecult.eve.surface_state.v1", recordKey = "erycina") { + const events = []; + const release = source.forProvider(providerId).watchLifecycle(schemaId, recordKey, (event) => events.push(event)); + return { events, release }; +} + +test("first watch emits a snapshot of the provider's document", async () => { + const h = harness([{ title: "Erycina" }]); + const { events } = collect(h.source); + await flush(); + + assert.equal(events.length, 1); + assert.equal(events[0].kind, "snapshot"); + assert.deepEqual(events[0].value, { title: "Erycina" }); +}); + +test("an unchanged document emits nothing further", async () => { + const h = harness([{ title: "Erycina" }]); + const { events } = collect(h.source); + await flush(); + await h.poll(); + await h.poll(); + + assert.equal(events.length, 1); +}); + +test("a changed document emits an update", async () => { + const h = harness([{ version: 1 }]); + const { events } = collect(h.source); + await flush(); + h.set({ version: 2 }); + await h.poll(); + + assert.equal(events.length, 2); + assert.equal(events[1].kind, "update"); + assert.deepEqual(events[1].value, { version: 2 }); + assert.ok(events[1].sequence > events[0].sequence); +}); + +test("a document that disappears is withdrawn", async () => { + const h = harness([{ version: 1 }]); + const { events } = collect(h.source); + await flush(); + h.set(null); + await h.poll(); + + assert.equal(events.at(-1).kind, "withdrawn"); + assert.equal(events.at(-1).reason, "withdrawn"); +}); + +test("a document that returns after withdrawal emits a fresh snapshot", async () => { + const h = harness([{ version: 1 }]); + const { events } = collect(h.source); + await flush(); + h.set(null); + await h.poll(); + h.set({ version: 3 }); + await h.poll(); + + assert.equal(events.at(-1).kind, "snapshot"); + assert.deepEqual(events.at(-1).value, { version: 3 }); +}); + +test("a read failure is not a withdrawal", async () => { + // A provider restart or a dropped packet must not look like the provider + // retracting state it still holds. This is the invariant that stops a + // transport hiccup from being rendered as authoritative absence. + const h = harness([{ version: 1 }]); + const { events } = collect(h.source); + await flush(); + const before = events.length; + + h.set(new Error("rudp timeout")); + await h.poll(); + await h.poll(); + + assert.equal(events.length, before); + assert.equal(events.at(-1).kind, "snapshot"); +}); + +test("state survives the failure and updates once reads recover", async () => { + const h = harness([{ version: 1 }]); + const { events } = collect(h.source); + await flush(); + h.set(new Error("rudp timeout")); + await h.poll(); + h.set({ version: 9 }); + await h.poll(); + + assert.equal(events.at(-1).kind, "update"); + assert.deepEqual(events.at(-1).value, { version: 9 }); +}); + +test("releasing the last listener stops polling", async () => { + const h = harness([{ version: 1 }]); + const { release } = collect(h.source); + await flush(); + assert.ok(h.hasTimer()); + + release(); + + assert.equal(h.state.cleared, 1); + assert.equal(h.hasTimer(), false); +}); + +test("a second listener shares one poll and receives the current snapshot", async () => { + const h = harness([{ version: 1 }]); + const first = collect(h.source); + await flush(); + const callsAfterFirst = h.state.calls; + + const second = collect(h.source); + await flush(); + + assert.equal(second.events[0].kind, "snapshot"); + assert.deepEqual(second.events[0].value, { version: 1 }); + // The shared entry polls once per interval regardless of listener count. + await h.poll(); + assert.ok(h.state.calls <= callsAfterFirst + 2); + + first.release(); + assert.equal(h.state.cleared, 0, "the entry survives while one listener remains"); + second.release(); + assert.equal(h.state.cleared, 1); +}); + +test("watch skips withdrawal events and yields values only", async () => { + const h = harness([{ version: 1 }]); + const values = []; + h.source.forProvider("erycina").watch("s", "k", (value) => values.push(value)); + await flush(); + h.set(null); + await h.poll(); + h.set({ version: 2 }); + await h.poll(); + + assert.deepEqual(values, [{ version: 1 }, { version: 2 }]); +}); + +test("latest refuses to invent a document the provider does not publish", async () => { + const h = harness([null]); + await assert.rejects( + () => h.source.forProvider("erycina").latest("gamecult.eve.surface_state.v1", "erycina"), + /published no/, + ); +}); + +test("a subscription requires provider, schema, and record key", () => { + const h = harness([{}]); + assert.throws(() => h.source.forProvider("").watchLifecycle("s", "k", () => {}), /requires providerId/); + assert.throws(() => h.source.forProvider("p").watchLifecycle("", "k", () => {}), /requires providerId/); + assert.throws(() => h.source.forProvider("p").watchLifecycle("s", "", () => {}), /requires providerId/); +});