diff --git a/src/odin-coordinator.cjs b/src/odin-coordinator.cjs index 7f1e20d..d820ba6 100644 --- a/src/odin-coordinator.cjs +++ b/src/odin-coordinator.cjs @@ -10,6 +10,7 @@ const { defineOdinDocuments } = require("./odin/documents.cjs"); const { createInterfaceDiscovery } = require("./odin/interfaces.cjs"); const { createIdunnRudpHealthPublisher, publishIdunnRudpHealth } = require("./odin/idunn-rudp.cjs"); const { createLayoutStore } = require("./odin/layout.cjs"); +const { createLiveProviderRegistry } = require("./odin/provider-ingress.cjs"); const { createStateBuilder } = require("./odin/state.cjs"); const { broadcastState, createDashboardServer } = require("./odin/websocket.cjs"); @@ -24,10 +25,12 @@ if (cultRuntime.error) { const documents = defineOdinDocuments(cultRuntime.defineDocumentType); const layoutStore = createLayoutStore(config.layoutPath); +const liveProviderRegistry = createLiveProviderRegistry(); const interfaceDiscovery = createInterfaceDiscovery({ CultMesh: cultRuntime.CultMesh, documents, interfaceBindingStores: config.interfaceBindingStores, + liveProviderRegistry, seedDeckUrls: config.seedDeckUrls, }); const stateBuilder = createStateBuilder({ @@ -71,6 +74,9 @@ async function main() { } return (await meshNodePromise).cache; }, + onDocumentPutRaw: (document) => { + liveProviderRegistry.ingestDocument(document, document.remote); + }, }); await cultNetRudpSurfaceServer.start(); console.log(`CultNet/RUDP snapshot: ${config.cultnetRudpBind}`); diff --git a/src/odin/cultnet-rudp.cjs b/src/odin/cultnet-rudp.cjs index 5a31ef7..2f19086 100644 --- a/src/odin/cultnet-rudp.cjs +++ b/src/odin/cultnet-rudp.cjs @@ -161,6 +161,16 @@ function createCultNetRudpSurfaceServer(options) { case "cultnet.schema_catalog_request.v0": sendSchemaMessage(record, cultNetBuiltinSchemaRegistry.createCatalogResponse(message)); return; + case "cultnet.document_put_raw.v0": { + if (typeof options.onDocumentPutRaw === "function") { + try { + options.onDocumentPutRaw(normalizeRawDocumentPut(message, record.remote)); + } catch (error) { + logError(options, "CultNet/RUDP raw document ingest failed", error); + } + } + return; + } default: sendSchemaMessage(record, { schemaVersion: "cultnet.error.v0", @@ -192,6 +202,26 @@ function createCultNetRudpSurfaceServer(options) { }; } +function normalizeRawDocumentPut(message, remote) { + const document = message?.document; + if (!document?.schemaId || !document?.recordKey) { + throw new Error("raw document put is missing schemaId or recordKey"); + } + if (document.payloadEncoding !== "messagepack") { + throw new Error(`unsupported raw payload encoding ${document.payloadEncoding}`); + } + return { + schemaId: document.schemaId, + recordKey: document.recordKey, + storedAt: document.storedAt || new Date().toISOString(), + payload: decode(document.payload), + sourceRuntimeId: document.sourceRuntimeId || null, + sourceRole: document.sourceRole || null, + tags: Array.isArray(document.tags) ? document.tags : [], + remote, + }; +} + function parseEndpoint(value) { const text = String(value || "").trim(); const ipv6 = text.match(/^\[([^\]]+)\]:(\d+)$/); diff --git a/src/odin/interfaces.cjs b/src/odin/interfaces.cjs index c79aacc..abe2428 100644 --- a/src/odin/interfaces.cjs +++ b/src/odin/interfaces.cjs @@ -17,6 +17,7 @@ function createInterfaceDiscovery({ CultMesh, documents, interfaceBindingStores, + liveProviderRegistry, seedDeckUrls, }) { let discoveredDeckUrls = [...seedDeckUrls]; @@ -39,9 +40,13 @@ function createInterfaceDiscovery({ [...manifestsByProvider.values()].map(({ provider, deckUrl }) => fetchEveProvider(deckUrl, provider.id, provider)), ); const { interfaces: cultMeshInterfaces, providerAdvertisements } = await discoverCultMeshEntries(); + const liveAnnouncements = liveProviderRegistry?.snapshot?.() || { + interfaces: [], + providerAdvertisements: [], + }; const interfaces = [...eveInterfaces]; - for (const entry of cultMeshInterfaces) { + for (const entry of [...cultMeshInterfaces, ...liveAnnouncements.interfaces]) { const existingIndex = interfaces.findIndex((candidate) => candidate.providerId === entry.providerId); if (existingIndex >= 0) { interfaces[existingIndex] = entry; @@ -50,8 +55,17 @@ function createInterfaceDiscovery({ } } interfaces.sort((left, right) => left.providerId.localeCompare(right.providerId)); - providerAdvertisements.sort((left, right) => String(left.id).localeCompare(String(right.id))); - return { interfaces, providerAdvertisements }; + const allProviderAdvertisements = [...providerAdvertisements, ...liveAnnouncements.providerAdvertisements]; + const providersById = new Map(); + for (const provider of allProviderAdvertisements) { + if (provider?.id) { + providersById.set(String(provider.id), provider); + } + } + return { + interfaces, + providerAdvertisements: [...providersById.values()].sort((left, right) => String(left.id).localeCompare(String(right.id))), + }; } function cultMeshDocumentsAvailable() { diff --git a/src/odin/provider-ingress.cjs b/src/odin/provider-ingress.cjs new file mode 100644 index 0000000..cad6bc7 --- /dev/null +++ b/src/odin/provider-ingress.cjs @@ -0,0 +1,173 @@ +"use strict"; + +function createLiveProviderRegistry(options = {}) { + const maxAgeMs = Math.max(1_000, Number(options.maxAgeMs || 120_000)); + const records = new Map(); + + function ingestDocument(document, source = {}) { + if (!document?.schemaId || !document?.recordKey) { + return; + } + const now = Date.now(); + records.set(`${document.schemaId}:${document.recordKey}`, { + ...document, + receivedAtMs: now, + source, + }); + prune(now); + } + + function snapshot() { + const now = Date.now(); + prune(now); + + const advertisements = new Map(); + const surfaces = new Map(); + const commandBoundaries = new Map(); + const transportProfiles = new Map(); + + for (const record of records.values()) { + switch (record.schemaId) { + case "gamecult.eve.provider_advertisement": + if (record.payload?.providerId) { + advertisements.set(String(record.payload.providerId), record); + } + break; + case "gamecult.eve.surface_state": + if (record.payload?.providerId) { + surfaces.set(String(record.payload.providerId), record); + } + break; + default: { + const payload = record.payload || {}; + const providerId = payload.provider_id || payload.providerId; + if (!providerId) break; + if (String(record.schemaId).endsWith(".command_boundary")) { + commandBoundaries.set(String(providerId), payload); + } else if (String(record.schemaId).endsWith(".transport_profile")) { + transportProfiles.set(String(providerId), payload); + } + break; + } + } + } + + const providerAdvertisements = [...advertisements.values()] + .map((record) => normalizeProviderAdvertisementRecord(record, commandBoundaries, transportProfiles)) + .filter(Boolean) + .sort((left, right) => String(left.id).localeCompare(String(right.id))); + + const interfaces = providerAdvertisements + .map((provider) => { + const surfaceRecord = surfaces.get(String(provider.id)); + if (!surfaceRecord?.payload?.surface?.root) { + return null; + } + return liveProviderInterface(provider, surfaceRecord.payload, surfaceRecord.source); + }) + .filter(Boolean) + .sort((left, right) => String(left.providerId).localeCompare(String(right.providerId))); + + return { interfaces, providerAdvertisements }; + } + + function prune(now = Date.now()) { + for (const [key, record] of records) { + if (now - record.receivedAtMs > maxAgeMs) { + records.delete(key); + } + } + } + + return { + ingestDocument, + snapshot, + }; +} + +function normalizeProviderAdvertisementRecord(record, commandBoundaries, transportProfiles) { + const advertisement = record.payload; + const providerId = advertisement?.providerId || advertisement?.provider?.id || advertisement?.id; + if (!providerId) { + return null; + } + return { + id: providerId, + title: advertisement.title || advertisement.provider?.title || providerId, + description: advertisement.description || "Provider-owned CultNet/RUDP advertisement.", + version: String(advertisement.version || 0), + endpoint: advertisement.cultMeshAddress || advertisement.endpoints?.[0]?.address || advertisement.provider?.endpoint || sourceLabel(record.source), + canonicalService: advertisement.canonicalService || null, + locatedService: advertisement.locatedService || null, + cultMeshAddress: advertisement.cultMeshAddress || null, + endpoints: Array.isArray(advertisement.endpoints) ? advertisement.endpoints : [], + routes: Array.isArray(advertisement.routes) ? advertisement.routes : [], + transportEndpoint: advertisement.routes?.find((route) => route.transport === "cultnet")?.address + || advertisement.routes?.find((route) => route.transport === "compatibility-eve-deck")?.address + || advertisement.provider?.endpoint + || sourceLabel(record.source), + capabilities: advertisement.provider?.capabilities || advertisement.capabilities || [], + operatorState: null, + commandBoundary: commandBoundaries.get(String(providerId)) || null, + transportProfile: transportProfiles.get(String(providerId)) || null, + usesCultMesh: false, + transport: "CultNet/RUDP provider advertisement", + status: advertisement.status || "unknown", + updatedAt: advertisement.updatedAt || record.storedAt || new Date(record.receivedAtMs).toISOString(), + source: sourceLabel(record.source), + commandSurface: advertisement.commandSurface || null, + }; +} + +function liveProviderInterface(provider, surfaceState, source) { + const surface = surfaceState.surface || null; + return { + providerId: provider.id, + title: surfaceState.title || provider.title || provider.id, + state: "active", + detail: `${surface?.root?.kind || surface?.root?.type || "surface"} ${countSurfaceNodes(surface, surfaceState)} nodes via live CultNet/RUDP announcement`, + version: surfaceState.version || 0, + updatedAt: surfaceState.updatedAt || provider.updatedAt || new Date().toISOString(), + source: sourceLabel(source), + manifest: provider, + canonicalService: provider.canonicalService || null, + locatedService: provider.locatedService || null, + cultMeshAddress: provider.cultMeshAddress || null, + endpoints: provider.endpoints || [], + routes: provider.routes || [], + commandBoundary: provider.commandBoundary || null, + transportProfile: provider.transportProfile || null, + surface, + }; +} + +function countSurfaceNodes(surface, state = null) { + if (Array.isArray(state?.nodes)) { + return state.nodes.length; + } + if (!surface?.root) { + return 0; + } + let count = 0; + const stack = [surface.root]; + while (stack.length > 0) { + const node = stack.pop(); + if (!node || typeof node !== "object") continue; + count += 1; + if (Array.isArray(node.children)) { + for (const child of node.children) stack.push(child); + } + } + return count; +} + +function sourceLabel(source) { + if (!source?.address) { + return "cultnet-rudp:unknown"; + } + return `cultnet-rudp://${source.address}:${source.port}`; +} + +module.exports = { + createLiveProviderRegistry, +}; diff --git a/src/odin/websocket.cjs b/src/odin/websocket.cjs index 022fed7..59d68da 100644 --- a/src/odin/websocket.cjs +++ b/src/odin/websocket.cjs @@ -57,26 +57,32 @@ function providerCatalogFromState(state) { const props = child.props || {}; const embeddedRoot = Array.isArray(child.children) ? child.children[0] : null; const providerId = String(props.providerId); + const existing = providers.get(providerId) || {}; providers.set(providerId, { + ...existing, id: providerId, title: String(props.title || props.providerId), - description: String(props.detail || "Provider-owned Eve/CultUI interface discovered by Odin."), + description: String(props.detail || existing.description || "Provider-owned Eve/CultUI interface discovered by Odin."), version: String(props.version || 0), endpoint: `/eve/deck/${encodeURIComponent(providerId)}`, - canonicalService: props.canonicalService || null, - locatedService: props.locatedService || null, - cultMeshAddress: props.cultMeshAddress || null, - endpoints: Array.isArray(props.endpoints) ? props.endpoints : [], - routes: Array.isArray(props.routes) ? props.routes : [], + canonicalService: props.canonicalService || existing.canonicalService || null, + locatedService: props.locatedService || existing.locatedService || null, + cultMeshAddress: props.cultMeshAddress || existing.cultMeshAddress || null, + endpoints: Array.isArray(props.endpoints) ? props.endpoints : (existing.endpoints || []), + routes: Array.isArray(props.routes) ? props.routes : (existing.routes || []), transportEndpoint: `/eve/deck/${encodeURIComponent(providerId)}`, capabilities: providerCapabilities(embeddedRoot), - usesCultMesh: String(props.source || "").startsWith("cultmesh:"), - transport: String(props.source || "").startsWith("cultmesh:") + usesCultMesh: existing.usesCultMesh ?? String(props.source || "").startsWith("cultmesh:"), + transport: existing.transport || (String(props.source || "").startsWith("cultmesh:") ? "Odin provider proxy from CultMesh Eve interface binding" - : "Odin provider proxy from Eve WebSocket provider", + : "Odin provider proxy from Eve WebSocket provider"), status: props.status || "unknown", updatedAt: props.updatedAt || state.updatedAt, - source: props.source || "", + source: existing.source || props.source || "", + operatorState: existing.operatorState || null, + commandBoundary: existing.commandBoundary || null, + transportProfile: existing.transportProfile || null, + commandSurface: existing.commandSurface || null, }); } return [...providers.values()].sort((left, right) => String(left.id).localeCompare(String(right.id)));