@abyss-project/runtime 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.eslintrc.js +32 -0
- package/.prettierrc +5 -0
- package/README.md +25 -3
- package/dist/access/access.types.d.ts +14 -0
- package/dist/access/access.types.js +9 -0
- package/dist/access/access.types.js.map +1 -0
- package/dist/access/host-match.d.ts +1 -0
- package/dist/access/host-match.js +14 -0
- package/dist/access/host-match.js.map +1 -0
- package/dist/definition/definition.schema.d.ts +8 -0
- package/dist/definition/definition.schema.js +107 -0
- package/dist/definition/definition.schema.js.map +1 -0
- package/dist/definition/definition.types.d.ts +98 -0
- package/dist/definition/definition.types.js +29 -0
- package/dist/definition/definition.types.js.map +1 -0
- package/dist/definition/validate-definition.d.ts +9 -0
- package/dist/definition/validate-definition.js +163 -0
- package/dist/definition/validate-definition.js.map +1 -0
- package/dist/definition/walk-steps.d.ts +5 -0
- package/dist/definition/walk-steps.js +31 -0
- package/dist/definition/walk-steps.js.map +1 -0
- package/dist/errors/runtime-error-code.enum.d.ts +18 -0
- package/dist/errors/runtime-error-code.enum.js +19 -0
- package/dist/errors/runtime-error-code.enum.js.map +1 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.js +38 -0
- package/dist/index.js.map +1 -0
- package/dist/interpreter/interpreter-error.d.ts +5 -0
- package/dist/interpreter/interpreter-error.js +12 -0
- package/dist/interpreter/interpreter-error.js.map +1 -0
- package/dist/interpreter/interpreter.d.ts +4 -0
- package/dist/interpreter/interpreter.js +241 -0
- package/dist/interpreter/interpreter.js.map +1 -0
- package/dist/interpreter/interpreter.types.d.ts +121 -0
- package/dist/interpreter/interpreter.types.js +25 -0
- package/dist/interpreter/interpreter.types.js.map +1 -0
- package/dist/interpreter/sequence-path.d.ts +6 -0
- package/dist/interpreter/sequence-path.js +53 -0
- package/dist/interpreter/sequence-path.js.map +1 -0
- package/dist/interpreter/test-host.d.ts +16 -0
- package/dist/interpreter/test-host.js +37 -0
- package/dist/interpreter/test-host.js.map +1 -0
- package/dist/runner-protocol/runner-protocol.types.d.ts +92 -0
- package/dist/runner-protocol/runner-protocol.types.js +26 -0
- package/dist/runner-protocol/runner-protocol.types.js.map +1 -0
- package/dist/server/code-runner-client.d.ts +13 -0
- package/dist/server/code-runner-client.js +155 -0
- package/dist/server/code-runner-client.js.map +1 -0
- package/dist/server/code-runner-error.d.ts +5 -0
- package/dist/server/code-runner-error.js +12 -0
- package/dist/server/code-runner-error.js.map +1 -0
- package/dist/server/index.d.ts +3 -0
- package/dist/server/index.js +8 -0
- package/dist/server/index.js.map +1 -0
- package/dist/steps/execute-step.d.ts +40 -0
- package/dist/steps/execute-step.js +99 -0
- package/dist/steps/execute-step.js.map +1 -0
- package/dist/steps/step-access.d.ts +8 -0
- package/dist/steps/step-access.js +39 -0
- package/dist/steps/step-access.js.map +1 -0
- package/dist/steps/step-fields.d.ts +5 -0
- package/dist/steps/step-fields.js +60 -0
- package/dist/steps/step-fields.js.map +1 -0
- package/dist/steps/value-source.d.ts +6 -0
- package/dist/steps/value-source.js +58 -0
- package/dist/steps/value-source.js.map +1 -0
- package/jest.config.ts +11 -0
- package/package.json +60 -3
- package/src/__tests__/surface.test.ts +53 -0
- package/src/access/__tests__/host-match.test.ts +24 -0
- package/src/access/access.types.ts +25 -0
- package/src/access/host-match.ts +13 -0
- package/src/definition/__tests__/validate-definition.test.ts +303 -0
- package/src/definition/definition.schema.ts +139 -0
- package/src/definition/definition.types.ts +143 -0
- package/src/definition/validate-definition.ts +206 -0
- package/src/definition/walk-steps.ts +44 -0
- package/src/errors/runtime-error-code.enum.ts +37 -0
- package/src/index.ts +18 -0
- package/src/interpreter/__tests__/interpreter.test.ts +854 -0
- package/src/interpreter/interpreter-error.ts +12 -0
- package/src/interpreter/interpreter.ts +342 -0
- package/src/interpreter/interpreter.types.ts +140 -0
- package/src/interpreter/sequence-path.ts +67 -0
- package/src/interpreter/test-host.ts +74 -0
- package/src/runner-protocol/runner-protocol.types.ts +117 -0
- package/src/server/__tests__/code-runner-client.test.ts +262 -0
- package/src/server/code-runner-client.ts +201 -0
- package/src/server/code-runner-error.ts +12 -0
- package/src/server/index.ts +4 -0
- package/src/steps/execute-step.ts +132 -0
- package/src/steps/step-access.ts +56 -0
- package/src/steps/step-fields.ts +79 -0
- package/src/steps/value-source.ts +69 -0
- package/tsconfig.check.json +15 -0
- package/tsconfig.json +35 -0
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import type { RuntimeErrorCode, RuntimeErrorDetail } from '../errors/runtime-error-code.enum';
|
|
2
|
+
|
|
3
|
+
/** WebSocket sub-protocol; a new version is a new name, never a silent change. */
|
|
4
|
+
export const RUNNER_PROTOCOL = 'abyss-runtime.v1';
|
|
5
|
+
|
|
6
|
+
export enum EvaluationKind {
|
|
7
|
+
/** A full JavaScript expression. */
|
|
8
|
+
EXPRESSION = 'EXPRESSION',
|
|
9
|
+
/** A string with `{{ … }}` placeholders; a lone placeholder keeps its value's type. */
|
|
10
|
+
TEMPLATE = 'TEMPLATE',
|
|
11
|
+
/** JavaScript statements; the value of their `return` is the result. */
|
|
12
|
+
CODE = 'CODE',
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface EvaluationItem {
|
|
16
|
+
/** Unique within the lot. */
|
|
17
|
+
id: string;
|
|
18
|
+
kind: EvaluationKind;
|
|
19
|
+
source: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export type EvaluationResult =
|
|
23
|
+
| { id: string; ok: true; value: unknown }
|
|
24
|
+
| { id: string; ok: false; error: RuntimeErrorDetail };
|
|
25
|
+
|
|
26
|
+
export interface RunnerLimits {
|
|
27
|
+
/** Wall-clock limit per item. */
|
|
28
|
+
timeoutMs: number;
|
|
29
|
+
/** CPU time limit per item. */
|
|
30
|
+
cpuTimeMs: number;
|
|
31
|
+
/** Heap limit of the lot's isolate. */
|
|
32
|
+
memoryMb: number;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The limits AbyssFlow applies today (abyss-console workflow.constants.ts). */
|
|
36
|
+
export const DEFAULT_RUNNER_LIMITS: RunnerLimits = {
|
|
37
|
+
timeoutMs: 5_000,
|
|
38
|
+
cpuTimeMs: 10_000,
|
|
39
|
+
memoryMb: 128,
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
/** Upper bound on `fn.*` calls during one lot. */
|
|
43
|
+
export const MAX_HOST_CALLS_PER_LOT = 50;
|
|
44
|
+
|
|
45
|
+
/** Upper bound, in JSON bytes, on the arguments of one `fn.*` call and on the value of its result. */
|
|
46
|
+
export const MAX_HOST_CALL_BYTES = 1_048_576;
|
|
47
|
+
|
|
48
|
+
export enum RunnerMessageType {
|
|
49
|
+
RUN = 'run',
|
|
50
|
+
CALL = 'call',
|
|
51
|
+
CALL_RESULT = 'callResult',
|
|
52
|
+
RESULT = 'result',
|
|
53
|
+
REJECTED = 'rejected',
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Caller → runner: the lot to evaluate. One lot per connection. */
|
|
57
|
+
export interface RunMessage {
|
|
58
|
+
type: RunnerMessageType.RUN;
|
|
59
|
+
lotId: string;
|
|
60
|
+
items: EvaluationItem[];
|
|
61
|
+
/** JSON data exposed to every item; copied once per lot. */
|
|
62
|
+
context: Record<string, unknown>;
|
|
63
|
+
/** Names the caller can serve; exposed in the isolate as `fn.<name>(...args)`. */
|
|
64
|
+
functions: string[];
|
|
65
|
+
limits: RunnerLimits;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Runner → caller: an item awaits `fn.<name>(...args)`. */
|
|
69
|
+
export interface CallMessage {
|
|
70
|
+
type: RunnerMessageType.CALL;
|
|
71
|
+
callId: string;
|
|
72
|
+
name: string;
|
|
73
|
+
args: unknown[];
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Caller → runner: the answer to one `call`. */
|
|
77
|
+
export type CallResultMessage =
|
|
78
|
+
| { type: RunnerMessageType.CALL_RESULT; callId: string; ok: true; value: unknown }
|
|
79
|
+
| { type: RunnerMessageType.CALL_RESULT; callId: string; ok: false; error: { message: string } };
|
|
80
|
+
|
|
81
|
+
export interface LotDurations {
|
|
82
|
+
queueMs: number;
|
|
83
|
+
wallMs: number;
|
|
84
|
+
cpuMs: number;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Runner → caller: one result per item, in the order of the items. Closes the lot. */
|
|
88
|
+
export interface ResultMessage {
|
|
89
|
+
type: RunnerMessageType.RESULT;
|
|
90
|
+
lotId: string;
|
|
91
|
+
items: EvaluationResult[];
|
|
92
|
+
durations: LotDurations;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Runner → caller: the lot was not run at all. */
|
|
96
|
+
export interface RejectedMessage {
|
|
97
|
+
type: RunnerMessageType.REJECTED;
|
|
98
|
+
lotId: string;
|
|
99
|
+
code: RuntimeErrorCode.RUNNER_SATURATED | RuntimeErrorCode.INVALID_REQUEST;
|
|
100
|
+
message: string;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export type CallerMessage = RunMessage | CallResultMessage;
|
|
104
|
+
export type RunnerMessage = CallMessage | ResultMessage | RejectedMessage;
|
|
105
|
+
|
|
106
|
+
/** What a caller hands over; the client turns it into a `RunMessage`. */
|
|
107
|
+
export interface Lot {
|
|
108
|
+
lotId: string;
|
|
109
|
+
items: EvaluationItem[];
|
|
110
|
+
context: Record<string, unknown>;
|
|
111
|
+
limits: RunnerLimits;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export interface LotResult {
|
|
115
|
+
items: EvaluationResult[];
|
|
116
|
+
durations: LotDurations;
|
|
117
|
+
}
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import { createServer } from 'http';
|
|
2
|
+
import type { AddressInfo } from 'net';
|
|
3
|
+
import { WebSocketServer } from 'ws';
|
|
4
|
+
import type { WebSocket as ServerSocket } from 'ws';
|
|
5
|
+
import { RuntimeErrorCode } from '../../errors/runtime-error-code.enum';
|
|
6
|
+
import {
|
|
7
|
+
DEFAULT_RUNNER_LIMITS,
|
|
8
|
+
EvaluationKind,
|
|
9
|
+
RUNNER_PROTOCOL,
|
|
10
|
+
RunnerMessageType,
|
|
11
|
+
} from '../../runner-protocol/runner-protocol.types';
|
|
12
|
+
import type { Lot } from '../../runner-protocol/runner-protocol.types';
|
|
13
|
+
import { CodeRunnerClient } from '../code-runner-client';
|
|
14
|
+
import { CodeRunnerError } from '../code-runner-error';
|
|
15
|
+
|
|
16
|
+
const TOKEN = 'secret-token';
|
|
17
|
+
const lot: Lot = {
|
|
18
|
+
lotId: 'lot-1',
|
|
19
|
+
items: [{ id: 'a', kind: EvaluationKind.EXPRESSION, source: '1 + 1' }],
|
|
20
|
+
context: { x: 1 },
|
|
21
|
+
limits: DEFAULT_RUNNER_LIMITS,
|
|
22
|
+
};
|
|
23
|
+
const durations = { queueMs: 1, wallMs: 2, cpuMs: 3 };
|
|
24
|
+
|
|
25
|
+
type Incoming = Record<string, unknown>;
|
|
26
|
+
|
|
27
|
+
interface FakeRunner {
|
|
28
|
+
url: string;
|
|
29
|
+
headers: Array<{ authorization?: string; protocol?: string }>;
|
|
30
|
+
close: () => Promise<void>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const startRunner = async (
|
|
34
|
+
onConnection: (socket: ServerSocket, onMessage: (cb: (msg: Incoming) => void) => void) => void,
|
|
35
|
+
options: { reject401?: boolean } = {},
|
|
36
|
+
): Promise<FakeRunner> => {
|
|
37
|
+
const headers: FakeRunner['headers'] = [];
|
|
38
|
+
const httpServer = createServer();
|
|
39
|
+
const wss = new WebSocketServer({
|
|
40
|
+
server: httpServer,
|
|
41
|
+
handleProtocols: (protocols) => (protocols.has(RUNNER_PROTOCOL) ? RUNNER_PROTOCOL : false),
|
|
42
|
+
verifyClient: (info, done) => {
|
|
43
|
+
headers.push({
|
|
44
|
+
authorization: info.req.headers.authorization,
|
|
45
|
+
protocol: info.req.headers['sec-websocket-protocol'],
|
|
46
|
+
});
|
|
47
|
+
if (options.reject401 || info.req.headers.authorization !== `Bearer ${TOKEN}`) {
|
|
48
|
+
done(false, 401, 'Unauthorized');
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
done(true);
|
|
52
|
+
},
|
|
53
|
+
});
|
|
54
|
+
wss.on('connection', (socket) =>
|
|
55
|
+
onConnection(socket, (cb) => socket.on('message', (raw) => cb(JSON.parse(raw.toString())))),
|
|
56
|
+
);
|
|
57
|
+
await new Promise<void>((resolve) => httpServer.listen(0, '127.0.0.1', resolve));
|
|
58
|
+
const { port } = httpServer.address() as AddressInfo;
|
|
59
|
+
return {
|
|
60
|
+
url: `ws://127.0.0.1:${port}`,
|
|
61
|
+
headers,
|
|
62
|
+
close: async () => {
|
|
63
|
+
wss.clients.forEach((c) => c.terminate());
|
|
64
|
+
await new Promise<void>((resolve) => wss.close(() => resolve()));
|
|
65
|
+
await new Promise<void>((resolve) => httpServer.close(() => resolve()));
|
|
66
|
+
},
|
|
67
|
+
};
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
const client = (url: string, lotTimeoutMs = 2_000): CodeRunnerClient =>
|
|
71
|
+
new CodeRunnerClient({ url, token: TOKEN, connectTimeoutMs: 1_000, lotTimeoutMs });
|
|
72
|
+
|
|
73
|
+
const expectRunnerError = async (promise: Promise<unknown>): Promise<CodeRunnerError> => {
|
|
74
|
+
const error = await promise.then(
|
|
75
|
+
() => undefined,
|
|
76
|
+
(e: unknown) => e,
|
|
77
|
+
);
|
|
78
|
+
expect(error).toBeInstanceOf(CodeRunnerError);
|
|
79
|
+
return error as CodeRunnerError;
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
const resultJson = JSON.stringify({ type: 'result', lotId: 'lot-1', items: [], durations });
|
|
83
|
+
|
|
84
|
+
describe('CodeRunnerClient', () => {
|
|
85
|
+
let runner: FakeRunner | undefined;
|
|
86
|
+
afterEach(async () => {
|
|
87
|
+
await runner?.close();
|
|
88
|
+
runner = undefined;
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it('resolves the result and sends the exact header, sub-protocol and run message', async () => {
|
|
92
|
+
let run: Incoming | undefined;
|
|
93
|
+
runner = await startRunner((socket, onMessage) => {
|
|
94
|
+
onMessage((msg) => {
|
|
95
|
+
run = msg;
|
|
96
|
+
socket.send(
|
|
97
|
+
JSON.stringify({
|
|
98
|
+
type: RunnerMessageType.RESULT,
|
|
99
|
+
lotId: 'lot-1',
|
|
100
|
+
items: [{ id: 'a', ok: true, value: 2 }],
|
|
101
|
+
durations,
|
|
102
|
+
}),
|
|
103
|
+
);
|
|
104
|
+
});
|
|
105
|
+
});
|
|
106
|
+
const result = await client(runner.url).evaluate(lot, { double: async () => 1 });
|
|
107
|
+
expect(result).toEqual({ items: [{ id: 'a', ok: true, value: 2 }], durations });
|
|
108
|
+
expect(runner.headers).toEqual([
|
|
109
|
+
{ authorization: `Bearer ${TOKEN}`, protocol: RUNNER_PROTOCOL },
|
|
110
|
+
]);
|
|
111
|
+
expect(run).toEqual({
|
|
112
|
+
type: RunnerMessageType.RUN,
|
|
113
|
+
lotId: 'lot-1',
|
|
114
|
+
items: lot.items,
|
|
115
|
+
context: lot.context,
|
|
116
|
+
functions: ['double'],
|
|
117
|
+
limits: DEFAULT_RUNNER_LIMITS,
|
|
118
|
+
});
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
it('rejects with RUNNER_UNAVAILABLE a result that answers another lot', async () => {
|
|
122
|
+
runner = await startRunner((socket, onMessage) => {
|
|
123
|
+
onMessage(() => {
|
|
124
|
+
socket.send(JSON.stringify({ type: 'result', lotId: 'other-lot', items: [], durations }));
|
|
125
|
+
});
|
|
126
|
+
});
|
|
127
|
+
const error = await expectRunnerError(client(runner.url).evaluate(lot, {}));
|
|
128
|
+
expect(error.code).toBe(RuntimeErrorCode.RUNNER_UNAVAILABLE);
|
|
129
|
+
expect(error.message).toContain('other-lot');
|
|
130
|
+
expect(error.message).toContain('lot-1');
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
it('serves concurrent host calls independently, including a rejecting function', async () => {
|
|
134
|
+
const replies: Incoming[] = [];
|
|
135
|
+
runner = await startRunner((socket, onMessage) => {
|
|
136
|
+
onMessage((msg) => {
|
|
137
|
+
if (msg.type === RunnerMessageType.RUN) {
|
|
138
|
+
socket.send(JSON.stringify({ type: 'call', callId: 'c1', name: 'slow', args: [1] }));
|
|
139
|
+
socket.send(JSON.stringify({ type: 'call', callId: 'c2', name: 'boom', args: [] }));
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
replies.push(msg);
|
|
143
|
+
if (replies.length === 2) {
|
|
144
|
+
socket.send(resultJson);
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
});
|
|
148
|
+
await client(runner.url).evaluate(lot, {
|
|
149
|
+
slow: async (n) => {
|
|
150
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
151
|
+
return (n as number) + 1;
|
|
152
|
+
},
|
|
153
|
+
boom: async () => {
|
|
154
|
+
throw new Error('exploded');
|
|
155
|
+
},
|
|
156
|
+
});
|
|
157
|
+
expect(replies[0]).toEqual({
|
|
158
|
+
type: RunnerMessageType.CALL_RESULT,
|
|
159
|
+
callId: 'c2',
|
|
160
|
+
ok: false,
|
|
161
|
+
error: { message: 'exploded' },
|
|
162
|
+
});
|
|
163
|
+
expect(replies[1]).toEqual({
|
|
164
|
+
type: RunnerMessageType.CALL_RESULT,
|
|
165
|
+
callId: 'c1',
|
|
166
|
+
ok: true,
|
|
167
|
+
value: 2,
|
|
168
|
+
});
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
it('answers ok:false with only a message for an unknown function name', async () => {
|
|
172
|
+
let reply: Incoming | undefined;
|
|
173
|
+
runner = await startRunner((socket, onMessage) => {
|
|
174
|
+
onMessage((msg) => {
|
|
175
|
+
if (msg.type === RunnerMessageType.RUN) {
|
|
176
|
+
socket.send(JSON.stringify({ type: 'call', callId: 'c1', name: 'toString', args: [] }));
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
reply = msg;
|
|
180
|
+
socket.send(resultJson);
|
|
181
|
+
});
|
|
182
|
+
});
|
|
183
|
+
await client(runner.url).evaluate(lot, {});
|
|
184
|
+
expect(reply).toEqual({
|
|
185
|
+
type: RunnerMessageType.CALL_RESULT,
|
|
186
|
+
callId: 'c1',
|
|
187
|
+
ok: false,
|
|
188
|
+
error: { message: 'Unknown host function "toString"' },
|
|
189
|
+
});
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
it('rejects with the code of a saturated rejection', async () => {
|
|
193
|
+
runner = await startRunner((socket, onMessage) => {
|
|
194
|
+
onMessage(() =>
|
|
195
|
+
socket.send(
|
|
196
|
+
JSON.stringify({
|
|
197
|
+
type: 'rejected',
|
|
198
|
+
lotId: 'lot-1',
|
|
199
|
+
code: RuntimeErrorCode.RUNNER_SATURATED,
|
|
200
|
+
message: 'queue full',
|
|
201
|
+
}),
|
|
202
|
+
),
|
|
203
|
+
);
|
|
204
|
+
});
|
|
205
|
+
const error = await expectRunnerError(client(runner.url).evaluate(lot, {}));
|
|
206
|
+
expect(error.code).toBe(RuntimeErrorCode.RUNNER_SATURATED);
|
|
207
|
+
expect(error.message).toBe('queue full');
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
it('reports RUNNER_UNAVAILABLE when the server is absent', async () => {
|
|
211
|
+
runner = await startRunner(() => undefined);
|
|
212
|
+
const url = runner.url;
|
|
213
|
+
await runner.close();
|
|
214
|
+
runner = undefined;
|
|
215
|
+
const error = await expectRunnerError(client(url).evaluate(lot, {}));
|
|
216
|
+
expect(error.code).toBe(RuntimeErrorCode.RUNNER_UNAVAILABLE);
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
it('reports RUNNER_UNAVAILABLE with a message naming the 401', async () => {
|
|
220
|
+
runner = await startRunner(() => undefined, { reject401: true });
|
|
221
|
+
const error = await expectRunnerError(client(runner.url).evaluate(lot, {}));
|
|
222
|
+
expect(error.code).toBe(RuntimeErrorCode.RUNNER_UNAVAILABLE);
|
|
223
|
+
expect(error.message).toContain('401');
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
it('reports RUNNER_UNAVAILABLE when the connection drops before the result', async () => {
|
|
227
|
+
runner = await startRunner((socket, onMessage) => {
|
|
228
|
+
onMessage(() => socket.terminate());
|
|
229
|
+
});
|
|
230
|
+
const error = await expectRunnerError(client(runner.url).evaluate(lot, {}));
|
|
231
|
+
expect(error.code).toBe(RuntimeErrorCode.RUNNER_UNAVAILABLE);
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
it('reports RUNNER_UNAVAILABLE when the lot timeout is exceeded', async () => {
|
|
235
|
+
runner = await startRunner(() => undefined);
|
|
236
|
+
const error = await expectRunnerError(client(runner.url, 100).evaluate(lot, {}));
|
|
237
|
+
expect(error.code).toBe(RuntimeErrorCode.RUNNER_UNAVAILABLE);
|
|
238
|
+
expect(error.message).toContain('100 ms');
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
it.each([
|
|
242
|
+
['invalid JSON', 'not json'],
|
|
243
|
+
['unknown type', JSON.stringify({ type: 'nope' })],
|
|
244
|
+
['malformed call', JSON.stringify({ type: 'call', callId: 1 })],
|
|
245
|
+
])(
|
|
246
|
+
'closes and reports RUNNER_UNAVAILABLE on a non-conforming message (%s)',
|
|
247
|
+
async (_n, payload) => {
|
|
248
|
+
let closed = false;
|
|
249
|
+
runner = await startRunner((socket, onMessage) => {
|
|
250
|
+
socket.on('close', () => {
|
|
251
|
+
closed = true;
|
|
252
|
+
});
|
|
253
|
+
onMessage(() => socket.send(payload));
|
|
254
|
+
});
|
|
255
|
+
const error = await expectRunnerError(client(runner.url).evaluate(lot, {}));
|
|
256
|
+
expect(error.code).toBe(RuntimeErrorCode.RUNNER_UNAVAILABLE);
|
|
257
|
+
expect(error.message).toContain('Code runner sent');
|
|
258
|
+
await new Promise((r) => setTimeout(r, 100));
|
|
259
|
+
expect(closed).toBe(true);
|
|
260
|
+
},
|
|
261
|
+
);
|
|
262
|
+
});
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { WebSocket } from 'ws';
|
|
2
|
+
import type { RawData } from 'ws';
|
|
3
|
+
import { RuntimeErrorCode } from '../errors/runtime-error-code.enum';
|
|
4
|
+
import { RUNNER_PROTOCOL, RunnerMessageType } from '../runner-protocol/runner-protocol.types';
|
|
5
|
+
import type {
|
|
6
|
+
CallMessage,
|
|
7
|
+
CallResultMessage,
|
|
8
|
+
Lot,
|
|
9
|
+
LotResult,
|
|
10
|
+
RejectedMessage,
|
|
11
|
+
ResultMessage,
|
|
12
|
+
RunMessage,
|
|
13
|
+
RunnerMessage,
|
|
14
|
+
} from '../runner-protocol/runner-protocol.types';
|
|
15
|
+
import { CodeRunnerError } from './code-runner-error';
|
|
16
|
+
|
|
17
|
+
export type HostFunctions = Record<string, (...args: unknown[]) => Promise<unknown>>;
|
|
18
|
+
|
|
19
|
+
export interface CodeRunnerClientOptions {
|
|
20
|
+
/** `ws://` or `wss://` URL of the code runner. */
|
|
21
|
+
url: string;
|
|
22
|
+
/** Bearer token the runner knows by fingerprint. */
|
|
23
|
+
token: string;
|
|
24
|
+
/** Maximum time to open the connection. */
|
|
25
|
+
connectTimeoutMs: number;
|
|
26
|
+
/** Maximum time for the whole lot, connection included; past it the call fails with RUNNER_UNAVAILABLE. */
|
|
27
|
+
lotTimeoutMs: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
|
31
|
+
typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
32
|
+
|
|
33
|
+
const parseRunnerMessage = (raw: RawData): RunnerMessage => {
|
|
34
|
+
let parsed: unknown;
|
|
35
|
+
try {
|
|
36
|
+
parsed = JSON.parse(raw.toString());
|
|
37
|
+
} catch {
|
|
38
|
+
throw new Error('Code runner sent a message that is not valid JSON');
|
|
39
|
+
}
|
|
40
|
+
if (!isRecord(parsed)) {
|
|
41
|
+
throw new Error('Code runner sent a message that is not an object');
|
|
42
|
+
}
|
|
43
|
+
switch (parsed.type) {
|
|
44
|
+
case RunnerMessageType.CALL:
|
|
45
|
+
if (
|
|
46
|
+
typeof parsed.callId !== 'string' ||
|
|
47
|
+
typeof parsed.name !== 'string' ||
|
|
48
|
+
!Array.isArray(parsed.args)
|
|
49
|
+
) {
|
|
50
|
+
throw new Error('Code runner sent a malformed "call" message');
|
|
51
|
+
}
|
|
52
|
+
return parsed as unknown as CallMessage;
|
|
53
|
+
case RunnerMessageType.RESULT:
|
|
54
|
+
if (!Array.isArray(parsed.items) || !isRecord(parsed.durations)) {
|
|
55
|
+
throw new Error('Code runner sent a malformed "result" message');
|
|
56
|
+
}
|
|
57
|
+
return parsed as unknown as ResultMessage;
|
|
58
|
+
case RunnerMessageType.REJECTED:
|
|
59
|
+
if (
|
|
60
|
+
(parsed.code !== RuntimeErrorCode.RUNNER_SATURATED &&
|
|
61
|
+
parsed.code !== RuntimeErrorCode.INVALID_REQUEST) ||
|
|
62
|
+
typeof parsed.message !== 'string'
|
|
63
|
+
) {
|
|
64
|
+
throw new Error('Code runner sent a malformed "rejected" message');
|
|
65
|
+
}
|
|
66
|
+
return parsed as unknown as RejectedMessage;
|
|
67
|
+
default:
|
|
68
|
+
throw new Error('Code runner sent a message of unknown type');
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const errorMessage = (error: unknown): string =>
|
|
73
|
+
error instanceof Error ? error.message : String(error);
|
|
74
|
+
|
|
75
|
+
/** Node client of the code runner: one WebSocket connection per `evaluate` call. */
|
|
76
|
+
export class CodeRunnerClient {
|
|
77
|
+
private readonly options: CodeRunnerClientOptions;
|
|
78
|
+
|
|
79
|
+
constructor(options: CodeRunnerClientOptions) {
|
|
80
|
+
this.options = options;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
public evaluate(lot: Lot, functions: HostFunctions): Promise<LotResult> {
|
|
84
|
+
const { url, token, connectTimeoutMs, lotTimeoutMs } = this.options;
|
|
85
|
+
|
|
86
|
+
return new Promise<LotResult>((resolve, reject) => {
|
|
87
|
+
let settled = false;
|
|
88
|
+
const ws = new WebSocket(url, RUNNER_PROTOCOL, {
|
|
89
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
90
|
+
handshakeTimeout: connectTimeoutMs,
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
const finish = (outcome: () => void): void => {
|
|
94
|
+
if (settled) {
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
settled = true;
|
|
98
|
+
clearTimeout(lotTimer);
|
|
99
|
+
if (ws.readyState === WebSocket.OPEN) {
|
|
100
|
+
ws.close();
|
|
101
|
+
} else {
|
|
102
|
+
ws.terminate();
|
|
103
|
+
}
|
|
104
|
+
outcome();
|
|
105
|
+
};
|
|
106
|
+
const fail = (code: RuntimeErrorCode, message: string): void =>
|
|
107
|
+
finish(() => reject(new CodeRunnerError(code, message)));
|
|
108
|
+
const unavailable = (message: string): void =>
|
|
109
|
+
fail(RuntimeErrorCode.RUNNER_UNAVAILABLE, message);
|
|
110
|
+
|
|
111
|
+
const lotTimer = setTimeout(
|
|
112
|
+
() => unavailable(`Code runner did not answer within ${lotTimeoutMs} ms`),
|
|
113
|
+
lotTimeoutMs,
|
|
114
|
+
);
|
|
115
|
+
|
|
116
|
+
const send = (message: RunMessage | CallResultMessage): void => {
|
|
117
|
+
if (ws.readyState === WebSocket.OPEN) {
|
|
118
|
+
ws.send(JSON.stringify(message));
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
const serveCall = async (call: CallMessage): Promise<void> => {
|
|
123
|
+
const fn = Object.prototype.hasOwnProperty.call(functions, call.name)
|
|
124
|
+
? functions[call.name]
|
|
125
|
+
: undefined;
|
|
126
|
+
if (!fn) {
|
|
127
|
+
send({
|
|
128
|
+
type: RunnerMessageType.CALL_RESULT,
|
|
129
|
+
callId: call.callId,
|
|
130
|
+
ok: false,
|
|
131
|
+
error: { message: `Unknown host function "${call.name}"` },
|
|
132
|
+
});
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
try {
|
|
136
|
+
const value = await fn(...call.args);
|
|
137
|
+
send({ type: RunnerMessageType.CALL_RESULT, callId: call.callId, ok: true, value });
|
|
138
|
+
} catch (error) {
|
|
139
|
+
send({
|
|
140
|
+
type: RunnerMessageType.CALL_RESULT,
|
|
141
|
+
callId: call.callId,
|
|
142
|
+
ok: false,
|
|
143
|
+
error: { message: errorMessage(error) },
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
ws.on('unexpected-response', (_request, response) => {
|
|
149
|
+
const status = response.statusCode;
|
|
150
|
+
unavailable(
|
|
151
|
+
status === 401
|
|
152
|
+
? 'Code runner refused the token (401 Unauthorized)'
|
|
153
|
+
: `Code runner refused the connection (HTTP ${status})`,
|
|
154
|
+
);
|
|
155
|
+
});
|
|
156
|
+
ws.on('error', (error) => unavailable(`Code runner unreachable: ${error.message}`));
|
|
157
|
+
ws.on('close', () => unavailable('Code runner connection closed before the result'));
|
|
158
|
+
|
|
159
|
+
ws.on('open', () => {
|
|
160
|
+
send({
|
|
161
|
+
type: RunnerMessageType.RUN,
|
|
162
|
+
lotId: lot.lotId,
|
|
163
|
+
items: lot.items,
|
|
164
|
+
context: lot.context,
|
|
165
|
+
functions: Object.keys(functions),
|
|
166
|
+
limits: lot.limits,
|
|
167
|
+
});
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
ws.on('message', (raw) => {
|
|
171
|
+
if (settled) {
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
let message: RunnerMessage;
|
|
175
|
+
try {
|
|
176
|
+
message = parseRunnerMessage(raw);
|
|
177
|
+
} catch (error) {
|
|
178
|
+
unavailable(errorMessage(error));
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
switch (message.type) {
|
|
182
|
+
case RunnerMessageType.CALL:
|
|
183
|
+
void serveCall(message);
|
|
184
|
+
break;
|
|
185
|
+
case RunnerMessageType.RESULT:
|
|
186
|
+
if (message.lotId !== lot.lotId) {
|
|
187
|
+
unavailable(
|
|
188
|
+
`Code runner answered lot "${message.lotId}" instead of lot "${lot.lotId}"`,
|
|
189
|
+
);
|
|
190
|
+
break;
|
|
191
|
+
}
|
|
192
|
+
finish(() => resolve({ items: message.items, durations: message.durations }));
|
|
193
|
+
break;
|
|
194
|
+
case RunnerMessageType.REJECTED:
|
|
195
|
+
fail(message.code, message.message);
|
|
196
|
+
break;
|
|
197
|
+
}
|
|
198
|
+
});
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { RuntimeErrorCode } from '../errors/runtime-error-code.enum';
|
|
2
|
+
|
|
3
|
+
/** Thrown by `CodeRunnerClient` when a lot did not produce a result. */
|
|
4
|
+
export class CodeRunnerError extends Error {
|
|
5
|
+
public readonly code: RuntimeErrorCode;
|
|
6
|
+
|
|
7
|
+
constructor(code: RuntimeErrorCode, message: string) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.name = 'CodeRunnerError';
|
|
10
|
+
this.code = code;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// Entry point `@abyss-project/runtime/server`: the only place where `ws` and Node modules are allowed.
|
|
2
|
+
export { CodeRunnerClient } from './code-runner-client';
|
|
3
|
+
export type { CodeRunnerClientOptions, HostFunctions } from './code-runner-client';
|
|
4
|
+
export { CodeRunnerError } from './code-runner-error';
|