mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 12:02:50 +08:00
feat(skin): prototype bounded wasm UI event loop
This commit is contained in:
1 parent
dd0d779e49
commit
26b74c5be4
6 files changed
+229
-7
No files matched your search
@@ -0,0 +1,85 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
createSkinExtensionWasmUiLoopPrototype,
|
||||
SKIN_EXTENSION_WASM_UI_EVENT_QUEUE_LIMIT,
|
||||
} from "./skin-extension-wasm-ui-loop.js";
|
||||
import type { SkinExtensionUiInput } from "../../../src/shared/skin-extension-ui-input.js";
|
||||
|
||||
function uiOutput(count: number): string {
|
||||
return JSON.stringify({
|
||||
schemaVersion: 5,
|
||||
components: [{
|
||||
id: "counter",
|
||||
name: "Counter",
|
||||
page: "voice",
|
||||
accessibleName: "Local counter",
|
||||
state: { count },
|
||||
root: { tag: "button", events: { click: "increment" }, children: [{ text: String(count) }] },
|
||||
}],
|
||||
});
|
||||
}
|
||||
|
||||
function clickInput(count: number, handlerId = "increment"): unknown {
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
state: { count },
|
||||
event: { componentId: "counter", handlerId, eventName: "click" },
|
||||
};
|
||||
}
|
||||
|
||||
test("Wasm UI callback reruns receive only declared component state and replace validated output", async () => {
|
||||
const jobs: SkinExtensionUiInput[] = [];
|
||||
const outputDocuments: string[] = [];
|
||||
const loop = createSkinExtensionWasmUiLoopPrototype({
|
||||
createRun(input) {
|
||||
jobs.push(input);
|
||||
const count = input.event ? Number(input.state.count) + 1 : 0;
|
||||
return { result: Promise.resolve({ uiOutput: uiOutput(count) }), close: () => undefined };
|
||||
},
|
||||
onOutput(output) { outputDocuments.push(output); },
|
||||
});
|
||||
|
||||
assert.equal(await loop.start(), true);
|
||||
assert.equal(loop.output, uiOutput(0));
|
||||
assert.equal(await loop.dispatch(clickInput(0)), true);
|
||||
assert.equal(loop.output, uiOutput(1));
|
||||
assert.deepEqual(jobs.map((job) => job.event), [null, { componentId: "counter", handlerId: "increment", eventName: "click" }]);
|
||||
assert.deepEqual({ ...jobs[1].state }, { count: 0 });
|
||||
assert.equal(outputDocuments.length, 2);
|
||||
assert.equal(await loop.dispatch(clickInput(1, "not-a-real-handler")), false);
|
||||
assert.equal(await loop.dispatch({
|
||||
schemaVersion: 1,
|
||||
state: { count: 1, injected: "value" },
|
||||
event: { componentId: "counter", handlerId: "increment", eventName: "click" },
|
||||
}), false);
|
||||
assert.equal(jobs.length, 2, "invalid or stale callbacks must not start a Wasm job");
|
||||
loop.close();
|
||||
});
|
||||
|
||||
test("Wasm UI callback queue is bounded and close cancels active and waiting work", async () => {
|
||||
let rejectActive!: (error: Error) => void;
|
||||
let held = false;
|
||||
const loop = createSkinExtensionWasmUiLoopPrototype({
|
||||
createRun(input) {
|
||||
if (input.event && !held) {
|
||||
held = true;
|
||||
const result = new Promise<{ uiOutput: string | null }>((_resolve, reject) => { rejectActive = reject; });
|
||||
return { result, close: () => rejectActive(new Error("closed")) };
|
||||
}
|
||||
return { result: Promise.resolve({ uiOutput: uiOutput(0) }), close: () => undefined };
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(await loop.start(), true);
|
||||
const active = loop.dispatch(clickInput(0));
|
||||
const pending = Array.from({ length: SKIN_EXTENSION_WASM_UI_EVENT_QUEUE_LIMIT }, () => loop.dispatch(clickInput(0)));
|
||||
assert.equal(loop.pendingEventCount, SKIN_EXTENSION_WASM_UI_EVENT_QUEUE_LIMIT);
|
||||
assert.equal(await loop.dispatch(clickInput(0)), false);
|
||||
|
||||
loop.close("skin-unmounted");
|
||||
assert.equal(await active, false);
|
||||
assert.deepEqual(await Promise.all(pending), Array(SKIN_EXTENSION_WASM_UI_EVENT_QUEUE_LIMIT).fill(false));
|
||||
assert.equal(loop.pendingEventCount, 0);
|
||||
assert.equal(loop.closed, true);
|
||||
});
|
||||
@@ -0,0 +1,136 @@
|
||||
import {
|
||||
parseSkinExtensionUiInput,
|
||||
type SkinExtensionUiInput,
|
||||
} from "../../../src/shared/skin-extension-ui-input.js";
|
||||
import { parseSkinExtensionUiOutput } from "../../../src/shared/skin-extension-ui.js";
|
||||
import type { SkinPluginComponent, SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
|
||||
import type { SkinExtensionWasmSandboxResult } from "./skin-extension-wasm-sandbox.js";
|
||||
|
||||
export const SKIN_EXTENSION_WASM_UI_EVENT_QUEUE_LIMIT = 8;
|
||||
|
||||
export interface SkinExtensionWasmUiLoopRunHandle {
|
||||
result: Promise<Pick<SkinExtensionWasmSandboxResult, "uiOutput">>;
|
||||
close(reason?: string): void;
|
||||
}
|
||||
|
||||
export interface SkinExtensionWasmUiLoopOptions {
|
||||
/** Creates one bounded, disposable Wasm job for the supplied UI input. */
|
||||
createRun(input: SkinExtensionUiInput): SkinExtensionWasmUiLoopRunHandle;
|
||||
onOutput?(output: string, document: SkinPluginDocument): void | Promise<void>;
|
||||
onError?(error: Error): void;
|
||||
}
|
||||
|
||||
export class SkinExtensionWasmUiLoopError extends Error {
|
||||
constructor(readonly code: string, message: string) {
|
||||
super(message);
|
||||
this.name = "SkinExtensionWasmUiLoopError";
|
||||
}
|
||||
}
|
||||
|
||||
function isDeclaredCallback(component: SkinPluginComponent, handlerId: string, eventName: string): boolean {
|
||||
let found = false;
|
||||
const visit = (node: SkinPluginComponent["root"]): void => {
|
||||
if (node.events?.[eventName as keyof typeof node.events] === handlerId) found = true;
|
||||
node.children?.forEach(visit);
|
||||
};
|
||||
visit(component.root);
|
||||
return found;
|
||||
}
|
||||
|
||||
function acceptsEvent(document: SkinPluginDocument | null, input: SkinExtensionUiInput): boolean {
|
||||
const event = input.event;
|
||||
if (!document || !event) return false;
|
||||
const component = document.components.find((candidate) => candidate.id === event.componentId);
|
||||
if (!component?.runtimeCallbacks || !component.state) return false;
|
||||
if (Object.keys(input.state).some((key) => !Object.hasOwn(component.state!, key))) return false;
|
||||
return isDeclaredCallback(component, event.handlerId, event.eventName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Development-only callback lifecycle. Every event starts a fresh bounded job;
|
||||
* plugin memory and execution state never persist outside the explicit scalar UI state.
|
||||
*/
|
||||
export function createSkinExtensionWasmUiLoopPrototype(options: SkinExtensionWasmUiLoopOptions) {
|
||||
let started = false;
|
||||
let closed = false;
|
||||
let running = false;
|
||||
let output: string | null = null;
|
||||
let document: SkinPluginDocument | null = null;
|
||||
let activeRun: SkinExtensionWasmUiLoopRunHandle | null = null;
|
||||
const queue: Array<{ input: SkinExtensionUiInput; resolve: (ran: boolean) => void }> = [];
|
||||
|
||||
function report(error: unknown): void {
|
||||
try { options.onError?.(error instanceof Error ? error : new Error("The bounded Wasm UI callback failed.")); }
|
||||
catch { /* Host diagnostics must not interrupt queued callback cleanup. */ }
|
||||
}
|
||||
|
||||
async function execute(input: SkinExtensionUiInput): Promise<boolean> {
|
||||
let run: SkinExtensionWasmUiLoopRunHandle | null = null;
|
||||
try {
|
||||
run = options.createRun(input);
|
||||
activeRun = run;
|
||||
const result = await run.result;
|
||||
if (closed || activeRun !== run) return false;
|
||||
if (result.uiOutput !== null) {
|
||||
const nextDocument = parseSkinExtensionUiOutput(result.uiOutput);
|
||||
output = result.uiOutput;
|
||||
document = nextDocument;
|
||||
await options.onOutput?.(output, nextDocument);
|
||||
}
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (!closed) report(error);
|
||||
return false;
|
||||
} finally {
|
||||
if (activeRun === run) activeRun = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function drain(): Promise<void> {
|
||||
if (running || closed) return;
|
||||
running = true;
|
||||
try {
|
||||
while (queue.length && !closed) {
|
||||
const pending = queue.shift()!;
|
||||
if (!acceptsEvent(document, pending.input)) {
|
||||
pending.resolve(false);
|
||||
continue;
|
||||
}
|
||||
pending.resolve(await execute(pending.input));
|
||||
}
|
||||
} finally {
|
||||
running = false;
|
||||
if (queue.length && !closed) void drain();
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
get output() { return output; },
|
||||
get pendingEventCount() { return queue.length; },
|
||||
get running() { return running || activeRun !== null; },
|
||||
get closed() { return closed; },
|
||||
async start(): Promise<boolean> {
|
||||
if (started || closed) throw new SkinExtensionWasmUiLoopError("SKIN_EXTENSION_WASM_UI_LOOP_STATE", "The Wasm UI loop has already started or closed.");
|
||||
started = true;
|
||||
const initialInput = parseSkinExtensionUiInput({ schemaVersion: 1, state: {}, event: null });
|
||||
return execute(initialInput);
|
||||
},
|
||||
dispatch(inputValue: unknown): Promise<boolean> {
|
||||
if (!started || closed) return Promise.resolve(false);
|
||||
let input: SkinExtensionUiInput;
|
||||
try { input = parseSkinExtensionUiInput(inputValue); }
|
||||
catch { return Promise.resolve(false); }
|
||||
if (!acceptsEvent(document, input) || queue.length >= SKIN_EXTENSION_WASM_UI_EVENT_QUEUE_LIMIT) return Promise.resolve(false);
|
||||
const result = new Promise<boolean>((resolve) => queue.push({ input, resolve }));
|
||||
void drain();
|
||||
return result;
|
||||
},
|
||||
close(reason = "closed"): void {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
queue.splice(0).forEach((pending) => pending.resolve(false));
|
||||
activeRun?.close(reason);
|
||||
activeRun = null;
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user