Ingest live provider session state
This commit is contained in:
parent
2796884d26
commit
5cb819e94c
5 changed files with 345 additions and 6 deletions
|
|
@ -9,6 +9,9 @@ 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 { HermodrStateStreamRegistry } = require("./hermodr-state-stream.cjs");
|
||||
|
||||
const repoRoot = path.resolve(__dirname, "..");
|
||||
const projectsRoot = path.resolve(repoRoot, "..");
|
||||
|
|
@ -24,8 +27,10 @@ const defaultProviderCatalogKeys = [];
|
|||
const cultCacheRequire = createRequire(resolveCultCachePackagePath());
|
||||
const cultMeshRequire = createRequire(resolveCultMeshPackagePath());
|
||||
const { defineDocumentType } = cultCacheRequire(resolveCultCacheRuntimePath());
|
||||
const { CultMesh } = cultMeshRequire(resolveCultMeshRuntimePath());
|
||||
const cultMeshRuntime = cultMeshRequire(resolveCultMeshRuntimePath());
|
||||
const { CultMesh, CultMeshProviderSessionBroker, decodeProviderConnectEvidence } = cultMeshRuntime;
|
||||
const { decode: decodeMessagePack } = cultMeshRequire("@msgpack/msgpack");
|
||||
const { CultNetDocumentRegistry } = cultMeshRequire("cultnet-ts");
|
||||
|
||||
const documents = defineOdinDocuments(defineDocumentType);
|
||||
const odinDocumentDefinitions = Object.values(documents).filter(Boolean);
|
||||
|
|
@ -56,7 +61,18 @@ async function main() {
|
|||
return;
|
||||
}
|
||||
|
||||
const bridge = createHermodrBridge(options);
|
||||
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);
|
||||
const server = http.createServer((request, response) => {
|
||||
bridge.handle(request, response).catch((error) => {
|
||||
writeJson(response, error?.statusCode || 500, {
|
||||
|
|
@ -96,6 +112,7 @@ async function main() {
|
|||
const shutdown = () => {
|
||||
if (healthTimer) clearInterval(healthTimer);
|
||||
server.close(() => {});
|
||||
providerIngress?.close();
|
||||
closeProviderRudpPeers();
|
||||
};
|
||||
process.once("SIGINT", shutdown);
|
||||
|
|
@ -124,6 +141,8 @@ 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 || ""),
|
||||
sleipnirProviderId: stringOption(parsed.sleipnirProviderId, process.env.HERMODR_SLEIPNIR_PROVIDER_ID || "sleipnir.input-mirror.starfire"),
|
||||
idunnRudpHealth: idunnRudpHealthOptions(parsed),
|
||||
idunnHealthIntervalMs: Math.max(1_000, numberOption(
|
||||
|
|
@ -190,7 +209,8 @@ function rejectRemovedOptions(options) {
|
|||
}
|
||||
}
|
||||
|
||||
function createHermodrBridge(options) {
|
||||
function createHermodrBridge(options, livePublicationSource) {
|
||||
const stateStreams = livePublicationSource ? new HermodrStateStreamRegistry(livePublicationSource) : null;
|
||||
return {
|
||||
async handle(request, response) {
|
||||
const url = new URL(request.url || "/", `http://${request.headers.host || "localhost"}`);
|
||||
|
|
@ -264,6 +284,24 @@ function createHermodrBridge(options) {
|
|||
return;
|
||||
}
|
||||
|
||||
if (request.method === "GET" && url.pathname.startsWith("/hermodr/state/")) {
|
||||
const selection = normalizeStateBindingSource({
|
||||
providerId: decodeURIComponent(url.pathname.slice("/hermodr/state/".length)),
|
||||
sourceId: stringOption(url.searchParams.get("sourceId"), ""),
|
||||
schemaId: stringOption(url.searchParams.get("schemaId"), ""),
|
||||
});
|
||||
if (!selection) {
|
||||
writeJson(response, 400, { ok: false, error: "providerId, sourceId, and schemaId are required for a typed state stream." });
|
||||
return;
|
||||
}
|
||||
if (!stateStreams) {
|
||||
writeJson(response, 503, { ok: false, error: "Provider-session live publication ingress is unavailable." });
|
||||
return;
|
||||
}
|
||||
openStateEventStream(request, response, stateStreams, selection);
|
||||
return;
|
||||
}
|
||||
|
||||
if (request.method === "POST" && url.pathname === "/hermodr/commands/sleipnir/input-mapping") {
|
||||
const body = await readJsonBody(request);
|
||||
writeJson(response, 202, await publishSleipnirMapping(options, body));
|
||||
|
|
@ -291,6 +329,36 @@ function createHermodrBridge(options) {
|
|||
};
|
||||
}
|
||||
|
||||
function normalizeStateBindingSource(value) {
|
||||
const providerId = String(value?.providerId || "").trim();
|
||||
const sourceId = String(value?.sourceId || "").trim();
|
||||
const schemaId = String(value?.schemaId || "").trim();
|
||||
if (!providerId || !sourceId || !schemaId) return null;
|
||||
const prefix = `${schemaId.replace(/\.v\d+$/, "")}:`;
|
||||
const recordKey = sourceId.startsWith(prefix) ? sourceId.slice(prefix.length) : sourceId;
|
||||
return recordKey ? { providerId, sourceId, schemaId, recordKey } : null;
|
||||
}
|
||||
|
||||
function openStateEventStream(request, response, registry, selection) {
|
||||
writeCors(response, 200);
|
||||
response.setHeader("Content-Type", "text/event-stream; charset=utf-8");
|
||||
response.setHeader("Cache-Control", "no-cache, no-transform");
|
||||
response.setHeader("Connection", "keep-alive");
|
||||
response.flushHeaders?.();
|
||||
const release = registry.acquire(selection, event => {
|
||||
response.write(`id: ${event.sequence}\n`);
|
||||
response.write(`event: ${event.type}\n`);
|
||||
response.write(`data: ${JSON.stringify(event)}\n\n`);
|
||||
});
|
||||
request.once("close", release);
|
||||
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) {
|
||||
|
|
@ -1351,7 +1419,7 @@ function resolveCultCachePackagePath() {
|
|||
}
|
||||
|
||||
function resolveCultMeshPackagePath() {
|
||||
const candidate = path.resolve(projectsRoot, "CultLib", "packages", "cultmesh-ts", "package.json");
|
||||
const candidate = path.resolve(process.env.CULTLIB_ROOT || path.resolve(projectsRoot, "CultLib"), "packages", "cultmesh-ts", "package.json");
|
||||
if (!fs.existsSync(candidate)) {
|
||||
throw new Error(`CultMesh TypeScript runtime is unavailable at ${candidate}`);
|
||||
}
|
||||
|
|
@ -1363,7 +1431,7 @@ function resolveCultCacheRuntimePath() {
|
|||
}
|
||||
|
||||
function resolveCultMeshRuntimePath() {
|
||||
return path.resolve(projectsRoot, "CultLib", "packages", "cultmesh-ts", "dist", "index.js");
|
||||
return path.resolve(process.env.CULTLIB_ROOT || path.resolve(projectsRoot, "CultLib"), "packages", "cultmesh-ts", "dist", "index.js");
|
||||
}
|
||||
|
||||
function printUsage() {
|
||||
|
|
@ -1371,7 +1439,9 @@ function printUsage() {
|
|||
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, daemon health, or raw command transport.
|
||||
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.
|
||||
`);
|
||||
}
|
||||
|
||||
|
|
@ -1385,7 +1455,9 @@ if (require.main === module) {
|
|||
|
||||
module.exports = {
|
||||
createBrowserCatalog,
|
||||
createHermodrBridge,
|
||||
findProviderCdnRoute,
|
||||
normalizeStateBindingSource,
|
||||
normalizeProviderAdvertisement,
|
||||
surfaceRecordKeys,
|
||||
};
|
||||
|
|
|
|||
32
src/hermodr-state-stream.cjs
Normal file
32
src/hermodr-state-stream.cjs
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
"use strict";
|
||||
|
||||
class HermodrStateStreamRegistry {
|
||||
constructor(source) { this.source = source; this.entries = new Map(); }
|
||||
acquire(selection, listener) {
|
||||
const key = `${selection.schemaId}\u001f${selection.recordKey}`;
|
||||
let entry = this.entries.get(key);
|
||||
if (!entry) {
|
||||
entry = { listeners: new Set([listener]), sequence: 0, stale: false, unsubscribe: null };
|
||||
entry.unsubscribe = this.source.forProvider(selection.providerId).watchLifecycle(selection.schemaId, selection.recordKey, event => {
|
||||
const type = event.kind === "withdrawn" ? "stale" : entry.stale ? "reconnected" : event.kind;
|
||||
entry.stale = type === "stale";
|
||||
const lowered = { type, sequence: ++entry.sequence, source: selection,
|
||||
...(event.value === undefined ? {} : { value: event.value }),
|
||||
...(event.reason ? { reason: event.reason } : {}) };
|
||||
for (const subscriber of entry.listeners) subscriber(lowered);
|
||||
});
|
||||
this.entries.set(key, entry);
|
||||
} else {
|
||||
entry.listeners.add(listener);
|
||||
}
|
||||
let released = false;
|
||||
return () => {
|
||||
if (released) return;
|
||||
released = true;
|
||||
entry.listeners.delete(listener);
|
||||
if (entry.listeners.size === 0) { entry.unsubscribe(); this.entries.delete(key); }
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { HermodrStateStreamRegistry };
|
||||
76
src/odin/live-publication-source.cjs
Normal file
76
src/odin/live-publication-source.cjs
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
"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 };
|
||||
38
src/odin/provider-session-ingress.cjs
Normal file
38
src/odin/provider-session-ingress.cjs
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
"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 };
|
||||
Loading…
Reference in a new issue