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

main
ts 359 lines 14.2 KB
Raw
1 import { fileURLToPath } from "node:url";
2 import * as AWS from "@alchemy.run/aws";
3 import { flociServices } from "@alchemy.run/aws/Local/FlociServices";
4 import { expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as DynamoDB from "@distilled.cloud/aws/dynamodb";
7 import * as S3 from "@distilled.cloud/aws/s3";
8 import * as SQS from "@distilled.cloud/aws/sqs";
9 import * as SSM from "@distilled.cloud/aws/ssm";
10 import * as Alchemy from "alchemy";
11 /**
12 * Actions under `alchemy dev`: the common shapes a deploy-time binding client
13 * takes, each proven to land on the floci emulator rather than the real
14 * cloud.
15 *
16 * In a dev run every dualized resource resolves to its LOCAL provider, so the
17 * physical resource exists only on the emulator. An Action body runs at
18 * deploy time in the plan process — whose ambient AWS environment is the
19 * live `testing` profile — so without per-resource routing its binding
20 * clients would miss the emulated resource or mutate the real cloud. #1308
21 * routes each client to the bound resource's registered data plane; this
22 * suite pins that for the shapes users actually write:
23 *
24 * - one Action binding several services (S3 + SQS + DynamoDB) — each
25 * client routed independently;
26 * - an Action's output feeding a downstream resource's props;
27 * - a single-resource binding on a hand-written floci dual
28 * (`InvokeFunction(fn)`) — the case that used to be left UNROUTED and
29 * silently hit the real cloud;
30 * - a multi-resource binding spanning a `flociDual` and a hand-written
31 * dual (`RunTask(cluster, task)`) — the reported "mixed data planes"
32 * failure;
33 * - a binding that genuinely spans modes (`Alchemy.remote()` on one side)
34 * fails at bind time with a per-resource explanation.
35 *
36 * Out-of-band checks use the distilled SDK under `flociServices()` (the
37 * emulator) and, where it matters, the ambient live environment (to prove
38 * absence). Requires Docker (floci runs as a container).
39 */
40 import { Action } from "alchemy/Action";
41 import * as Cause from "effect/Cause";
42 import * as Effect from "effect/Effect";
43 import * as Exit from "effect/Exit";
44 import * as Layer from "effect/Layer";
45 import * as Redacted from "effect/Redacted";
46 import * as Stream from "effect/Stream";
47 import { liveContext } from "./fixtures/live.ts";
48
49 const { test } = Test.make({ providers: AWS.providers(), dev: true });
50
51 const echoHandlerPath = fileURLToPath(new URL("./fixtures/actions/echo.mjs", import.meta.url));
52
53 /** The emulator runs task containers on THIS machine. */
54 const hostRuntimePlatform = {
55 cpuArchitecture: process.arch === "arm64" ? ("ARM64" as const) : ("X86_64" as const),
56 operatingSystemFamily: "LINUX" as const,
57 };
58
59 /** Collect a streaming SDK body into its decoded text. */
60 const readBody = (body: Stream.Stream<Uint8Array, Error>) =>
61 Stream.runCollect(body).pipe(
62 Effect.map((chunks) => new TextDecoder().decode(Buffer.concat([...chunks]))),
63 );
64
65 test.provider(
66 "one Action binding S3, SQS and DynamoDB routes every client to the emulator",
67 (stack) =>
68 Effect.gen(function* () {
69 yield* stack.destroy();
70
71 const outputs = yield* stack.deploy(
72 Effect.gen(function* () {
73 const bucket = yield* AWS.S3.Bucket("ActionsBucket", {
74 forceDestroy: true,
75 });
76 const queue = yield* AWS.SQS.Queue("ActionsQueue");
77 const table = yield* AWS.DynamoDB.Table("ActionsTable", {
78 partitionKey: "id",
79 attributes: { id: "S" },
80 });
81
82 // A realistic "ingest" Action: write the object, record it, and
83 // enqueue its key — three services behind one body.
84 const Ingest = Action(
85 "Ingest",
86 Effect.gen(function* () {
87 const putObject = yield* AWS.S3.PutObject(bucket);
88 const getObject = yield* AWS.S3.GetObject(bucket);
89 const sendMessage = yield* AWS.SQS.SendMessage(queue);
90 const putItem = yield* AWS.DynamoDB.PutItem(table);
91 return Effect.fn(function* (input: { key: string }) {
92 yield* putObject({ Key: input.key, Body: "ingested" });
93 const object = yield* getObject({ Key: input.key });
94 const body = yield* readBody(object.Body!);
95 yield* putItem({
96 Item: { id: { S: input.key }, body: { S: body } },
97 });
98 const sent = yield* sendMessage({ MessageBody: input.key });
99 return { body, messageId: sent.MessageId };
100 });
101 }).pipe(
102 Effect.provide(
103 Layer.mergeAll(
104 AWS.S3.PutObjectHttp,
105 AWS.S3.GetObjectHttp,
106 AWS.SQS.SendMessageHttp,
107 AWS.DynamoDB.PutItemHttp,
108 ),
109 ),
110 ),
111 );
112 const ingested = yield* Ingest({ key: "uploads/hello.txt" });
113 return {
114 bucketName: bucket.bucketName,
115 queueUrl: queue.queueUrl,
116 tableName: table.tableName,
117 ingested,
118 };
119 }),
120 );
121
122 // The Action read back what it wrote — through the emulator.
123 expect(outputs.ingested.body).toBe("ingested");
124 expect(outputs.ingested.messageId).toBeTruthy();
125
126 // Every side effect landed on the emulator…
127 const head = yield* S3.headObject({
128 Bucket: outputs.bucketName,
129 Key: "uploads/hello.txt",
130 }).pipe(Effect.provide(flociServices()));
131 expect(head.ContentLength).toBe("ingested".length);
132
133 const item = yield* DynamoDB.getItem({
134 TableName: outputs.tableName,
135 Key: { id: { S: "uploads/hello.txt" } },
136 }).pipe(Effect.provide(flociServices()));
137 expect(item.Item?.body).toEqual({ S: "ingested" });
138
139 const received = yield* SQS.receiveMessage({
140 QueueUrl: outputs.queueUrl,
141 MaxNumberOfMessages: 1,
142 WaitTimeSeconds: 5,
143 }).pipe(Effect.provide(flociServices()));
144 expect(received.Messages?.[0]?.Body).toBe("uploads/hello.txt");
145
146 // …and the bucket never existed on the real cloud. The ambient
147 // environment in a dev run is the emulator, so the real cloud is
148 // reached EXPLICITLY via the live environment chain.
149 const live = yield* S3.headBucket({ Bucket: outputs.bucketName }).pipe(
150 Effect.map(() => "found" as const),
151 Effect.catchTag("NotFound", () => Effect.succeed("not-found" as const)),
152 Effect.provide(liveContext),
153 );
154 expect(live).toBe("not-found");
155
156 yield* stack.destroy();
157 }),
158 {
159 tags: ["provider:aws", "provider:aws:dynamodb", "provider:aws:s3", "provider:aws:sqs", "live"],
160 timeout: 300_000,
161 },
162 );
163
164 test.provider(
165 "an Action's output feeds a downstream resource",
166 (stack) =>
167 Effect.gen(function* () {
168 yield* stack.destroy();
169
170 const outputs = yield* stack.deploy(
171 Effect.gen(function* () {
172 const source = yield* AWS.SSM.Parameter("ActionsSource", {
173 value: "region-a",
174 });
175 // Read one parameter through its binding, derive a value, and
176 // hand the Action's Output to a second resource's props.
177 const Derive = Action(
178 "Derive",
179 Effect.gen(function* () {
180 const getParameter = yield* AWS.SSM.GetParameter(source);
181 return Effect.fn(function* () {
182 const current = yield* getParameter({ WithDecryption: true });
183 const raw = current.Parameter?.Value;
184 const value = typeof raw === "string" ? raw : Redacted.value(raw!);
185 return { derived: `${value}:derived` };
186 });
187 }).pipe(Effect.provide(AWS.SSM.GetParameterHttp)),
188 );
189 const derived = yield* Derive({});
190 const target = yield* AWS.SSM.Parameter("ActionsTarget", {
191 value: derived.derived,
192 });
193 return { sourceArn: source.parameterArn, target };
194 }),
195 );
196
197 expect(outputs.sourceArn).toContain(":000000000000:");
198 expect(outputs.target.parameterArn).toContain(":000000000000:");
199
200 // The downstream parameter carries the Action-derived value — on the
201 // emulator, where the Action's GetParameter read from.
202 const stored = yield* SSM.getParameter({
203 Name: outputs.target.parameterName,
204 }).pipe(Effect.provide(flociServices()));
205 const value = stored.Parameter?.Value;
206 expect(typeof value === "string" ? value : Redacted.value(value!)).toBe("region-a:derived");
207
208 yield* stack.destroy();
209 }),
210 { tags: ["provider:aws", "provider:aws:ssm", "local"], timeout: 300_000 },
211 );
212
213 test.provider(
214 "InvokeFunction(fn) Action invokes the dev Lambda on the emulator",
215 (stack) =>
216 Effect.gen(function* () {
217 yield* stack.destroy();
218
219 const outputs = yield* stack.deploy(
220 Effect.gen(function* () {
221 const fn = yield* AWS.Lambda.Function("ActionsEcho", {
222 main: echoHandlerPath,
223 handler: "handler",
224 bundle: false,
225 functionUrl: false,
226 });
227 // A single-resource binding on a hand-written floci dual. Before
228 // Lambda.Function declared its data plane this client was left
229 // unrouted and the invoke went to the real cloud.
230 const Ping = Action(
231 "Ping",
232 Effect.gen(function* () {
233 const invoke = yield* AWS.Lambda.InvokeFunction(fn);
234 return Effect.fn(function* (input: { message: string }) {
235 const response = yield* invoke({
236 Payload: new TextEncoder().encode(JSON.stringify(input)),
237 });
238 const result = JSON.parse(yield* readBody(response.Payload!)) as {
239 echoed: { message: string };
240 from: string;
241 };
242 return { statusCode: response.StatusCode, result };
243 });
244 }).pipe(Effect.provide(AWS.Lambda.InvokeFunctionHttp)),
245 );
246 return {
247 functionArn: fn.functionArn,
248 ping: yield* Ping({ message: "hello" }),
249 };
250 }),
251 );
252
253 expect(outputs.functionArn).toContain(":000000000000:");
254 expect(outputs.ping.statusCode).toBe(200);
255 expect(outputs.ping.result.from).toBe("floci-echo");
256 expect(outputs.ping.result.echoed).toEqual({ message: "hello" });
257
258 yield* stack.destroy();
259 }),
260 // First invoke pulls the Lambda runtime image on a cold machine.
261 { tags: ["provider:aws", "provider:aws:lambda", "local"], timeout: 600_000 },
262 );
263
264 test.provider(
265 "RunTask(cluster, task) Action launches the task on the emulator",
266 (stack) =>
267 Effect.gen(function* () {
268 yield* stack.destroy();
269
270 const outputs = yield* stack.deploy(
271 Effect.gen(function* () {
272 const cluster = yield* AWS.ECS.Cluster("ActionsCluster");
273 const task = yield* AWS.ECS.Task("ActionsTask", {
274 image: "busybox:stable",
275 command: ["true"],
276 cpu: 256,
277 memory: 512,
278 requiresCompatibilities: ["EC2"],
279 // awsvpc (the default) needs a network configuration on RunTask,
280 // which the emulator enforces like ECS does; bridge needs none.
281 networkMode: "bridge",
282 runtimePlatform: hostRuntimePlatform,
283 });
284 // A multi-resource binding spanning a `flociDual` (Cluster) and a
285 // hand-written dual (Task). The reported bug: with Task
286 // undeclared this bind died with "mixed data planes".
287 const Launch = Action(
288 "Launch",
289 Effect.gen(function* () {
290 const runTask = yield* AWS.ECS.RunTask(cluster, task);
291 return () =>
292 runTask({ launchType: "EC2", count: 1 }).pipe(
293 Effect.map((response) => ({
294 taskArn: response.tasks?.[0]?.taskArn,
295 failures: response.failures ?? [],
296 })),
297 );
298 }).pipe(Effect.provide(AWS.ECS.RunTaskHttp)),
299 );
300 return {
301 clusterArn: cluster.clusterArn,
302 launched: yield* Launch({}),
303 };
304 }),
305 );
306
307 expect(outputs.clusterArn).toContain(":000000000000:");
308 expect(outputs.launched.failures).toEqual([]);
309 expect(outputs.launched.taskArn).toContain(":000000000000:");
310
311 yield* stack.destroy();
312 }),
313 { tags: ["provider:aws", "provider:aws:ecs", "local"], timeout: 300_000 },
314 );
315
316 test.provider(
317 "a binding spanning a remote() resource and a local one fails at bind with a per-resource explanation",
318 (stack) =>
319 Effect.gen(function* () {
320 yield* stack.destroy();
321
322 const exit = yield* Effect.exit(
323 stack.deploy(
324 Effect.gen(function* () {
325 // Pinned live: its clients belong to the real cloud…
326 const cluster = yield* AWS.ECS.Cluster("MixedCluster").pipe(Alchemy.remote());
327 // …while the task is emulated. One API call cannot span both.
328 const task = yield* AWS.ECS.Task("MixedTask", {
329 image: "busybox:stable",
330 command: ["true"],
331 cpu: 256,
332 memory: 512,
333 requiresCompatibilities: ["EC2"],
334 runtimePlatform: hostRuntimePlatform,
335 });
336 const Launch = Action(
337 "MixedLaunch",
338 Effect.gen(function* () {
339 const runTask = yield* AWS.ECS.RunTask(cluster, task);
340 return () => runTask({ launchType: "EC2", count: 1 });
341 }).pipe(Effect.provide(AWS.ECS.RunTaskHttp)),
342 );
343 return { launched: yield* Launch({}) };
344 }),
345 ),
346 );
347
348 expect(Exit.isFailure(exit)).toBe(true);
349 const message = Exit.isFailure(exit) ? Cause.pretty(exit.cause) : "";
350 // Each resource is named with WHERE it lands and WHY — never the old
351 // "(some local, some live)" that hid which one and for what reason.
352 expect(message).toContain("Binding client spans mixed data planes");
353 expect(message).toContain("MixedCluster → real cloud (live mode)");
354 expect(message).toContain("MixedTask → local emulator");
355
356 yield* stack.destroy();
357 }),
358 { tags: ["provider:aws", "provider:aws:ecs", "live"], timeout: 300_000 },
359 );