145 lines
7.0 KiB
JavaScript
145 lines
7.0 KiB
JavaScript
import { ReplayTimeline, fnv1a64 } from "./replay.mjs";
|
|
import { capabilities, validateLimit } from "./capabilities.mjs";
|
|
import { mapCoreError } from "./error-map.mjs";
|
|
|
|
const PROTOCOL_SCHEMA = 1;
|
|
const CONTEXT_ID = "linuxcnc-2.10.0-pre0-wasm-m0-c1";
|
|
|
|
function text(value) {
|
|
return typeof value === "string" && value.length > 0 ? value : null;
|
|
}
|
|
|
|
function call(core, name, ...args) {
|
|
if (args.some((value) => typeof value === "string") && typeof core.ccall === "function") {
|
|
return core.ccall(name, "number", args.map((value) => typeof value === "string" ? "string" : "number"), args);
|
|
}
|
|
const direct = core[`_${name}`] ?? core[name];
|
|
if (typeof direct === "function") return direct(...args);
|
|
if (typeof core.cwrap === "function") {
|
|
const wrapped = core.cwrap(name, "number", args.map((value) => typeof value === "string" ? "string" : "number"));
|
|
return wrapped(...args);
|
|
}
|
|
throw new Error(`missing core export: ${name}`);
|
|
}
|
|
|
|
function appendCoreEvent(core, seq, tick, kind, payload) {
|
|
if (typeof core.ccall !== "function") return 0;
|
|
const bytes = new TextEncoder().encode(canonicalPayload(payload));
|
|
return core.ccall("sim_event_append", "number", ["number", "number", "string", "array", "number"], [seq, tick, kind, bytes, bytes.length]);
|
|
}
|
|
|
|
function canonicalPayload(value) {
|
|
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
if (Array.isArray(value)) return `[${value.map(canonicalPayload).join(",")}]`;
|
|
return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalPayload(value[key])}`).join(",")}}`;
|
|
}
|
|
|
|
export class SimSession {
|
|
constructor(core, { contextId = CONTEXT_ID, sessionId = "" } = {}) {
|
|
this.core = core;
|
|
this.contextId = contextId;
|
|
this.sessionId = sessionId;
|
|
this.tick = 0;
|
|
this.created = false;
|
|
this.timeline = new ReplayTimeline();
|
|
call(core, "sim_protocol_reset");
|
|
if (typeof core.ccall === "function") core.ccall("sim_event_reset", null, [], []);
|
|
}
|
|
|
|
envelope(kind, input, payload, tick = this.tick) {
|
|
return {
|
|
schema_version: PROTOCOL_SCHEMA,
|
|
kind,
|
|
context_id: this.contextId,
|
|
session_id: this.sessionId,
|
|
seq: input.seq,
|
|
...(text(input.operation_id) ? { operation_id: input.operation_id } : {}),
|
|
simulation_tick: tick,
|
|
payload,
|
|
};
|
|
}
|
|
|
|
error(input, code, messageKey, retryable = false) {
|
|
return this.envelope("ERROR", input, {
|
|
status: "error",
|
|
code,
|
|
message_key: messageKey,
|
|
retryable,
|
|
operation_id: input.operation_id ?? null,
|
|
simulation_tick: this.tick,
|
|
});
|
|
}
|
|
|
|
coreError(input, result, source) {
|
|
const mapped = mapCoreError(result, { operation_id: input.operation_id, simulation_tick: this.tick, source });
|
|
return this.envelope("ERROR", input, mapped);
|
|
}
|
|
|
|
validateEnvelope(input) {
|
|
if (!input || typeof input !== "object") return ["protocol_argument", "invalid_envelope"];
|
|
if (input.schema_version !== PROTOCOL_SCHEMA) return ["protocol_schema", "unsupported_schema"];
|
|
if (input.context_id !== this.contextId) return ["protocol_context", "context_mismatch"];
|
|
if (!text(input.kind) || !Number.isSafeInteger(input.seq) || input.seq <= 0) return ["protocol_argument", "invalid_sequence_or_kind"];
|
|
if (this.sessionId && input.session_id !== this.sessionId) return ["protocol_session", "session_mismatch"];
|
|
if (!this.sessionId && text(input.session_id)) this.sessionId = input.session_id;
|
|
return null;
|
|
}
|
|
|
|
accept(input) {
|
|
const invalid = this.validateEnvelope(input);
|
|
if (invalid) return this.error(input ?? {}, invalid[0], invalid[1]);
|
|
const result = call(this.core, "sim_protocol_accept", input.schema_version, input.seq, input.kind, input.operation_id ?? "", input.simulation_tick ?? this.tick);
|
|
if (result !== 0) return this.coreError(input, result, "sim_protocol_accept");
|
|
if (Number.isSafeInteger(input.simulation_tick) && input.simulation_tick >= this.tick) this.tick = input.simulation_tick;
|
|
const eventTick = input.kind === "SIM_STEP" && Number.isSafeInteger(input.payload?.cycles)
|
|
? this.tick + input.payload.cycles : this.tick;
|
|
try {
|
|
this.timeline.appendEvent(input.seq, eventTick, input.kind, input.payload ?? {});
|
|
} catch (error) {
|
|
return this.error(input, "event_log", String(error?.message ?? error));
|
|
}
|
|
const coreEventResult = appendCoreEvent(this.core, input.seq, eventTick, input.kind, input.payload ?? {});
|
|
if (coreEventResult !== 0) return this.error(input, "event_log", "core_event_append_failed");
|
|
|
|
switch (input.kind) {
|
|
case "HELLO":
|
|
return this.envelope("CAPABILITIES", input, capabilities(this.contextId));
|
|
case "SESSION_ATTACH":
|
|
if (!this.created) {
|
|
const createResult = call(this.core, "sim_create", 0, 0);
|
|
if (createResult !== 0) return this.coreError(input, createResult, "sim_create");
|
|
this.created = true;
|
|
}
|
|
return this.envelope("SESSION_READY", input, { state_hash: fnv1a64({ tick: this.tick }), subscriptions: [] });
|
|
case "LOAD_WORKSPACE": {
|
|
const rootPath = input.payload?.root_path;
|
|
if (!text(rootPath) || !rootPath.startsWith("/") || rootPath.includes("..")) return this.error(input, "workspace_path", "invalid_workspace_path");
|
|
const loadResult = call(this.core, "sim_load_workspace", rootPath);
|
|
return loadResult === 0 ? this.envelope("COMMAND_RESULT", input, { status: "verified", command: input.kind, state_hash: fnv1a64({ tick: this.tick }) }) : this.coreError(input, loadResult, "sim_load_workspace");
|
|
}
|
|
case "SIM_STEP": {
|
|
const cycles = input.payload?.cycles;
|
|
const limit = validateLimit("max_tick_step", cycles);
|
|
if (limit.status !== "accepted") return this.envelope("ERROR", input, { ...limit, operation_id: input.operation_id ?? null, simulation_tick: this.tick, retryable: false });
|
|
const stepResult = call(this.core, "sim_step", cycles);
|
|
if (stepResult !== 0) return this.coreError(input, stepResult, "sim_step");
|
|
this.tick += cycles;
|
|
const protocolTick = call(this.core, "sim_protocol_set_tick", this.tick);
|
|
if (protocolTick !== 0) return this.error(input, "protocol_tick", "tick_update_failed");
|
|
const snapshot = this.timeline.checkpoint(input.seq, this.tick, { tick: this.tick, cycles }, this.timeline.snapshots.latest()?.snapshot_id ?? null);
|
|
return this.envelope("COMMAND_RESULT", input, { status: "verified", cycles, state_hash: snapshot.state_hash, snapshot });
|
|
}
|
|
case "SNAPSHOT_REQUEST":
|
|
return this.envelope("STATE_SNAPSHOT", input, { snapshot_schema: 1, tick: this.tick, state_hash: fnv1a64({ tick: this.tick }), snapshot: this.timeline.snapshots.latest() });
|
|
case "DESTROY":
|
|
call(this.core, "sim_destroy");
|
|
this.created = false;
|
|
return this.envelope("COMMAND_RESULT", input, { status: "verified", destroyed: true, replay: this.timeline.export() });
|
|
default:
|
|
return this.envelope("COMMAND_RESULT", input, { status: "verified", command: input.kind });
|
|
}
|
|
}
|
|
}
|
|
|
|
export { CONTEXT_ID, PROTOCOL_SCHEMA };
|