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

main
ts 242 lines 8.12 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import type { PolicyStatement } from "@alchemy.run/aws/IAM";
3 import * as Context from "effect/Context";
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
11 // Deterministic names shared by the fixture and the test (the test seeds the
12 // source prefix out-of-band and filters flow events by name).
13 export const FLOW_BUCKET = "alchemy-test-appflow-bindings";
14 export const FLOW_NAME = "alchemy-test-appflow-bindings-flow";
15 const BUCKET_ARN = `arn:aws:s3:::${FLOW_BUCKET}`;
16
17 // AppFlow's S3 connector requires the bucket policy to authorize the service
18 // principal for reads (source) and writes (destination).
19 const appflowBucketPolicy: PolicyStatement[] = [
20 {
21 Effect: "Allow",
22 Principal: { Service: "appflow.amazonaws.com" },
23 Action: ["s3:GetObject", "s3:ListBucket"],
24 Resource: [BUCKET_ARN, `${BUCKET_ARN}/*`],
25 },
26 {
27 Effect: "Allow",
28 Principal: { Service: "appflow.amazonaws.com" },
29 Action: [
30 "s3:PutObject",
31 "s3:AbortMultipartUpload",
32 "s3:ListMultipartUploadParts",
33 "s3:ListBucketMultipartUploads",
34 "s3:GetBucketAcl",
35 "s3:PutObjectAcl",
36 ],
37 Resource: [BUCKET_ARN, `${BUCKET_ARN}/*`],
38 },
39 ];
40
41 /**
42 * The flow's source/destination bucket, exported on its own so the test can
43 * deploy it FIRST and seed `input/` before the flow is created — AppFlow
44 * validates the source prefix is non-empty at `CreateFlow` time.
45 */
46 export const FlowBucket = Effect.gen(function* () {
47 return yield* AWS.S3.Bucket("FlowBucket", {
48 bucketName: FLOW_BUCKET,
49 forceDestroy: true,
50 policy: appflowBucketPolicy,
51 });
52 });
53
54 export class AppFlowApiFunction extends AWS.Lambda.Function<AWS.Lambda.Function>()(
55 "AppFlowApiFunction",
56 ) {}
57
58 /**
59 * Shared infrastructure for the AppFlow bindings fixture:
60 * - the S3-to-S3 on-demand flow the bindings are exercised against
61 * - an SQS sink queue where the `flowEvents` consume loop forwards AppFlow
62 * run reports so the test can observe them out-of-band.
63 */
64 export class FlowFixture extends Context.Service<
65 FlowFixture,
66 {
67 bucket: AWS.S3.Bucket;
68 flow: AWS.AppFlow.Flow;
69 eventsQueue: AWS.SQS.Queue;
70 }
71 >()("AppFlowFlowFixture") {}
72
73 export const FlowFixtureLive = Layer.effect(
74 FlowFixture,
75 Effect.gen(function* () {
76 const bucket = yield* FlowBucket;
77 const flow = yield* AWS.AppFlow.Flow("BindingsFlow", {
78 flowName: FLOW_NAME,
79 triggerConfig: { triggerType: "OnDemand" },
80 sourceFlowConfig: {
81 connectorType: "S3",
82 sourceConnectorProperties: {
83 S3: { bucketName: bucket.bucketName, bucketPrefix: "input" },
84 },
85 },
86 destinationFlowConfigList: [
87 {
88 connectorType: "S3",
89 destinationConnectorProperties: {
90 S3: { bucketName: bucket.bucketName, bucketPrefix: "output" },
91 },
92 },
93 ],
94 tasks: [
95 {
96 taskType: "Map_all",
97 sourceFields: [],
98 connectorOperator: { S3: "NO_OP" },
99 taskProperties: {},
100 },
101 ],
102 });
103 const eventsQueue = yield* AWS.SQS.Queue("FlowEventsSink");
104 return { bucket, flow, eventsQueue };
105 }),
106 );
107
108 export const AppFlowApiFunctionLive = AppFlowApiFunction.make(
109 {
110 main: import.meta.url,
111 functionUrl: true,
112 timeout: Duration.seconds(30),
113 },
114 Effect.gen(function* () {
115 const { flow, eventsQueue } = yield* FlowFixture;
116
117 const startFlow = yield* AWS.AppFlow.StartFlow(flow);
118 const stopFlow = yield* AWS.AppFlow.StopFlow(flow);
119 const cancelFlowExecutions = yield* AWS.AppFlow.CancelFlowExecutions(flow);
120 const describeFlowExecutionRecords = yield* AWS.AppFlow.DescribeFlowExecutionRecords(flow);
121 const eventsSink = yield* AWS.SQS.QueueSink(eventsQueue);
122 const flowEventPattern = AWS.AppFlow.flowEvents({
123 flowNames: [FLOW_NAME],
124 });
125
126 // Forward this flow's AppFlow run reports into the sink queue so the test
127 // can observe them out-of-band via `sqs.receiveMessage`. Native AppFlow
128 // reports use the reserved `aws.appflow` source and are best-effort. Keep
129 // that production pattern and add a custom source solely so the test can
130 // publish a deterministic readiness/report probe through PutEvents.
131 yield* AWS.EventBridge.consumeBusEvents(
132 {
133 ...flowEventPattern,
134 source: [...flowEventPattern.source, "alchemy.test.appflow"],
135 },
136 (events: Stream.Stream<AWS.EventBridge.EventRecord>) =>
137 events.pipe(
138 Stream.map((event) => ({
139 MessageBody: JSON.stringify({
140 detailType: event["detail-type"],
141 detail: event.detail,
142 }),
143 })),
144 Stream.run(eventsSink),
145 Effect.orDie,
146 ),
147 );
148
149 return {
150 fetch: Effect.gen(function* () {
151 const request = yield* HttpServerRequest;
152 const url = new URL(request.originalUrl);
153 const pathname = url.pathname;
154
155 if (request.method === "GET" && pathname === "/ready") {
156 return yield* HttpServerResponse.json({ ok: true });
157 }
158
159 if (request.method === "POST" && pathname === "/start") {
160 const result = yield* startFlow();
161 return yield* HttpServerResponse.json({
162 executionId: result.executionId,
163 flowStatus: result.flowStatus,
164 flowArn: result.flowArn,
165 });
166 }
167
168 // OnDemand flows cannot be stopped; AppFlow answers with a typed
169 // UnsupportedOperationException — surfaced as `{ ok: false, error }`
170 // so the test can assert the exact tag.
171 if (request.method === "POST" && pathname === "/stop") {
172 const response = yield* stopFlow().pipe(
173 Effect.match({
174 onFailure: (error) => ({
175 ok: false as const,
176 error: error._tag,
177 }),
178 onSuccess: (value) => ({ ok: true as const, value }),
179 }),
180 );
181 return yield* HttpServerResponse.json(response);
182 }
183
184 if (request.method === "POST" && pathname === "/cancel") {
185 const body = (yield* request.json) as {
186 executionIds?: string[];
187 };
188 const response = yield* cancelFlowExecutions({
189 executionIds: body.executionIds,
190 }).pipe(
191 Effect.match({
192 onFailure: (error) => ({
193 ok: false as const,
194 error: error._tag,
195 }),
196 onSuccess: (value) => ({
197 ok: true as const,
198 invalidExecutions: value.invalidExecutions ?? [],
199 }),
200 }),
201 );
202 return yield* HttpServerResponse.json(response);
203 }
204
205 if (request.method === "GET" && pathname === "/executions") {
206 const result = yield* describeFlowExecutionRecords();
207 return yield* HttpServerResponse.json({
208 flowExecutions: (result.flowExecutions ?? []).map((record) => ({
209 executionId: record.executionId,
210 executionStatus: record.executionStatus,
211 })),
212 });
213 }
214
215 return yield* HttpServerResponse.json(
216 { error: "Not found", method: request.method, pathname },
217 { status: 404 },
218 );
219 }).pipe(Effect.orDie),
220 };
221 }).pipe(
222 Effect.provide(
223 Layer.provideMerge(
224 Layer.mergeAll(
225 AWS.Lambda.EventSource,
226 AWS.AppFlow.StartFlowHttp,
227 AWS.AppFlow.StopFlowHttp,
228 AWS.AppFlow.CancelFlowExecutionsHttp,
229 AWS.AppFlow.DescribeFlowExecutionRecordsHttp,
230 AWS.SQS.QueueSinkHttp,
231 FlowFixtureLive,
232 ),
233 Layer.mergeAll(AWS.SQS.SendMessageBatchHttp),
234 ),
235 ),
236 ),
237 // Re-merge so the deploying test can `yield* FlowFixture` and expose the
238 // flow name / queue url as deploy outputs. Reusing the same reference keeps
239 // it a single shared flow/queue.
240 ).pipe(Layer.provideMerge(FlowFixtureLive));
241
242 export default AppFlowApiFunctionLive;