@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 369 lines 12.1 KB
Raw
1 /**
2 * Local interpreter for Step Functions programs — the payoff of the AST.
3 *
4 * `simulate` runs the *same* `SfnEffect` a `StateMachine.fromProgram`
5 * deploys, in-process, as a real `Effect`: Task states dispatch to
6 * caller-provided handler stubs, Choice conditions evaluate against the
7 * live variable environment, `catchTag`/`retry` follow the exact ASL error
8 * semantics (`{ Error, Cause }` error output, `States.ALL` matching), and
9 * `Wait` states are skipped (simulations are instantaneous).
10 */
11 import * as Data from "effect/Data";
12 import * as Effect from "effect/Effect";
13 import * as Result from "effect/Result";
14 import { inputExpr, isExpr, nodeOf, variableExpr, type ExprNode } from "./Jsonata.ts";
15 import type { AslNode } from "./Node.ts";
16 import { isSfnEffect, type SfnEffect } from "./Program.ts";
17
18 /**
19 * The simulation itself went wrong — a missing handler, an unsupported raw
20 * JSONata expression, or a structurally invalid program. Distinct from the
21 * program's own typed failures, which flow through the `E` channel.
22 */
23 export class SimulateError extends Data.TaggedError("SimulateError")<{
24 readonly message: string;
25 }> {}
26
27 /**
28 * Handler stubs for the program's Task states, keyed by:
29 * - the function's `LogicalId` for `Sfn.invoke` states,
30 * - the integration resource ARN (including any `.waitForTaskToken`
31 * suffix) for `Sfn.integrate` / `Sfn.waitForTaskToken` states.
32 */
33 export interface SimulateHandlers {
34 readonly [key: string]: (payload: unknown) => Effect.Effect<any, any>;
35 }
36
37 export interface SimulateOptions {
38 /** Task handler stubs. @default {} */
39 readonly handlers?: SimulateHandlers;
40 /** The task token exposed as `Sfn.taskToken`. @default "SIMULATED_TASK_TOKEN" */
41 readonly taskToken?: string;
42 }
43
44 interface Env {
45 readonly input: unknown;
46 /** Variable scope — prototype chain mirrors ASL variable scoping. */
47 vars: Record<string, unknown>;
48 readonly taskToken: string;
49 readonly handlers: SimulateHandlers;
50 counter: { n: number };
51 }
52
53 /**
54 * Internal failure wrapper preserving the exact ASL `Error`/`Cause` pair a
55 * `Fail` state declares, so `catch` handlers observe the same
56 * `$states.errorOutput` the cloud would produce. Unwrapped back to the
57 * user's typed failure at the simulation boundary.
58 */
59 class FailStateFailure {
60 readonly _sim = "FailStateFailure";
61 constructor(
62 readonly error: string,
63 readonly cause: string,
64 readonly failure: unknown,
65 ) {}
66 }
67
68 const isFailStateFailure = (value: unknown): value is FailStateFailure =>
69 value instanceof FailStateFailure;
70
71 /** The ASL error name of a simulated failure (`_tag` convention). */
72 const errorNameOf = (failure: unknown): string => {
73 if (isFailStateFailure(failure)) return failure.error;
74 if (
75 typeof failure === "object" &&
76 failure !== null &&
77 "_tag" in failure &&
78 typeof (failure as { _tag: unknown })._tag === "string"
79 ) {
80 return (failure as { _tag: string })._tag;
81 }
82 return "States.TaskFailed";
83 };
84
85 const causeOf = (failure: unknown): string => {
86 if (isFailStateFailure(failure)) return failure.cause;
87 if (typeof failure === "object" && failure !== null) {
88 const message = (failure as { message?: unknown }).message;
89 if (typeof message === "string" && message.length > 0) return message;
90 try {
91 return JSON.stringify(failure);
92 } catch {
93 return errorNameOf(failure);
94 }
95 }
96 return String(failure);
97 };
98
99 const evalExprNode = (node: ExprNode, env: Env): unknown => {
100 switch (node._) {
101 case "root":
102 switch (node.root.kind) {
103 case "input":
104 return env.input;
105 case "variable":
106 return env.vars[node.root.name];
107 case "token":
108 return env.taskToken;
109 }
110 case "prop": {
111 const parent = evalExprNode(node.parent, env) as Record<string, unknown> | null | undefined;
112 return parent == null ? undefined : parent[node.name];
113 }
114 case "literal":
115 return node.value;
116 case "binop": {
117 const left = evalExprNode(node.left, env) as any;
118 const right = evalExprNode(node.right, env) as any;
119 switch (node.op) {
120 case "=":
121 return left === right;
122 case "!=":
123 return left !== right;
124 case ">":
125 return left > right;
126 case ">=":
127 return left >= right;
128 case "<":
129 return left < right;
130 case "<=":
131 return left <= right;
132 case "and":
133 return Boolean(left) && Boolean(right);
134 case "or":
135 return Boolean(left) || Boolean(right);
136 }
137 }
138 case "not":
139 return !evalExprNode(node.inner, env);
140 case "raw":
141 throw new SimulateError({
142 message: `raw JSONata expressions are not supported by simulate: ${node.jsonata}`,
143 });
144 }
145 };
146
147 /** Deep-evaluate a payload value: `Expr` references resolve against `env`. */
148 const evalValue = (value: unknown, env: Env): unknown => {
149 if (value === undefined) return null;
150 if (isExpr(value)) return evalExprNode(nodeOf(value), env);
151 if (Array.isArray(value)) return value.map((entry) => evalValue(entry, env));
152 if (typeof value === "object" && value !== null) {
153 return Object.fromEntries(
154 Object.entries(value).map(([key, entry]) => [key, evalValue(entry, env)]),
155 );
156 }
157 return value;
158 };
159
160 const evalExpr = (value: unknown, env: Env) =>
161 Effect.try({
162 try: () => evalValue(value, env),
163 catch: (error) =>
164 error instanceof SimulateError ? error : new SimulateError({ message: String(error) }),
165 });
166
167 const allocVar = (env: Env): string => `sim${env.counter.n++}`;
168
169 /** Child scope with an ASL scope barrier (Parallel branch / Map iteration). */
170 const childEnv = (env: Env): Env => ({
171 ...env,
172 vars: Object.create(env.vars) as Record<string, unknown>,
173 });
174
175 const runNode = (node: AslNode, env: Env): Effect.Effect<unknown, any> => {
176 switch (node.kind) {
177 case "invoke": {
178 const handler = env.handlers[node.fn.LogicalId];
179 if (handler === undefined) {
180 return Effect.fail(
181 new SimulateError({
182 message: `no simulate handler for function "${node.fn.LogicalId}"`,
183 }),
184 );
185 }
186 return evalExpr(node.payload, env).pipe(Effect.flatMap(handler));
187 }
188
189 case "integrate": {
190 const key = node.waitForTaskToken
191 ? `${node.options.resource}.waitForTaskToken`
192 : node.options.resource;
193 const handler = env.handlers[key];
194 if (handler === undefined) {
195 return Effect.fail(
196 new SimulateError({
197 message: `no simulate handler for integration "${key}"`,
198 }),
199 );
200 }
201 return evalExpr(node.options.arguments, env).pipe(Effect.flatMap(handler));
202 }
203
204 case "all":
205 return Effect.forEach(node.branches, (branch) => runNode(branch.node, childEnv(env)));
206
207 case "forEach":
208 return evalExpr(node.items, env).pipe(
209 Effect.flatMap((items) => {
210 if (!Array.isArray(items)) {
211 return Effect.fail(
212 new SimulateError({
213 message: "Sfn.forEach items did not evaluate to an array",
214 }),
215 );
216 }
217 return Effect.forEach(items, (item) => {
218 // mirror compile: the item is bound to a fresh variable scoped
219 // to the iteration
220 const scope = childEnv(env);
221 const itemVar = allocVar(scope);
222 scope.vars[itemVar] = item;
223 const body = node.body(variableExpr(itemVar));
224 if (!isSfnEffect(body)) {
225 return Effect.fail(
226 new SimulateError({
227 message: "Sfn.forEach body must return an Sfn effect",
228 }),
229 );
230 }
231 return runNode(body.node, scope);
232 });
233 }),
234 );
235
236 case "sleep":
237 // simulations are instantaneous — Wait states are skipped
238 return Effect.succeed(null);
239
240 case "when":
241 return evalExpr(node.condition, env).pipe(
242 Effect.flatMap((condition) =>
243 condition
244 ? runNode(node.onTrue.node, env)
245 : node.onFalse !== undefined
246 ? runNode(node.onFalse.node, env)
247 : Effect.succeed(null),
248 ),
249 );
250
251 case "match":
252 return evalExpr(node.value, env).pipe(
253 Effect.flatMap((value) => {
254 const program = node.cases[String(value)] ?? node.otherwise;
255 if (program === undefined) {
256 return Effect.fail(
257 new SimulateError({
258 message: `States.NoChoiceMatched: no case for ${JSON.stringify(value)}`,
259 }),
260 );
261 }
262 return runNode(program.node, env);
263 }),
264 );
265
266 case "succeed":
267 return evalExpr(node.value, env);
268
269 case "fail":
270 return Effect.fail(new FailStateFailure(node.error, node.cause, node.failure));
271
272 case "retry": {
273 const tags =
274 node.options.while === undefined
275 ? ["States.ALL"]
276 : typeof node.options.while === "string"
277 ? [node.options.while]
278 : [...node.options.while];
279 const maxAttempts = node.options.maxAttempts ?? 3;
280 const attempt = (retriesLeft: number): Effect.Effect<unknown, any> =>
281 Effect.result(runNode(node.inner.node, env)).pipe(
282 Effect.flatMap((result) => {
283 if (Result.isSuccess(result)) return Effect.succeed(result.success);
284 const failure = result.failure;
285 const retryable =
286 !(failure instanceof SimulateError) &&
287 (tags.includes("States.ALL") || tags.includes(errorNameOf(failure)));
288 return retryable && retriesLeft > 0 ? attempt(retriesLeft - 1) : Effect.fail(failure);
289 }),
290 );
291 return attempt(maxAttempts);
292 }
293
294 case "catch":
295 return Effect.result(runNode(node.inner.node, env)).pipe(
296 Effect.flatMap((result) => {
297 if (Result.isSuccess(result)) return Effect.succeed(result.success);
298 const failure = result.failure;
299 const matches =
300 !(failure instanceof SimulateError) &&
301 (node.tags.includes("States.ALL") || node.tags.includes(errorNameOf(failure)));
302 if (!matches) return Effect.fail(failure);
303 const errorVar = allocVar(env);
304 env.vars[errorVar] = {
305 Error: errorNameOf(failure),
306 Cause: causeOf(failure),
307 };
308 const handler = node.handler(variableExpr(errorVar));
309 if (!isSfnEffect(handler)) {
310 return Effect.fail(
311 new SimulateError({
312 message: "Sfn.catchTag/catchAll handler must return an Sfn effect",
313 }),
314 );
315 }
316 return runNode(handler.node, env);
317 }),
318 );
319
320 case "gen":
321 return Effect.gen(function* () {
322 const iterator = node.body(inputExpr());
323 let step = iterator.next();
324 while (!step.done) {
325 const program: unknown = step.value;
326 if (!isSfnEffect(program)) {
327 return yield* new SimulateError({
328 message: "Sfn.gen may only yield Sfn effects",
329 });
330 }
331 const value = yield* runNode(program.node, env);
332 const name = allocVar(env);
333 env.vars[name] = value;
334 step = iterator.next(variableExpr(name));
335 }
336 return yield* evalExpr(step.value, env);
337 });
338 }
339 };
340
341 /**
342 * Run a Step Functions program in-process as an `Effect` — same AST the
343 * cloud executes, interpreted locally for unit tests.
344 *
345 * ```typescript
346 * const result = yield* simulate(program, { value: 6, items: [1, 2, 3] }, {
347 * handlers: {
348 * Doubler: (payload) =>
349 * Effect.succeed({ doubled: (payload as { value: number }).value * 2 }),
350 * },
351 * });
352 * ```
353 */
354 export const simulate = <A, E>(
355 program: SfnEffect<A, E>,
356 input: unknown,
357 options?: SimulateOptions,
358 ): Effect.Effect<A, E | SimulateError> => {
359 const env: Env = {
360 input,
361 vars: Object.create(null) as Record<string, unknown>,
362 taskToken: options?.taskToken ?? "SIMULATED_TASK_TOKEN",
363 handlers: options?.handlers ?? {},
364 counter: { n: 0 },
365 };
366 return runNode(program.node, env).pipe(
367 Effect.mapError((failure) => (isFailStateFailure(failure) ? failure.failure : failure)),
368 ) as Effect.Effect<A, E | SimulateError>;
369 };