@abyss-project/runtime 0.0.0-stage → 2.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 +28 -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/cost/execution-cost.d.ts +45 -0
- package/dist/cost/execution-cost.js +114 -0
- package/dist/cost/execution-cost.js.map +1 -0
- package/dist/definition/definition.limits.d.ts +4 -0
- package/dist/definition/definition.limits.js +8 -0
- package/dist/definition/definition.limits.js.map +1 -0
- package/dist/definition/definition.schema.d.ts +8 -0
- package/dist/definition/definition.schema.js +123 -0
- package/dist/definition/definition.schema.js.map +1 -0
- package/dist/definition/definition.types.d.ts +117 -0
- package/dist/definition/definition.types.js +37 -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/engine/engine-entry.d.ts +1 -0
- package/dist/engine/engine-entry.js +6 -0
- package/dist/engine/engine-entry.js.map +1 -0
- package/dist/engine/engine-global.d.ts +1 -0
- package/dist/engine/engine-global.js +5 -0
- package/dist/engine/engine-global.js.map +1 -0
- package/dist/engine/engine-source.d.ts +2 -0
- package/dist/engine/engine-source.js +3 -0
- package/dist/engine/run-in-isolate.d.ts +34 -0
- package/dist/engine/run-in-isolate.js +267 -0
- package/dist/engine/run-in-isolate.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 +21 -0
- package/dist/index.js +47 -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 +30 -0
- package/dist/interpreter/interpreter.js +313 -0
- package/dist/interpreter/interpreter.js.map +1 -0
- package/dist/interpreter/interpreter.types.d.ts +152 -0
- package/dist/interpreter/interpreter.types.js +31 -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 +18 -0
- package/dist/interpreter/test-host.js +43 -0
- package/dist/interpreter/test-host.js.map +1 -0
- package/dist/runner-protocol/evaluation.types.d.ts +20 -0
- package/dist/runner-protocol/evaluation.types.js +10 -0
- package/dist/runner-protocol/evaluation.types.js.map +1 -0
- package/dist/runner-protocol/execution-protocol.types.d.ts +132 -0
- package/dist/runner-protocol/execution-protocol.types.js +48 -0
- package/dist/runner-protocol/execution-protocol.types.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/code-runner-session.d.ts +28 -0
- package/dist/server/code-runner-session.js +208 -0
- package/dist/server/code-runner-session.js.map +1 -0
- package/dist/server/index.d.ts +3 -0
- package/dist/server/index.js +10 -0
- package/dist/server/index.js.map +1 -0
- package/dist/steps/execute-step.d.ts +50 -0
- package/dist/steps/execute-step.js +136 -0
- package/dist/steps/execute-step.js.map +1 -0
- package/dist/steps/global-references.d.ts +2 -0
- package/dist/steps/global-references.js +28 -0
- package/dist/steps/global-references.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 +68 -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 +68 -3
- package/scripts/build-engine.cjs +70 -0
- package/src/__tests__/engine-bundle.test.ts +121 -0
- 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/cost/__tests__/execution-cost.test.ts +200 -0
- package/src/cost/execution-cost.ts +192 -0
- package/src/definition/__tests__/validate-definition.test.ts +354 -0
- package/src/definition/definition.limits.ts +9 -0
- package/src/definition/definition.schema.ts +172 -0
- package/src/definition/definition.types.ts +171 -0
- package/src/definition/validate-definition.ts +206 -0
- package/src/definition/walk-steps.ts +44 -0
- package/src/engine/__tests__/run-in-isolate.test.ts +468 -0
- package/src/engine/engine-entry.ts +3 -0
- package/src/engine/engine-global.ts +2 -0
- package/src/engine/run-in-isolate.ts +404 -0
- package/src/errors/runtime-error-code.enum.ts +37 -0
- package/src/index.ts +30 -0
- package/src/interpreter/__tests__/interpreter.test.ts +854 -0
- package/src/interpreter/__tests__/log-respond-resume.test.ts +223 -0
- package/src/interpreter/interpreter-error.ts +12 -0
- package/src/interpreter/interpreter.ts +461 -0
- package/src/interpreter/interpreter.types.ts +192 -0
- package/src/interpreter/sequence-path.ts +67 -0
- package/src/interpreter/test-host.ts +85 -0
- package/src/runner-protocol/evaluation.types.ts +21 -0
- package/src/runner-protocol/execution-protocol.types.ts +221 -0
- package/src/server/__tests__/code-runner-session.test.ts +311 -0
- package/src/server/code-runner-error.ts +12 -0
- package/src/server/code-runner-session.ts +310 -0
- package/src/server/index.ts +11 -0
- package/src/steps/__tests__/global-references.test.ts +113 -0
- package/src/steps/execute-step.ts +186 -0
- package/src/steps/global-references.ts +48 -0
- package/src/steps/step-access.ts +56 -0
- package/src/steps/step-fields.ts +87 -0
- package/src/steps/value-source.ts +69 -0
- package/tsconfig.check.json +15 -0
- package/tsconfig.json +35 -0
|
@@ -0,0 +1,311 @@
|
|
|
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 { CURRENT_FORMAT_VERSION } from '../../definition/definition.types';
|
|
6
|
+
import { RuntimeErrorCode } from '../../errors/runtime-error-code.enum';
|
|
7
|
+
import {
|
|
8
|
+
EXECUTION_PROTOCOL,
|
|
9
|
+
ExecutionMessageType,
|
|
10
|
+
ExecutionStatus,
|
|
11
|
+
StepPhase,
|
|
12
|
+
StepStatus,
|
|
13
|
+
} from '../../runner-protocol/execution-protocol.types';
|
|
14
|
+
import { CodeRunnerError } from '../code-runner-error';
|
|
15
|
+
import { CapabilityError, CodeRunnerSession, SUSPEND_EXECUTION } from '../code-runner-session';
|
|
16
|
+
import type { CapabilityHandlers, ExecutionRequest } from '../code-runner-session';
|
|
17
|
+
|
|
18
|
+
const TOKEN = 'secret-token';
|
|
19
|
+
|
|
20
|
+
const request: ExecutionRequest = {
|
|
21
|
+
executionId: 'exec-1',
|
|
22
|
+
definition: { formatVersion: CURRENT_FORMAT_VERSION, accesses: [], steps: [] },
|
|
23
|
+
input: { a: 1 },
|
|
24
|
+
limits: { memoryMb: 128, cpuTimeMs: 1_000, wallTimeMs: 300, guaranteedCpu: false },
|
|
25
|
+
budget: { maxSteps: 10, maxEffects: 10 },
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const metrics = { queueMs: 1, wallMs: 2, cpuMs: 3, heapPeakBytes: 4, memoryLimitBytes: 5 };
|
|
29
|
+
const finished = {
|
|
30
|
+
type: ExecutionMessageType.FINISHED,
|
|
31
|
+
outcome: { status: ExecutionStatus.SUCCEEDED, output: 'done' },
|
|
32
|
+
metrics,
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
type Incoming = Record<string, unknown>;
|
|
36
|
+
|
|
37
|
+
interface FakeRunner {
|
|
38
|
+
url: string;
|
|
39
|
+
headers: Array<{ authorization?: string; protocol?: string }>;
|
|
40
|
+
closed: Promise<void>;
|
|
41
|
+
close: () => Promise<void>;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const startRunner = async (
|
|
45
|
+
onConnection: (socket: ServerSocket, next: () => Promise<Incoming>) => void,
|
|
46
|
+
): Promise<FakeRunner> => {
|
|
47
|
+
const headers: FakeRunner['headers'] = [];
|
|
48
|
+
let markClosed: () => void = () => undefined;
|
|
49
|
+
const closed = new Promise<void>((resolve) => {
|
|
50
|
+
markClosed = resolve;
|
|
51
|
+
});
|
|
52
|
+
const httpServer = createServer();
|
|
53
|
+
const wss = new WebSocketServer({
|
|
54
|
+
server: httpServer,
|
|
55
|
+
handleProtocols: (protocols) =>
|
|
56
|
+
protocols.has(EXECUTION_PROTOCOL) ? EXECUTION_PROTOCOL : false,
|
|
57
|
+
verifyClient: (info, done) => {
|
|
58
|
+
headers.push({
|
|
59
|
+
authorization: info.req.headers.authorization,
|
|
60
|
+
protocol: info.req.headers['sec-websocket-protocol'],
|
|
61
|
+
});
|
|
62
|
+
if (info.req.headers.authorization !== `Bearer ${TOKEN}`) {
|
|
63
|
+
done(false, 401, 'Unauthorized');
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
done(true);
|
|
67
|
+
},
|
|
68
|
+
});
|
|
69
|
+
wss.on('connection', (socket) => {
|
|
70
|
+
const queue: Incoming[] = [];
|
|
71
|
+
const waiting: Array<(message: Incoming) => void> = [];
|
|
72
|
+
socket.on('message', (raw) => {
|
|
73
|
+
const message = JSON.parse(raw.toString()) as Incoming;
|
|
74
|
+
const waiter = waiting.shift();
|
|
75
|
+
if (waiter) {
|
|
76
|
+
waiter(message);
|
|
77
|
+
} else {
|
|
78
|
+
queue.push(message);
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
socket.on('close', () => markClosed());
|
|
82
|
+
const next = (): Promise<Incoming> => {
|
|
83
|
+
const queued = queue.shift();
|
|
84
|
+
return queued ? Promise.resolve(queued) : new Promise((resolve) => waiting.push(resolve));
|
|
85
|
+
};
|
|
86
|
+
onConnection(socket, next);
|
|
87
|
+
});
|
|
88
|
+
await new Promise<void>((resolve) => httpServer.listen(0, '127.0.0.1', resolve));
|
|
89
|
+
const { port } = httpServer.address() as AddressInfo;
|
|
90
|
+
return {
|
|
91
|
+
url: `ws://127.0.0.1:${port}`,
|
|
92
|
+
headers,
|
|
93
|
+
closed,
|
|
94
|
+
close: async () => {
|
|
95
|
+
wss.clients.forEach((client) => client.terminate());
|
|
96
|
+
await new Promise<void>((resolve) => wss.close(() => resolve()));
|
|
97
|
+
await new Promise<void>((resolve) => httpServer.close(() => resolve()));
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
const session = (url: string, token = TOKEN): CodeRunnerSession =>
|
|
103
|
+
new CodeRunnerSession({ url, token, connectTimeoutMs: 1_000, wallTimeGraceMs: 200 });
|
|
104
|
+
|
|
105
|
+
const send = (socket: ServerSocket, message: unknown): void => socket.send(JSON.stringify(message));
|
|
106
|
+
|
|
107
|
+
const runnerErrorOf = async (promise: Promise<unknown>): Promise<CodeRunnerError> => {
|
|
108
|
+
const error = await promise.then(
|
|
109
|
+
() => undefined,
|
|
110
|
+
(e: unknown) => e,
|
|
111
|
+
);
|
|
112
|
+
expect(error).toBeInstanceOf(CodeRunnerError);
|
|
113
|
+
return error as CodeRunnerError;
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
describe('CodeRunnerSession', () => {
|
|
117
|
+
let runner: FakeRunner | undefined;
|
|
118
|
+
|
|
119
|
+
afterEach(async () => {
|
|
120
|
+
await runner?.close();
|
|
121
|
+
runner = undefined;
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it('sends one execute, serves the calls, forwards progress and resolves the finished payload', async () => {
|
|
125
|
+
const results: Incoming[] = [];
|
|
126
|
+
let execute: Incoming | undefined;
|
|
127
|
+
runner = await startRunner(async (socket, next) => {
|
|
128
|
+
execute = await next();
|
|
129
|
+
const calls = [
|
|
130
|
+
{ callId: 'c1', stepId: 's1', capability: 'store.get', args: { key: 'k' } },
|
|
131
|
+
{ callId: 'c2', stepId: 's2', capability: 'secret.get', args: { name: 'X' } },
|
|
132
|
+
{ callId: 'c3', stepId: 's3', capability: 'store.set', args: {} },
|
|
133
|
+
{ callId: 'c4', stepId: 's4', capability: 'boom', args: null },
|
|
134
|
+
];
|
|
135
|
+
for (const call of calls) {
|
|
136
|
+
send(socket, { type: ExecutionMessageType.CALL, ...call });
|
|
137
|
+
results.push(await next());
|
|
138
|
+
}
|
|
139
|
+
send(socket, { type: ExecutionMessageType.PROGRESS, stepId: 's1', phase: StepPhase.STARTED });
|
|
140
|
+
send(socket, {
|
|
141
|
+
type: ExecutionMessageType.PROGRESS,
|
|
142
|
+
stepId: 's1',
|
|
143
|
+
phase: StepPhase.FINISHED,
|
|
144
|
+
status: StepStatus.SUCCEEDED,
|
|
145
|
+
durationMs: 4,
|
|
146
|
+
metrics: { cpuMs: 1, heapPeakBytes: 2, wallMs: 4 },
|
|
147
|
+
});
|
|
148
|
+
send(socket, finished);
|
|
149
|
+
});
|
|
150
|
+
const contexts: unknown[] = [];
|
|
151
|
+
const handlers: CapabilityHandlers = {
|
|
152
|
+
'store.get': async (args, context) => {
|
|
153
|
+
contexts.push(context);
|
|
154
|
+
return { found: (args as { key: string }).key };
|
|
155
|
+
},
|
|
156
|
+
'store.set': async () => {
|
|
157
|
+
throw new CapabilityError(RuntimeErrorCode.ACCESS_DENIED, 'read only');
|
|
158
|
+
},
|
|
159
|
+
boom: async () => {
|
|
160
|
+
throw new Error('exploded');
|
|
161
|
+
},
|
|
162
|
+
};
|
|
163
|
+
const progress: unknown[] = [];
|
|
164
|
+
|
|
165
|
+
const result = await session(runner.url).execute(request, handlers, {
|
|
166
|
+
onProgress: (p) => progress.push(p),
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
expect(result).toEqual({ outcome: finished.outcome, metrics });
|
|
170
|
+
expect(runner.headers).toEqual([
|
|
171
|
+
{ authorization: `Bearer ${TOKEN}`, protocol: EXECUTION_PROTOCOL },
|
|
172
|
+
]);
|
|
173
|
+
expect(execute).toEqual({
|
|
174
|
+
...request,
|
|
175
|
+
type: ExecutionMessageType.EXECUTE,
|
|
176
|
+
capabilities: ['store.get', 'store.set', 'boom'],
|
|
177
|
+
});
|
|
178
|
+
expect(contexts).toEqual([{ stepId: 's1' }]);
|
|
179
|
+
expect(results).toEqual([
|
|
180
|
+
{ type: ExecutionMessageType.CALL_RESULT, callId: 'c1', ok: true, value: { found: 'k' } },
|
|
181
|
+
{
|
|
182
|
+
type: ExecutionMessageType.CALL_RESULT,
|
|
183
|
+
callId: 'c2',
|
|
184
|
+
ok: false,
|
|
185
|
+
error: {
|
|
186
|
+
code: RuntimeErrorCode.ACCESS_DENIED,
|
|
187
|
+
message: expect.stringContaining('secret.get'),
|
|
188
|
+
},
|
|
189
|
+
},
|
|
190
|
+
{
|
|
191
|
+
type: ExecutionMessageType.CALL_RESULT,
|
|
192
|
+
callId: 'c3',
|
|
193
|
+
ok: false,
|
|
194
|
+
error: { code: RuntimeErrorCode.ACCESS_DENIED, message: 'read only' },
|
|
195
|
+
},
|
|
196
|
+
{
|
|
197
|
+
type: ExecutionMessageType.CALL_RESULT,
|
|
198
|
+
callId: 'c4',
|
|
199
|
+
ok: false,
|
|
200
|
+
error: { message: 'exploded' },
|
|
201
|
+
},
|
|
202
|
+
]);
|
|
203
|
+
expect(progress).toEqual([
|
|
204
|
+
expect.objectContaining({ stepId: 's1', phase: StepPhase.STARTED }),
|
|
205
|
+
expect.objectContaining({
|
|
206
|
+
stepId: 's1',
|
|
207
|
+
phase: StepPhase.FINISHED,
|
|
208
|
+
metrics: { cpuMs: 1, heapPeakBytes: 2, wallMs: 4 },
|
|
209
|
+
}),
|
|
210
|
+
]);
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
it('answers suspend when a handler resolves SUSPEND_EXECUTION', async () => {
|
|
214
|
+
let answer: Incoming | undefined;
|
|
215
|
+
runner = await startRunner(async (socket, next) => {
|
|
216
|
+
await next();
|
|
217
|
+
send(socket, {
|
|
218
|
+
type: ExecutionMessageType.CALL,
|
|
219
|
+
callId: 'c1',
|
|
220
|
+
stepId: 'approve',
|
|
221
|
+
capability: 'approval.wait',
|
|
222
|
+
args: {},
|
|
223
|
+
});
|
|
224
|
+
answer = await next();
|
|
225
|
+
send(socket, {
|
|
226
|
+
...finished,
|
|
227
|
+
outcome: { status: ExecutionStatus.SUSPENDED, state: { stateVersion: 1 } },
|
|
228
|
+
});
|
|
229
|
+
});
|
|
230
|
+
const result = await session(runner.url).execute(request, {
|
|
231
|
+
'approval.wait': async () => SUSPEND_EXECUTION,
|
|
232
|
+
});
|
|
233
|
+
expect(answer).toEqual({
|
|
234
|
+
type: ExecutionMessageType.CALL_RESULT,
|
|
235
|
+
callId: 'c1',
|
|
236
|
+
ok: true,
|
|
237
|
+
suspend: true,
|
|
238
|
+
});
|
|
239
|
+
expect(result.outcome.status).toBe(ExecutionStatus.SUSPENDED);
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
it.each([
|
|
243
|
+
RuntimeErrorCode.RUNNER_SATURATED,
|
|
244
|
+
RuntimeErrorCode.INVALID_REQUEST,
|
|
245
|
+
RuntimeErrorCode.STATE_VERSION_UNSUPPORTED,
|
|
246
|
+
])('rejects with %s when the runner refuses the execution', async (code) => {
|
|
247
|
+
runner = await startRunner(async (socket, next) => {
|
|
248
|
+
await next();
|
|
249
|
+
send(socket, { type: ExecutionMessageType.REJECTED, code, message: 'no' });
|
|
250
|
+
});
|
|
251
|
+
const error = await runnerErrorOf(session(runner.url).execute(request, {}));
|
|
252
|
+
expect(error.code).toBe(code);
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
it('fails with TIMEOUT past the wall time plus the grace, and closes the connection', async () => {
|
|
256
|
+
runner = await startRunner(() => undefined);
|
|
257
|
+
const started = Date.now();
|
|
258
|
+
const error = await runnerErrorOf(session(runner.url).execute(request, {}));
|
|
259
|
+
expect(error.code).toBe(RuntimeErrorCode.TIMEOUT);
|
|
260
|
+
expect(Date.now() - started).toBeGreaterThanOrEqual(450);
|
|
261
|
+
await runner.closed;
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
it('rejects with the abort reason and closes the connection when aborted', async () => {
|
|
265
|
+
const controller = new AbortController();
|
|
266
|
+
runner = await startRunner(async (_socket, next) => {
|
|
267
|
+
await next();
|
|
268
|
+
controller.abort(new Error('pod stopping'));
|
|
269
|
+
});
|
|
270
|
+
await expect(
|
|
271
|
+
session(runner.url).execute(request, {}, { signal: controller.signal }),
|
|
272
|
+
).rejects.toThrow('pod stopping');
|
|
273
|
+
await runner.closed;
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
it('does not connect when the signal is already aborted', async () => {
|
|
277
|
+
runner = await startRunner(() => undefined);
|
|
278
|
+
const controller = new AbortController();
|
|
279
|
+
controller.abort(new Error('already'));
|
|
280
|
+
await expect(
|
|
281
|
+
session(runner.url).execute(request, {}, { signal: controller.signal }),
|
|
282
|
+
).rejects.toThrow('already');
|
|
283
|
+
expect(runner.headers).toEqual([]);
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
it('fails with RUNNER_UNAVAILABLE on a refused token, an unreachable runner or a dropped connection', async () => {
|
|
287
|
+
runner = await startRunner(async (socket, next) => {
|
|
288
|
+
await next();
|
|
289
|
+
socket.close();
|
|
290
|
+
});
|
|
291
|
+
expect((await runnerErrorOf(session(runner.url, 'wrong').execute(request, {}))).code).toBe(
|
|
292
|
+
RuntimeErrorCode.RUNNER_UNAVAILABLE,
|
|
293
|
+
);
|
|
294
|
+
expect((await runnerErrorOf(session(runner.url).execute(request, {}))).code).toBe(
|
|
295
|
+
RuntimeErrorCode.RUNNER_UNAVAILABLE,
|
|
296
|
+
);
|
|
297
|
+
expect((await runnerErrorOf(session('ws://127.0.0.1:1').execute(request, {}))).code).toBe(
|
|
298
|
+
RuntimeErrorCode.RUNNER_UNAVAILABLE,
|
|
299
|
+
);
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
it('fails with RUNNER_UNAVAILABLE on a malformed runner message', async () => {
|
|
303
|
+
runner = await startRunner(async (socket, next) => {
|
|
304
|
+
await next();
|
|
305
|
+
send(socket, { type: ExecutionMessageType.FINISHED, outcome: { status: 'MAYBE' } });
|
|
306
|
+
});
|
|
307
|
+
const error = await runnerErrorOf(session(runner.url).execute(request, {}));
|
|
308
|
+
expect(error.code).toBe(RuntimeErrorCode.RUNNER_UNAVAILABLE);
|
|
309
|
+
expect(error.message).toContain('malformed');
|
|
310
|
+
});
|
|
311
|
+
});
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { RuntimeErrorCode } from '../errors/runtime-error-code.enum';
|
|
2
|
+
|
|
3
|
+
/** Thrown by `CodeRunnerSession` when an execution did not produce a `finished` message. */
|
|
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,310 @@
|
|
|
1
|
+
import { WebSocket } from 'ws';
|
|
2
|
+
import type { RawData } from 'ws';
|
|
3
|
+
import { RuntimeErrorCode } from '../errors/runtime-error-code.enum';
|
|
4
|
+
import {
|
|
5
|
+
EXECUTION_PROTOCOL,
|
|
6
|
+
ExecutionMessageType,
|
|
7
|
+
ExecutionStatus,
|
|
8
|
+
StepPhase,
|
|
9
|
+
} from '../runner-protocol/execution-protocol.types';
|
|
10
|
+
import type {
|
|
11
|
+
CallError,
|
|
12
|
+
ExecuteMessage,
|
|
13
|
+
ExecutionCallMessage,
|
|
14
|
+
ExecutionCallResultMessage,
|
|
15
|
+
ExecutionRejectedMessage,
|
|
16
|
+
ExecutionRunnerMessage,
|
|
17
|
+
FinishedMessage,
|
|
18
|
+
ProgressMessage,
|
|
19
|
+
} from '../runner-protocol/execution-protocol.types';
|
|
20
|
+
import { CodeRunnerError } from './code-runner-error';
|
|
21
|
+
|
|
22
|
+
export interface CodeRunnerSessionOptions {
|
|
23
|
+
/** `ws://` or `wss://` URL of the code runner. */
|
|
24
|
+
url: string;
|
|
25
|
+
/** Bearer token the runner knows by fingerprint. */
|
|
26
|
+
token: string;
|
|
27
|
+
/** Maximum time to open the connection; past it the execution fails with RUNNER_UNAVAILABLE. */
|
|
28
|
+
connectTimeoutMs: number;
|
|
29
|
+
/**
|
|
30
|
+
* Added to `limits.wallTimeMs` once the connection is open: time the runner may spend
|
|
31
|
+
* queueing the execution and reporting its end. Past the sum, the execution fails with
|
|
32
|
+
* TIMEOUT and the connection is closed, which stops the execution in the runner.
|
|
33
|
+
*/
|
|
34
|
+
wallTimeGraceMs: number;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface CapabilityContext {
|
|
38
|
+
/** The step that made the call. */
|
|
39
|
+
stepId: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* One handler per capability the execution may call; their names are the `capabilities` sent
|
|
44
|
+
* to the runner. A handler resolves the call's value, resolves `SUSPEND_EXECUTION` to suspend
|
|
45
|
+
* the execution after this step, or throws (a `CapabilityError` to choose the error code).
|
|
46
|
+
*/
|
|
47
|
+
export type CapabilityHandlers = Record<
|
|
48
|
+
string,
|
|
49
|
+
(args: unknown, context: CapabilityContext) => Promise<unknown>
|
|
50
|
+
>;
|
|
51
|
+
|
|
52
|
+
/** Resolved by a capability handler: the runner finishes SUSPENDED after the calling step. */
|
|
53
|
+
export const SUSPEND_EXECUTION: unique symbol = Symbol('abyss-runtime.suspend-execution');
|
|
54
|
+
|
|
55
|
+
/** Thrown by a capability handler to fail the call with a given code (ACCESS_DENIED...). */
|
|
56
|
+
export class CapabilityError extends Error {
|
|
57
|
+
public readonly code: RuntimeErrorCode;
|
|
58
|
+
|
|
59
|
+
constructor(code: RuntimeErrorCode, message: string) {
|
|
60
|
+
super(message);
|
|
61
|
+
this.name = 'CapabilityError';
|
|
62
|
+
this.code = code;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** What the host sends; `capabilities` is derived from the handlers. */
|
|
67
|
+
export type ExecutionRequest = Omit<ExecuteMessage, 'type' | 'capabilities'>;
|
|
68
|
+
|
|
69
|
+
export interface ExecuteOptions {
|
|
70
|
+
onProgress?: (progress: Omit<ProgressMessage, 'type'>) => void;
|
|
71
|
+
/** Aborting closes the connection, which stops the execution; the promise rejects with the signal's reason. */
|
|
72
|
+
signal?: AbortSignal;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export type ExecutionResult = Omit<FinishedMessage, 'type'>;
|
|
76
|
+
|
|
77
|
+
const REJECTION_CODES = new Set<string>([
|
|
78
|
+
RuntimeErrorCode.RUNNER_SATURATED,
|
|
79
|
+
RuntimeErrorCode.INVALID_REQUEST,
|
|
80
|
+
RuntimeErrorCode.STATE_VERSION_UNSUPPORTED,
|
|
81
|
+
]);
|
|
82
|
+
const EXECUTION_STATUSES = new Set<string>(Object.values(ExecutionStatus));
|
|
83
|
+
const STEP_PHASES = new Set<string>(Object.values(StepPhase));
|
|
84
|
+
|
|
85
|
+
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
|
86
|
+
typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
87
|
+
|
|
88
|
+
const malformed = (type: string): Error =>
|
|
89
|
+
new Error(`Code runner sent a malformed "${type}" message`);
|
|
90
|
+
|
|
91
|
+
const parseRunnerMessage = (raw: RawData): ExecutionRunnerMessage => {
|
|
92
|
+
let parsed: unknown;
|
|
93
|
+
try {
|
|
94
|
+
parsed = JSON.parse(raw.toString());
|
|
95
|
+
} catch {
|
|
96
|
+
throw new Error('Code runner sent a message that is not valid JSON');
|
|
97
|
+
}
|
|
98
|
+
if (!isRecord(parsed)) {
|
|
99
|
+
throw new Error('Code runner sent a message that is not an object');
|
|
100
|
+
}
|
|
101
|
+
switch (parsed.type) {
|
|
102
|
+
case ExecutionMessageType.CALL:
|
|
103
|
+
if (
|
|
104
|
+
typeof parsed.callId !== 'string' ||
|
|
105
|
+
typeof parsed.stepId !== 'string' ||
|
|
106
|
+
typeof parsed.capability !== 'string'
|
|
107
|
+
) {
|
|
108
|
+
throw malformed(parsed.type);
|
|
109
|
+
}
|
|
110
|
+
return parsed as unknown as ExecutionCallMessage;
|
|
111
|
+
case ExecutionMessageType.PROGRESS:
|
|
112
|
+
if (typeof parsed.stepId !== 'string' || !STEP_PHASES.has(parsed.phase as string)) {
|
|
113
|
+
throw malformed(parsed.type);
|
|
114
|
+
}
|
|
115
|
+
return parsed as unknown as ProgressMessage;
|
|
116
|
+
case ExecutionMessageType.FINISHED:
|
|
117
|
+
if (
|
|
118
|
+
!isRecord(parsed.outcome) ||
|
|
119
|
+
!EXECUTION_STATUSES.has(parsed.outcome.status as string) ||
|
|
120
|
+
!isRecord(parsed.metrics)
|
|
121
|
+
) {
|
|
122
|
+
throw malformed(parsed.type);
|
|
123
|
+
}
|
|
124
|
+
return parsed as unknown as FinishedMessage;
|
|
125
|
+
case ExecutionMessageType.REJECTED:
|
|
126
|
+
if (!REJECTION_CODES.has(parsed.code as string) || typeof parsed.message !== 'string') {
|
|
127
|
+
throw malformed(parsed.type);
|
|
128
|
+
}
|
|
129
|
+
return parsed as unknown as ExecutionRejectedMessage;
|
|
130
|
+
default:
|
|
131
|
+
throw new Error('Code runner sent a message of unknown type');
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
const errorMessage = (error: unknown): string =>
|
|
136
|
+
error instanceof Error ? error.message : String(error);
|
|
137
|
+
|
|
138
|
+
const callErrorOf = (error: unknown): CallError =>
|
|
139
|
+
error instanceof CapabilityError
|
|
140
|
+
? { code: error.code, message: error.message }
|
|
141
|
+
: { message: errorMessage(error) };
|
|
142
|
+
|
|
143
|
+
const abortReason = (signal: AbortSignal): unknown =>
|
|
144
|
+
signal.reason ?? new Error('The execution was aborted');
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Node client of the code runner for `abyss-runtime.v2`: one WebSocket connection per
|
|
148
|
+
* execution, one `execute`, the runner's calls served by the host's capability handlers.
|
|
149
|
+
*/
|
|
150
|
+
export class CodeRunnerSession {
|
|
151
|
+
private readonly options: CodeRunnerSessionOptions;
|
|
152
|
+
|
|
153
|
+
constructor(options: CodeRunnerSessionOptions) {
|
|
154
|
+
this.options = options;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
public execute(
|
|
158
|
+
request: ExecutionRequest,
|
|
159
|
+
handlers: CapabilityHandlers,
|
|
160
|
+
executeOptions: ExecuteOptions = {},
|
|
161
|
+
): Promise<ExecutionResult> {
|
|
162
|
+
const { url, token, connectTimeoutMs, wallTimeGraceMs } = this.options;
|
|
163
|
+
const { onProgress, signal } = executeOptions;
|
|
164
|
+
if (signal?.aborted) {
|
|
165
|
+
return Promise.reject(abortReason(signal));
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
return new Promise<ExecutionResult>((resolve, reject) => {
|
|
169
|
+
let settled = false;
|
|
170
|
+
let wallTimer: ReturnType<typeof setTimeout> | undefined;
|
|
171
|
+
const ws = new WebSocket(url, EXECUTION_PROTOCOL, {
|
|
172
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
173
|
+
handshakeTimeout: connectTimeoutMs,
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
const onAbort = (): void => finish(() => reject(abortReason(signal as AbortSignal)));
|
|
177
|
+
|
|
178
|
+
function finish(outcome: () => void): void {
|
|
179
|
+
if (settled) {
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
settled = true;
|
|
183
|
+
clearTimeout(connectTimer);
|
|
184
|
+
clearTimeout(wallTimer);
|
|
185
|
+
signal?.removeEventListener('abort', onAbort);
|
|
186
|
+
if (ws.readyState === WebSocket.OPEN) {
|
|
187
|
+
ws.close();
|
|
188
|
+
} else {
|
|
189
|
+
ws.terminate();
|
|
190
|
+
}
|
|
191
|
+
outcome();
|
|
192
|
+
}
|
|
193
|
+
const fail = (code: RuntimeErrorCode, message: string): void =>
|
|
194
|
+
finish(() => reject(new CodeRunnerError(code, message)));
|
|
195
|
+
const unavailable = (message: string): void =>
|
|
196
|
+
fail(RuntimeErrorCode.RUNNER_UNAVAILABLE, message);
|
|
197
|
+
|
|
198
|
+
const connectTimer = setTimeout(
|
|
199
|
+
() =>
|
|
200
|
+
unavailable(`Code runner did not accept the connection within ${connectTimeoutMs} ms`),
|
|
201
|
+
connectTimeoutMs,
|
|
202
|
+
);
|
|
203
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
204
|
+
|
|
205
|
+
const send = (message: ExecuteMessage | ExecutionCallResultMessage): void => {
|
|
206
|
+
if (!settled && ws.readyState === WebSocket.OPEN) {
|
|
207
|
+
ws.send(JSON.stringify(message));
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
|
|
211
|
+
const serveCall = async (call: ExecutionCallMessage): Promise<void> => {
|
|
212
|
+
const handler = Object.prototype.hasOwnProperty.call(handlers, call.capability)
|
|
213
|
+
? handlers[call.capability]
|
|
214
|
+
: undefined;
|
|
215
|
+
if (!handler) {
|
|
216
|
+
send({
|
|
217
|
+
type: ExecutionMessageType.CALL_RESULT,
|
|
218
|
+
callId: call.callId,
|
|
219
|
+
ok: false,
|
|
220
|
+
error: {
|
|
221
|
+
code: RuntimeErrorCode.ACCESS_DENIED,
|
|
222
|
+
message: `Capability "${call.capability}" is not granted to the execution`,
|
|
223
|
+
},
|
|
224
|
+
});
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
try {
|
|
228
|
+
const value = await handler(call.args, { stepId: call.stepId });
|
|
229
|
+
send(
|
|
230
|
+
value === SUSPEND_EXECUTION
|
|
231
|
+
? {
|
|
232
|
+
type: ExecutionMessageType.CALL_RESULT,
|
|
233
|
+
callId: call.callId,
|
|
234
|
+
ok: true,
|
|
235
|
+
suspend: true,
|
|
236
|
+
}
|
|
237
|
+
: { type: ExecutionMessageType.CALL_RESULT, callId: call.callId, ok: true, value },
|
|
238
|
+
);
|
|
239
|
+
} catch (error) {
|
|
240
|
+
send({
|
|
241
|
+
type: ExecutionMessageType.CALL_RESULT,
|
|
242
|
+
callId: call.callId,
|
|
243
|
+
ok: false,
|
|
244
|
+
error: callErrorOf(error),
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
ws.on('unexpected-response', (_request, response) => {
|
|
250
|
+
const status = response.statusCode;
|
|
251
|
+
unavailable(
|
|
252
|
+
status === 401
|
|
253
|
+
? 'Code runner refused the token (401 Unauthorized)'
|
|
254
|
+
: `Code runner refused the connection (HTTP ${status})`,
|
|
255
|
+
);
|
|
256
|
+
});
|
|
257
|
+
ws.on('error', (error) => unavailable(`Code runner unreachable: ${error.message}`));
|
|
258
|
+
ws.on('close', () => unavailable('Code runner connection closed before the end'));
|
|
259
|
+
|
|
260
|
+
ws.on('open', () => {
|
|
261
|
+
clearTimeout(connectTimer);
|
|
262
|
+
const wallLimitMs = request.limits.wallTimeMs + wallTimeGraceMs;
|
|
263
|
+
wallTimer = setTimeout(
|
|
264
|
+
() => fail(RuntimeErrorCode.TIMEOUT, `Execution did not finish within ${wallLimitMs} ms`),
|
|
265
|
+
wallLimitMs,
|
|
266
|
+
);
|
|
267
|
+
send({
|
|
268
|
+
...request,
|
|
269
|
+
type: ExecutionMessageType.EXECUTE,
|
|
270
|
+
capabilities: Object.keys(handlers),
|
|
271
|
+
});
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
ws.on('message', (raw) => {
|
|
275
|
+
if (settled) {
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
let message: ExecutionRunnerMessage;
|
|
279
|
+
try {
|
|
280
|
+
message = parseRunnerMessage(raw);
|
|
281
|
+
} catch (error) {
|
|
282
|
+
unavailable(errorMessage(error));
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
switch (message.type) {
|
|
286
|
+
case ExecutionMessageType.CALL:
|
|
287
|
+
void serveCall(message);
|
|
288
|
+
break;
|
|
289
|
+
case ExecutionMessageType.PROGRESS: {
|
|
290
|
+
if (!onProgress) {
|
|
291
|
+
break;
|
|
292
|
+
}
|
|
293
|
+
try {
|
|
294
|
+
onProgress(message);
|
|
295
|
+
} catch (error) {
|
|
296
|
+
finish(() => reject(error));
|
|
297
|
+
}
|
|
298
|
+
break;
|
|
299
|
+
}
|
|
300
|
+
case ExecutionMessageType.FINISHED:
|
|
301
|
+
finish(() => resolve({ outcome: message.outcome, metrics: message.metrics }));
|
|
302
|
+
break;
|
|
303
|
+
case ExecutionMessageType.REJECTED:
|
|
304
|
+
fail(message.code, message.message);
|
|
305
|
+
break;
|
|
306
|
+
}
|
|
307
|
+
});
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// Entry point `@abyss-project/runtime/server`: the only place where `ws` and Node modules are allowed.
|
|
2
|
+
export { CodeRunnerError } from './code-runner-error';
|
|
3
|
+
export { CapabilityError, CodeRunnerSession, SUSPEND_EXECUTION } from './code-runner-session';
|
|
4
|
+
export type {
|
|
5
|
+
CapabilityContext,
|
|
6
|
+
CapabilityHandlers,
|
|
7
|
+
CodeRunnerSessionOptions,
|
|
8
|
+
ExecuteOptions,
|
|
9
|
+
ExecutionRequest,
|
|
10
|
+
ExecutionResult,
|
|
11
|
+
} from './code-runner-session';
|