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

main
ts 489 lines 18.3 KB
Raw
1 import * as Lambda from "@alchemy.run/aws/Lambda";
2 import * as SQS from "@alchemy.run/aws/SQS";
3 import * as StepFunctions from "@alchemy.run/aws/StepFunctions";
4 import * as Duration from "effect/Duration";
5 import * as Effect from "effect/Effect";
6 import { HttpServerRequest } from "effect/http/HttpServerRequest";
7 import * as HttpServerResponse from "effect/http/HttpServerResponse";
8 import * as Layer from "effect/Layer";
9 import * as Redacted from "effect/Redacted";
10 import * as Stream from "effect/Stream";
11 import path from "pathe";
12
13 const main = path.resolve(import.meta.dirname, "handler.ts");
14
15 const plain = (value: string | Redacted.Redacted<string> | undefined): string | undefined =>
16 value === undefined ? undefined : typeof value === "string" ? value : Redacted.value(value);
17
18 export class SFNTestFunction extends Lambda.Function<Lambda.Function>()("SFNTestFunction") {}
19
20 export default SFNTestFunction.make(
21 {
22 main,
23 functionUrl: true,
24 // routes long-poll SQS/GetActivityTask (up to 60s when no task is
25 // scheduled) and round-trip whole workflows — AWS's 3s default
26 // intermittently times out under cold starts
27 timeout: Duration.seconds(75),
28 },
29 Effect.gen(function* () {
30 // EXPRESS workflow for synchronous invocation
31 const express = yield* StepFunctions.StateMachine("TestExpressMachine", {
32 type: "EXPRESS",
33 definition: {
34 StartAt: "Echo",
35 States: {
36 Echo: {
37 Type: "Pass",
38 Parameters: { "echo.$": "$", greeting: "hello" },
39 End: true,
40 },
41 },
42 },
43 });
44
45 // STANDARD workflow for async start + describe polling
46 const standard = yield* StepFunctions.StateMachine("TestStandardMachine", {
47 definition: {
48 StartAt: "Done",
49 States: {
50 Done: { Type: "Pass", Result: { done: true }, End: true },
51 },
52 },
53 });
54
55 // Callback-pattern workflow: parks on .waitForTaskToken after sending
56 // the task token to an SQS queue.
57 const callbackQueue = yield* SQS.Queue("CallbackQueue");
58 const callback = yield* StepFunctions.StateMachine("TestCallbackMachine", {
59 definition: {
60 StartAt: "WaitForCallback",
61 States: {
62 WaitForCallback: {
63 Type: "Task",
64 Resource: "arn:aws:states:::sqs:sendMessage.waitForTaskToken",
65 Parameters: {
66 QueueUrl: callbackQueue.queueUrl,
67 MessageBody: {
68 "token.$": "$$.Task.Token",
69 "executionArn.$": "$$.Execution.Id",
70 },
71 },
72 TimeoutSeconds: 300,
73 End: true,
74 },
75 },
76 },
77 policyStatements: [
78 {
79 Effect: "Allow",
80 Action: ["sqs:SendMessage"],
81 Resource: [callbackQueue.queueArn],
82 },
83 ],
84 });
85
86 // Activity-worker workflow: a Task state that parks on an Activity ARN
87 // until a worker polls it with GetActivityTask and completes it.
88 const activity = yield* StepFunctions.Activity("PollActivity", {});
89 const activityMachine = yield* StepFunctions.StateMachine("TestActivityMachine", {
90 definition: {
91 StartAt: "WaitForWorker",
92 States: {
93 WaitForWorker: {
94 Type: "Task",
95 Resource: activity.activityArn,
96 TimeoutSeconds: 300,
97 End: true,
98 },
99 },
100 },
101 });
102
103 // Distributed Map workflow: produces a Map Run per execution for the
104 // ListMapRuns/DescribeMapRun/UpdateMapRun bindings.
105 const mapMachine = yield* StepFunctions.StateMachine("TestMapMachine", {
106 definition: {
107 StartAt: "MapItems",
108 States: {
109 MapItems: {
110 Type: "Map",
111 ItemsPath: "$.items",
112 MaxConcurrency: 1,
113 ItemProcessor: {
114 ProcessorConfig: {
115 Mode: "DISTRIBUTED",
116 ExecutionType: "EXPRESS",
117 },
118 StartAt: "PassItem",
119 States: { PassItem: { Type: "Pass", End: true } },
120 },
121 End: true,
122 },
123 },
124 },
125 // A Distributed Map's execution role starts (and observes) child
126 // EXPRESS executions of the machine itself — self-referential, so
127 // grant service-wide.
128 policyStatements: [
129 {
130 Effect: "Allow",
131 Action: ["states:StartExecution", "states:DescribeExecution", "states:StopExecution"],
132 Resource: ["*"],
133 },
134 ],
135 });
136
137 // Event source: subscribe the host to this machine's execution status
138 // changes. The deploy proves the EventBridge rule + invoke permission
139 // wiring (and that Output-valued ARNs resolve inside the pattern).
140 yield* StepFunctions.consumeExecutionEvents(
141 { stateMachines: [standard], statuses: ["SUCCEEDED", "FAILED"] },
142 (events) =>
143 Stream.runForEach(events, (event) =>
144 Effect.log(`execution ${event.detail.executionArn}: ${event.detail.status}`),
145 ),
146 );
147
148 const startSyncExecution = yield* StepFunctions.StartSyncExecution(express);
149 const startExecution = yield* StepFunctions.StartExecution(standard);
150 const startCallbackExecution = yield* StepFunctions.StartExecution(callback);
151 const describeStandardExecution = yield* StepFunctions.DescribeExecution(standard);
152 const describeCallbackExecution = yield* StepFunctions.DescribeExecution(callback);
153 const stopExecution = yield* StepFunctions.StopExecution(callback);
154 const sendTaskSuccess = yield* StepFunctions.SendTaskSuccess();
155 const sendTaskFailure = yield* StepFunctions.SendTaskFailure();
156 const sendTaskHeartbeat = yield* StepFunctions.SendTaskHeartbeat();
157 const validateDefinition = yield* StepFunctions.ValidateStateMachineDefinition();
158 const testState = yield* StepFunctions.TestState();
159 const receiveMessage = yield* SQS.ReceiveMessage(callbackQueue);
160 const deleteMessage = yield* SQS.DeleteMessage(callbackQueue);
161
162 const startActivityExecution = yield* StepFunctions.StartExecution(activityMachine);
163 const describeActivityExecution = yield* StepFunctions.DescribeExecution(activityMachine);
164 const getActivityTask = yield* StepFunctions.GetActivityTask(activity);
165 const listExecutions = yield* StepFunctions.ListExecutions(standard);
166 const getExecutionHistory = yield* StepFunctions.GetExecutionHistory(standard);
167 const redriveExecution = yield* StepFunctions.RedriveExecution(standard);
168 const startMapExecution = yield* StepFunctions.StartExecution(mapMachine);
169 const describeMapExecution = yield* StepFunctions.DescribeExecution(mapMachine);
170 const listMapRuns = yield* StepFunctions.ListMapRuns(mapMachine);
171 const describeMapRun = yield* StepFunctions.DescribeMapRun(mapMachine);
172 const updateMapRun = yield* StepFunctions.UpdateMapRun(mapMachine);
173
174 return {
175 fetch: Effect.gen(function* () {
176 const request = yield* HttpServerRequest;
177 const url = new URL(request.originalUrl);
178 const pathname = url.pathname;
179
180 if (request.method === "GET" && pathname === "/health") {
181 return HttpServerResponse.text("ok");
182 }
183
184 if (request.method === "POST" && pathname === "/start-sync") {
185 const body = (yield* request.json) as unknown as { input?: string };
186 const result = yield* startSyncExecution({ input: body.input });
187 return yield* HttpServerResponse.json({
188 executionArn: result.executionArn,
189 status: result.status,
190 output: plain(result.output),
191 error: plain(result.error),
192 cause: plain(result.cause),
193 });
194 }
195
196 if (request.method === "POST" && pathname === "/start") {
197 const body = (yield* request.json) as unknown as { input?: string };
198 const result = yield* startExecution({ input: body.input });
199 return yield* HttpServerResponse.json({
200 executionArn: result.executionArn,
201 });
202 }
203
204 if (request.method === "POST" && pathname === "/start-callback") {
205 const result = yield* startCallbackExecution();
206 return yield* HttpServerResponse.json({
207 executionArn: result.executionArn,
208 });
209 }
210
211 if (request.method === "GET" && pathname === "/describe-standard") {
212 const executionArn = url.searchParams.get("executionArn")!;
213 const result = yield* describeStandardExecution({ executionArn });
214 return yield* HttpServerResponse.json({
215 status: result.status,
216 output: plain(result.output),
217 });
218 }
219
220 if (request.method === "GET" && pathname === "/describe-callback") {
221 const executionArn = url.searchParams.get("executionArn")!;
222 const result = yield* describeCallbackExecution({ executionArn });
223 return yield* HttpServerResponse.json({
224 status: result.status,
225 output: plain(result.output),
226 error: plain(result.error),
227 });
228 }
229
230 if (request.method === "GET" && pathname === "/receive-token") {
231 const result = yield* receiveMessage({
232 MaxNumberOfMessages: 1,
233 WaitTimeSeconds: 5,
234 // resurface quickly if a failed invocation consumed the message
235 VisibilityTimeout: 15,
236 });
237 const message = result.Messages?.[0];
238 if (!message?.Body) {
239 return yield* HttpServerResponse.json({ token: null });
240 }
241 yield* deleteMessage({ ReceiptHandle: message.ReceiptHandle! });
242 const parsed = JSON.parse(message.Body) as {
243 token: string;
244 executionArn: string;
245 };
246 return yield* HttpServerResponse.json({
247 token: parsed.token,
248 executionArn: parsed.executionArn,
249 });
250 }
251
252 if (request.method === "POST" && pathname === "/task-success") {
253 const body = (yield* request.json) as unknown as {
254 token: string;
255 output: string;
256 };
257 yield* sendTaskSuccess({
258 taskToken: body.token,
259 output: body.output,
260 });
261 return yield* HttpServerResponse.json({ sent: true });
262 }
263
264 if (request.method === "POST" && pathname === "/task-failure") {
265 const body = (yield* request.json) as unknown as {
266 token: string;
267 error?: string;
268 cause?: string;
269 };
270 yield* sendTaskFailure({
271 taskToken: body.token,
272 error: body.error,
273 cause: body.cause,
274 });
275 return yield* HttpServerResponse.json({ sent: true });
276 }
277
278 if (request.method === "POST" && pathname === "/task-heartbeat") {
279 const body = (yield* request.json) as unknown as { token: string };
280 yield* sendTaskHeartbeat({ taskToken: body.token });
281 return yield* HttpServerResponse.json({ sent: true });
282 }
283
284 if (request.method === "POST" && pathname === "/validate-definition") {
285 const body = (yield* request.json) as unknown as {
286 definition: string;
287 type?: "STANDARD" | "EXPRESS";
288 };
289 const report = yield* validateDefinition({
290 definition: body.definition,
291 type: body.type,
292 severity: "ERROR",
293 });
294 return yield* HttpServerResponse.json({
295 result: report.result,
296 diagnostics: report.diagnostics.map((diagnostic) => ({
297 severity: diagnostic.severity,
298 code: plain(diagnostic.code),
299 message: plain(diagnostic.message),
300 })),
301 });
302 }
303
304 if (request.method === "POST" && pathname === "/test-state") {
305 const body = (yield* request.json) as unknown as {
306 definition: string;
307 input?: string;
308 };
309 const result = yield* testState({
310 definition: body.definition,
311 input: body.input,
312 });
313 return yield* HttpServerResponse.json({
314 status: result.status,
315 output: plain(result.output),
316 error: plain(result.error),
317 });
318 }
319
320 if (request.method === "POST" && pathname === "/stop") {
321 const body = (yield* request.json) as unknown as {
322 executionArn: string;
323 };
324 const result = yield* stopExecution({
325 executionArn: body.executionArn,
326 error: "TestStop",
327 cause: "stopped by integration test",
328 });
329 return yield* HttpServerResponse.json({
330 stopDate: result.stopDate.toISOString(),
331 });
332 }
333
334 if (request.method === "POST" && pathname === "/start-activity") {
335 const result = yield* startActivityExecution();
336 return yield* HttpServerResponse.json({
337 executionArn: result.executionArn,
338 });
339 }
340
341 if (request.method === "GET" && pathname === "/activity-task") {
342 const task = yield* getActivityTask({
343 workerName: "sfn-bindings-test",
344 });
345 return yield* HttpServerResponse.json({
346 taskToken: task.taskToken ?? null,
347 input: plain(task.input) ?? null,
348 });
349 }
350
351 if (request.method === "GET" && pathname === "/describe-activity") {
352 const executionArn = url.searchParams.get("executionArn")!;
353 const result = yield* describeActivityExecution({ executionArn });
354 return yield* HttpServerResponse.json({
355 status: result.status,
356 output: plain(result.output),
357 });
358 }
359
360 if (request.method === "GET" && pathname === "/list-executions") {
361 const statusFilter = url.searchParams.get("status") ?? undefined;
362 const result = yield* listExecutions({
363 statusFilter: statusFilter as "SUCCEEDED" | undefined,
364 });
365 return yield* HttpServerResponse.json({
366 count: result.executions.length,
367 executionArns: result.executions.map((e) => e.executionArn),
368 });
369 }
370
371 if (request.method === "GET" && pathname === "/history") {
372 const executionArn = url.searchParams.get("executionArn")!;
373 const result = yield* getExecutionHistory({
374 executionArn,
375 reverseOrder: true,
376 maxResults: 20,
377 });
378 return yield* HttpServerResponse.json({
379 count: result.events.length,
380 lastType: result.events[0]?.type ?? null,
381 });
382 }
383
384 if (request.method === "POST" && pathname === "/redrive") {
385 const body = (yield* request.json) as unknown as {
386 executionArn: string;
387 };
388 const result = yield* redriveExecution({
389 executionArn: body.executionArn,
390 }).pipe(
391 Effect.map(() => ({ redriven: true as const })),
392 Effect.catchTag("ExecutionNotRedrivable", () =>
393 Effect.succeed({
394 redriven: false as const,
395 error: "ExecutionNotRedrivable",
396 }),
397 ),
398 );
399 return yield* HttpServerResponse.json(result);
400 }
401
402 if (request.method === "POST" && pathname === "/start-map") {
403 const result = yield* startMapExecution({
404 input: JSON.stringify({ items: [1, 2] }),
405 });
406 return yield* HttpServerResponse.json({
407 executionArn: result.executionArn,
408 });
409 }
410
411 if (request.method === "GET" && pathname === "/describe-map") {
412 const executionArn = url.searchParams.get("executionArn")!;
413 const result = yield* describeMapExecution({ executionArn });
414 return yield* HttpServerResponse.json({ status: result.status });
415 }
416
417 if (request.method === "GET" && pathname === "/map-runs") {
418 const executionArn = url.searchParams.get("executionArn")!;
419 const result = yield* listMapRuns({ executionArn });
420 return yield* HttpServerResponse.json({
421 mapRunArns: result.mapRuns.map((run) => run.mapRunArn),
422 });
423 }
424
425 if (request.method === "GET" && pathname === "/describe-map-run") {
426 const mapRunArn = url.searchParams.get("mapRunArn")!;
427 const result = yield* describeMapRun({ mapRunArn });
428 return yield* HttpServerResponse.json({
429 status: result.status,
430 maxConcurrency: result.maxConcurrency,
431 succeeded: result.itemCounts?.succeeded,
432 });
433 }
434
435 if (request.method === "POST" && pathname === "/update-map-run") {
436 const body = (yield* request.json) as unknown as {
437 mapRunArn: string;
438 maxConcurrency?: number;
439 };
440 // UpdateMapRun targets in-progress Map Runs; a completed one
441 // answers with the typed ValidationException — either way the
442 // IAM grant and typed union are exercised.
443 const result = yield* updateMapRun({
444 mapRunArn: body.mapRunArn,
445 maxConcurrency: body.maxConcurrency ?? 2,
446 }).pipe(
447 Effect.map(() => ({ updated: true as const })),
448 Effect.catchTag("ValidationException", () =>
449 Effect.succeed({
450 updated: false as const,
451 error: "ValidationException",
452 }),
453 ),
454 );
455 return yield* HttpServerResponse.json(result);
456 }
457
458 return yield* HttpServerResponse.json(
459 { error: "Not found", method: request.method, pathname },
460 { status: 404 },
461 );
462 }).pipe(Effect.orDie),
463 };
464 }).pipe(
465 Effect.provide(
466 Layer.mergeAll(
467 StepFunctions.StartExecutionHttp,
468 StepFunctions.StartSyncExecutionHttp,
469 StepFunctions.DescribeExecutionHttp,
470 StepFunctions.StopExecutionHttp,
471 StepFunctions.SendTaskSuccessHttp,
472 StepFunctions.SendTaskFailureHttp,
473 StepFunctions.SendTaskHeartbeatHttp,
474 StepFunctions.ValidateStateMachineDefinitionHttp,
475 StepFunctions.TestStateHttp,
476 StepFunctions.GetActivityTaskHttp,
477 StepFunctions.ListExecutionsHttp,
478 StepFunctions.GetExecutionHistoryHttp,
479 StepFunctions.RedriveExecutionHttp,
480 StepFunctions.ListMapRunsHttp,
481 StepFunctions.DescribeMapRunHttp,
482 StepFunctions.UpdateMapRunHttp,
483 Lambda.EventSource,
484 SQS.ReceiveMessageHttp,
485 SQS.DeleteMessageHttp,
486 ),
487 ),
488 ),
489 );