Files
core/sdk/javascript/dever_component.mjs
T
2026-11-27 06:03:56 +00:00

118 lines
5.0 KiB
JavaScript

import { Channel, ProtocolError, exact } from './wire.mjs';
import { typed } from './types.mjs';
export class BusinessError extends Error {
constructor(identity, payload) {
super(identity);
this.identity = identity;
this.payload = payload;
}
}
async function stop(active) {
active.controller.abort();
let timer;
try {
await Promise.race([
active.done,
new Promise((_, reject) => { timer = setTimeout(() => reject(new ProtocolError('handler did not stop after cancellation')), 1000); }),
]);
} finally { clearTimeout(timer); }
}
export class Worker {
constructor(manifest, handlers) {
exact(handlers, manifest.operations);
if (Object.values(handlers).some(handler => typeof handler !== 'function')) throw new TypeError('expected Worker handlers');
this.manifest = manifest;
this.handlers = handlers;
}
async serve() {
const channel = new Channel();
try { await this.#serve(channel); }
finally { channel.close(); }
}
async #serve(channel) {
const manifest = this.manifest;
const hello = await channel.receive();
exact(hello, ['kind', 'version', 'port', 'schema', 'adapter', 'operations', 'capabilities', 'setting']);
const identity = Object.fromEntries(['port', 'schema', 'adapter', 'operations', 'capabilities'].map(name => [name, manifest[name]]));
if (hello.kind !== 'hello' || hello.version !== 'dever-component-1' || Object.entries(identity).some(([name, value]) => JSON.stringify(hello[name]) !== JSON.stringify(value))) throw new ProtocolError('handshake differs from the checked Port');
const setting = hello.setting;
if (manifest.setting !== null) typed(setting, manifest.setting);
else if (setting !== null) throw new ProtocolError('unexpected setting');
await channel.send({ ...identity, kind: 'ready', version: 'dever-component-1' });
// 只保留一个管道读取和一个当前 handler,不另建消息队列或调度器。
const read = () => channel.receive().then(frame => ({ frame }), fault => ({ fault }));
let pending = read();
let active = null;
let next = 1;
let cancelled = false;
try {
for (;;) {
const event = await (active ? Promise.race([pending, active.done]) : pending);
if (event.fault) throw event.fault;
if (Object.hasOwn(event, 'done')) {
const { id, operation } = active;
active = null;
cancelled = false;
if (Object.hasOwn(event, 'error')) {
const error = event.error;
if (!(error instanceof BusinessError)) throw error;
if (!Object.hasOwn(manifest.errors, error.identity)) throw new ProtocolError('undeclared business error');
typed(error.payload, manifest.errors[error.identity]);
await channel.send({ kind: 'error', id, error: error.identity, payload: error.payload });
} else {
typed(event.done, manifest.outputs[operation]);
await channel.send({ kind: 'result', id, payload: event.done });
}
continue;
}
const message = event.frame;
switch (message.kind) {
case 'health':
exact(message, ['kind', 'id']);
if (message.id !== 0) throw new ProtocolError('invalid health id');
await channel.send(message);
break;
case 'call': {
exact(message, ['kind', 'id', 'operation', 'payload']);
if (message.id !== next || active || !Object.hasOwn(this.handlers, message.operation)) throw new ProtocolError('invalid call');
next++;
const operation = message.operation;
typed(message.payload, manifest.inputs[operation]);
const controller = new AbortController();
const done = Promise.resolve().then(() => this.handlers[operation](message.payload, setting, controller.signal)).then(done => ({ done }), error => ({ done: null, error }));
active = { id: message.id, operation, controller, done };
break;
}
case 'cancel':
exact(message, ['kind', 'id']);
if (active && active.id === message.id) {
const previous = active;
active = null;
await stop(previous);
cancelled = true;
await channel.send({ kind: 'error', id: message.id, error: 'dever.cancelled', payload: null });
} else if (!Number.isSafeInteger(message.id) || message.id === 0 || message.id !== next - 1 || cancelled) throw new ProtocolError('unknown cancel id');
break;
case 'shutdown':
exact(message, ['kind']);
if (active) { const previous = active; active = null; await stop(previous); }
await channel.send({ kind: 'shutdown' });
return;
default: throw new ProtocolError('unknown protocol message');
}
pending = read();
}
} finally { if (active) await stop(active); }
}
}
export async function main(worker) {
try { await worker.serve(); }
catch (error) { console.error(error); process.exitCode = 1; }
}