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

main
ts 210 lines 7.58 KB
Raw
1 /**
2 * In-process unit tests for the Step Functions program DSL: `Sfn.simulate`
3 * interprets the SAME program the live `FromProgram.test.ts` deploys, plus
4 * the ASL error semantics (`catchTag`, `retry`, `match`) and compile
5 * determinism (the `normalizeDefinition` drift obligation).
6 */
7 import { Sfn } from "@alchemy.run/aws/StepFunctions";
8 import { describe, expect, it } from "@alchemy.run/test";
9 import * as Data from "effect/Data";
10 import * as Effect from "effect/Effect";
11 import * as Result from "effect/Result";
12 import { makeOrderProgram, OrderRejected, type OrderInput } from "./fixtures/order-program.ts";
13
14 const doubler: Sfn.InvokableFunction = {
15 LogicalId: "SfnDoubler",
16 functionArn: "arn:aws:lambda:us-east-1:000000000000:function:doubler",
17 };
18
19 const doublerHandlers: Sfn.SimulateHandlers = {
20 SfnDoubler: (payload) =>
21 Effect.succeed({ doubled: ((payload as { value: number }).value ?? 0) * 2 }),
22 };
23
24 describe(
25 "Sfn.simulate",
26 { tags: ["unit", "provider:aws", "provider:aws:stepfunctions", "local"] },
27 () => {
28 it.effect("runs the order program in-process", () =>
29 Effect.gen(function* () {
30 const result = yield* Sfn.simulate(
31 makeOrderProgram(doubler),
32 { value: 6, items: [1, 2, 3] } satisfies OrderInput,
33 { handlers: doublerHandlers },
34 );
35 expect(result).toEqual({
36 doubled: 12,
37 items: [2, 4, 6],
38 size: "big",
39 recovered: "no stock",
40 });
41 }),
42 );
43
44 it.effect("takes the false Choice branch for small inputs", () =>
45 Effect.gen(function* () {
46 const result = yield* Sfn.simulate(
47 makeOrderProgram(doubler),
48 { value: 2, items: [] } satisfies OrderInput,
49 { handlers: doublerHandlers },
50 );
51 expect(result.size).toBe("small");
52 expect(result.items).toEqual([]);
53 }),
54 );
55
56 it.effect("uncaught Sfn.fail surfaces as the typed failure", () =>
57 Effect.gen(function* () {
58 const result = yield* Effect.result(
59 Sfn.simulate(Sfn.fail(new OrderRejected({ reason: "nope" })), {}),
60 );
61 expect(Result.isFailure(result)).toBe(true);
62 if (Result.isFailure(result) && !(result.failure instanceof Sfn.SimulateError)) {
63 expect(result.failure._tag).toBe("OrderRejected");
64 expect(result.failure.reason).toBe("nope");
65 }
66 }),
67 );
68
69 it.effect("catchTag ignores non-matching tags", () =>
70 Effect.gen(function* () {
71 const program = Sfn.fail(new OrderRejected({ reason: "nope" })).pipe(
72 Sfn.catchTag("SomethingElse", () => Sfn.succeed("recovered")),
73 );
74 const result = yield* Effect.result(Sfn.simulate(program, {}));
75 expect(Result.isFailure(result)).toBe(true);
76 }),
77 );
78
79 it.effect("retry re-runs matching tags up to maxAttempts", () =>
80 Effect.gen(function* () {
81 class Transient extends Data.TaggedError("Transient")<{}> {}
82 let calls = 0;
83 const program = Sfn.invoke<{ ok: boolean }, Transient>(doubler).pipe(
84 Sfn.retry({ while: "Transient", maxAttempts: 5 }),
85 );
86 const result = yield* Sfn.simulate(program, null, {
87 handlers: {
88 SfnDoubler: () =>
89 Effect.suspend(() => {
90 calls++;
91 return calls < 3 ? Effect.fail(new Transient()) : Effect.succeed({ ok: true });
92 }),
93 },
94 });
95 expect(result).toEqual({ ok: true });
96 expect(calls).toBe(3);
97 }),
98 );
99
100 it.effect("retry does not retry non-matching tags", () =>
101 Effect.gen(function* () {
102 let calls = 0;
103 const program = Sfn.invoke(doubler).pipe(Sfn.retry({ while: "Transient", maxAttempts: 5 }));
104 const result = yield* Effect.result(
105 Sfn.simulate(program, null, {
106 handlers: {
107 SfnDoubler: () =>
108 Effect.suspend(() => {
109 calls++;
110 return Effect.fail(new OrderRejected({ reason: "permanent" }));
111 }),
112 },
113 }),
114 );
115 expect(Result.isFailure(result)).toBe(true);
116 expect(calls).toBe(1);
117 }),
118 );
119
120 it.effect("match dispatches on literal cases with a fallback", () =>
121 Effect.gen(function* () {
122 const program = Sfn.gen(function* (input: Sfn.Expr<{ kind: string }>) {
123 return yield* Sfn.match(
124 input.kind,
125 { a: Sfn.succeed(1), b: Sfn.succeed(2) },
126 Sfn.succeed(0),
127 );
128 });
129 expect(yield* Sfn.simulate(program, { kind: "b" })).toBe(2);
130 expect(yield* Sfn.simulate(program, { kind: "z" })).toBe(0);
131 }),
132 );
133
134 it.effect("all runs branches and returns the tuple", () =>
135 Effect.gen(function* () {
136 const program = Sfn.all([
137 Sfn.succeed("left"),
138 Sfn.invoke<{ doubled: number }>(doubler, { value: 4 }),
139 ]);
140 const result = yield* Sfn.simulate(program, null, { handlers: doublerHandlers });
141 expect(result).toEqual(["left", { doubled: 8 }]);
142 }),
143 );
144
145 it.effect("waitForTaskToken dispatches to the integration handler", () =>
146 Effect.gen(function* () {
147 const program = Sfn.waitForTaskToken<{ approved: boolean }>({
148 resource: "arn:aws:states:::sqs:sendMessage",
149 arguments: { MessageBody: { token: Sfn.taskToken } },
150 });
151 const result = yield* Sfn.simulate(program, null, {
152 taskToken: "tok-123",
153 handlers: {
154 "arn:aws:states:::sqs:sendMessage.waitForTaskToken": (payload) =>
155 Effect.succeed({
156 approved:
157 (payload as { MessageBody: { token: string } }).MessageBody.token === "tok-123",
158 }),
159 },
160 });
161 expect(result).toEqual({ approved: true });
162 }),
163 );
164
165 it.effect("missing handler fails with SimulateError", () =>
166 Effect.gen(function* () {
167 const result = yield* Effect.result(Sfn.simulate(Sfn.invoke(doubler), null));
168 expect(Result.isFailure(result)).toBe(true);
169 if (Result.isFailure(result)) {
170 expect(result.failure._tag).toBe("SimulateError");
171 }
172 }),
173 );
174 },
175 );
176
177 describe(
178 "Sfn.compileProgram",
179 { tags: ["unit", "provider:aws", "provider:aws:stepfunctions", "local"] },
180 () => {
181 it("compiles deterministically (drift-stable definitions)", () => {
182 const first = Sfn.compileProgram(makeOrderProgram(doubler));
183 const second = Sfn.compileProgram(makeOrderProgram(doubler));
184 expect(JSON.stringify(first.definition)).toBe(JSON.stringify(second.definition));
185 expect(first.definition.QueryLanguage).toBe("JSONata");
186 expect(typeof first.definition.StartAt).toBe("string");
187 // one lambda:InvokeFunction statement per invoked function (deduped)
188 expect(first.policyStatements).toHaveLength(1);
189 });
190
191 it("rejects unreachable steps after an unconditional Sfn.fail", () => {
192 const program = Sfn.gen(function* () {
193 yield* Sfn.fail(new OrderRejected({ reason: "always" }));
194 yield* Sfn.succeed("unreachable");
195 return null;
196 });
197 expect(() => Sfn.compileProgram(program)).toThrow(/unreachable steps/);
198 });
199
200 it("rejects yielding a non-Sfn value at compile time", () => {
201 const program = Sfn.gen(function* () {
202 // a real Effect is a compile-time type error; simulate the runtime
203 // guard with a plain value smuggled past the types
204 yield* Effect.succeed(1) as unknown as Sfn.SfnEffect<number>;
205 return null;
206 });
207 expect(() => Sfn.compileProgram(program)).toThrow(/may only yield Sfn effects/);
208 });
209 },
210 );