@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,12 @@
|
|
|
1
|
+
import { RuntimeErrorCode } from '../errors/runtime-error-code.enum';
|
|
2
|
+
|
|
3
|
+
/** Thrown for a misuse of the interpreter (unexpected event, corrupted state), never for a run failure. */
|
|
4
|
+
export class InterpreterError extends Error {
|
|
5
|
+
readonly code: RuntimeErrorCode;
|
|
6
|
+
|
|
7
|
+
constructor(code: RuntimeErrorCode, message: string) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.name = 'InterpreterError';
|
|
10
|
+
this.code = code;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
import { RuntimeErrorCode } from '../errors/runtime-error-code.enum';
|
|
2
|
+
import type { RuntimeErrorDetail } from '../errors/runtime-error-code.enum';
|
|
3
|
+
import { MAX_WAIT_DURATION_MS } from '../definition/definition.schema';
|
|
4
|
+
import { CURRENT_FORMAT_VERSION, StopStatus } from '../definition/definition.types';
|
|
5
|
+
import type { RuntimeDefinition, Step } from '../definition/definition.types';
|
|
6
|
+
import { StepActionKind, executeStep } from '../steps/execute-step';
|
|
7
|
+
import type { StepAction } from '../steps/execute-step';
|
|
8
|
+
import { collectStepItems, resolveStepFields } from '../steps/step-fields';
|
|
9
|
+
import { AccessVerdict, checkHostActionAccess, checkHttpAccess } from '../steps/step-access';
|
|
10
|
+
import { InterpreterError } from './interpreter-error';
|
|
11
|
+
import { EffectType, RunEventType, RunStatus } from './interpreter.types';
|
|
12
|
+
import type {
|
|
13
|
+
Effect,
|
|
14
|
+
RunEvent,
|
|
15
|
+
RunOptions,
|
|
16
|
+
RunState,
|
|
17
|
+
StepResult,
|
|
18
|
+
WaitEffect,
|
|
19
|
+
} from './interpreter.types';
|
|
20
|
+
import { ROOT_SEQUENCE_PATH, branchPath, resolveSequence, resolveStep } from './sequence-path';
|
|
21
|
+
|
|
22
|
+
const NO_RESULTS: ReadonlyMap<string, unknown> = new Map();
|
|
23
|
+
|
|
24
|
+
const invalidRequest = (message: string): InterpreterError =>
|
|
25
|
+
new InterpreterError(RuntimeErrorCode.INVALID_REQUEST, message);
|
|
26
|
+
|
|
27
|
+
/** A copy whose containers can be changed freely; the caller's state is never touched. */
|
|
28
|
+
const draftOf = (state: RunState): RunState => ({
|
|
29
|
+
...state,
|
|
30
|
+
stack: state.stack.map((frame) => ({ ...frame })),
|
|
31
|
+
outputs: { ...state.outputs },
|
|
32
|
+
vars: { ...state.vars },
|
|
33
|
+
counters: { ...state.counters },
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
/** Own, enumerable data property: unlike `target[key] = value`, a key such as `__proto__` stays a key. */
|
|
37
|
+
const setOwn = <T>(target: Record<string, T>, key: string, value: T): void => {
|
|
38
|
+
Object.defineProperty(target, key, {
|
|
39
|
+
value,
|
|
40
|
+
writable: true,
|
|
41
|
+
enumerable: true,
|
|
42
|
+
configurable: true,
|
|
43
|
+
});
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const topFrame = (draft: RunState) => draft.stack[draft.stack.length - 1];
|
|
47
|
+
|
|
48
|
+
const advance = (draft: RunState): void => {
|
|
49
|
+
topFrame(draft).index += 1;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const settle = (draft: RunState, status: RunStatus): StepResult => {
|
|
53
|
+
draft.status = status;
|
|
54
|
+
draft.pending = null;
|
|
55
|
+
return { state: draft, effects: [], status };
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
const failRun = (draft: RunState, error: RuntimeErrorDetail, stepId: string): StepResult => {
|
|
59
|
+
draft.outcome = { status: StopStatus.FAILED, error: { ...error, stepId } };
|
|
60
|
+
return settle(draft, RunStatus.FAILED);
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const emit = (draft: RunState, effect: Effect, options: RunOptions): StepResult => {
|
|
64
|
+
if (draft.counters.effects + 1 > options.budget.maxEffects) {
|
|
65
|
+
return failRun(
|
|
66
|
+
draft,
|
|
67
|
+
{ code: RuntimeErrorCode.BUDGET_EXCEEDED, message: 'Effect budget exceeded' },
|
|
68
|
+
effect.stepId,
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
draft.counters.effects += 1;
|
|
72
|
+
draft.pending = effect;
|
|
73
|
+
draft.status = RunStatus.WAITING;
|
|
74
|
+
return { state: draft, effects: [effect], status: RunStatus.WAITING };
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
const accessDenied = (verdict: AccessVerdict, subject: string): RuntimeErrorDetail => ({
|
|
78
|
+
code: RuntimeErrorCode.ACCESS_DENIED,
|
|
79
|
+
message:
|
|
80
|
+
verdict === AccessVerdict.NOT_DECLARED
|
|
81
|
+
? `${subject} is not declared by the definition`
|
|
82
|
+
: `${subject} is not granted to the run`,
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
const validateHostInput = (
|
|
86
|
+
step: Extract<StepAction, { kind: StepActionKind.HOST }>,
|
|
87
|
+
options: RunOptions,
|
|
88
|
+
): { input: Record<string, unknown> } | { error: RuntimeErrorDetail } => {
|
|
89
|
+
const definition = options.catalog.get(step.action);
|
|
90
|
+
if (!definition) {
|
|
91
|
+
return {
|
|
92
|
+
error: { code: RuntimeErrorCode.HOST_ERROR, message: 'Host action is not in the catalog' },
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
const { error, value } = definition.inputSchema.validate(step.input, { abortEarly: false });
|
|
96
|
+
if (error) {
|
|
97
|
+
const reasons = error.details.map((detail) => detail.message).join('; ');
|
|
98
|
+
return {
|
|
99
|
+
error: {
|
|
100
|
+
code: RuntimeErrorCode.HOST_ERROR,
|
|
101
|
+
message: `Invalid host action input: ${reasons}`,
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
return { input: value as Record<string, unknown> };
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
const applyAction = (
|
|
109
|
+
definition: RuntimeDefinition,
|
|
110
|
+
draft: RunState,
|
|
111
|
+
step: Step,
|
|
112
|
+
action: StepAction,
|
|
113
|
+
options: RunOptions,
|
|
114
|
+
): StepResult | null => {
|
|
115
|
+
switch (action.kind) {
|
|
116
|
+
case StepActionKind.FAIL:
|
|
117
|
+
return failRun(draft, action.error, step.id);
|
|
118
|
+
case StepActionKind.STOP:
|
|
119
|
+
draft.outcome = { status: action.status, output: action.output };
|
|
120
|
+
return settle(
|
|
121
|
+
draft,
|
|
122
|
+
action.status === StopStatus.SUCCEEDED ? RunStatus.SUCCEEDED : RunStatus.FAILED,
|
|
123
|
+
);
|
|
124
|
+
case StepActionKind.DONE: {
|
|
125
|
+
setOwn(draft.outputs, step.id, { output: action.output });
|
|
126
|
+
if (action.variable) {
|
|
127
|
+
setOwn(draft.vars, action.variable.name, action.variable.value);
|
|
128
|
+
}
|
|
129
|
+
if (action.branch === undefined) {
|
|
130
|
+
advance(draft);
|
|
131
|
+
} else {
|
|
132
|
+
draft.stack.push({ sequencePath: branchPath(topFrame(draft), action.branch), index: 0 });
|
|
133
|
+
}
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
case StepActionKind.WAIT: {
|
|
137
|
+
// A host budget never loosens the bound the validation applies to a literal duration.
|
|
138
|
+
const maxWaitMs = Math.min(options.budget.maxWaitMs, MAX_WAIT_DURATION_MS);
|
|
139
|
+
if (action.durationMs !== undefined && action.durationMs > maxWaitMs) {
|
|
140
|
+
return failRun(
|
|
141
|
+
draft,
|
|
142
|
+
{
|
|
143
|
+
code: RuntimeErrorCode.BUDGET_EXCEEDED,
|
|
144
|
+
message: `Wait duration exceeds the budget of ${maxWaitMs} ms`,
|
|
145
|
+
},
|
|
146
|
+
step.id,
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
const effect: WaitEffect = { type: EffectType.WAIT, stepId: step.id };
|
|
150
|
+
if (action.durationMs !== undefined) {
|
|
151
|
+
effect.durationMs = action.durationMs;
|
|
152
|
+
}
|
|
153
|
+
if (action.until !== undefined) {
|
|
154
|
+
effect.until = action.until;
|
|
155
|
+
}
|
|
156
|
+
return emit(draft, effect, options);
|
|
157
|
+
}
|
|
158
|
+
case StepActionKind.HTTP: {
|
|
159
|
+
const verdict = checkHttpAccess(action.request.url, definition.accesses, options.grants);
|
|
160
|
+
if (verdict !== AccessVerdict.ALLOWED) {
|
|
161
|
+
return failRun(draft, accessDenied(verdict, 'HTTP request host'), step.id);
|
|
162
|
+
}
|
|
163
|
+
return emit(
|
|
164
|
+
draft,
|
|
165
|
+
{ type: EffectType.HTTP, stepId: step.id, request: action.request },
|
|
166
|
+
options,
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
case StepActionKind.HOST: {
|
|
170
|
+
const verdict = checkHostActionAccess(action.action, definition.accesses, options.grants);
|
|
171
|
+
if (verdict !== AccessVerdict.ALLOWED) {
|
|
172
|
+
return failRun(draft, accessDenied(verdict, 'Host action'), step.id);
|
|
173
|
+
}
|
|
174
|
+
const validated = validateHostInput(action, options);
|
|
175
|
+
if ('error' in validated) {
|
|
176
|
+
return failRun(draft, validated.error, step.id);
|
|
177
|
+
}
|
|
178
|
+
return emit(
|
|
179
|
+
draft,
|
|
180
|
+
{ type: EffectType.HOST, stepId: step.id, action: action.action, input: validated.input },
|
|
181
|
+
options,
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Runs the current step: evaluates it first when it has non-literal values (`results` undefined),
|
|
189
|
+
* then applies it. Returns null when the step finished and the run goes on.
|
|
190
|
+
*/
|
|
191
|
+
const runStep = (
|
|
192
|
+
definition: RuntimeDefinition,
|
|
193
|
+
draft: RunState,
|
|
194
|
+
step: Step,
|
|
195
|
+
results: ReadonlyMap<string, unknown> | undefined,
|
|
196
|
+
options: RunOptions,
|
|
197
|
+
): StepResult | null => {
|
|
198
|
+
if (results === undefined) {
|
|
199
|
+
const items = collectStepItems(step);
|
|
200
|
+
if (items.length > 0) {
|
|
201
|
+
const context = { input: draft.input, steps: draft.outputs, vars: draft.vars };
|
|
202
|
+
return emit(draft, { type: EffectType.EVALUATE, stepId: step.id, items, context }, options);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
const fields = resolveStepFields(step, results ?? NO_RESULTS);
|
|
206
|
+
return applyAction(definition, draft, step, executeStep(step, fields), options);
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
/** Enters steps one after the other until an effect is emitted or the run ends. */
|
|
210
|
+
const drive = (definition: RuntimeDefinition, draft: RunState, options: RunOptions): StepResult => {
|
|
211
|
+
for (;;) {
|
|
212
|
+
const frame = topFrame(draft);
|
|
213
|
+
if (!frame) {
|
|
214
|
+
draft.outcome = { status: StopStatus.SUCCEEDED };
|
|
215
|
+
return settle(draft, RunStatus.SUCCEEDED);
|
|
216
|
+
}
|
|
217
|
+
const sequence = resolveSequence(definition, frame.sequencePath);
|
|
218
|
+
if (frame.index >= sequence.length) {
|
|
219
|
+
draft.stack.pop();
|
|
220
|
+
if (draft.stack.length > 0) {
|
|
221
|
+
advance(draft);
|
|
222
|
+
}
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
const step = sequence[frame.index];
|
|
226
|
+
if (draft.counters.steps + 1 > options.budget.maxSteps) {
|
|
227
|
+
return failRun(
|
|
228
|
+
draft,
|
|
229
|
+
{ code: RuntimeErrorCode.BUDGET_EXCEEDED, message: 'Step budget exceeded' },
|
|
230
|
+
step.id,
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
draft.counters.steps += 1;
|
|
234
|
+
const result = runStep(definition, draft, step, undefined, options);
|
|
235
|
+
if (result) {
|
|
236
|
+
return result;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
|
|
241
|
+
export const start = (
|
|
242
|
+
definition: RuntimeDefinition,
|
|
243
|
+
input: unknown,
|
|
244
|
+
options: RunOptions,
|
|
245
|
+
): StepResult =>
|
|
246
|
+
drive(
|
|
247
|
+
definition,
|
|
248
|
+
{
|
|
249
|
+
formatVersion: CURRENT_FORMAT_VERSION,
|
|
250
|
+
status: RunStatus.WAITING,
|
|
251
|
+
input,
|
|
252
|
+
stack: [{ sequencePath: ROOT_SEQUENCE_PATH, index: 0 }],
|
|
253
|
+
outputs: {},
|
|
254
|
+
vars: {},
|
|
255
|
+
pending: null,
|
|
256
|
+
counters: { steps: 0, effects: 0 },
|
|
257
|
+
},
|
|
258
|
+
options,
|
|
259
|
+
);
|
|
260
|
+
|
|
261
|
+
const unexpected = (event: RunEvent, pending: Effect): InterpreterError =>
|
|
262
|
+
invalidRequest(`Event ${event.type} does not answer the pending ${pending.type} effect`);
|
|
263
|
+
|
|
264
|
+
/** Maps each item id to its value, or returns the first failing item's error. */
|
|
265
|
+
const readEvaluation = (
|
|
266
|
+
pending: Effect,
|
|
267
|
+
results: Extract<RunEvent, { type: RunEventType.EVALUATED }>['results'],
|
|
268
|
+
): ReadonlyMap<string, unknown> | RuntimeErrorDetail => {
|
|
269
|
+
if (pending.type !== EffectType.EVALUATE) {
|
|
270
|
+
throw invalidRequest(
|
|
271
|
+
`Event ${RunEventType.EVALUATED} does not answer the pending ${pending.type} effect`,
|
|
272
|
+
);
|
|
273
|
+
}
|
|
274
|
+
const values = new Map<string, unknown>();
|
|
275
|
+
for (const item of pending.items) {
|
|
276
|
+
const result = results.find((candidate) => candidate.id === item.id);
|
|
277
|
+
if (!result) {
|
|
278
|
+
throw invalidRequest('Evaluation results do not cover every item of the lot');
|
|
279
|
+
}
|
|
280
|
+
if (!result.ok) {
|
|
281
|
+
return result.error;
|
|
282
|
+
}
|
|
283
|
+
values.set(item.id, result.value);
|
|
284
|
+
}
|
|
285
|
+
return values;
|
|
286
|
+
};
|
|
287
|
+
|
|
288
|
+
const complete = (
|
|
289
|
+
definition: RuntimeDefinition,
|
|
290
|
+
draft: RunState,
|
|
291
|
+
step: Step,
|
|
292
|
+
output: unknown,
|
|
293
|
+
options: RunOptions,
|
|
294
|
+
): StepResult => {
|
|
295
|
+
setOwn(draft.outputs, step.id, { output });
|
|
296
|
+
advance(draft);
|
|
297
|
+
return drive(definition, draft, options);
|
|
298
|
+
};
|
|
299
|
+
|
|
300
|
+
export const step = (
|
|
301
|
+
definition: RuntimeDefinition,
|
|
302
|
+
state: RunState,
|
|
303
|
+
event: RunEvent,
|
|
304
|
+
options: RunOptions,
|
|
305
|
+
): StepResult => {
|
|
306
|
+
const pending = state.pending;
|
|
307
|
+
if (state.status !== RunStatus.WAITING || !pending) {
|
|
308
|
+
throw invalidRequest(`Event ${event.type} received by a run that waits for nothing`);
|
|
309
|
+
}
|
|
310
|
+
const draft = draftOf(state);
|
|
311
|
+
draft.pending = null;
|
|
312
|
+
const current = resolveStep(definition, topFrame(draft));
|
|
313
|
+
|
|
314
|
+
switch (event.type) {
|
|
315
|
+
case RunEventType.EVALUATED: {
|
|
316
|
+
const values = readEvaluation(pending, event.results);
|
|
317
|
+
if (!(values instanceof Map)) {
|
|
318
|
+
return failRun(draft, values as RuntimeErrorDetail, current.id);
|
|
319
|
+
}
|
|
320
|
+
return (
|
|
321
|
+
runStep(definition, draft, current, values, options) ?? drive(definition, draft, options)
|
|
322
|
+
);
|
|
323
|
+
}
|
|
324
|
+
case RunEventType.HTTP_COMPLETED:
|
|
325
|
+
if (pending.type !== EffectType.HTTP) {
|
|
326
|
+
throw unexpected(event, pending);
|
|
327
|
+
}
|
|
328
|
+
return complete(definition, draft, current, event.response, options);
|
|
329
|
+
case RunEventType.HOST_COMPLETED:
|
|
330
|
+
if (pending.type !== EffectType.HOST) {
|
|
331
|
+
throw unexpected(event, pending);
|
|
332
|
+
}
|
|
333
|
+
return complete(definition, draft, current, event.output, options);
|
|
334
|
+
case RunEventType.WAIT_ELAPSED:
|
|
335
|
+
if (pending.type !== EffectType.WAIT) {
|
|
336
|
+
throw unexpected(event, pending);
|
|
337
|
+
}
|
|
338
|
+
return complete(definition, draft, current, null, options);
|
|
339
|
+
case RunEventType.EFFECT_FAILED:
|
|
340
|
+
return failRun(draft, event.error, current.id);
|
|
341
|
+
}
|
|
342
|
+
};
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import type { AccessGrant } from '../access/access.types';
|
|
2
|
+
import type { HostActionCatalog, HttpMethod, StopStatus } from '../definition/definition.types';
|
|
3
|
+
import type { RuntimeErrorDetail } from '../errors/runtime-error-code.enum';
|
|
4
|
+
import type { EvaluationItem, EvaluationResult } from '../runner-protocol/runner-protocol.types';
|
|
5
|
+
|
|
6
|
+
export enum RunStatus {
|
|
7
|
+
/** Waiting for the result of the effect it just emitted. */
|
|
8
|
+
WAITING = 'WAITING',
|
|
9
|
+
SUCCEEDED = 'SUCCEEDED',
|
|
10
|
+
FAILED = 'FAILED',
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface RunBudget {
|
|
14
|
+
maxSteps: number;
|
|
15
|
+
maxEffects: number;
|
|
16
|
+
/** Longest `durationMs` a WAIT may ask for; the host applies the same bound to `until`. */
|
|
17
|
+
maxWaitMs: number;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface RunOptions {
|
|
21
|
+
catalog: HostActionCatalog;
|
|
22
|
+
/** What this run is actually allowed to do; compared to the definition's declarations. */
|
|
23
|
+
grants: AccessGrant[];
|
|
24
|
+
budget: RunBudget;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Data an evaluation sees: `input`, `steps.<id>.output`, `vars`. `fn.*` is added by the runner. */
|
|
28
|
+
export interface EvaluationContext {
|
|
29
|
+
input: unknown;
|
|
30
|
+
steps: Record<string, { output: unknown }>;
|
|
31
|
+
vars: Record<string, unknown>;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export enum EffectType {
|
|
35
|
+
EVALUATE = 'EVALUATE',
|
|
36
|
+
HTTP = 'HTTP',
|
|
37
|
+
HOST = 'HOST',
|
|
38
|
+
WAIT = 'WAIT',
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Every expression and template of one step, sent to the code runner as one lot. */
|
|
42
|
+
export interface EvaluateEffect {
|
|
43
|
+
type: EffectType.EVALUATE;
|
|
44
|
+
stepId: string;
|
|
45
|
+
items: EvaluationItem[];
|
|
46
|
+
context: EvaluationContext;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface HttpRequest {
|
|
50
|
+
method: HttpMethod;
|
|
51
|
+
url: string;
|
|
52
|
+
headers: Record<string, string>;
|
|
53
|
+
body?: unknown;
|
|
54
|
+
timeoutMs?: number;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface HttpEffect {
|
|
58
|
+
type: EffectType.HTTP;
|
|
59
|
+
stepId: string;
|
|
60
|
+
request: HttpRequest;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export interface HostEffect {
|
|
64
|
+
type: EffectType.HOST;
|
|
65
|
+
stepId: string;
|
|
66
|
+
action: string;
|
|
67
|
+
input: Record<string, unknown>;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The interpreter has no clock: the host turns either field into a wake-up. It bounds
|
|
72
|
+
* `durationMs` against `RunBudget.maxWaitMs` itself, but cannot bound `until`: the host must
|
|
73
|
+
* refuse an `until` further from now than the same `maxWaitMs`.
|
|
74
|
+
*/
|
|
75
|
+
export interface WaitEffect {
|
|
76
|
+
type: EffectType.WAIT;
|
|
77
|
+
stepId: string;
|
|
78
|
+
durationMs?: number;
|
|
79
|
+
/** ISO 8601. */
|
|
80
|
+
until?: string;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export type Effect = EvaluateEffect | HttpEffect | HostEffect | WaitEffect;
|
|
84
|
+
|
|
85
|
+
export enum RunEventType {
|
|
86
|
+
EVALUATED = 'EVALUATED',
|
|
87
|
+
HTTP_COMPLETED = 'HTTP_COMPLETED',
|
|
88
|
+
HOST_COMPLETED = 'HOST_COMPLETED',
|
|
89
|
+
WAIT_ELAPSED = 'WAIT_ELAPSED',
|
|
90
|
+
EFFECT_FAILED = 'EFFECT_FAILED',
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export interface HttpResponse {
|
|
94
|
+
status: number;
|
|
95
|
+
headers: Record<string, string>;
|
|
96
|
+
body: unknown;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export type RunEvent =
|
|
100
|
+
| { type: RunEventType.EVALUATED; results: EvaluationResult[] }
|
|
101
|
+
| { type: RunEventType.HTTP_COMPLETED; response: HttpResponse }
|
|
102
|
+
| { type: RunEventType.HOST_COMPLETED; output: unknown }
|
|
103
|
+
| { type: RunEventType.WAIT_ELAPSED }
|
|
104
|
+
| { type: RunEventType.EFFECT_FAILED; error: RuntimeErrorDetail };
|
|
105
|
+
|
|
106
|
+
/** Position in the step tree: indexes from the root sequence down to the current step. */
|
|
107
|
+
export interface Frame {
|
|
108
|
+
/** Path of the sequence, e.g. `steps`, `steps[2].then`, `steps[1].cases[0].steps`. */
|
|
109
|
+
sequencePath: string;
|
|
110
|
+
index: number;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Plain JSON: a host can persist it during a long wait (Flow) or keep it in memory (Reflex).
|
|
115
|
+
* Only the interpreter reads or writes its fields.
|
|
116
|
+
*/
|
|
117
|
+
export interface RunState {
|
|
118
|
+
formatVersion: number;
|
|
119
|
+
status: RunStatus;
|
|
120
|
+
input: unknown;
|
|
121
|
+
stack: Frame[];
|
|
122
|
+
outputs: Record<string, { output: unknown }>;
|
|
123
|
+
vars: Record<string, unknown>;
|
|
124
|
+
/** The effect the run waits for, if any. */
|
|
125
|
+
pending: Effect | null;
|
|
126
|
+
counters: { steps: number; effects: number };
|
|
127
|
+
/** Set once the run is SUCCEEDED (stop output) or FAILED. */
|
|
128
|
+
outcome?: {
|
|
129
|
+
status: StopStatus;
|
|
130
|
+
output?: unknown;
|
|
131
|
+
error?: RuntimeErrorDetail & { stepId?: string };
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export interface StepResult {
|
|
136
|
+
state: RunState;
|
|
137
|
+
/** Zero or one effect: the interpreter waits for one result at a time. */
|
|
138
|
+
effects: Effect[];
|
|
139
|
+
status: RunStatus;
|
|
140
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { RuntimeErrorCode } from '../errors/runtime-error-code.enum';
|
|
2
|
+
import { StepType } from '../definition/definition.types';
|
|
3
|
+
import type { RuntimeDefinition, Step } from '../definition/definition.types';
|
|
4
|
+
import { InterpreterError } from './interpreter-error';
|
|
5
|
+
import type { Frame } from './interpreter.types';
|
|
6
|
+
|
|
7
|
+
const ROOT = 'steps';
|
|
8
|
+
const SEGMENT = /\[(\d+)\]\.(?:(then|else|default)|cases\[(\d+)\]\.steps)/y;
|
|
9
|
+
|
|
10
|
+
const corrupted = (path: string): InterpreterError =>
|
|
11
|
+
new InterpreterError(
|
|
12
|
+
RuntimeErrorCode.INVALID_REQUEST,
|
|
13
|
+
`Run state points outside the definition: ${path}`,
|
|
14
|
+
);
|
|
15
|
+
|
|
16
|
+
const branchOf = (
|
|
17
|
+
step: Step,
|
|
18
|
+
name: string | undefined,
|
|
19
|
+
caseIndex: string | undefined,
|
|
20
|
+
): Step[] | undefined => {
|
|
21
|
+
if (step.type === StepType.CONDITION) {
|
|
22
|
+
return name === 'then' ? step.then : name === 'else' ? step.else : undefined;
|
|
23
|
+
}
|
|
24
|
+
if (step.type === StepType.SWITCH) {
|
|
25
|
+
return name === 'default'
|
|
26
|
+
? step.default
|
|
27
|
+
: caseIndex === undefined
|
|
28
|
+
? undefined
|
|
29
|
+
: step.cases[Number(caseIndex)]?.steps;
|
|
30
|
+
}
|
|
31
|
+
return undefined;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/** The sequence a frame iterates: the root one, or a branch reached through the path. */
|
|
35
|
+
export const resolveSequence = (definition: RuntimeDefinition, path: string): Step[] => {
|
|
36
|
+
if (!path.startsWith(ROOT)) {
|
|
37
|
+
throw corrupted(path);
|
|
38
|
+
}
|
|
39
|
+
let sequence = definition.steps;
|
|
40
|
+
let position = ROOT.length;
|
|
41
|
+
while (position < path.length) {
|
|
42
|
+
SEGMENT.lastIndex = position;
|
|
43
|
+
const match = SEGMENT.exec(path);
|
|
44
|
+
const next = match ? branchOf(sequence[Number(match[1])], match[2], match[3]) : undefined;
|
|
45
|
+
if (!match || !next) {
|
|
46
|
+
throw corrupted(path);
|
|
47
|
+
}
|
|
48
|
+
sequence = next;
|
|
49
|
+
position = SEGMENT.lastIndex;
|
|
50
|
+
}
|
|
51
|
+
return sequence;
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
/** The step a frame points at. */
|
|
55
|
+
export const resolveStep = (definition: RuntimeDefinition, frame: Frame): Step => {
|
|
56
|
+
const step = resolveSequence(definition, frame.sequencePath)[frame.index];
|
|
57
|
+
if (!step) {
|
|
58
|
+
throw corrupted(frame.sequencePath);
|
|
59
|
+
}
|
|
60
|
+
return step;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
/** Path of a branch of the step the frame points at. */
|
|
64
|
+
export const branchPath = (frame: Frame, branch: string): string =>
|
|
65
|
+
`${frame.sequencePath}[${frame.index}].${branch}`;
|
|
66
|
+
|
|
67
|
+
export const ROOT_SEQUENCE_PATH = ROOT;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import type { RuntimeDefinition } from '../definition/definition.types';
|
|
2
|
+
import { start, step } from './interpreter';
|
|
3
|
+
import { EffectType, RunEventType } from './interpreter.types';
|
|
4
|
+
import type {
|
|
5
|
+
Effect,
|
|
6
|
+
EvaluateEffect,
|
|
7
|
+
HostEffect,
|
|
8
|
+
HttpEffect,
|
|
9
|
+
HttpResponse,
|
|
10
|
+
RunEvent,
|
|
11
|
+
RunOptions,
|
|
12
|
+
RunState,
|
|
13
|
+
StepResult,
|
|
14
|
+
WaitEffect,
|
|
15
|
+
} from './interpreter.types';
|
|
16
|
+
import type { EvaluationResult } from '../runner-protocol/runner-protocol.types';
|
|
17
|
+
|
|
18
|
+
type MaybePromise<T> = T | Promise<T>;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* How a simulated host answers each effect. `evaluate` is mandatory: the package evaluates no
|
|
22
|
+
* JavaScript. The other handlers default to an empty answer; `wait` always elapses at once.
|
|
23
|
+
*/
|
|
24
|
+
export interface TestHostHandlers {
|
|
25
|
+
evaluate: (effect: EvaluateEffect) => MaybePromise<EvaluationResult[]>;
|
|
26
|
+
http?: (effect: HttpEffect) => MaybePromise<HttpResponse>;
|
|
27
|
+
host?: (effect: HostEffect) => MaybePromise<unknown>;
|
|
28
|
+
wait?: (effect: WaitEffect) => MaybePromise<void>;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface TestRunResult {
|
|
32
|
+
state: RunState;
|
|
33
|
+
/** Every effect the interpreter emitted, in order. */
|
|
34
|
+
effects: Effect[];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const DEFAULT_HTTP_RESPONSE: HttpResponse = { status: 200, headers: {}, body: null };
|
|
38
|
+
|
|
39
|
+
const answer = async (effect: Effect, handlers: TestHostHandlers): Promise<RunEvent> => {
|
|
40
|
+
switch (effect.type) {
|
|
41
|
+
case EffectType.EVALUATE:
|
|
42
|
+
return { type: RunEventType.EVALUATED, results: await handlers.evaluate(effect) };
|
|
43
|
+
case EffectType.HTTP:
|
|
44
|
+
return {
|
|
45
|
+
type: RunEventType.HTTP_COMPLETED,
|
|
46
|
+
response: handlers.http ? await handlers.http(effect) : DEFAULT_HTTP_RESPONSE,
|
|
47
|
+
};
|
|
48
|
+
case EffectType.HOST:
|
|
49
|
+
return {
|
|
50
|
+
type: RunEventType.HOST_COMPLETED,
|
|
51
|
+
output: handlers.host ? await handlers.host(effect) : null,
|
|
52
|
+
};
|
|
53
|
+
case EffectType.WAIT:
|
|
54
|
+
await handlers.wait?.(effect);
|
|
55
|
+
return { type: RunEventType.WAIT_ELAPSED };
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
/** Runs a definition to its end, answering every effect with `handlers` and executing nothing. */
|
|
60
|
+
export const runToCompletion = async (
|
|
61
|
+
definition: RuntimeDefinition,
|
|
62
|
+
input: unknown,
|
|
63
|
+
options: RunOptions,
|
|
64
|
+
handlers: TestHostHandlers,
|
|
65
|
+
): Promise<TestRunResult> => {
|
|
66
|
+
const effects: Effect[] = [];
|
|
67
|
+
let result: StepResult = start(definition, input, options);
|
|
68
|
+
while (result.effects.length > 0) {
|
|
69
|
+
const [effect] = result.effects;
|
|
70
|
+
effects.push(effect);
|
|
71
|
+
result = step(definition, result.state, await answer(effect, handlers), options);
|
|
72
|
+
}
|
|
73
|
+
return { state: result.state, effects };
|
|
74
|
+
};
|