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

main
ts 239 lines 8.89 KB
Raw
1 import * as IAM from "@alchemy.run/aws/IAM";
2 import * as Lambda from "@alchemy.run/aws/Lambda";
3 import * as MWAAServerless from "@alchemy.run/aws/MWAAServerless";
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 Stream from "effect/Stream";
10 import path from "pathe";
11
12 const main = path.resolve(import.meta.dirname, "handler.ts");
13
14 // A well-formed-but-nonexistent run id. Probes must answer with a typed
15 // service error (ResourceNotFoundException or ValidationException), which
16 // proves the IAM grant passed authorization AND the workflow ARN was
17 // injected from the binding.
18 const FAKE_RUN_ID = "00000000-0000-4000-8000-000000000000";
19
20 /** Deterministic names shared with the test for out-of-band verification. */
21 export const BINDINGS_WORKFLOW_NAME = "alchemy-test-mwaas-bind";
22 export const BINDINGS_ROLE_NAME = "alchemy-test-mwaas-bind-role";
23 // S3 bucket names are globally unique — keep a stable random-ish suffix.
24 export const BINDINGS_BUCKET_NAME = "alchemy-test-mwaas-bind-defs-8k2f";
25 export const DEFINITION_KEY = "workflows/bindings.yaml";
26
27 /**
28 * The checked-in workflow definition the test uploads to S3 before the
29 * fixture deploys: a single S3ListOperator task listing the definitions
30 * bucket, schedule `null` so runs are on-demand only.
31 */
32 export const WORKFLOW_DEFINITION = [
33 "alchemy-mwaa-serverless-bindings-test:",
34 " default_args:",
35 " owner: alchemy",
36 " schedule: null",
37 " tasks:",
38 " list_definitions:",
39 " operator: airflow.providers.amazon.aws.operators.s3.S3ListOperator",
40 ` bucket: ${BINDINGS_BUCKET_NAME}`,
41 " prefix: workflows/",
42 "",
43 ].join("\n");
44
45 export class MwaaServerlessTestFunction extends Lambda.Function<Lambda.Function>()(
46 "MwaaServerlessTestFunction",
47 ) {}
48
49 export default MwaaServerlessTestFunction.make(
50 {
51 main,
52 functionUrl: true,
53 timeout: Duration.seconds(30),
54 },
55 Effect.gen(function* () {
56 // The execution role the workflow's tasks assume — read access to the
57 // definitions bucket so the single S3ListOperator task can succeed.
58 const role = yield* IAM.Role("WorkflowRole", {
59 roleName: BINDINGS_ROLE_NAME,
60 assumeRolePolicyDocument: {
61 Version: "2012-10-17",
62 Statement: [
63 {
64 Effect: "Allow",
65 Principal: { Service: "airflow-serverless.amazonaws.com" },
66 Action: ["sts:AssumeRole"],
67 },
68 ],
69 },
70 inlinePolicies: {
71 definitions: {
72 Version: "2012-10-17",
73 Statement: [
74 {
75 Effect: "Allow",
76 Action: ["s3:GetObject*", "s3:GetBucket*", "s3:List*"],
77 Resource: [
78 `arn:aws:s3:::${BINDINGS_BUCKET_NAME}`,
79 `arn:aws:s3:::${BINDINGS_BUCKET_NAME}/*`,
80 ],
81 },
82 ],
83 },
84 },
85 });
86
87 // The workflow the bindings are bound to. The definition object is
88 // uploaded out-of-band by the test BEFORE this fixture deploys.
89 const workflow = yield* MWAAServerless.Workflow("BindingWorkflow", {
90 name: BINDINGS_WORKFLOW_NAME,
91 definitionS3Location: {
92 bucket: BINDINGS_BUCKET_NAME,
93 objectKey: DEFINITION_KEY,
94 },
95 roleArn: role.roleArn,
96 description: "alchemy mwaa-serverless bindings fixture",
97 tags: { purpose: "alchemy-test" },
98 });
99
100 // Event source: subscribe the host to workflow-run state changes. The
101 // deploy proves the EventBridge rule + invoke permission.
102 yield* MWAAServerless.consumeWorkflowRunEvents(
103 { runStates: ["Succeeded", "Failed", "Stopped"] },
104 (events) =>
105 Stream.runForEach(events, (event) =>
106 Effect.log(`mwaa-serverless run ${event.detail.runId} -> ${event["detail-type"]}`),
107 ),
108 );
109
110 const startWorkflowRun = yield* MWAAServerless.StartWorkflowRun(workflow);
111 const getWorkflowRun = yield* MWAAServerless.GetWorkflowRun(workflow);
112 const stopWorkflowRun = yield* MWAAServerless.StopWorkflowRun(workflow);
113 const listWorkflowRuns = yield* MWAAServerless.ListWorkflowRuns(workflow);
114 const getTaskInstance = yield* MWAAServerless.GetTaskInstance(workflow);
115 const listTaskInstances = yield* MWAAServerless.ListTaskInstances(workflow);
116 const listWorkflowVersions = yield* MWAAServerless.ListWorkflowVersions(workflow);
117
118 const bound = {
119 startWorkflowRun,
120 getWorkflowRun,
121 stopWorkflowRun,
122 listWorkflowRuns,
123 getTaskInstance,
124 listTaskInstances,
125 listWorkflowVersions,
126 };
127
128 // Run an operation and answer with its typed outcome: `ok` on success,
129 // the error's `_tag` otherwise. Probes assert the tag — a typed service
130 // error (not AccessDeniedException) proves the IAM grant and the
131 // injected workflow ARN both work.
132 const probe = <A, E extends { _tag: string }>(effect: Effect.Effect<A, E>) =>
133 effect.pipe(
134 Effect.map(() => ({ tag: "ok", detail: "" }) as const),
135 Effect.catch((error) =>
136 Effect.succeed({ tag: error._tag, detail: String(error) } as const),
137 ),
138 Effect.flatMap((outcome) => HttpServerResponse.json(outcome)),
139 );
140
141 return {
142 fetch: Effect.gen(function* () {
143 const request = yield* HttpServerRequest;
144 const url = new URL(request.originalUrl);
145 const pathname = url.pathname;
146
147 if (request.method === "GET" && pathname === "/bindings") {
148 return yield* HttpServerResponse.json({ bound: Object.keys(bound) });
149 }
150
151 // Real reads: workflow ARN injected from the binding.
152 if (request.method === "GET" && pathname === "/runs") {
153 const { WorkflowRuns } = yield* listWorkflowRuns().pipe(Effect.orDie);
154 return yield* HttpServerResponse.json({
155 ids: (WorkflowRuns ?? []).map((run) => run.RunId),
156 });
157 }
158 if (request.method === "GET" && pathname === "/versions") {
159 const { WorkflowVersions } = yield* listWorkflowVersions().pipe(Effect.orDie);
160 return yield* HttpServerResponse.json({
161 versions: (WorkflowVersions ?? []).map((v) => v.WorkflowVersion),
162 });
163 }
164
165 // Typed not-found probes on a nonexistent run.
166 if (request.method === "GET" && pathname === "/run-fake") {
167 return yield* probe(getWorkflowRun({ RunId: FAKE_RUN_ID }));
168 }
169 if (request.method === "GET" && pathname === "/tasks-fake") {
170 return yield* probe(listTaskInstances({ RunId: FAKE_RUN_ID }));
171 }
172 if (request.method === "GET" && pathname === "/task-fake") {
173 return yield* probe(
174 getTaskInstance({
175 RunId: FAKE_RUN_ID,
176 TaskInstanceId: FAKE_RUN_ID,
177 }),
178 );
179 }
180 if (request.method === "POST" && pathname === "/run-stop-fake") {
181 return yield* probe(stopWorkflowRun({ RunId: FAKE_RUN_ID }));
182 }
183
184 // Real run round trip: start an on-demand run; the test observes it
185 // and stops it immediately after.
186 if (request.method === "POST" && pathname === "/run-start") {
187 const started = yield* startWorkflowRun().pipe(Effect.orDie);
188 return yield* HttpServerResponse.json({
189 runId: started.RunId,
190 status: started.Status,
191 });
192 }
193 if (request.method === "GET" && pathname === "/run-detail") {
194 const id = url.searchParams.get("id");
195 if (!id) {
196 return yield* HttpServerResponse.json(
197 { error: "id query parameter required" },
198 { status: 400 },
199 );
200 }
201 const run = yield* getWorkflowRun({ RunId: id }).pipe(Effect.orDie);
202 return yield* HttpServerResponse.json({
203 runId: run.RunId,
204 status: run.RunDetail?.RunState,
205 runType: run.RunType,
206 });
207 }
208 if (request.method === "POST" && pathname === "/run-stop") {
209 const id = url.searchParams.get("id");
210 if (!id) {
211 return yield* HttpServerResponse.json(
212 { error: "id query parameter required" },
213 { status: 400 },
214 );
215 }
216 return yield* probe(stopWorkflowRun({ RunId: id }));
217 }
218
219 return yield* HttpServerResponse.json(
220 { error: "Not found", method: request.method, pathname },
221 { status: 404 },
222 );
223 }).pipe(Effect.orDie),
224 };
225 }).pipe(
226 Effect.provide(
227 Layer.mergeAll(
228 Lambda.EventSource,
229 MWAAServerless.StartWorkflowRunHttp,
230 MWAAServerless.GetWorkflowRunHttp,
231 MWAAServerless.StopWorkflowRunHttp,
232 MWAAServerless.ListWorkflowRunsHttp,
233 MWAAServerless.GetTaskInstanceHttp,
234 MWAAServerless.ListTaskInstancesHttp,
235 MWAAServerless.ListWorkflowVersionsHttp,
236 ),
237 ),
238 ),
239 );