Merge Odin CultMesh catalog work
This commit is contained in:
commit
c238003048
14 changed files with 675 additions and 598 deletions
|
|
@ -96,12 +96,16 @@ The Eve/CultUI deck endpoint is a compatibility bridge:
|
|||
ws://127.0.0.1:8797/eve/deck
|
||||
```
|
||||
|
||||
The native CultNet/RUDP snapshot endpoint is:
|
||||
The native CultMesh/RUDP document catalog endpoint is:
|
||||
|
||||
```text
|
||||
127.0.0.1:17871
|
||||
```
|
||||
|
||||
That endpoint accepts typed document publication and schema/catalog requests
|
||||
through the shared CultMesh runtime. Consumers that need Odin's accepted surface
|
||||
can still request the current CultNet snapshot over the same transport.
|
||||
|
||||
Legacy browser/deck lowerers can consume the LAN bridge endpoint:
|
||||
|
||||
```text
|
||||
|
|
|
|||
|
|
@ -1768,6 +1768,12 @@ fn daemon_surgery_plan(target: &DaemonTarget, updated_at: &str) -> IdunnDaemonSu
|
|||
fn swarm_targets(options: &SwarmOptions) -> Result<Vec<DaemonTarget>> {
|
||||
let repo_root = options.repo_root.display().to_string();
|
||||
let script = |name: &str| format!(r"{}\scripts\{}", repo_root, name);
|
||||
let powershell_script = |name: &str| {
|
||||
format!(
|
||||
r#"C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -ExecutionPolicy Bypass -File "{}\scripts\{}""#,
|
||||
repo_root, name
|
||||
)
|
||||
};
|
||||
let project = |name: &str| PathBuf::from(format!(r"E:\Projects\{name}"));
|
||||
|
||||
match options.profile.as_str() {
|
||||
|
|
@ -1777,9 +1783,9 @@ fn swarm_targets(options: &SwarmOptions) -> Result<Vec<DaemonTarget>> {
|
|||
verse_id: "starfire.local".to_string(),
|
||||
name: "Odin all-seer".to_string(),
|
||||
health_contract: health_contract("odin.cultnet-rudp-provider-health", "failed"),
|
||||
health_command: Some(script("health-odin.cmd")),
|
||||
health_command: Some(powershell_script("health-odin.ps1")),
|
||||
deploy_command: None,
|
||||
restart_command: Some(script("restart-odin.cmd")),
|
||||
restart_command: Some(powershell_script("restart-odin.ps1")),
|
||||
release: None,
|
||||
enabled: true,
|
||||
interval_seconds: 30,
|
||||
|
|
@ -2701,9 +2707,15 @@ mod tests {
|
|||
verse_id: "starfire.local".to_string(),
|
||||
name: "Odin".to_string(),
|
||||
health_contract: health_contract("odin.cultnet-rudp-provider-health", "failed"),
|
||||
health_command: Some("health-odin.cmd".to_string()),
|
||||
health_command: Some(
|
||||
r#"C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -ExecutionPolicy Bypass -File "E:\Projects\Odin\scripts\health-odin.ps1""#
|
||||
.to_string(),
|
||||
),
|
||||
deploy_command: None,
|
||||
restart_command: Some("restart-odin.cmd".to_string()),
|
||||
restart_command: Some(
|
||||
r#"C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -ExecutionPolicy Bypass -File "E:\Projects\Odin\scripts\restart-odin.ps1""#
|
||||
.to_string(),
|
||||
),
|
||||
release: None,
|
||||
enabled: true,
|
||||
interval_seconds: 30,
|
||||
|
|
|
|||
|
|
@ -1,2 +1,2 @@
|
|||
@echo off
|
||||
curl.exe -fsS http://127.0.0.1:8797/health >NUL
|
||||
"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\health-odin.ps1
|
||||
|
|
|
|||
80
scripts/health-odin.ps1
Normal file
80
scripts/health-odin.ps1
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
param(
|
||||
[int] $Port = 8797,
|
||||
[string] $StateDir = "E:\Projects\Odin\scratch\odin",
|
||||
[int] $MaxSilenceSeconds = 120,
|
||||
[string] $CultNetRudpBind = "0.0.0.0:17871"
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
$pidPath = Join-Path $StateDir "odin.pid"
|
||||
$outLog = Join-Path $StateDir "odin.out.log"
|
||||
$errLog = Join-Path $StateDir "odin.err.log"
|
||||
|
||||
if (-not (Test-Path -LiteralPath $pidPath)) {
|
||||
throw "Odin PID file is missing at $pidPath"
|
||||
}
|
||||
|
||||
$pidText = (Get-Content -LiteralPath $pidPath -Raw).Trim()
|
||||
if ($pidText -notmatch '^\d+$') {
|
||||
throw "Odin PID file is invalid at ${pidPath}: '$pidText'"
|
||||
}
|
||||
|
||||
$process = Get-CimInstance Win32_Process -Filter "ProcessId = $pidText" -ErrorAction SilentlyContinue
|
||||
if ($null -eq $process) {
|
||||
throw "Odin process $pidText is not running"
|
||||
}
|
||||
|
||||
foreach ($pattern in @(
|
||||
'node.exe',
|
||||
'src\odin-coordinator.cjs',
|
||||
"--port $Port",
|
||||
"--stateDir $StateDir",
|
||||
"--cultnet-rudp-bind $CultNetRudpBind",
|
||||
'--idunn-daemon odin',
|
||||
'--idunn-health-contract odin.cultnet-rudp-provider-health'
|
||||
)) {
|
||||
if ($process.CommandLine -notlike "*$pattern*") {
|
||||
throw "Odin process command line is missing expected segment ${pattern}: $($process.CommandLine)"
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($logPath in @($outLog, $errLog)) {
|
||||
if (-not (Test-Path -LiteralPath $logPath)) {
|
||||
throw "Odin log is missing at $logPath"
|
||||
}
|
||||
}
|
||||
|
||||
$newestLogWriteUtc = @($outLog, $errLog) |
|
||||
ForEach-Object { (Get-Item -LiteralPath $_).LastWriteTimeUtc } |
|
||||
Sort-Object -Descending |
|
||||
Select-Object -First 1
|
||||
$logAgeSeconds = ([DateTime]::UtcNow - $newestLogWriteUtc).TotalSeconds
|
||||
|
||||
$healthUri = "http://127.0.0.1:$Port/health"
|
||||
try {
|
||||
$health = Invoke-RestMethod -Uri $healthUri -TimeoutSec 10
|
||||
} catch {
|
||||
throw "Odin health endpoint is unavailable at ${healthUri}: $($_.Exception.Message)"
|
||||
}
|
||||
|
||||
if (-not $health.ok) {
|
||||
throw "Odin health endpoint reports ok=false"
|
||||
}
|
||||
|
||||
$tcpListener = Get-NetTCPConnection -State Listen -LocalPort $Port -ErrorAction SilentlyContinue |
|
||||
Where-Object { $_.OwningProcess -eq [int]$pidText } |
|
||||
Select-Object -First 1
|
||||
if ($null -eq $tcpListener) {
|
||||
throw "Odin is not listening on TCP port $Port as process $pidText"
|
||||
}
|
||||
|
||||
$rudpPort = [int](($CultNetRudpBind -split ':')[-1])
|
||||
$udpListener = Get-NetUDPEndpoint -LocalPort $rudpPort -ErrorAction SilentlyContinue |
|
||||
Where-Object { $_.OwningProcess -eq [int]$pidText } |
|
||||
Select-Object -First 1
|
||||
if ($null -eq $udpListener) {
|
||||
throw "Odin is not listening on UDP port $rudpPort as process $pidText"
|
||||
}
|
||||
|
||||
Write-Host "Odin healthy: pid=$pidText tcp=$Port udp=$rudpPort log_age=$([math]::Round($logAgeSeconds))s"
|
||||
|
|
@ -1,2 +1,2 @@
|
|||
@echo off
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\start-odin.ps1
|
||||
"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\restart-odin.ps1
|
||||
|
|
|
|||
35
scripts/restart-odin.ps1
Normal file
35
scripts/restart-odin.ps1
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
param(
|
||||
[int] $Port = 8797,
|
||||
[string] $StateDir = "E:\Projects\Odin\scratch\odin",
|
||||
[string] $CultNetRudpBind = "0.0.0.0:17871",
|
||||
[string] $IdunnRudpHealth = "127.0.0.1:17870",
|
||||
[string] $IdunnDaemon = "odin",
|
||||
[string] $IdunnHealthContract = "odin.cultnet-rudp-provider-health"
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
$repoRoot = Split-Path -Parent $PSScriptRoot
|
||||
$stopScript = Join-Path $PSScriptRoot "stop-odin.ps1"
|
||||
$startScript = Join-Path $PSScriptRoot "start-odin.ps1"
|
||||
$healthScript = Join-Path $PSScriptRoot "health-odin.ps1"
|
||||
$powerShellExe = Join-Path $env:WINDIR "System32\WindowsPowerShell\v1.0\powershell.exe"
|
||||
|
||||
if (-not (Test-Path -LiteralPath $powerShellExe)) {
|
||||
throw "PowerShell executable is missing at $powerShellExe"
|
||||
}
|
||||
|
||||
& $powerShellExe -NoProfile -ExecutionPolicy Bypass -File $stopScript -StateDir $StateDir
|
||||
|
||||
& $powerShellExe -NoProfile -ExecutionPolicy Bypass -File $startScript `
|
||||
-Port $Port `
|
||||
-StateDir $StateDir `
|
||||
-CultNetRudpBind $CultNetRudpBind `
|
||||
-IdunnRudpHealth $IdunnRudpHealth `
|
||||
-IdunnDaemon $IdunnDaemon `
|
||||
-IdunnHealthContract $IdunnHealthContract
|
||||
|
||||
& $powerShellExe -NoProfile -ExecutionPolicy Bypass -File $healthScript `
|
||||
-Port $Port `
|
||||
-StateDir $StateDir `
|
||||
-CultNetRudpBind $CultNetRudpBind
|
||||
|
|
@ -58,4 +58,4 @@ if ($proc.HasExited) {
|
|||
Write-Host "Odin started as PID $($proc.Id)."
|
||||
Write-Host "Health: http://127.0.0.1:$Port/health"
|
||||
Write-Host "Eve deck: ws://127.0.0.1:$Port/eve/deck"
|
||||
Write-Host "CultNet/RUDP snapshot: $CultNetRudpBind"
|
||||
Write-Host "CultMesh/RUDP document catalog: $CultNetRudpBind"
|
||||
|
|
|
|||
|
|
@ -5,11 +5,12 @@ const fs = require("fs");
|
|||
const path = require("path");
|
||||
|
||||
const { buildConfig, loadCultRuntime } = require("./odin/config.cjs");
|
||||
const { createCultNetRudpSurfaceServer } = require("./odin/cultnet-rudp.cjs");
|
||||
const { createCultMeshRudpDocumentServer } = require("./odin/cultnet-rudp.cjs");
|
||||
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");
|
||||
|
||||
|
|
@ -19,15 +20,17 @@ const idunnRudpHealthPublisher = createIdunnRudpHealthPublisher(config.idunnRudp
|
|||
|
||||
const cultRuntime = loadCultRuntime();
|
||||
if (cultRuntime.error) {
|
||||
console.error("CultMesh runtime unavailable; durable mesh snapshot disabled:", cultRuntime.error.message);
|
||||
console.error("CultMesh runtime unavailable; durable mesh catalog disabled:", cultRuntime.error.message);
|
||||
}
|
||||
|
||||
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({
|
||||
|
|
@ -42,7 +45,7 @@ const stateBuilder = createStateBuilder({
|
|||
});
|
||||
|
||||
let meshNodePromise = null;
|
||||
let cultNetRudpSurfaceServer = null;
|
||||
let cultMeshRudpDocumentServer = null;
|
||||
let currentState = stateBuilder.buildPendingState("Coordinator starting");
|
||||
let lastRefresh = {
|
||||
completedAt: null,
|
||||
|
|
@ -62,18 +65,22 @@ async function main() {
|
|||
meshNodePromise = createDurableSurfaceNode();
|
||||
}
|
||||
if (config.cultnetRudpBind) {
|
||||
cultNetRudpSurfaceServer = createCultNetRudpSurfaceServer({
|
||||
cultMeshRudpDocumentServer = createCultMeshRudpDocumentServer({
|
||||
CultMesh: cultRuntime.CultMesh,
|
||||
bind: config.cultnetRudpBind,
|
||||
documents,
|
||||
getCache: async () => {
|
||||
if (!meshNodePromise) {
|
||||
throw new Error("CultMesh runtime is unavailable; Odin cannot serve a CultNet/RUDP snapshot.");
|
||||
throw new Error("CultMesh runtime is unavailable; Odin cannot serve a CultMesh/RUDP document catalog.");
|
||||
}
|
||||
return (await meshNodePromise).cache;
|
||||
},
|
||||
onDocumentPutRaw: (document) => {
|
||||
liveProviderRegistry.ingestDocument(document, document.remote);
|
||||
},
|
||||
});
|
||||
await cultNetRudpSurfaceServer.start();
|
||||
console.log(`CultNet/RUDP snapshot: ${config.cultnetRudpBind}`);
|
||||
await cultMeshRudpDocumentServer.start();
|
||||
console.log(`CultMesh/RUDP document catalog: ${config.cultnetRudpBind}`);
|
||||
}
|
||||
|
||||
const dashboardServer = createDashboardServer({
|
||||
|
|
|
|||
|
|
@ -39,13 +39,9 @@ function buildConfig(argv) {
|
|||
path.join(repoRoot, "..", "VoidBot", ".voidbot", "status", "cultmesh", "voidbot-swarm-state.cc"),
|
||||
path.join(repoRoot, "..", "Bifrost", ".bifrost", "provider-advertisement.cc"),
|
||||
path.join(repoRoot, "..", "weksa", ".weksa", "provider-advertisement-store.cc"),
|
||||
"sftp://raven/E:/Projects/Vili/.vili/vili.service.cc",
|
||||
path.join(repoRoot, "..", "Stonks", "scratch", "stonks", "stonks-state.cc"),
|
||||
path.join(repoRoot, "..", "StreamPixels", ".streampixels-data", "cultcache", "streampixels.service.cc"),
|
||||
"sftp://raven/C:/Meta/Odin/state/muninn.telemetry.cc",
|
||||
"C:\\Meta\\Odin\\state\\starfire.muninn.telemetry.cc",
|
||||
"sftp://nightwing/home/metacrat/.local/state/gamecult/muninn/muninn.telemetry.cc",
|
||||
"sftp://nightwing/var/lib/gamecult/gjallar/cultcache/gjallar.service.cc",
|
||||
].join(",");
|
||||
const interfaceBindingStores = String(
|
||||
args.interfaceBindingStore ||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
"use strict";
|
||||
|
||||
const dgram = require("dgram");
|
||||
const path = require("path");
|
||||
const { createRequire } = require("module");
|
||||
|
||||
|
|
@ -17,178 +16,55 @@ const requireCultNet = createRequire(path.resolve(
|
|||
|
||||
const {
|
||||
CultNetDocumentRegistry,
|
||||
CultNetRudpSession,
|
||||
cultNetBuiltinSchemaRegistry,
|
||||
decodeRudpPacket,
|
||||
defineCultNetDocumentBinding,
|
||||
encodeCultNetMessageForWire,
|
||||
encodeRudpPacket,
|
||||
parseCultNetMessage,
|
||||
} = requireCultNet("./dist/index.js");
|
||||
const { decode, encode } = requireCultNet("@msgpack/msgpack");
|
||||
|
||||
const ODIN_RUDP_CONNECTION_ID = 0x0d1d0002;
|
||||
const DEFAULT_SESSION_TIMEOUT_MS = 30_000;
|
||||
|
||||
function createCultNetRudpSurfaceServer(options) {
|
||||
function createCultMeshRudpDocumentServer(options) {
|
||||
if (!options?.bind) return null;
|
||||
if (!options.CultMesh?.createRudpDocumentServer) {
|
||||
throw new Error("Odin requires a CultMesh runtime with createRudpDocumentServer.");
|
||||
}
|
||||
if (!options.documents?.surfaceDefinition) {
|
||||
throw new Error("Odin CultNet/RUDP surface server requires a surface document definition.");
|
||||
throw new Error("Odin CultMesh/RUDP document server requires a surface document definition.");
|
||||
}
|
||||
if (typeof options.getCache !== "function") {
|
||||
throw new Error("Odin CultNet/RUDP surface server requires an async getCache function.");
|
||||
throw new Error("Odin CultMesh/RUDP document server requires an async getCache function.");
|
||||
}
|
||||
|
||||
const bind = parseEndpoint(options.bind);
|
||||
const documentRegistry = new CultNetDocumentRegistry([
|
||||
const registry = new CultNetDocumentRegistry([
|
||||
defineCultNetDocumentBinding({ definition: options.documents.surfaceDefinition }),
|
||||
]);
|
||||
const sessions = new Map();
|
||||
const socket = dgram.createSocket(bind.host.includes(":") ? "udp6" : "udp4");
|
||||
const resendPollMs = Math.max(10, Number(options.resendPollMs || 25));
|
||||
const sessionTimeoutMs = Math.max(1_000, Number(options.sessionTimeoutMs || DEFAULT_SESSION_TIMEOUT_MS));
|
||||
let resendTimer = null;
|
||||
|
||||
socket.on("message", (wire, remote) => {
|
||||
try {
|
||||
const packet = decodeRudpPacket(wire);
|
||||
handlePacket(packet, remote).catch((error) => {
|
||||
logError(options, `CultNet/RUDP packet handling failed for ${remote.address}:${remote.port}`, error);
|
||||
});
|
||||
} catch (error) {
|
||||
logError(options, "CultNet/RUDP packet decode failed", error);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on("error", (error) => {
|
||||
logError(options, "CultNet/RUDP socket error", error);
|
||||
});
|
||||
|
||||
async function start() {
|
||||
await new Promise((resolve, reject) => {
|
||||
socket.once("error", reject);
|
||||
socket.bind(bind.port, bind.host, () => {
|
||||
socket.off("error", reject);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
resendTimer = setInterval(() => {
|
||||
try {
|
||||
const nowMs = Date.now();
|
||||
for (const [key, record] of sessions) {
|
||||
if (record.session.checkTimeout(nowMs, sessionTimeoutMs)) {
|
||||
sessions.delete(key);
|
||||
continue;
|
||||
}
|
||||
for (const packet of record.session.dueResends(nowMs)) {
|
||||
sendPacket(record.remote, packet);
|
||||
}
|
||||
const server = options.CultMesh.createRudpDocumentServer(
|
||||
"odin-cultmesh-catalog",
|
||||
ODIN_RUDP_CONNECTION_ID,
|
||||
{
|
||||
bindHost: bind.host,
|
||||
bindPort: bind.port,
|
||||
documents: registry,
|
||||
getCache: options.getCache,
|
||||
onError: (error) => {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
if (typeof options.logError === "function") {
|
||||
options.logError(`CultMesh/RUDP document server error: ${message}`);
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
logError(options, "CultNet/RUDP resend loop failed", error);
|
||||
}
|
||||
}, resendPollMs);
|
||||
resendTimer.unref?.();
|
||||
}
|
||||
|
||||
function close() {
|
||||
if (resendTimer) {
|
||||
clearInterval(resendTimer);
|
||||
resendTimer = null;
|
||||
}
|
||||
sessions.clear();
|
||||
socket.close();
|
||||
}
|
||||
|
||||
async function handlePacket(packet, remote) {
|
||||
const key = remoteKey(remote);
|
||||
const nowMs = Date.now();
|
||||
let record = sessions.get(key);
|
||||
|
||||
if (packet.packetType === "connect") {
|
||||
record = {
|
||||
remote: { address: remote.address, family: remote.family, port: remote.port },
|
||||
session: new CultNetRudpSession({
|
||||
connectionId: ODIN_RUDP_CONNECTION_ID,
|
||||
initialSequence: 1,
|
||||
resendDelayMs: 100,
|
||||
}),
|
||||
};
|
||||
sessions.set(key, record);
|
||||
sendPacket(record.remote, record.session.acceptConnect(packet, nowMs, new Uint8Array()));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!record) {
|
||||
return;
|
||||
}
|
||||
|
||||
const result = record.session.receive(packet, nowMs);
|
||||
if (result.reply) {
|
||||
sendPacket(record.remote, result.reply);
|
||||
}
|
||||
for (const frame of result.delivered) {
|
||||
if (frame.channelId !== "schema") {
|
||||
continue;
|
||||
}
|
||||
await handleSchemaFrame(record, frame.payload);
|
||||
}
|
||||
if (result.disconnected) {
|
||||
sessions.delete(key);
|
||||
return;
|
||||
}
|
||||
if (packet.packetType === "accept" || result.delivered.length > 0) {
|
||||
sendPacket(record.remote, record.session.createAck());
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSchemaFrame(record, payload) {
|
||||
const message = parseCultNetMessage(decode(payload), "cultnet.schema.v0");
|
||||
switch (message.schemaVersion) {
|
||||
case "cultnet.snapshot_request.v0": {
|
||||
try {
|
||||
const cache = await options.getCache();
|
||||
const response = documentRegistry.createRawSnapshotResponse(cache, message.messageId, message);
|
||||
sendSchemaMessage(record, response);
|
||||
} catch (error) {
|
||||
sendSchemaMessage(record, {
|
||||
schemaVersion: "cultnet.error.v0",
|
||||
error: error.message,
|
||||
});
|
||||
console.error(`CultMesh/RUDP document server error: ${message}`);
|
||||
},
|
||||
onDocumentPutRaw: (document) => {
|
||||
if (typeof options.onDocumentPutRaw === "function") {
|
||||
options.onDocumentPutRaw(document);
|
||||
}
|
||||
return;
|
||||
}
|
||||
case "cultnet.schema_catalog_request.v0":
|
||||
sendSchemaMessage(record, cultNetBuiltinSchemaRegistry.createCatalogResponse(message));
|
||||
return;
|
||||
default:
|
||||
sendSchemaMessage(record, {
|
||||
schemaVersion: "cultnet.error.v0",
|
||||
error: `Unsupported Odin CultNet/RUDP request ${message.schemaVersion}.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function sendSchemaMessage(record, message) {
|
||||
const payload = encode(encodeCultNetMessageForWire(message, "cultnet.schema.v0"));
|
||||
for (const packet of record.session.sendMany("schema", payload, {
|
||||
reliable: true,
|
||||
ordered: true,
|
||||
nowMs: Date.now(),
|
||||
})) {
|
||||
sendPacket(record.remote, packet);
|
||||
}
|
||||
}
|
||||
|
||||
function sendPacket(remote, packet) {
|
||||
const wire = Buffer.from(encodeRudpPacket(packet));
|
||||
socket.send(wire, remote.port, remote.address);
|
||||
}
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
bind,
|
||||
start,
|
||||
close,
|
||||
start: () => server.start(),
|
||||
close: () => server.close(),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -198,7 +74,7 @@ function parseEndpoint(value) {
|
|||
if (ipv6) return { host: ipv6[1], port: parsePort(ipv6[2]) };
|
||||
const index = text.lastIndexOf(":");
|
||||
if (index <= 0) {
|
||||
throw new Error(`CultNet/RUDP bind must be host:port, got "${value}".`);
|
||||
throw new Error(`CultMesh/RUDP bind must be host:port, got "${value}".`);
|
||||
}
|
||||
return { host: text.slice(0, index), port: parsePort(text.slice(index + 1)) };
|
||||
}
|
||||
|
|
@ -206,24 +82,11 @@ function parseEndpoint(value) {
|
|||
function parsePort(value) {
|
||||
const port = Number(value);
|
||||
if (!Number.isInteger(port) || port <= 0 || port > 65535) {
|
||||
throw new Error(`CultNet/RUDP port is invalid: ${value}`);
|
||||
throw new Error(`CultMesh/RUDP port is invalid: ${value}`);
|
||||
}
|
||||
return port;
|
||||
}
|
||||
|
||||
function remoteKey(remote) {
|
||||
return `${remote.address}:${remote.port}`;
|
||||
}
|
||||
|
||||
function logError(options, label, error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
if (typeof options?.logError === "function") {
|
||||
options.logError(`${label}: ${message}`);
|
||||
return;
|
||||
}
|
||||
console.error(`${label}: ${message}`);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
createCultNetRudpSurfaceServer,
|
||||
createCultMeshRudpDocumentServer,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
"use strict";
|
||||
|
||||
const childProcess = require("child_process");
|
||||
const fs = require("fs");
|
||||
const { createRequire } = require("module");
|
||||
const os = require("os");
|
||||
|
|
@ -18,15 +17,122 @@ function createInterfaceDiscovery({
|
|||
CultMesh,
|
||||
documents,
|
||||
interfaceBindingStores,
|
||||
liveProviderRegistry,
|
||||
seedDeckUrls,
|
||||
}) {
|
||||
let discoveredDeckUrls = [...seedDeckUrls];
|
||||
let lastLanScanAt = 0;
|
||||
|
||||
async function discoverInterfaces() {
|
||||
const { interfaces } = await discoverAll();
|
||||
return interfaces;
|
||||
}
|
||||
|
||||
async function discoverProviderAdvertisements() {
|
||||
const { providerAdvertisements } = await discoverAll();
|
||||
return providerAdvertisements;
|
||||
}
|
||||
|
||||
async function discoverAll() {
|
||||
await refreshLanDeckDiscovery();
|
||||
const manifestsByProvider = await discoverDeckProviderManifests();
|
||||
const eveInterfaces = await Promise.all(
|
||||
[...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, ...liveAnnouncements.interfaces]) {
|
||||
const existingIndex = interfaces.findIndex((candidate) => candidate.providerId === entry.providerId);
|
||||
if (existingIndex >= 0) {
|
||||
interfaces[existingIndex] = entry;
|
||||
} else {
|
||||
interfaces.push(entry);
|
||||
}
|
||||
}
|
||||
interfaces.sort((left, right) => left.providerId.localeCompare(right.providerId));
|
||||
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() {
|
||||
const {
|
||||
interfaceBindingDefinition,
|
||||
idunnDaemonHealthDefinition,
|
||||
muninnCaptureStreamDefinition,
|
||||
muninnCommandBoundaryDefinition,
|
||||
muninnMoveControllerStateDefinition,
|
||||
muninnMoveIdentityDefinition,
|
||||
muninnMoveLightCommandDefinition,
|
||||
muninnMoveMarkerCandidateDefinition,
|
||||
muninnObsStreamCatalogDefinition,
|
||||
muninnQuestAccessDefinition,
|
||||
muninnTelemetrySurfaceDefinition,
|
||||
muninnTransportProfileDefinition,
|
||||
operatorStateDefinition,
|
||||
providerAdvertisementDefinition,
|
||||
stonksCommandBoundaryDefinition,
|
||||
stonksMarketSnapshotDefinition,
|
||||
stonksRequestEventDefinition,
|
||||
stonksTransportProfileDefinition,
|
||||
streamPixelsCommandBoundaryDefinition,
|
||||
streamPixelsTransportProfileDefinition,
|
||||
surfaceDefinition,
|
||||
viliCommandBoundaryDefinition,
|
||||
viliTransportProfileDefinition,
|
||||
weksaCommandBoundaryDefinition,
|
||||
weksaOperatorStateDefinition,
|
||||
weksaTransportProfileDefinition,
|
||||
voidbotSwarmSnapshotDefinition,
|
||||
} = documents;
|
||||
return Boolean(
|
||||
CultMesh &&
|
||||
interfaceBindingDefinition &&
|
||||
idunnDaemonHealthDefinition &&
|
||||
muninnCaptureStreamDefinition &&
|
||||
muninnCommandBoundaryDefinition &&
|
||||
muninnMoveControllerStateDefinition &&
|
||||
muninnMoveIdentityDefinition &&
|
||||
muninnMoveLightCommandDefinition &&
|
||||
muninnMoveMarkerCandidateDefinition &&
|
||||
muninnObsStreamCatalogDefinition &&
|
||||
muninnQuestAccessDefinition &&
|
||||
muninnTelemetrySurfaceDefinition &&
|
||||
muninnTransportProfileDefinition &&
|
||||
operatorStateDefinition &&
|
||||
providerAdvertisementDefinition &&
|
||||
stonksCommandBoundaryDefinition &&
|
||||
stonksMarketSnapshotDefinition &&
|
||||
stonksRequestEventDefinition &&
|
||||
stonksTransportProfileDefinition &&
|
||||
streamPixelsCommandBoundaryDefinition &&
|
||||
streamPixelsTransportProfileDefinition &&
|
||||
surfaceDefinition &&
|
||||
viliCommandBoundaryDefinition &&
|
||||
viliTransportProfileDefinition &&
|
||||
weksaCommandBoundaryDefinition &&
|
||||
weksaOperatorStateDefinition &&
|
||||
weksaTransportProfileDefinition &&
|
||||
voidbotSwarmSnapshotDefinition
|
||||
);
|
||||
}
|
||||
|
||||
async function discoverDeckProviderManifests() {
|
||||
const manifestsByProvider = new Map();
|
||||
for (const deckUrl of discoveredDeckUrls) {
|
||||
await Promise.all(discoveredDeckUrls.map(async (deckUrl) => {
|
||||
const manifestUrl = deckUrl.replace(/^ws:/, "http:").replace(/\/eve\/deck.*$/, "/eve/deck/providers");
|
||||
try {
|
||||
const catalog = JSON.parse(await httpGet(manifestUrl, 2500));
|
||||
|
|
@ -40,25 +146,11 @@ function createInterfaceDiscovery({
|
|||
} catch {
|
||||
// Discovery is opportunistic. Failed endpoints fall out of the next pass.
|
||||
}
|
||||
}
|
||||
|
||||
const interfaces = [];
|
||||
for (const { provider, deckUrl } of manifestsByProvider.values()) {
|
||||
interfaces.push(await fetchEveProvider(deckUrl, provider.id, provider));
|
||||
}
|
||||
for (const entry of await discoverCultMeshInterfaceBindings()) {
|
||||
const existingIndex = interfaces.findIndex((candidate) => candidate.providerId === entry.providerId);
|
||||
if (existingIndex >= 0) {
|
||||
interfaces[existingIndex] = entry;
|
||||
} else {
|
||||
interfaces.push(entry);
|
||||
}
|
||||
}
|
||||
interfaces.sort((left, right) => left.providerId.localeCompare(right.providerId));
|
||||
return interfaces;
|
||||
}));
|
||||
return manifestsByProvider;
|
||||
}
|
||||
|
||||
async function discoverProviderAdvertisements() {
|
||||
async function discoverCultMeshEntries() {
|
||||
const {
|
||||
interfaceBindingDefinition,
|
||||
idunnDaemonHealthDefinition,
|
||||
|
|
@ -88,280 +180,87 @@ function createInterfaceDiscovery({
|
|||
weksaTransportProfileDefinition,
|
||||
voidbotSwarmSnapshotDefinition,
|
||||
} = documents;
|
||||
if (!CultMesh || !interfaceBindingDefinition || !idunnDaemonHealthDefinition || !muninnCaptureStreamDefinition || !muninnCommandBoundaryDefinition || !muninnMoveControllerStateDefinition || !muninnMoveIdentityDefinition || !muninnMoveLightCommandDefinition || !muninnMoveMarkerCandidateDefinition || !muninnObsStreamCatalogDefinition || !muninnQuestAccessDefinition || !muninnTelemetrySurfaceDefinition || !muninnTransportProfileDefinition || !operatorStateDefinition || !stonksCommandBoundaryDefinition || !stonksMarketSnapshotDefinition || !stonksRequestEventDefinition || !stonksTransportProfileDefinition || !streamPixelsCommandBoundaryDefinition || !streamPixelsTransportProfileDefinition || !surfaceDefinition || !viliCommandBoundaryDefinition || !viliTransportProfileDefinition || !weksaCommandBoundaryDefinition || !weksaOperatorStateDefinition || !weksaTransportProfileDefinition || !voidbotSwarmSnapshotDefinition || !providerAdvertisementDefinition) {
|
||||
return [];
|
||||
if (!cultMeshDocumentsAvailable()) {
|
||||
return { interfaces: [], providerAdvertisements: [] };
|
||||
}
|
||||
|
||||
const providers = [];
|
||||
for (const storeSpec of interfaceBindingStores) {
|
||||
const nodeDocuments = [
|
||||
voidbotSwarmSnapshotDefinition,
|
||||
stonksRequestEventDefinition,
|
||||
stonksMarketSnapshotDefinition,
|
||||
providerAdvertisementDefinition,
|
||||
interfaceBindingDefinition,
|
||||
surfaceDefinition,
|
||||
stonksCommandBoundaryDefinition,
|
||||
stonksTransportProfileDefinition,
|
||||
streamPixelsCommandBoundaryDefinition,
|
||||
streamPixelsTransportProfileDefinition,
|
||||
idunnDaemonHealthDefinition,
|
||||
muninnCaptureStreamDefinition,
|
||||
muninnCommandBoundaryDefinition,
|
||||
muninnMoveControllerStateDefinition,
|
||||
muninnMoveIdentityDefinition,
|
||||
muninnMoveLightCommandDefinition,
|
||||
muninnMoveMarkerCandidateDefinition,
|
||||
muninnObsStreamCatalogDefinition,
|
||||
muninnQuestAccessDefinition,
|
||||
muninnTelemetrySurfaceDefinition,
|
||||
muninnTransportProfileDefinition,
|
||||
operatorStateDefinition,
|
||||
viliCommandBoundaryDefinition,
|
||||
viliTransportProfileDefinition,
|
||||
weksaOperatorStateDefinition,
|
||||
weksaCommandBoundaryDefinition,
|
||||
weksaTransportProfileDefinition,
|
||||
];
|
||||
|
||||
const storeEntries = await Promise.all(interfaceBindingStores.map(async (storeSpec) => {
|
||||
let resolvedStore = null;
|
||||
try {
|
||||
resolvedStore = resolveInterfaceBindingStore(storeSpec);
|
||||
if (!resolvedStore) {
|
||||
continue;
|
||||
return { interfaces: [], providerAdvertisements: [] };
|
||||
}
|
||||
const { localPath: storePath, sourceId } = resolvedStore;
|
||||
if (!fs.existsSync(storePath)) {
|
||||
continue;
|
||||
return { interfaces: [], providerAdvertisements: [] };
|
||||
}
|
||||
const node = await CultMesh.createNode(storePath, {
|
||||
documents: [
|
||||
voidbotSwarmSnapshotDefinition,
|
||||
stonksRequestEventDefinition,
|
||||
stonksMarketSnapshotDefinition,
|
||||
providerAdvertisementDefinition,
|
||||
interfaceBindingDefinition,
|
||||
surfaceDefinition,
|
||||
stonksCommandBoundaryDefinition,
|
||||
stonksTransportProfileDefinition,
|
||||
streamPixelsCommandBoundaryDefinition,
|
||||
streamPixelsTransportProfileDefinition,
|
||||
idunnDaemonHealthDefinition,
|
||||
muninnCaptureStreamDefinition,
|
||||
muninnCommandBoundaryDefinition,
|
||||
muninnMoveControllerStateDefinition,
|
||||
muninnMoveIdentityDefinition,
|
||||
muninnMoveLightCommandDefinition,
|
||||
muninnMoveMarkerCandidateDefinition,
|
||||
muninnObsStreamCatalogDefinition,
|
||||
muninnQuestAccessDefinition,
|
||||
muninnTelemetrySurfaceDefinition,
|
||||
muninnTransportProfileDefinition,
|
||||
operatorStateDefinition,
|
||||
viliCommandBoundaryDefinition,
|
||||
viliTransportProfileDefinition,
|
||||
weksaOperatorStateDefinition,
|
||||
weksaCommandBoundaryDefinition,
|
||||
weksaTransportProfileDefinition,
|
||||
],
|
||||
const node = await CultMesh.createNode(storePath, { documents: nodeDocuments });
|
||||
return inspectCultMeshStore({
|
||||
documents,
|
||||
interfaceBindingDefinition,
|
||||
muninnTelemetrySurfaceDefinition,
|
||||
node,
|
||||
providerAdvertisementDefinition,
|
||||
sourceId,
|
||||
storePath,
|
||||
});
|
||||
const advertisements = typeof node.cache?.getAll === "function"
|
||||
? node.cache.getAll(providerAdvertisementDefinition).map(unwrapDocumentRecord)
|
||||
: [];
|
||||
for (const advertisement of advertisements) {
|
||||
const providerId = advertisement?.providerId || advertisement?.provider?.id || advertisement?.id;
|
||||
if (!providerId) {
|
||||
continue;
|
||||
}
|
||||
providers.push({
|
||||
id: providerId,
|
||||
title: advertisement.title || advertisement.provider?.title || providerId,
|
||||
description: advertisement.description || "Provider-owned CultMesh advertisement.",
|
||||
version: String(advertisement.version || 0),
|
||||
endpoint: advertisement.cultMeshAddress || advertisement.endpoints?.[0]?.address || advertisement.provider?.endpoint || `cultmesh:${sourceId}`,
|
||||
canonicalService: advertisement.canonicalService || null,
|
||||
locatedService: advertisement.locatedService || null,
|
||||
cultMeshAddress: advertisement.cultMeshAddress || null,
|
||||
endpoints: advertisement.endpoints || [],
|
||||
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
|
||||
|| `cultmesh:${sourceId}`,
|
||||
capabilities: advertisement.provider?.capabilities || advertisement.capabilities || [],
|
||||
operatorState: providerRecord(node, [
|
||||
operatorStateDefinition,
|
||||
weksaOperatorStateDefinition,
|
||||
], advertisement) || null,
|
||||
commandBoundary: providerRecord(node, [
|
||||
muninnCommandBoundaryDefinition,
|
||||
viliCommandBoundaryDefinition,
|
||||
weksaCommandBoundaryDefinition,
|
||||
stonksCommandBoundaryDefinition,
|
||||
streamPixelsCommandBoundaryDefinition,
|
||||
], advertisement) || null,
|
||||
transportProfile: providerRecord(node, [
|
||||
muninnTransportProfileDefinition,
|
||||
viliTransportProfileDefinition,
|
||||
weksaTransportProfileDefinition,
|
||||
stonksTransportProfileDefinition,
|
||||
streamPixelsTransportProfileDefinition,
|
||||
], advertisement) || null,
|
||||
usesCultMesh: true,
|
||||
transport: advertisement.provider?.transport || "CultMesh provider advertisement",
|
||||
status: advertisement.status || "unknown",
|
||||
updatedAt: advertisement.updatedAt || new Date().toISOString(),
|
||||
source: `cultmesh:${sourceId}`,
|
||||
commandSurface: advertisement.commandSurface || null,
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// Provider advertisements are optional discovery hints; broken stores
|
||||
// are still surfaced through interface discovery when possible.
|
||||
} catch (error) {
|
||||
const interfaces = [];
|
||||
const providerAdvertisements = [];
|
||||
if (resolvedStore?.localPath && fs.existsSync(resolvedStore.localPath)) {
|
||||
providers.push(...inspectProviderAdvertisementsFromStore(
|
||||
interfaces.push(...inspectCultMeshInterfacesFromStore(
|
||||
resolvedStore.localPath,
|
||||
resolvedStore.sourceId,
|
||||
));
|
||||
providerAdvertisements.push(...inspectProviderAdvertisementsFromStore(
|
||||
resolvedStore.localPath,
|
||||
resolvedStore.sourceId,
|
||||
));
|
||||
}
|
||||
if (interfaces.length === 0) {
|
||||
interfaces.push(dashboardUnavailable(`cultmesh:${storeSpec}`, `cultmesh:${storeSpec}`, error.message));
|
||||
}
|
||||
return { interfaces, providerAdvertisements };
|
||||
} finally {
|
||||
resolvedStore?.cleanup?.();
|
||||
}
|
||||
}
|
||||
}));
|
||||
|
||||
providers.sort((left, right) => String(left.id).localeCompare(String(right.id)));
|
||||
return providers;
|
||||
}
|
||||
|
||||
async function discoverCultMeshInterfaceBindings() {
|
||||
const {
|
||||
interfaceBindingDefinition,
|
||||
idunnDaemonHealthDefinition,
|
||||
muninnCaptureStreamDefinition,
|
||||
muninnCommandBoundaryDefinition,
|
||||
muninnMoveControllerStateDefinition,
|
||||
muninnMoveIdentityDefinition,
|
||||
muninnMoveLightCommandDefinition,
|
||||
muninnMoveMarkerCandidateDefinition,
|
||||
muninnObsStreamCatalogDefinition,
|
||||
muninnQuestAccessDefinition,
|
||||
muninnTelemetrySurfaceDefinition,
|
||||
muninnTransportProfileDefinition,
|
||||
operatorStateDefinition,
|
||||
providerAdvertisementDefinition,
|
||||
stonksCommandBoundaryDefinition,
|
||||
stonksMarketSnapshotDefinition,
|
||||
stonksRequestEventDefinition,
|
||||
stonksTransportProfileDefinition,
|
||||
streamPixelsCommandBoundaryDefinition,
|
||||
streamPixelsTransportProfileDefinition,
|
||||
surfaceDefinition,
|
||||
viliCommandBoundaryDefinition,
|
||||
viliTransportProfileDefinition,
|
||||
weksaCommandBoundaryDefinition,
|
||||
weksaOperatorStateDefinition,
|
||||
weksaTransportProfileDefinition,
|
||||
voidbotSwarmSnapshotDefinition,
|
||||
} = documents;
|
||||
if (!CultMesh || !interfaceBindingDefinition || !idunnDaemonHealthDefinition || !muninnCaptureStreamDefinition || !muninnCommandBoundaryDefinition || !muninnMoveControllerStateDefinition || !muninnMoveIdentityDefinition || !muninnMoveLightCommandDefinition || !muninnMoveMarkerCandidateDefinition || !muninnObsStreamCatalogDefinition || !muninnQuestAccessDefinition || !muninnTelemetrySurfaceDefinition || !muninnTransportProfileDefinition || !operatorStateDefinition || !stonksCommandBoundaryDefinition || !stonksMarketSnapshotDefinition || !stonksRequestEventDefinition || !stonksTransportProfileDefinition || !streamPixelsCommandBoundaryDefinition || !streamPixelsTransportProfileDefinition || !surfaceDefinition || !viliCommandBoundaryDefinition || !viliTransportProfileDefinition || !weksaCommandBoundaryDefinition || !weksaOperatorStateDefinition || !weksaTransportProfileDefinition || !voidbotSwarmSnapshotDefinition || !providerAdvertisementDefinition) {
|
||||
return [];
|
||||
}
|
||||
const interfaces = [];
|
||||
for (const storeSpec of interfaceBindingStores) {
|
||||
let resolvedStore = null;
|
||||
try {
|
||||
resolvedStore = resolveInterfaceBindingStore(storeSpec);
|
||||
if (!resolvedStore) {
|
||||
continue;
|
||||
}
|
||||
const { localPath: storePath, sourceId } = resolvedStore;
|
||||
if (!fs.existsSync(storePath)) {
|
||||
continue;
|
||||
}
|
||||
const node = await CultMesh.createNode(storePath, {
|
||||
documents: [
|
||||
voidbotSwarmSnapshotDefinition,
|
||||
stonksRequestEventDefinition,
|
||||
stonksMarketSnapshotDefinition,
|
||||
providerAdvertisementDefinition,
|
||||
interfaceBindingDefinition,
|
||||
surfaceDefinition,
|
||||
stonksCommandBoundaryDefinition,
|
||||
stonksTransportProfileDefinition,
|
||||
streamPixelsCommandBoundaryDefinition,
|
||||
streamPixelsTransportProfileDefinition,
|
||||
idunnDaemonHealthDefinition,
|
||||
muninnCaptureStreamDefinition,
|
||||
muninnCommandBoundaryDefinition,
|
||||
muninnMoveControllerStateDefinition,
|
||||
muninnMoveIdentityDefinition,
|
||||
muninnMoveLightCommandDefinition,
|
||||
muninnMoveMarkerCandidateDefinition,
|
||||
muninnObsStreamCatalogDefinition,
|
||||
muninnQuestAccessDefinition,
|
||||
muninnTelemetrySurfaceDefinition,
|
||||
muninnTransportProfileDefinition,
|
||||
operatorStateDefinition,
|
||||
viliCommandBoundaryDefinition,
|
||||
viliTransportProfileDefinition,
|
||||
weksaOperatorStateDefinition,
|
||||
weksaCommandBoundaryDefinition,
|
||||
weksaTransportProfileDefinition,
|
||||
],
|
||||
});
|
||||
const advertisements = typeof node.cache?.getAll === "function"
|
||||
? node.cache.getAll(providerAdvertisementDefinition).map(unwrapDocumentRecord)
|
||||
: [];
|
||||
for (const advertisement of advertisements) {
|
||||
if (!advertisement?.providerId) {
|
||||
continue;
|
||||
}
|
||||
const state = providerSurfaceState(
|
||||
node,
|
||||
advertisement,
|
||||
surfaceDefinition,
|
||||
muninnTelemetrySurfaceDefinition,
|
||||
);
|
||||
if (!state?.surface?.root) {
|
||||
continue;
|
||||
}
|
||||
interfaces.push(cultMeshProviderInterface({
|
||||
advertisement,
|
||||
state,
|
||||
storePath: sourceId,
|
||||
operatorState: providerRecord(node, [
|
||||
operatorStateDefinition,
|
||||
weksaOperatorStateDefinition,
|
||||
], advertisement) || null,
|
||||
commandBoundary: providerRecord(node, [
|
||||
muninnCommandBoundaryDefinition,
|
||||
viliCommandBoundaryDefinition,
|
||||
weksaCommandBoundaryDefinition,
|
||||
stonksCommandBoundaryDefinition,
|
||||
streamPixelsCommandBoundaryDefinition,
|
||||
], advertisement) || null,
|
||||
transportProfile: providerRecord(node, [
|
||||
muninnTransportProfileDefinition,
|
||||
viliTransportProfileDefinition,
|
||||
weksaTransportProfileDefinition,
|
||||
stonksTransportProfileDefinition,
|
||||
streamPixelsTransportProfileDefinition,
|
||||
], advertisement) || null,
|
||||
}));
|
||||
}
|
||||
const bindings = typeof node.cache?.getAll === "function"
|
||||
? node.cache.getAll(interfaceBindingDefinition).map(unwrapDocumentRecord)
|
||||
: [unwrapDocumentRecord(node.get(interfaceBindingDefinition, "voidbot.swarm"))].filter(Boolean);
|
||||
for (const binding of bindings) {
|
||||
if (!binding?.providerId) {
|
||||
continue;
|
||||
}
|
||||
const state = unwrapDocumentRecord(node.get(surfaceDefinition, binding.providerId));
|
||||
const surface = state?.surface || binding.surface || null;
|
||||
interfaces.push({
|
||||
providerId: binding.providerId,
|
||||
title: binding.title || state?.title || binding.providerId,
|
||||
state: "active",
|
||||
detail: `${surface?.root?.kind || binding.kind || "surface"} ${countSurfaceNodes(surface, state)} nodes via CultMesh`,
|
||||
version: state?.version || 0,
|
||||
updatedAt: state?.updatedAt || binding.updatedAt || new Date().toISOString(),
|
||||
source: `cultmesh:${sourceId}`,
|
||||
manifest: binding.provider || null,
|
||||
canonicalService: binding.provider?.canonicalService || null,
|
||||
locatedService: binding.provider?.locatedService || null,
|
||||
cultMeshAddress: binding.provider?.cultMeshAddress || binding.provider?.endpoint || null,
|
||||
endpoints: binding.provider?.endpoints || [],
|
||||
routes: binding.provider?.routes || [],
|
||||
surface,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
if (resolvedStore?.localPath && fs.existsSync(resolvedStore.localPath)) {
|
||||
const fallbackInterfaces = inspectCultMeshInterfacesFromStore(
|
||||
resolvedStore.localPath,
|
||||
resolvedStore.sourceId,
|
||||
);
|
||||
if (fallbackInterfaces.length > 0) {
|
||||
interfaces.push(...fallbackInterfaces);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
interfaces.push(dashboardUnavailable(`cultmesh:${storeSpec}`, `cultmesh:${storeSpec}`, error.message));
|
||||
} finally {
|
||||
resolvedStore?.cleanup?.();
|
||||
}
|
||||
}
|
||||
return interfaces;
|
||||
return {
|
||||
interfaces: storeEntries.flatMap((entry) => entry.interfaces),
|
||||
providerAdvertisements: storeEntries.flatMap((entry) => entry.providerAdvertisements),
|
||||
};
|
||||
}
|
||||
|
||||
async function refreshLanDeckDiscovery() {
|
||||
|
|
@ -383,6 +282,7 @@ function createInterfaceDiscovery({
|
|||
}
|
||||
|
||||
return {
|
||||
discoverAll,
|
||||
discoverProviderAdvertisements,
|
||||
discoverInterfaces,
|
||||
getDiscoveredDeckUrls: () => [...discoveredDeckUrls],
|
||||
|
|
@ -421,6 +321,146 @@ function cultMeshProviderInterface({
|
|||
};
|
||||
}
|
||||
|
||||
function inspectCultMeshStore({
|
||||
documents,
|
||||
interfaceBindingDefinition,
|
||||
muninnTelemetrySurfaceDefinition,
|
||||
node,
|
||||
providerAdvertisementDefinition,
|
||||
sourceId,
|
||||
}) {
|
||||
const {
|
||||
operatorStateDefinition,
|
||||
stonksCommandBoundaryDefinition,
|
||||
stonksTransportProfileDefinition,
|
||||
streamPixelsCommandBoundaryDefinition,
|
||||
streamPixelsTransportProfileDefinition,
|
||||
surfaceDefinition,
|
||||
viliCommandBoundaryDefinition,
|
||||
viliTransportProfileDefinition,
|
||||
weksaCommandBoundaryDefinition,
|
||||
weksaOperatorStateDefinition,
|
||||
weksaTransportProfileDefinition,
|
||||
muninnCommandBoundaryDefinition,
|
||||
muninnTransportProfileDefinition,
|
||||
} = documents;
|
||||
|
||||
const providerAdvertisements = [];
|
||||
const interfaces = [];
|
||||
const advertisements = typeof node.cache?.getAll === "function"
|
||||
? node.cache.getAll(providerAdvertisementDefinition).map(unwrapDocumentRecord)
|
||||
: [];
|
||||
|
||||
for (const advertisement of advertisements) {
|
||||
const providerId = advertisement?.providerId || advertisement?.provider?.id || advertisement?.id;
|
||||
if (!providerId) {
|
||||
continue;
|
||||
}
|
||||
providerAdvertisements.push({
|
||||
id: providerId,
|
||||
title: advertisement.title || advertisement.provider?.title || providerId,
|
||||
description: advertisement.description || "Provider-owned CultMesh advertisement.",
|
||||
version: String(advertisement.version || 0),
|
||||
endpoint: advertisement.cultMeshAddress || advertisement.endpoints?.[0]?.address || advertisement.provider?.endpoint || `cultmesh:${sourceId}`,
|
||||
canonicalService: advertisement.canonicalService || null,
|
||||
locatedService: advertisement.locatedService || null,
|
||||
cultMeshAddress: advertisement.cultMeshAddress || null,
|
||||
endpoints: advertisement.endpoints || [],
|
||||
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
|
||||
|| `cultmesh:${sourceId}`,
|
||||
capabilities: advertisement.provider?.capabilities || advertisement.capabilities || [],
|
||||
operatorState: providerRecord(node, [
|
||||
operatorStateDefinition,
|
||||
weksaOperatorStateDefinition,
|
||||
], advertisement) || null,
|
||||
commandBoundary: providerRecord(node, [
|
||||
muninnCommandBoundaryDefinition,
|
||||
viliCommandBoundaryDefinition,
|
||||
weksaCommandBoundaryDefinition,
|
||||
stonksCommandBoundaryDefinition,
|
||||
streamPixelsCommandBoundaryDefinition,
|
||||
], advertisement) || null,
|
||||
transportProfile: providerRecord(node, [
|
||||
muninnTransportProfileDefinition,
|
||||
viliTransportProfileDefinition,
|
||||
weksaTransportProfileDefinition,
|
||||
stonksTransportProfileDefinition,
|
||||
streamPixelsTransportProfileDefinition,
|
||||
], advertisement) || null,
|
||||
usesCultMesh: true,
|
||||
transport: advertisement.provider?.transport || "CultMesh provider advertisement",
|
||||
status: advertisement.status || "unknown",
|
||||
updatedAt: advertisement.updatedAt || new Date().toISOString(),
|
||||
source: `cultmesh:${sourceId}`,
|
||||
commandSurface: advertisement.commandSurface || null,
|
||||
});
|
||||
|
||||
const state = providerSurfaceState(
|
||||
node,
|
||||
advertisement,
|
||||
surfaceDefinition,
|
||||
muninnTelemetrySurfaceDefinition,
|
||||
);
|
||||
if (state?.surface?.root) {
|
||||
interfaces.push(cultMeshProviderInterface({
|
||||
advertisement,
|
||||
state,
|
||||
storePath: sourceId,
|
||||
operatorState: providerRecord(node, [
|
||||
operatorStateDefinition,
|
||||
weksaOperatorStateDefinition,
|
||||
], advertisement) || null,
|
||||
commandBoundary: providerRecord(node, [
|
||||
muninnCommandBoundaryDefinition,
|
||||
viliCommandBoundaryDefinition,
|
||||
weksaCommandBoundaryDefinition,
|
||||
stonksCommandBoundaryDefinition,
|
||||
streamPixelsCommandBoundaryDefinition,
|
||||
], advertisement) || null,
|
||||
transportProfile: providerRecord(node, [
|
||||
muninnTransportProfileDefinition,
|
||||
viliTransportProfileDefinition,
|
||||
weksaTransportProfileDefinition,
|
||||
stonksTransportProfileDefinition,
|
||||
streamPixelsTransportProfileDefinition,
|
||||
], advertisement) || null,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
const bindings = typeof node.cache?.getAll === "function"
|
||||
? node.cache.getAll(interfaceBindingDefinition).map(unwrapDocumentRecord)
|
||||
: [unwrapDocumentRecord(node.get(interfaceBindingDefinition, "voidbot.swarm"))].filter(Boolean);
|
||||
for (const binding of bindings) {
|
||||
if (!binding?.providerId) {
|
||||
continue;
|
||||
}
|
||||
const state = unwrapDocumentRecord(node.get(surfaceDefinition, binding.providerId));
|
||||
const surface = state?.surface || binding.surface || null;
|
||||
interfaces.push({
|
||||
providerId: binding.providerId,
|
||||
title: binding.title || state?.title || binding.providerId,
|
||||
state: "active",
|
||||
detail: `${surface?.root?.kind || binding.kind || "surface"} ${countSurfaceNodes(surface, state)} nodes via CultMesh`,
|
||||
version: state?.version || 0,
|
||||
updatedAt: state?.updatedAt || binding.updatedAt || new Date().toISOString(),
|
||||
source: `cultmesh:${sourceId}`,
|
||||
manifest: binding.provider || null,
|
||||
canonicalService: binding.provider?.canonicalService || null,
|
||||
locatedService: binding.provider?.locatedService || null,
|
||||
cultMeshAddress: binding.provider?.cultMeshAddress || binding.provider?.endpoint || null,
|
||||
endpoints: binding.provider?.endpoints || [],
|
||||
routes: binding.provider?.routes || [],
|
||||
surface,
|
||||
});
|
||||
}
|
||||
|
||||
return { interfaces, providerAdvertisements };
|
||||
}
|
||||
|
||||
function providerSurfaceState(node, advertisement, surfaceDefinition, muninnTelemetrySurfaceDefinition) {
|
||||
const surfaceKey = advertisement.surfaceId || advertisement.surface_id || advertisement.providerId;
|
||||
const surfaceState = unwrapDocumentRecord(node.get?.(surfaceDefinition, surfaceKey));
|
||||
|
|
@ -973,166 +1013,17 @@ function resolveInterfaceBindingStore(storeSpec) {
|
|||
if (typeof storeSpec !== "string" || !storeSpec.trim()) {
|
||||
return null;
|
||||
}
|
||||
if (!storeSpec.startsWith("sftp://")) {
|
||||
return {
|
||||
localPath: storeSpec,
|
||||
sourceId: storeSpec,
|
||||
cleanup: () => {},
|
||||
};
|
||||
}
|
||||
|
||||
const url = new URL(storeSpec);
|
||||
const host = url.hostname;
|
||||
let remotePath = decodeURIComponent(url.pathname);
|
||||
if (/^\/[A-Za-z]:\//.test(remotePath)) {
|
||||
remotePath = remotePath.slice(1);
|
||||
}
|
||||
if (!host || !remotePath) {
|
||||
throw new Error(`invalid sftp interface binding store: ${storeSpec}`);
|
||||
}
|
||||
|
||||
const cacheRoot = path.join(os.tmpdir(), "odin-cultmesh-stores");
|
||||
fs.mkdirSync(cacheRoot, { recursive: true });
|
||||
const suffix = path.extname(remotePath) || ".cc";
|
||||
const stem = `${stableId(host)}-${stableId(remotePath)}`;
|
||||
const transferId = `${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2, 10)}`;
|
||||
const localPath = path.join(cacheRoot, `${stem}-${transferId}${suffix}`);
|
||||
const batchPath = path.join(cacheRoot, `${stem}-${transferId}.sftp`);
|
||||
const stagedRemotePath = stageRemoteStoreForRead(host, remotePath, `${stem}-${transferId}`, suffix);
|
||||
fs.writeFileSync(
|
||||
batchPath,
|
||||
`get "${stagedRemotePath}" "${localPath.replace(/\\/g, "/")}"\n`,
|
||||
"ascii",
|
||||
);
|
||||
try {
|
||||
const result = childProcess.spawnSync(
|
||||
"sftp.exe",
|
||||
["-o", "BatchMode=yes", "-o", "ConnectTimeout=10", "-b", batchPath, host],
|
||||
{
|
||||
encoding: "utf8",
|
||||
timeout: 15000,
|
||||
windowsHide: true,
|
||||
},
|
||||
);
|
||||
if (result.status !== 0) {
|
||||
throw new Error((result.stderr || result.stdout || `sftp exited ${result.status}`).trim());
|
||||
}
|
||||
} finally {
|
||||
cleanupRemoteStagedStore(host, stagedRemotePath);
|
||||
try {
|
||||
fs.rmSync(batchPath, { force: true });
|
||||
} catch {
|
||||
// Best-effort temp cleanup. A later pass can reuse a fresh transfer id.
|
||||
}
|
||||
if (storeSpec.startsWith("sftp://")) {
|
||||
throw new Error(`remote interface binding stores are no longer supported by Odin discovery: ${storeSpec}`);
|
||||
}
|
||||
|
||||
return {
|
||||
localPath,
|
||||
localPath: storeSpec,
|
||||
sourceId: storeSpec,
|
||||
cleanup: () => {
|
||||
try {
|
||||
fs.rmSync(localPath, { force: true });
|
||||
} catch {
|
||||
// Best-effort temp cleanup. Live readers may still be releasing handles.
|
||||
}
|
||||
},
|
||||
cleanup: () => {},
|
||||
};
|
||||
}
|
||||
|
||||
function stageRemoteStoreForRead(host, remotePath, stem, suffix) {
|
||||
const stagedRemotePath = isWindowsRemoteStorePath(remotePath)
|
||||
? `C:/Windows/Temp/odin-interface-${stem}${suffix}`
|
||||
: `/tmp/odin-interface-${stem}${suffix}`;
|
||||
if (isWindowsRemoteStorePath(remotePath)) {
|
||||
const script = [
|
||||
"$ErrorActionPreference = 'Stop'",
|
||||
`$sourcePath = ${quotePowerShellSingle(remotePath)}`,
|
||||
`$stagedPath = ${quotePowerShellSingle(stagedRemotePath)}`,
|
||||
"$lockPath = $sourcePath + '.lock'",
|
||||
"if (-not (Test-Path -LiteralPath $sourcePath)) { throw \"remote store missing at $sourcePath\" }",
|
||||
"New-Item -ItemType Directory -Force -Path (Split-Path -Parent $stagedPath) | Out-Null",
|
||||
"$lockStream = [System.IO.File]::Open($lockPath, [System.IO.FileMode]::OpenOrCreate, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::ReadWrite)",
|
||||
"try {",
|
||||
" $lockStream.Lock(0, 1)",
|
||||
" Copy-Item -LiteralPath $sourcePath -Destination $stagedPath -Force",
|
||||
"} finally {",
|
||||
" try { $lockStream.Unlock(0, 1) } catch {}",
|
||||
" $lockStream.Dispose()",
|
||||
"}",
|
||||
].join("\n");
|
||||
runRemoteCommand(
|
||||
host,
|
||||
`powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand ${encodePowerShellCommand(script)}`,
|
||||
);
|
||||
} else {
|
||||
const command = [
|
||||
"set -eu",
|
||||
`src=${quotePosixSingle(remotePath)}`,
|
||||
`staged=${quotePosixSingle(stagedRemotePath)}`,
|
||||
'lock="${src}.lock"',
|
||||
'mkdir -p "$(dirname "$staged")"',
|
||||
'if [ -e "$lock" ]; then',
|
||||
' exec 9<"$lock"',
|
||||
' flock -s 9',
|
||||
'fi',
|
||||
'cp "$src" "$staged"',
|
||||
].join("\n");
|
||||
runRemoteCommand(host, `sh -lc ${quotePosixSingle(command)}`);
|
||||
}
|
||||
return stagedRemotePath;
|
||||
}
|
||||
|
||||
function cleanupRemoteStagedStore(host, stagedRemotePath) {
|
||||
try {
|
||||
if (isWindowsRemoteStorePath(stagedRemotePath)) {
|
||||
const script = [
|
||||
"$ErrorActionPreference = 'SilentlyContinue'",
|
||||
`$stagedPath = ${quotePowerShellSingle(stagedRemotePath)}`,
|
||||
"Remove-Item -LiteralPath $stagedPath -Force -ErrorAction SilentlyContinue",
|
||||
].join("\n");
|
||||
runRemoteCommand(
|
||||
host,
|
||||
`powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand ${encodePowerShellCommand(script)}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
runRemoteCommand(host, `sh -lc ${quotePosixSingle(`rm -f ${quotePosixSingle(stagedRemotePath)}`)}`);
|
||||
} catch {
|
||||
// Temp snapshot cleanup is opportunistic.
|
||||
}
|
||||
}
|
||||
|
||||
function runRemoteCommand(host, command) {
|
||||
const result = childProcess.spawnSync(
|
||||
"ssh.exe",
|
||||
["-o", "BatchMode=yes", "-o", "ConnectTimeout=10", host, command],
|
||||
{
|
||||
encoding: "utf8",
|
||||
timeout: 15000,
|
||||
windowsHide: true,
|
||||
},
|
||||
);
|
||||
if (result.status !== 0) {
|
||||
throw new Error((result.stderr || result.stdout || `ssh exited ${result.status}`).trim());
|
||||
}
|
||||
}
|
||||
|
||||
function isWindowsRemoteStorePath(remotePath) {
|
||||
return /^[A-Za-z]:\//.test(remotePath);
|
||||
}
|
||||
|
||||
function encodePowerShellCommand(script) {
|
||||
return Buffer.from(script, "utf16le").toString("base64");
|
||||
}
|
||||
|
||||
function quotePowerShellSingle(value) {
|
||||
return `'${String(value).replace(/'/g, "''")}'`;
|
||||
}
|
||||
|
||||
function quotePosixSingle(value) {
|
||||
return `'${String(value).replace(/'/g, `'\\''`)}'`;
|
||||
}
|
||||
|
||||
function localIpv4Prefixes() {
|
||||
const prefixes = new Set();
|
||||
for (const entries of Object.values(os.networkInterfaces())) {
|
||||
|
|
|
|||
173
src/odin/provider-ingress.cjs
Normal file
173
src/odin/provider-ingress.cjs
Normal file
|
|
@ -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,
|
||||
};
|
||||
|
|
@ -39,17 +39,27 @@ function createStateBuilder({ cachePath, gamecultTextDocumentStorePath, interfac
|
|||
async function buildState() {
|
||||
version += 1;
|
||||
const observedAt = new Date().toISOString();
|
||||
const [docker, adb, hosts, yggdrasilServices, nightwingServices, nightwingGpu, discoveredInterfaces, providerAdvertisements, observations] = await Promise.all([
|
||||
const [
|
||||
docker,
|
||||
adb,
|
||||
hosts,
|
||||
yggdrasilServices,
|
||||
nightwingServices,
|
||||
nightwingGpu,
|
||||
discovery,
|
||||
observations,
|
||||
] = await Promise.all([
|
||||
dockerSnapshot(),
|
||||
adbSnapshot(),
|
||||
hostChecks(),
|
||||
remoteServices("ygg", ["nginx", "streampixels-web", "streampixels-service", "heimdall", "repixelizer-gui", "bifrost"]),
|
||||
remoteServices("nightwing", ["ssh", "nightwing-eve-dashboard", "nightwing-eve-browser-reference", "gjallar", "docker"]),
|
||||
remoteGpu("nightwing"),
|
||||
interfaceDiscovery.discoverInterfaces(),
|
||||
interfaceDiscovery.discoverProviderAdvertisements(),
|
||||
interfaceDiscovery.discoverAll(),
|
||||
observationSnapshot(observationLogPath, observationFreshSeconds),
|
||||
]);
|
||||
const discoveredInterfaces = discovery.interfaces;
|
||||
const providerAdvertisements = discovery.providerAdvertisements;
|
||||
const interfaceById = new Map(discoveredInterfaces.map((entry) => [entry.providerId, entry]));
|
||||
const interfaces = [...interfaceById.values()];
|
||||
const marqueeText = await buildMarqueeText({ interfaces, textDocumentStorePath: gamecultTextDocumentStorePath, stonksBurstSize, stonksStateUrl });
|
||||
|
|
|
|||
|
|
@ -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)));
|
||||
|
|
|
|||
Loading…
Reference in a new issue