@abyss-project/runtime 1.0.0 → 2.0.1

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 (104) hide show
  1. package/README.md +6 -3
  2. package/dist/cost/execution-cost.d.ts +45 -0
  3. package/dist/cost/execution-cost.js +114 -0
  4. package/dist/cost/execution-cost.js.map +1 -0
  5. package/dist/definition/definition.limits.d.ts +4 -0
  6. package/dist/definition/definition.limits.js +8 -0
  7. package/dist/definition/definition.limits.js.map +1 -0
  8. package/dist/definition/definition.schema.d.ts +2 -2
  9. package/dist/definition/definition.schema.js +20 -4
  10. package/dist/definition/definition.schema.js.map +1 -1
  11. package/dist/definition/definition.types.d.ts +20 -1
  12. package/dist/definition/definition.types.js +9 -1
  13. package/dist/definition/definition.types.js.map +1 -1
  14. package/dist/engine/engine-entry.d.ts +1 -0
  15. package/dist/engine/engine-entry.js +6 -0
  16. package/dist/engine/engine-entry.js.map +1 -0
  17. package/dist/engine/engine-global.d.ts +1 -0
  18. package/dist/engine/engine-global.js +5 -0
  19. package/dist/engine/engine-global.js.map +1 -0
  20. package/dist/engine/engine-source.d.ts +2 -0
  21. package/dist/engine/engine-source.js +3 -0
  22. package/dist/engine/run-in-isolate.d.ts +34 -0
  23. package/dist/engine/run-in-isolate.js +267 -0
  24. package/dist/engine/run-in-isolate.js.map +1 -0
  25. package/dist/errors/runtime-error-code.enum.d.ts +2 -2
  26. package/dist/errors/runtime-error-code.enum.js +1 -1
  27. package/dist/errors/runtime-error-code.enum.js.map +1 -1
  28. package/dist/index.d.ts +8 -2
  29. package/dist/index.js +13 -4
  30. package/dist/index.js.map +1 -1
  31. package/dist/interpreter/interpreter.d.ts +27 -1
  32. package/dist/interpreter/interpreter.js +114 -42
  33. package/dist/interpreter/interpreter.js.map +1 -1
  34. package/dist/interpreter/interpreter.types.d.ts +35 -4
  35. package/dist/interpreter/interpreter.types.js +7 -1
  36. package/dist/interpreter/interpreter.types.js.map +1 -1
  37. package/dist/interpreter/test-host.d.ts +4 -2
  38. package/dist/interpreter/test-host.js +6 -0
  39. package/dist/interpreter/test-host.js.map +1 -1
  40. package/dist/runner-protocol/evaluation.types.d.ts +20 -0
  41. package/dist/runner-protocol/evaluation.types.js +10 -0
  42. package/dist/runner-protocol/evaluation.types.js.map +1 -0
  43. package/dist/runner-protocol/execution-protocol.types.d.ts +132 -0
  44. package/dist/runner-protocol/execution-protocol.types.js +48 -0
  45. package/dist/runner-protocol/execution-protocol.types.js.map +1 -0
  46. package/dist/server/code-runner-session.d.ts +28 -0
  47. package/dist/server/code-runner-session.js +208 -0
  48. package/dist/server/code-runner-session.js.map +1 -0
  49. package/dist/server/index.d.ts +2 -2
  50. package/dist/server/index.js +5 -3
  51. package/dist/server/index.js.map +1 -1
  52. package/dist/steps/execute-step.d.ts +12 -2
  53. package/dist/steps/execute-step.js +37 -0
  54. package/dist/steps/execute-step.js.map +1 -1
  55. package/dist/steps/global-references.d.ts +2 -0
  56. package/dist/steps/global-references.js +28 -0
  57. package/dist/steps/global-references.js.map +1 -0
  58. package/dist/steps/step-fields.d.ts +1 -1
  59. package/dist/steps/step-fields.js +10 -2
  60. package/dist/steps/step-fields.js.map +1 -1
  61. package/dist/steps/value-source.d.ts +1 -1
  62. package/dist/steps/value-source.js +3 -3
  63. package/dist/steps/value-source.js.map +1 -1
  64. package/package.json +10 -2
  65. package/scripts/build-engine.cjs +70 -0
  66. package/src/__tests__/engine-bundle.test.ts +121 -0
  67. package/src/cost/__tests__/execution-cost.test.ts +200 -0
  68. package/src/cost/execution-cost.ts +192 -0
  69. package/src/definition/__tests__/validate-definition.test.ts +354 -303
  70. package/src/definition/definition.limits.ts +9 -0
  71. package/src/definition/definition.schema.ts +172 -139
  72. package/src/definition/definition.types.ts +171 -143
  73. package/src/engine/__tests__/run-in-isolate.test.ts +468 -0
  74. package/src/engine/engine-entry.ts +3 -0
  75. package/src/engine/engine-global.ts +2 -0
  76. package/src/engine/run-in-isolate.ts +404 -0
  77. package/src/errors/runtime-error-code.enum.ts +37 -37
  78. package/src/index.ts +30 -18
  79. package/src/interpreter/__tests__/interpreter.test.ts +854 -854
  80. package/src/interpreter/__tests__/log-respond-resume.test.ts +223 -0
  81. package/src/interpreter/interpreter.ts +461 -342
  82. package/src/interpreter/interpreter.types.ts +192 -140
  83. package/src/interpreter/test-host.ts +85 -74
  84. package/src/runner-protocol/evaluation.types.ts +21 -0
  85. package/src/runner-protocol/execution-protocol.types.ts +221 -0
  86. package/src/server/__tests__/code-runner-session.test.ts +311 -0
  87. package/src/server/code-runner-error.ts +12 -12
  88. package/src/server/code-runner-session.ts +310 -0
  89. package/src/server/index.ts +11 -4
  90. package/src/steps/__tests__/global-references.test.ts +113 -0
  91. package/src/steps/execute-step.ts +186 -132
  92. package/src/steps/global-references.ts +48 -0
  93. package/src/steps/step-access.ts +56 -56
  94. package/src/steps/step-fields.ts +87 -79
  95. package/src/steps/value-source.ts +69 -69
  96. package/dist/runner-protocol/runner-protocol.types.d.ts +0 -92
  97. package/dist/runner-protocol/runner-protocol.types.js +0 -26
  98. package/dist/runner-protocol/runner-protocol.types.js.map +0 -1
  99. package/dist/server/code-runner-client.d.ts +0 -13
  100. package/dist/server/code-runner-client.js +0 -155
  101. package/dist/server/code-runner-client.js.map +0 -1
  102. package/src/runner-protocol/runner-protocol.types.ts +0 -117
  103. package/src/server/__tests__/code-runner-client.test.ts +0 -262
  104. package/src/server/code-runner-client.ts +0 -201
@@ -0,0 +1,221 @@
1
+ import type { RuntimeErrorCode } from '../errors/runtime-error-code.enum';
2
+ import type { RuntimeDefinition } from '../definition/definition.types';
3
+ import type { RunState } from '../interpreter/interpreter.types';
4
+
5
+ /**
6
+ * WebSocket sub-protocol of an execution (ADR-0239): one connection, one `execute`, one isolate
7
+ * running the whole definition. A new version is a new name, never a silent change.
8
+ */
9
+ export const EXECUTION_PROTOCOL = 'abyss-runtime.v2';
10
+
11
+ /** Upper bound, in JSON bytes, on the arguments of one `call` and on the value of its result. */
12
+ export const MAX_CALL_PAYLOAD_BYTES = 1_048_576;
13
+
14
+ /** Upper bound, in characters of JSON, on the step output a `progress` message carries. */
15
+ export const MAX_PROGRESS_OUTPUT_CHARS = 4_096;
16
+
17
+ /**
18
+ * Capabilities the core's own steps call. Every other name (Store, secrets, a product's
19
+ * actions) is declared by the host; the runner relays whatever the host lists.
20
+ */
21
+ export enum CoreCapability {
22
+ /** HTTP step, and `fetch()` in client code. Arguments: an `HttpRequest`. */
23
+ HTTP_FETCH = 'http.fetch',
24
+ /** WAIT step. Arguments: `{ durationMs }` or `{ until }`. */
25
+ WAIT = 'wait',
26
+ /** LOG step. Arguments: `{ level, message, data? }`. */
27
+ LOG_WRITE = 'log.write',
28
+ /** RESPOND step. Arguments: `{ status, headers, body? }`. */
29
+ HTTP_RESPOND = 'http.respond',
30
+ }
31
+
32
+ export enum ExecutionMessageType {
33
+ EXECUTE = 'execute',
34
+ CALL = 'call',
35
+ CALL_RESULT = 'callResult',
36
+ PROGRESS = 'progress',
37
+ FINISHED = 'finished',
38
+ REJECTED = 'rejected',
39
+ }
40
+
41
+ export type JSONValue =
42
+ | string
43
+ | number
44
+ | boolean
45
+ | null
46
+ | JSONValue[]
47
+ | { [key: string]: JSONValue };
48
+
49
+ /**
50
+ * Names `globals` cannot define: the evaluation context (`input`, `steps`, `vars`) and the
51
+ * client API (`fetch`, `abyss`, `console`).
52
+ */
53
+ export const RESERVED_GLOBAL_NAMES: readonly string[] = [
54
+ 'input',
55
+ 'steps',
56
+ 'vars',
57
+ 'fetch',
58
+ 'abyss',
59
+ 'console',
60
+ ];
61
+
62
+ export interface ExecutionLimits {
63
+ /** Heap of the execution's isolate: the memory of its resource profile. */
64
+ memoryMb: number;
65
+ /** CPU time of the whole execution (one segment when it suspends). */
66
+ cpuTimeMs: number;
67
+ /** Wall-clock time of the whole execution (one segment when it suspends). */
68
+ wallTimeMs: number;
69
+ /** Whether the execution holds a core of the runner for itself. */
70
+ guaranteedCpu: boolean;
71
+ }
72
+
73
+ export interface ExecutionBudget {
74
+ maxSteps: number;
75
+ maxEffects: number;
76
+ }
77
+
78
+ /** Host → runner: the execution to run. One per connection. */
79
+ export interface ExecuteMessage {
80
+ type: ExecutionMessageType.EXECUTE;
81
+ executionId: string;
82
+ definition: RuntimeDefinition;
83
+ input: unknown;
84
+ /** Present to resume a suspended execution: the `state` its `finished` message returned. */
85
+ state?: RunState;
86
+ /** On resume: becomes the output of the step that suspended. Absent for a timer wait. */
87
+ resumeInput?: unknown;
88
+ /** Names of the host functions the execution may call; nothing else is exposed. */
89
+ capabilities: string[];
90
+ limits: ExecutionLimits;
91
+ budget: ExecutionBudget;
92
+ /**
93
+ * A WAIT longer than this suspends the execution instead of calling `wait`. Absent: no wait
94
+ * suspends on its own, and the host bounds every wait (Reflex keeps waits in the execution).
95
+ */
96
+ suspendWaitAboveMs?: number;
97
+ /**
98
+ * Read-only values the host provides to the client code: each top-level key becomes a global
99
+ * (`secrets`, a workflow context...), deep-frozen and rebuilt in every evaluation. A key cannot
100
+ * be one of `RESERVED_GLOBAL_NAMES`: the runner refuses the request with `INVALID_REQUEST`.
101
+ * Never logged by the runner; the host masks what it stores. Dynamic access
102
+ * (`secrets[name]`) is not resolvable by the host: it yields `undefined`.
103
+ */
104
+ globals?: Record<string, JSONValue>;
105
+ }
106
+
107
+ /** Runner → host: the step `stepId` calls the host function `capability`. */
108
+ export interface ExecutionCallMessage {
109
+ type: ExecutionMessageType.CALL;
110
+ callId: string;
111
+ stepId: string;
112
+ capability: string;
113
+ args: unknown;
114
+ }
115
+
116
+ export interface CallError {
117
+ /** A `RuntimeErrorCode`; absent, the runner reports the capability's default code. */
118
+ code?: RuntimeErrorCode;
119
+ message: string;
120
+ }
121
+
122
+ /**
123
+ * Host → runner: the answer to one `call`. `suspend` asks the runner to stop after this step
124
+ * and finish SUSPENDED: a resume then gives the step its output through `resumeInput`.
125
+ */
126
+ export type ExecutionCallResultMessage =
127
+ | { type: ExecutionMessageType.CALL_RESULT; callId: string; ok: true; value: unknown }
128
+ | { type: ExecutionMessageType.CALL_RESULT; callId: string; ok: true; suspend: true }
129
+ | { type: ExecutionMessageType.CALL_RESULT; callId: string; ok: false; error: CallError };
130
+
131
+ export interface StepMetrics {
132
+ cpuMs: number;
133
+ heapPeakBytes: number;
134
+ wallMs: number;
135
+ }
136
+
137
+ export interface ExecutionMetrics {
138
+ queueMs: number;
139
+ wallMs: number;
140
+ cpuMs: number;
141
+ heapPeakBytes: number;
142
+ memoryLimitBytes: number;
143
+ }
144
+
145
+ export enum StepPhase {
146
+ STARTED = 'started',
147
+ FINISHED = 'finished',
148
+ }
149
+
150
+ export enum StepStatus {
151
+ SUCCEEDED = 'SUCCEEDED',
152
+ FAILED = 'FAILED',
153
+ /** The step's call was answered with `suspend`, or its wait is above `suspendWaitAboveMs`. */
154
+ SUSPENDED = 'SUSPENDED',
155
+ }
156
+
157
+ /** Runner → host: a step started or finished. The base of the trace. */
158
+ export interface ProgressMessage {
159
+ type: ExecutionMessageType.PROGRESS;
160
+ stepId: string;
161
+ phase: StepPhase;
162
+ /** On `finished`. */
163
+ status?: StepStatus;
164
+ /** On `finished`. */
165
+ durationMs?: number;
166
+ /** On `finished`, measured by the runner. */
167
+ metrics?: StepMetrics;
168
+ /**
169
+ * On `finished` with SUCCEEDED: the step's output, or, past `MAX_PROGRESS_OUTPUT_CHARS`, the
170
+ * beginning of its JSON with `outputTruncated`.
171
+ */
172
+ output?: unknown;
173
+ outputTruncated?: boolean;
174
+ /** On `finished` with FAILED. */
175
+ errorCode?: RuntimeErrorCode;
176
+ }
177
+
178
+ export enum ExecutionStatus {
179
+ SUCCEEDED = 'SUCCEEDED',
180
+ FAILED = 'FAILED',
181
+ SUSPENDED = 'SUSPENDED',
182
+ }
183
+
184
+ export interface ExecutionOutcome {
185
+ status: ExecutionStatus;
186
+ /** SUCCEEDED, or FAILED by a STOP step: the stop output. */
187
+ output?: unknown;
188
+ /** FAILED by an error; absent when a STOP step chose FAILED. */
189
+ errorCode?: RuntimeErrorCode;
190
+ errorMessage?: string;
191
+ /** FAILED: the step that failed, when one did. */
192
+ stepId?: string;
193
+ /** SUSPENDED: what to send back as `state` to resume. */
194
+ state?: RunState;
195
+ }
196
+
197
+ /** Runner → host: the execution ended. Closes the connection. */
198
+ export interface FinishedMessage {
199
+ type: ExecutionMessageType.FINISHED;
200
+ outcome: ExecutionOutcome;
201
+ metrics: ExecutionMetrics;
202
+ }
203
+
204
+ export type ExecutionRejectionCode =
205
+ | RuntimeErrorCode.RUNNER_SATURATED
206
+ | RuntimeErrorCode.INVALID_REQUEST
207
+ | RuntimeErrorCode.STATE_VERSION_UNSUPPORTED;
208
+
209
+ /** Runner → host: the execution was not run at all. */
210
+ export interface ExecutionRejectedMessage {
211
+ type: ExecutionMessageType.REJECTED;
212
+ code: ExecutionRejectionCode;
213
+ message: string;
214
+ }
215
+
216
+ export type ExecutionHostMessage = ExecuteMessage | ExecutionCallResultMessage;
217
+ export type ExecutionRunnerMessage =
218
+ | ExecutionCallMessage
219
+ | ProgressMessage
220
+ | FinishedMessage
221
+ | ExecutionRejectedMessage;
@@ -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
+ });
@@ -1,12 +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
- }
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
+ }