@abyss-project/runtime 3.0.0 → 3.2.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.
Files changed (41) hide show
  1. package/README.md +31 -0
  2. package/dist/discord/discord.types.d.ts +135 -0
  3. package/dist/discord/discord.types.js +59 -0
  4. package/dist/discord/discord.types.js.map +1 -0
  5. package/dist/index.d.ts +1 -0
  6. package/dist/index.js +1 -0
  7. package/dist/index.js.map +1 -1
  8. package/dist/runner-protocol/execution-protocol.types.js.map +1 -1
  9. package/package.json +1 -1
  10. package/scripts/build-engine.cjs +70 -70
  11. package/src/__tests__/engine-bundle.test.ts +121 -121
  12. package/src/cost/__tests__/execution-cost.test.ts +196 -196
  13. package/src/cost/execution-cost.ts +186 -186
  14. package/src/definition/__tests__/validate-definition.test.ts +354 -354
  15. package/src/definition/definition.limits.ts +9 -9
  16. package/src/definition/definition.schema.ts +172 -172
  17. package/src/definition/definition.types.ts +171 -171
  18. package/src/discord/discord.types.ts +181 -0
  19. package/src/engine/__tests__/run-in-isolate.test.ts +468 -468
  20. package/src/engine/engine-entry.ts +3 -3
  21. package/src/engine/engine-global.ts +2 -2
  22. package/src/engine/run-in-isolate.ts +404 -404
  23. package/src/errors/runtime-error-code.enum.ts +37 -37
  24. package/src/index.ts +31 -30
  25. package/src/interpreter/__tests__/interpreter.test.ts +854 -854
  26. package/src/interpreter/__tests__/log-respond-resume.test.ts +223 -223
  27. package/src/interpreter/interpreter.ts +461 -461
  28. package/src/interpreter/interpreter.types.ts +192 -192
  29. package/src/interpreter/test-host.ts +85 -85
  30. package/src/runner-protocol/evaluation.types.ts +21 -21
  31. package/src/runner-protocol/execution-protocol.types.ts +231 -225
  32. package/src/server/__tests__/code-runner-session.test.ts +311 -311
  33. package/src/server/code-runner-error.ts +12 -12
  34. package/src/server/code-runner-session.ts +310 -310
  35. package/src/server/index.ts +11 -11
  36. package/src/steps/__tests__/global-references.test.ts +133 -113
  37. package/src/steps/execute-step.ts +186 -186
  38. package/src/steps/global-references.ts +48 -48
  39. package/src/steps/step-access.ts +56 -56
  40. package/src/steps/step-fields.ts +87 -87
  41. package/src/steps/value-source.ts +69 -69
@@ -1,311 +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 },
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
- });
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 },
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
+ });
@@ -1,12 +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
- }
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
+ }