Dever v0.0.2
This commit is contained in:
commit
e6e175ebcf
816 files changed
+120349
No files matched your search
@@ -0,0 +1,117 @@
|
||||
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; }
|
||||
}
|
||||
Generated
+28
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"name": "@dever/component",
|
||||
"version": "0.0.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@dever/component",
|
||||
"version": "0.0.1",
|
||||
"dependencies": {
|
||||
"decimal.js": "10.6.0",
|
||||
"jsonc-parser": "3.3.1"
|
||||
}
|
||||
},
|
||||
"node_modules/decimal.js": {
|
||||
"version": "10.6.0",
|
||||
"resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz",
|
||||
"integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/jsonc-parser": {
|
||||
"version": "3.3.1",
|
||||
"resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.3.1.tgz",
|
||||
"integrity": "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==",
|
||||
"license": "MIT"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"name": "@dever/component",
|
||||
"version": "0.0.1",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"exports": "./dever_component.mjs",
|
||||
"dependencies": {"jsonc-parser": "3.3.1", "decimal.js": "10.6.0"}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import Decimal from 'decimal.js';
|
||||
import { ProtocolError, exact } from './wire.mjs';
|
||||
|
||||
export function typed(value, schema) {
|
||||
const result = decode(value, schema);
|
||||
if (value !== null && Object.hasOwn(schema, 'minimum')) {
|
||||
const number = new Decimal(value.toString());
|
||||
if (number.lt(schema.minimum) || number.gt(schema.maximum)) throw new ProtocolError('value is outside its declared range');
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function decode(value, schema) {
|
||||
switch (schema.type) {
|
||||
case 'enum':
|
||||
if (!schema.values.includes(value)) throw new ProtocolError('unknown enum value');
|
||||
return value;
|
||||
case 'nullable': return value === null ? null : typed(value, schema.value);
|
||||
case 'list':
|
||||
if (!Array.isArray(value)) throw new ProtocolError('expected list');
|
||||
for (let i = 0; i < value.length; i++) value[i] = typed(value[i], schema.value);
|
||||
return value;
|
||||
case 'record': {
|
||||
exact(value, Object.keys(schema.fields));
|
||||
for (const [name, field] of Object.entries(schema.fields)) value[name] = typed(value[name], field);
|
||||
return value;
|
||||
}
|
||||
case 'int64': case 'duration': case 'model_id': {
|
||||
if ((typeof value !== 'bigint' && !Number.isSafeInteger(value)) || BigInt(value) < -(1n << 63n) || BigInt(value) >= (1n << 63n)) throw new ProtocolError('expected signed 64-bit integer');
|
||||
return value;
|
||||
}
|
||||
case 'float64':
|
||||
if (JSON.isRawJSON(value)) value = Number(value.rawJSON);
|
||||
if ((typeof value !== 'number' && typeof value !== 'bigint') || !Number.isFinite(Number(value))) throw new ProtocolError('expected finite float');
|
||||
return Number(value);
|
||||
case 'bool':
|
||||
if (typeof value !== 'boolean') throw new ProtocolError('expected boolean');
|
||||
return value;
|
||||
case 'json': return value;
|
||||
case 'text': case 'id': case 'secret': case 'decimal': case 'uuid': case 'datetime': case 'date': case 'time':
|
||||
if (typeof value !== 'string') throw new ProtocolError('expected text');
|
||||
if (schema.type === 'decimal' && !/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(value)) throw new ProtocolError('invalid decimal');
|
||||
if (schema.type === 'uuid' && !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)) throw new ProtocolError('invalid UUID');
|
||||
if (schema.type === 'date' && (!/^\d{4}-\d{2}-\d{2}$/.test(value) || Number.isNaN(Date.parse(`${value}T00:00:00Z`)))) throw new ProtocolError('invalid Date');
|
||||
if (schema.type === 'time' && !/^\d{2}:\d{2}:\d{2}(?:\.\d{3})?$/.test(value)) throw new ProtocolError('invalid Time');
|
||||
if (schema.type === 'datetime' && (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/.test(value) || Number.isNaN(Date.parse(value)))) throw new ProtocolError('invalid DateTime');
|
||||
return value;
|
||||
default: throw new ProtocolError('unknown worker type');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
// JSON 词法、语法与字符串解析交给 jsonc-parser;这里只建立值与执行协议预算。
|
||||
import { visit } from 'jsonc-parser';
|
||||
import { once } from 'node:events';
|
||||
|
||||
export const MAX_BYTES = 16 * 1024 * 1024;
|
||||
const decoder = new TextDecoder('utf-8', { fatal: true });
|
||||
export class ProtocolError extends Error {}
|
||||
|
||||
export function parse(text) {
|
||||
let root;
|
||||
let count = 0;
|
||||
const parents = [];
|
||||
function value(item) {
|
||||
if (++count > 65536 || parents.length > 64) throw new ProtocolError('wire JSON exceeds limit');
|
||||
const parent = parents.at(-1);
|
||||
if (!parent) root = item;
|
||||
else if (Array.isArray(parent.value)) parent.value.push(item);
|
||||
else Object.defineProperty(parent.value, parent.key, { value: item, enumerable: true, writable: true });
|
||||
}
|
||||
function container(item) {
|
||||
if (parents.length === 64) throw new ProtocolError('wire JSON exceeds depth limit');
|
||||
value(item);
|
||||
parents.push({ value: item });
|
||||
}
|
||||
visit(text, {
|
||||
onObjectBegin: () => container({}),
|
||||
onArrayBegin: () => container([]),
|
||||
onObjectEnd: () => parents.pop(),
|
||||
onArrayEnd: () => parents.pop(),
|
||||
onObjectProperty(key) {
|
||||
const parent = parents.at(-1);
|
||||
if (Object.hasOwn(parent.value, key)) throw new ProtocolError('duplicate JSON field');
|
||||
parent.key = key;
|
||||
},
|
||||
onLiteralValue(item, offset, length) {
|
||||
if (typeof item === 'number') {
|
||||
const source = text.slice(offset, offset + length);
|
||||
if (!/[.eE]/.test(source) && !Number.isSafeInteger(item)) item = BigInt(source);
|
||||
else if (/[.eE]/.test(source)) item = JSON.rawJSON(source);
|
||||
}
|
||||
value(item);
|
||||
},
|
||||
onError: code => { throw new ProtocolError('invalid JSON: ' + code); },
|
||||
}, { disallowComments: true, allowTrailingComma: false, allowEmptyContent: false });
|
||||
if (!root || typeof root !== 'object' || Array.isArray(root)) throw new ProtocolError('expected protocol object');
|
||||
return root;
|
||||
}
|
||||
|
||||
export function exact(value, names) {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).length !== names.length || names.some(name => !Object.hasOwn(value, name))) {
|
||||
throw new ProtocolError('missing or extra record fields');
|
||||
}
|
||||
}
|
||||
|
||||
export class Channel {
|
||||
#input = process.stdin[Symbol.asyncIterator]();
|
||||
#chunk = Buffer.alloc(0);
|
||||
#offset = 0;
|
||||
|
||||
async #read(size) {
|
||||
const result = Buffer.allocUnsafe(size);
|
||||
let offset = 0;
|
||||
while (offset < size) {
|
||||
if (this.#offset === this.#chunk.length) {
|
||||
const next = await this.#input.next();
|
||||
if (next.done) throw new ProtocolError('incomplete component frame');
|
||||
this.#chunk = next.value;
|
||||
this.#offset = 0;
|
||||
}
|
||||
const length = Math.min(size - offset, this.#chunk.length - this.#offset);
|
||||
this.#chunk.copy(result, offset, this.#offset, this.#offset + length);
|
||||
this.#offset += length;
|
||||
offset += length;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async receive() {
|
||||
const size = (await this.#read(4)).readUInt32BE();
|
||||
if (size === 0 || size > MAX_BYTES) throw new ProtocolError('component frame exceeds byte limit');
|
||||
return parse(decoder.decode(await this.#read(size)));
|
||||
}
|
||||
|
||||
async send(message) {
|
||||
let count = 0;
|
||||
function bounded(value, depth) {
|
||||
if (++count > 65536 || depth > 64) throw new ProtocolError('wire JSON exceeds limit');
|
||||
if (typeof value === 'number' && !Number.isFinite(value)) throw new ProtocolError('non-finite JSON number');
|
||||
if (value && typeof value === 'object' && !JSON.isRawJSON(value)) {
|
||||
if (depth === 64) throw new ProtocolError('wire JSON exceeds depth limit');
|
||||
for (const item of Object.values(value)) bounded(item, depth + 1);
|
||||
}
|
||||
}
|
||||
bounded(message, 0);
|
||||
// 原生 JSON 保留完整 Int,不自写 JSON 编码器。运行时要求 Node 22 以上。
|
||||
const body = Buffer.from(JSON.stringify(message, (_key, value) => {
|
||||
if (typeof value === 'bigint') return JSON.rawJSON(value.toString());
|
||||
if (value === undefined || typeof value === 'function' || typeof value === 'symbol') throw new ProtocolError('invalid JSON value');
|
||||
return value;
|
||||
}));
|
||||
if (body.length > MAX_BYTES) throw new ProtocolError('component frame exceeds byte limit');
|
||||
const header = Buffer.allocUnsafe(4);
|
||||
header.writeUInt32BE(body.length);
|
||||
if (!process.stdout.write(header)) await once(process.stdout, 'drain');
|
||||
await new Promise((resolve, reject) => process.stdout.write(body, error => error ? reject(error) : resolve()));
|
||||
}
|
||||
|
||||
close() { process.stdin.destroy(); }
|
||||
}
|
||||
Reference in new issue
Block a user