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

main
ts 973 lines 39.3 KB
Raw
1 import { spawnSync } from "node:child_process";
2 /**
3 * Mode-scoped local dev for ECS: `Test.make({ dev: true })` routes the
4 * dualized `ECS.Cluster` / `ECS.Task` (and `ECS.TaskDefinition` /
5 * `ECS.Service`) to the floci emulator, where tasks run as REAL docker
6 * containers.
7 *
8 * Proof structure (mirrors DataPlane.local.test.ts):
9 * - attrs carry the dummy account (`:000000000000:` ARNs) and the
10 * `.localhost:` ECR repository URI — the live cloud can never mint
11 * these;
12 * - persisted state rows are stamped `providerMode: "local"`;
13 * - out-of-band raw HTTP against the emulator gateway runs the deployed
14 * task definition (RunTask) and observes it RUNNING as a real docker
15 * container (`docker ps` shows `floci-ecs-<taskId>-…`);
16 * - the container round-trips HTTP: floci publishes the LITERAL host
17 * port for bridge-mode port mappings (awsvpc tasks are expose-only
18 * when floci itself runs in a container), so the fixture uses
19 * `networkMode: "bridge"` and the test fetches
20 * `http://localhost:<port>` for the marker;
21 * - `stack.destroy()` drains the cluster (the running task is stopped
22 * and its container removed) and deletes the task definition, ECR
23 * repository, log group, and IAM roles — all verified gone.
24 *
25 * Requires Docker (floci runs as a container); skipped when unavailable.
26 */
27 import * as AWS from "@alchemy.run/aws";
28 import { describe, expect } from "@alchemy.run/test";
29 import * as Test from "@alchemy.run/test/Alchemy";
30 import * as Command from "alchemy/Command";
31 import * as Output from "alchemy/Output";
32 import { Stack } from "alchemy/Stack";
33 import { State, type ResourceState } from "alchemy/State";
34 import { initialCwd } from "alchemy/Util/Node";
35 import * as Data from "effect/Data";
36 import * as Effect from "effect/Effect";
37 import * as FileSystem from "effect/FileSystem";
38 import * as HttpClient from "effect/http/HttpClient";
39 import * as Path from "effect/Path";
40 import * as Schedule from "effect/Schedule";
41 import { cloneFixture } from "../../Cloudflare/Utils/Fixture.ts";
42 import EcsDevMainTask from "./fixtures/ecs-dev/main-task.ts";
43 import { rawAwsJson } from "./fixtures/raw.ts";
44
45 const { test } = Test.make({ providers: AWS.providers(), dev: true });
46
47 const contextDir = `${import.meta.dirname}/fixtures/ecs-dev`;
48
49 /** Must match the port baked into fixtures/ecs-dev/Dockerfile. */
50 const CONTEXT_PORT = 17356;
51 /** Must match the `port` on fixtures/ecs-dev/main-task.ts. */
52 const MAIN_PORT = 17357;
53 /** Must match the port baked into fixtures/ecs-reload/Dockerfile. */
54 const RELOAD_PORT = 17358;
55 /** Must match the port baked into fixtures/ecs-svc/Dockerfile. */
56 const SVC_PORT = 17359;
57 /** Must match the default port in fixtures/ecs-reload-main/server.ts. */
58 const MAIN_RELOAD_PORT = 17360;
59 /** Must match the port baked into fixtures/ecs-env/Dockerfile. */
60 const ENV_PORT = 17361;
61 /** Must match the port baked into fixtures/ecs-ext/Dockerfile.ecs. */
62 const EXT_PORT = 17363;
63
64 const FLOCI_REGION = "us-east-1";
65
66 const getState = Effect.fn(function* (fqn: string) {
67 const state = yield* yield* State;
68 const stk = yield* Stack;
69 return (yield* state.get({ stack: stk.name, stage: stk.stage, fqn })) as
70 | ResourceState
71 | undefined;
72 });
73
74 class RunTaskRejected extends Data.TaggedError("RunTaskRejected")<{ readonly status: number }> {}
75
76 /** Raw ECS operation against the emulator gateway (out-of-band). */
77 const rawEcs = (action: string, body: Record<string, unknown>) =>
78 rawAwsJson({
79 service: "ecs",
80 region: FLOCI_REGION,
81 target: `AmazonEC2ContainerServiceV20141113.${action}`,
82 contentType: "application/x-amz-json-1.1",
83 body,
84 });
85
86 /**
87 * The task definition revision is no longer ACTIVE. ECS keeps a deleted
88 * revision describable (`INACTIVE` / `DELETE_IN_PROGRESS`); an emulator that
89 * forgets it answers `ClientException` (400) instead.
90 */
91 const expectDefinitionGone = Effect.fn(function* (taskDefinitionArn: string) {
92 const response = yield* rawEcs("DescribeTaskDefinition", { taskDefinition: taskDefinitionArn });
93 if (response.status === 400) return;
94 expect(response.status).toBe(200);
95 const body = (yield* response.json) as { taskDefinition?: { status?: string } };
96 expect(["INACTIVE", "DELETE_IN_PROGRESS"]).toContain(body.taskDefinition?.status);
97 });
98
99 /** Names of the docker containers currently running on the host daemon. */
100 const runningContainerNames = Effect.sync(
101 () =>
102 spawnSync("docker", ["ps", "--format", "{{.Names}}"], { encoding: "utf8", timeout: 15_000 })
103 .stdout ?? "",
104 );
105
106 /** `arn:aws:ecs:…:task/<cluster>/<taskId>` → `<taskId>`. */
107 const taskIdOfArn = (arn: string) => arn.split("/").pop()!;
108
109 /**
110 * The emulator runs task containers on THIS machine — build for the host
111 * architecture so the image runs natively instead of under qemu.
112 */
113 const hostRuntimePlatform = {
114 cpuArchitecture: process.arch === "arm64" ? ("ARM64" as const) : ("X86_64" as const),
115 operatingSystemFamily: "LINUX" as const,
116 };
117
118 /**
119 * Deploy → RunTask → assert RUNNING container + HTTP marker → destroy →
120 * assert everything (including the docker container) is gone. Shared by the
121 * context-Dockerfile and bundled-main cases.
122 */
123 const runTaskRoundTrip = Effect.fn(function* (options: {
124 clusterName: string;
125 taskDefinitionArn: string;
126 port: number;
127 marker: string;
128 }) {
129 const client = yield* HttpClient.HttpClient;
130
131 // Out-of-band: run the deployed task definition on the deployed cluster
132 // through the raw gateway API. floci launches a REAL docker container.
133 // Full-suite load can 400 the first RunTask; retry until the emulator
134 // accepts it rather than failing the whole file.
135 const runResponse = yield* rawEcs("RunTask", {
136 cluster: options.clusterName,
137 taskDefinition: options.taskDefinitionArn,
138 count: 1,
139 launchType: "EC2",
140 }).pipe(
141 Effect.flatMap((response) =>
142 response.status === 200
143 ? Effect.succeed(response)
144 : Effect.fail(new RunTaskRejected({ status: response.status })),
145 ),
146 Effect.retry({
147 while: (e) => e._tag === "RunTaskRejected",
148 times: 8,
149 schedule: Schedule.exponential("500 millis"),
150 }),
151 );
152 const run = (yield* runResponse.json) as {
153 tasks?: { taskArn?: string; lastStatus?: string }[];
154 failures?: unknown[];
155 };
156 expect(run.failures ?? []).toEqual([]);
157 const taskArn = run.tasks?.[0]?.taskArn;
158 expect(taskArn).toBeTruthy();
159 const taskId = taskIdOfArn(taskArn!);
160
161 // DescribeTasks observes the task RUNNING…
162 const described = yield* rawEcs("DescribeTasks", {
163 cluster: options.clusterName,
164 tasks: [taskArn],
165 });
166 expect(described.status).toBe(200);
167 const tasks = (yield* described.json) as { tasks?: { lastStatus?: string }[] };
168 expect(tasks.tasks?.[0]?.lastStatus).toBe("RUNNING");
169
170 // …and the task is a REAL container on the host docker daemon
171 // (`floci-ecs-<taskId>-<containerName>`).
172 expect(yield* runningContainerNames).toContain(`floci-ecs-${taskId}`);
173
174 // Round-trip HTTP to the served marker. Bridge-mode port mappings are
175 // published literally on the docker host, so the container is reachable
176 // at localhost:<port>. (floci's DescribeTasks networkBindings mis-report
177 // the hostPort as the containerPort, so the literal port — equal by
178 // construction in the Task's port mapping — is the reliable address.)
179 const body = yield* client.get(`http://localhost:${options.port}/`).pipe(
180 Effect.retry({ schedule: Schedule.exponential("500 millis"), times: 10 }),
181 Effect.flatMap((response) => response.text),
182 );
183 expect(body).toContain(options.marker);
184
185 return { taskId };
186 });
187
188 /**
189 * Bounded poll of `http://localhost:<port>/` until the marker serves.
190 * Connection failures (the swap window between the old container stopping
191 * and the replacement serving) are retried; a stale marker repeats.
192 */
193 const pollMarker = Effect.fn(function* (options: {
194 port: number;
195 marker: string;
196 times?: number;
197 /** Path to poll (default `/`). */
198 path?: string;
199 }) {
200 const client = yield* HttpClient.HttpClient;
201 const times = options.times ?? 60;
202 const body = yield* client.get(`http://localhost:${options.port}${options.path ?? "/"}`).pipe(
203 Effect.flatMap((response) => response.text),
204 Effect.retry({ while: (): boolean => true, schedule: Schedule.spaced("2 seconds"), times }),
205 Effect.repeat({
206 schedule: Schedule.spaced("2 seconds"),
207 until: (b): boolean => b.includes(options.marker),
208 times,
209 }),
210 );
211 expect(body).toContain(options.marker);
212 });
213
214 /**
215 * Post-destroy (hot-reload variants, where the swap replaced the original
216 * task): observe until no running container belongs to the family's primary
217 * container (`floci-ecs-<taskId>-<containerName>`), then assert the cluster
218 * and task definition are gone from the emulator.
219 */
220 const assertFamilyTornDown = Effect.fn(function* (options: {
221 clusterName: string;
222 taskDefinitionArn: string;
223 containerName: string;
224 }) {
225 yield* runningContainerNames.pipe(
226 Effect.flatMap((names) =>
227 names
228 .split("\n")
229 .some((name) => name.startsWith("floci-ecs-") && name.endsWith(`-${options.containerName}`))
230 ? Effect.fail(new Error("family container still running"))
231 : Effect.void,
232 ),
233 Effect.retry({ schedule: Schedule.spaced("2 seconds"), times: 20 }),
234 );
235
236 const clusters = (yield* (yield* rawEcs("DescribeClusters", { clusters: [options.clusterName] }))
237 .json) as { clusters?: { status?: string }[] };
238 const active = (clusters.clusters ?? []).filter((cluster) => cluster.status !== "INACTIVE");
239 expect(active).toEqual([]);
240
241 yield* expectDefinitionGone(options.taskDefinitionArn);
242 });
243
244 /** Post-destroy: task container gone, cluster gone, task definition gone. */
245 const assertTornDown = Effect.fn(function* (options: {
246 clusterName: string;
247 taskDefinitionArn: string;
248 taskId: string;
249 }) {
250 // The running task's container was stopped and removed by the cluster
251 // delete (observe until the daemon agrees — stop is asynchronous).
252 yield* runningContainerNames.pipe(
253 Effect.flatMap((names) =>
254 names.includes(`floci-ecs-${options.taskId}`)
255 ? Effect.fail(new Error("task container still running"))
256 : Effect.void,
257 ),
258 Effect.retry({ schedule: Schedule.spaced("2 seconds"), times: 15 }),
259 );
260
261 // The cluster is gone (or INACTIVE) in the emulator.
262 const clusters = (yield* (yield* rawEcs("DescribeClusters", { clusters: [options.clusterName] }))
263 .json) as { clusters?: { status?: string }[] };
264 const active = (clusters.clusters ?? []).filter((cluster) => cluster.status !== "INACTIVE");
265 expect(active).toEqual([]);
266
267 // The task definition revision is gone.
268 yield* expectDefinitionGone(options.taskDefinitionArn);
269 });
270
271 // Sequential on purpose: each test runs a `docker buildx build`, and
272 // concurrent builds multiply pressure on Docker Desktop's shared
273 // `docker-credential-desktop` helper, which can wedge machine-wide under
274 // concurrent access (the same helper-race class documented on
275 // `Docker.image.push`). One build at a time keeps this file off that path.
276 describe.sequential("EcsDev", { tags: ["provider:aws", "provider:aws:ecs", "local"] }, () => {
277 test.provider(
278 "dev mode runs a context-Dockerfile ECS task as a real local container",
279 (stack) =>
280 Effect.gen(function* () {
281 yield* stack.destroy();
282
283 const outputs = yield* stack.deploy(
284 Effect.gen(function* () {
285 // Propless instantiation on purpose: pins the `news ?? {}`
286 // normalization in the Cluster reconciler (every ClusterProps
287 // field is optional, so `Cluster("Id")` is legal).
288 const cluster = yield* AWS.ECS.Cluster("EcsDevCluster");
289 const task = yield* AWS.ECS.Task("EcsDevTask", {
290 context: contextDir,
291 port: CONTEXT_PORT,
292 cpu: 256,
293 memory: 512,
294 // Bridge mode publishes the literal host port — the only
295 // host-reachable mode when floci runs inside a container.
296 networkMode: "bridge",
297 requiresCompatibilities: ["EC2"],
298 runtimePlatform: hostRuntimePlatform,
299 });
300 return { cluster, task };
301 }),
302 );
303
304 // --- Emulator-shaped identity: the live cloud can never mint these.
305 expect(outputs.cluster.clusterArn).toContain(":000000000000:");
306 expect(outputs.task.taskDefinitionArn).toContain(":000000000000:");
307 expect(outputs.task.taskRoleArn).toContain("::000000000000:");
308 expect(outputs.task.executionRoleArn).toContain("::000000000000:");
309 // The image was pushed to floci's loopback ECR registry.
310 expect(outputs.task.repositoryUri).toContain(".localhost:");
311 expect(outputs.task.imageUri).toContain(".localhost:");
312
313 // --- Stamped-mode proof.
314 for (const fqn of ["EcsDevCluster", "EcsDevTask"]) {
315 const row = yield* getState(fqn);
316 expect(`${fqn}:${row?.status}`).toBe(`${fqn}:created`);
317 expect(`${fqn}:${row?.providerMode}`).toBe(`${fqn}:local`);
318 }
319
320 // --- Run the task: real container, HTTP marker round-trip.
321 const { taskId } = yield* runTaskRoundTrip({
322 clusterName: outputs.cluster.clusterName,
323 taskDefinitionArn: outputs.task.taskDefinitionArn,
324 port: CONTEXT_PORT,
325 marker: "ecs-dev-local-marker",
326 });
327
328 // --- Destroy: the cluster delete stops the running task (container
329 // removed), and the task delete sweeps the definition + repository.
330 yield* stack.destroy();
331
332 yield* assertTornDown({
333 clusterName: outputs.cluster.clusterName,
334 taskDefinitionArn: outputs.task.taskDefinitionArn,
335 taskId,
336 });
337
338 // The ECR repository holding the built image is gone from the
339 // emulator's registry too.
340 const repositories = yield* rawAwsJson({
341 service: "ecr",
342 region: FLOCI_REGION,
343 target: "AmazonEC2ContainerRegistry_V20150921.DescribeRepositories",
344 contentType: "application/x-amz-json-1.1",
345 body: { repositoryNames: [outputs.task.repositoryName] },
346 });
347 expect(repositories.status).toBe(400); // RepositoryNotFoundException
348 }),
349 { timeout: 300_000 },
350 );
351
352 test.provider(
353 "dev mode applies logging.retention to the task's log group",
354 (stack) =>
355 Effect.gen(function* () {
356 yield* stack.destroy();
357
358 const deploy = (retention: "10 days" | "forever") =>
359 stack.deploy(
360 AWS.ECS.Task("EcsRetentionTask", {
361 context: contextDir,
362 port: CONTEXT_PORT,
363 cpu: 256,
364 memory: 512,
365 networkMode: "bridge",
366 requiresCompatibilities: ["EC2"],
367 runtimePlatform: hostRuntimePlatform,
368 logging: { retention },
369 }),
370 );
371
372 /** The task's log group as the emulator reports it, if it exists. */
373 const findGroup = Effect.fn(function* (logGroupName: string) {
374 const response = yield* rawAwsJson({
375 service: "logs",
376 region: FLOCI_REGION,
377 target: "Logs_20140328.DescribeLogGroups",
378 contentType: "application/x-amz-json-1.1",
379 body: { logGroupNamePrefix: logGroupName },
380 });
381 const page = (yield* response.json) as {
382 logGroups?: { logGroupName?: string; retentionInDays?: number }[];
383 };
384 return page.logGroups?.find((group) => group.logGroupName === logGroupName);
385 });
386
387 // 10 days rounds up to CloudWatch's 14.
388 const task = yield* deploy("10 days");
389 expect((yield* findGroup(task.logGroupName))?.retentionInDays).toBe(14);
390
391 // "forever" clears the policy and keeps the group.
392 yield* deploy("forever");
393 const cleared = yield* findGroup(task.logGroupName);
394 expect(cleared).toBeDefined();
395 expect(cleared?.retentionInDays).toBeUndefined();
396
397 // The task's destroy deletes its log group.
398 yield* stack.destroy();
399 expect(yield* findGroup(task.logGroupName)).toBeUndefined();
400 }),
401 { timeout: 300_000 },
402 );
403
404 test.provider(
405 "dev mode bundles a main-program ECS task and pushes through the local ECR registry",
406 (stack) =>
407 Effect.gen(function* () {
408 yield* stack.destroy();
409
410 const outputs = yield* stack.deploy(
411 Effect.gen(function* () {
412 const cluster = yield* AWS.ECS.Cluster("EcsDevMainCluster", {});
413 const task = yield* EcsDevMainTask;
414 return { cluster, task };
415 }),
416 );
417
418 expect(outputs.cluster.clusterArn).toContain(":000000000000:");
419 expect(outputs.task.taskDefinitionArn).toContain(":000000000000:");
420 expect(outputs.task.repositoryUri).toContain(".localhost:");
421
422 for (const fqn of ["EcsDevMainCluster", "EcsDevMainTask"]) {
423 const row = yield* getState(fqn);
424 expect(`${fqn}:${row?.status}`).toBe(`${fqn}:created`);
425 expect(`${fqn}:${row?.providerMode}`).toBe(`${fqn}:local`);
426 }
427
428 const { taskId } = yield* runTaskRoundTrip({
429 clusterName: outputs.cluster.clusterName,
430 taskDefinitionArn: outputs.task.taskDefinitionArn,
431 port: MAIN_PORT,
432 marker: "ecs-dev-main-marker",
433 });
434
435 yield* stack.destroy();
436
437 yield* assertTornDown({
438 clusterName: outputs.cluster.clusterName,
439 taskDefinitionArn: outputs.task.taskDefinitionArn,
440 taskId,
441 });
442 }),
443 { timeout: 300_000 },
444 );
445
446 test.provider(
447 "hot reloads a context-Dockerfile task without a deploy",
448 (stack) =>
449 Effect.gen(function* () {
450 const fs = yield* FileSystem.FileSystem;
451 const path = yield* Path.Path;
452 yield* stack.destroy();
453
454 // Clone the fixture so the hot-reload rewrite never touches the
455 // repo tree.
456 const clone = yield* cloneFixture(`${import.meta.dirname}/fixtures/ecs-reload`, {
457 prefix: "ecs-reload-",
458 });
459
460 const outputs = yield* stack.deploy(
461 Effect.gen(function* () {
462 const cluster = yield* AWS.ECS.Cluster("EcsReloadCluster");
463 const task = yield* AWS.ECS.Task("EcsReloadTask", {
464 context: clone,
465 port: RELOAD_PORT,
466 cpu: 256,
467 memory: 512,
468 networkMode: "bridge",
469 requiresCompatibilities: ["EC2"],
470 runtimePlatform: hostRuntimePlatform,
471 });
472 return { cluster, task };
473 }),
474 );
475 expect(outputs.task.taskDefinitionArn).toContain(":000000000000:");
476 expect(outputs.task.repositoryUri).toContain(".localhost:");
477
478 // Run the deployed revision out-of-band; marker v1 serves.
479 yield* runTaskRoundTrip({
480 clusterName: outputs.cluster.clusterName,
481 taskDefinitionArn: outputs.task.taskDefinitionArn,
482 port: RELOAD_PORT,
483 marker: "ecs-reload-v1",
484 });
485
486 // Hot reload: rewrite the CLONED context — no deploy in between.
487 // The sidecar watch loop rebuilds the image, pushes the new
488 // content-hash tag, registers a new task definition revision, and
489 // restarts the running standalone task on it.
490 const swapStartedAt = Date.now();
491 yield* fs.writeFileString(path.join(clone, "index.html"), "ecs-reload-v2\n");
492 yield* pollMarker({ port: RELOAD_PORT, marker: "ecs-reload-v2", times: 90 });
493 yield* Effect.log(`context task hot reload observed in ${Date.now() - swapStartedAt}ms`);
494
495 yield* stack.destroy();
496 yield* assertFamilyTornDown({
497 clusterName: outputs.cluster.clusterName,
498 taskDefinitionArn: outputs.task.taskDefinitionArn,
499 containerName: outputs.task.containerName,
500 });
501 }),
502 { timeout: 300_000 },
503 );
504
505 test.provider(
506 "keeps the recorded task definition revision when a Build rewrites the image context during an apply",
507 (stack) =>
508 Effect.gen(function* () {
509 const fs = yield* FileSystem.FileSystem;
510 const path = yield* Path.Path;
511 yield* stack.destroy();
512
513 const app = yield* cloneFixture(`${import.meta.dirname}/fixtures/ecs-reload`, {
514 prefix: "ecs-build-context-",
515 });
516
517 // The Build republishes `dist/` from the clone on every input change,
518 // so the Task's `context` changes underneath the running watcher in
519 // the same apply that updates the Task.
520 yield* fs.writeFileString(
521 path.join(app, "build.sh"),
522 "rm -rf dist\nmkdir dist\ncp Dockerfile index.html dist/\n",
523 );
524 const program = Effect.gen(function* () {
525 const build = yield* Command.Build("EcsBuildContextImage", {
526 command: "bash build.sh",
527 cwd: app,
528 outdir: "dist",
529 memo: { include: ["build.sh", "Dockerfile", "index.html"], lockfile: false },
530 });
531 return yield* AWS.ECS.Task("EcsBuildContextTask", {
532 // `build.outdir` is persisted relative to the initial cwd.
533 context: Output.map(build.outdir, (dir) => path.resolve(initialCwd, dir)),
534 port: RELOAD_PORT,
535 cpu: 256,
536 memory: 512,
537 networkMode: "bridge",
538 requiresCompatibilities: ["EC2"],
539 runtimePlatform: hostRuntimePlatform,
540 });
541 });
542
543 /** ACTIVE revisions of the task's family, as the emulator lists them. */
544 const activeRevisions = Effect.fn(function* (family: string) {
545 const response = yield* rawEcs("ListTaskDefinitions", {
546 familyPrefix: family,
547 status: "ACTIVE",
548 });
549 const page = (yield* response.json) as { taskDefinitionArns?: string[] };
550 return page.taskDefinitionArns ?? [];
551 });
552
553 /**
554 * Poll that the ARN the apply recorded stays the family's only ACTIVE
555 * revision. The dev watcher reacts to the rewritten context a few
556 * milliseconds after the engine's update, so a single read right after
557 * the deploy can miss a redundant swap.
558 */
559 const expectRecordedRevisionSettled = (task: {
560 readonly taskDefinitionArn: string;
561 readonly taskFamily: string;
562 }) =>
563 Effect.gen(function* () {
564 const described = yield* rawEcs("DescribeTaskDefinition", {
565 taskDefinition: task.taskDefinitionArn,
566 });
567 expect(described.status).toBe(200);
568 expect(yield* activeRevisions(task.taskFamily)).toEqual([task.taskDefinitionArn]);
569 }).pipe(Effect.repeat({ schedule: Schedule.spaced("1 second"), times: 6 }));
570
571 const first = yield* stack.deploy(program);
572 yield* expectRecordedRevisionSettled(first);
573
574 // Control: nothing changed, so the redeploy keeps the same revision.
575 const unchanged = yield* stack.deploy(program);
576 expect(unchanged.taskDefinitionArn).toBe(first.taskDefinitionArn);
577 yield* expectRecordedRevisionSettled(unchanged);
578
579 // Change the Build's input: the apply rebuilds `dist/` and then updates
580 // the Task. The watcher's trigger for that rewrite must not register
581 // another revision over the one the engine just recorded.
582 yield* fs.writeFileString(path.join(app, "index.html"), "ecs-build-context-v2\n");
583 const second = yield* stack.deploy(program);
584 expect(second.code.hash).not.toBe(first.code.hash);
585 expect(second.taskDefinitionArn).not.toBe(first.taskDefinitionArn);
586 yield* expectRecordedRevisionSettled(second);
587
588 // The state row holds the revision the emulator still serves.
589 const row = yield* getState("EcsBuildContextTask");
590 expect(row?.attr?.taskDefinitionArn).toBe(second.taskDefinitionArn);
591
592 yield* stack.destroy();
593 }),
594 { timeout: 300_000 },
595 );
596
597 test.provider(
598 "hot reloads a bundled-main task without a deploy",
599 (stack) =>
600 Effect.gen(function* () {
601 const fs = yield* FileSystem.FileSystem;
602 const path = yield* Path.Path;
603 yield* stack.destroy();
604
605 const clone = yield* cloneFixture(`${import.meta.dirname}/fixtures/ecs-reload-main`, {
606 prefix: "ecs-reload-main-",
607 });
608 const mainPath = path.join(clone, "server.ts");
609
610 const program = Effect.gen(function* () {
611 const cluster = yield* AWS.ECS.Cluster("EcsReloadMainCluster");
612 // Declared WITHOUT an inline impl — the platform marks it
613 // external and the bundle runs as-is (a plain Bun server).
614 const task = yield* AWS.ECS.Task("EcsReloadMainTask", {
615 main: mainPath,
616 image: "oven/bun:1",
617 port: MAIN_RELOAD_PORT,
618 cpu: 256,
619 memory: 512,
620 networkMode: "bridge",
621 requiresCompatibilities: ["EC2"],
622 runtimePlatform: hostRuntimePlatform,
623 });
624 return { cluster, task };
625 });
626 const outputs = yield* stack.deploy(program);
627 expect(outputs.task.taskDefinitionArn).toContain(":000000000000:");
628 expect(outputs.task.repositoryUri).toContain(".localhost:");
629
630 yield* runTaskRoundTrip({
631 clusterName: outputs.cluster.clusterName,
632 taskDefinitionArn: outputs.task.taskDefinitionArn,
633 port: MAIN_RELOAD_PORT,
634 marker: "ecs-reload-main-v1",
635 });
636
637 // Hot reload: rewrite the CLONED program source. The sidecar's
638 // `Bundle.watch` (the deploy's exact rolldown module graph)
639 // triggers the rebuild → push → re-register → restart.
640 const source = yield* fs.readFileString(mainPath);
641 const swapStartedAt = Date.now();
642 yield* fs.writeFileString(
643 mainPath,
644 source.replace("ecs-reload-main-v1", "ecs-reload-main-v2"),
645 );
646 yield* pollMarker({ port: MAIN_RELOAD_PORT, marker: "ecs-reload-main-v2", times: 90 });
647 yield* Effect.log(
648 `bundled-main task hot reload observed in ${Date.now() - swapStartedAt}ms`,
649 );
650
651 // A REPLAN after the watcher's swap must surface it. Persisted state
652 // still carries v1's code hash (the watcher updates the emulator and
653 // the sidecar's in-memory attrs, not the state store), so the dev
654 // diff plans an update — not a noop — and the fresh attrs flow to
655 // stack outputs. The reported bug had this replan noop, so
656 // `task.code.hash` never advanced and Actions keyed on it stayed
657 // skipped after a transitive-import change.
658 const replanned = yield* stack.deploy(program);
659 expect(replanned.task.code.hash).not.toBe(outputs.task.code.hash);
660 // And a second replan with nothing new IS a noop-equivalent: the
661 // attrs are settled, the hash stable.
662 const settled = yield* stack.deploy(program);
663 expect(settled.task.code.hash).toBe(replanned.task.code.hash);
664
665 yield* stack.destroy();
666 yield* assertFamilyTornDown({
667 clusterName: outputs.cluster.clusterName,
668 taskDefinitionArn: outputs.task.taskDefinitionArn,
669 containerName: outputs.task.containerName,
670 });
671 }),
672 { timeout: 300_000 },
673 );
674
675 test.provider(
676 "dev mode runs an image-owning ECS Service with hot reload",
677 (stack) =>
678 Effect.gen(function* () {
679 const fs = yield* FileSystem.FileSystem;
680 const path = yield* Path.Path;
681 yield* stack.destroy();
682
683 const clone = yield* cloneFixture(`${import.meta.dirname}/fixtures/ecs-svc`, {
684 prefix: "ecs-svc-",
685 });
686
687 const outputs = yield* stack.deploy(
688 Effect.gen(function* () {
689 const cluster = yield* AWS.ECS.Cluster("EcsDevSvcCluster");
690 const service = yield* AWS.ECS.Service("EcsDevService", {
691 cluster,
692 context: clone,
693 port: SVC_PORT,
694 cpu: 256,
695 memory: 512,
696 // Bridge mode publishes the literal host port — the only
697 // host-reachable mode when floci runs inside a container
698 // (managed ALB ingress is out of scope in dev: floci binds
699 // listener sockets inside its own container, and the managed
700 // `alchemy-floci` container only exposes the gateway port).
701 networkMode: "bridge",
702 requiresCompatibilities: ["EC2"],
703 launchType: "EC2",
704 desiredCount: 1,
705 runtimePlatform: hostRuntimePlatform,
706 deploymentStabilizationTimeout: "3 minutes",
707 });
708 return { cluster, service };
709 }),
710 );
711
712 // Emulator-shaped identity + stamped-mode proof.
713 expect(outputs.service.serviceArn).toContain(":000000000000:");
714 expect(outputs.service.taskDefinitionArn).toContain(":000000000000:");
715 expect(outputs.service.repositoryUri).toContain(".localhost:");
716 expect(outputs.service.status).toBe("ACTIVE");
717 for (const fqn of ["EcsDevSvcCluster", "EcsDevService"]) {
718 const row = yield* getState(fqn);
719 expect(`${fqn}:${row?.status}`).toBe(`${fqn}:created`);
720 expect(`${fqn}:${row?.providerMode}`).toBe(`${fqn}:local`);
721 }
722
723 // The floci service scheduler launched the task itself — a REAL
724 // container serving the marker (no manual RunTask).
725 yield* pollMarker({ port: SVC_PORT, marker: "ecs-svc-v1", times: 60 });
726 expect(yield* runningContainerNames).toContain(`-${outputs.service.containerName!}`);
727
728 // Hot reload: rewrite the CLONED context — no deploy in between.
729 // The sidecar watcher rebuilds + pushes the new content-hash tag,
730 // re-reconciles (updateService onto the new revision), and stops
731 // the old-revision task; the floci scheduler relaunches it.
732 const swapStartedAt = Date.now();
733 yield* fs.writeFileString(path.join(clone, "index.html"), "ecs-svc-v2\n");
734 yield* pollMarker({ port: SVC_PORT, marker: "ecs-svc-v2", times: 90 });
735 yield* Effect.log(`service hot reload observed in ${Date.now() - swapStartedAt}ms`);
736
737 // Destroy drains the service (desiredCount 0 → tasks stopped),
738 // deletes it, then sweeps the task-definition infrastructure.
739 yield* stack.destroy();
740 yield* assertFamilyTornDown({
741 clusterName: outputs.cluster.clusterName,
742 taskDefinitionArn: outputs.service.taskDefinitionArn,
743 containerName: outputs.service.containerName!,
744 });
745 const services = (yield* (yield* rawEcs("DescribeServices", {
746 cluster: outputs.cluster.clusterName,
747 services: [outputs.service.serviceName],
748 })).json) as { services?: { status?: string }[] };
749 const activeServices = (services.services ?? []).filter(
750 (service) => service.status === "ACTIVE",
751 );
752 expect(activeServices).toEqual([]);
753 }),
754 { timeout: 300_000 },
755 );
756
757 /**
758 * `Bundle.watch` emits its initial build, so a bundled-`main` Service's
759 * watcher fires once right after the apply with no content change. That
760 * trigger must not register another revision or roll the service's tasks.
761 */
762 test.provider(
763 "keeps the recorded task definition revision when the watcher's first emission changes nothing",
764 (stack) =>
765 Effect.gen(function* () {
766 const path = yield* Path.Path;
767 yield* stack.destroy();
768
769 const clone = yield* cloneFixture(`${import.meta.dirname}/fixtures/ecs-reload-main`, {
770 prefix: "ecs-svc-main-",
771 });
772
773 const program = Effect.gen(function* () {
774 const cluster = yield* AWS.ECS.Cluster("EcsSvcMainCluster");
775 const service = yield* AWS.ECS.Service("EcsSvcMainService", {
776 cluster,
777 main: path.join(clone, "server.ts"),
778 image: "oven/bun:1",
779 port: MAIN_RELOAD_PORT,
780 cpu: 256,
781 memory: 512,
782 networkMode: "bridge",
783 requiresCompatibilities: ["EC2"],
784 launchType: "EC2",
785 desiredCount: 1,
786 runtimePlatform: hostRuntimePlatform,
787 deploymentStabilizationTimeout: "3 minutes",
788 });
789 return { cluster, service };
790 });
791
792 /**
793 * Poll that the recorded revision stays the family's only ACTIVE
794 * revision and the service's current one. The initial `Bundle.watch`
795 * emission lands some seconds after the apply (a bundle build plus a
796 * debounce), so a single read right after the deploy can miss a
797 * redundant roll.
798 */
799 const expectRecordedRevisionSettled = (outputs: {
800 cluster: { clusterName: string };
801 service: { taskFamily?: string; taskDefinitionArn: string; serviceName: string };
802 }) =>
803 Effect.gen(function* () {
804 const { service } = outputs;
805 const listed = (yield* (yield* rawEcs("ListTaskDefinitions", {
806 familyPrefix: service.taskFamily,
807 status: "ACTIVE",
808 })).json) as { taskDefinitionArns?: string[] };
809 expect(listed.taskDefinitionArns ?? []).toEqual([service.taskDefinitionArn]);
810 const described = (yield* (yield* rawEcs("DescribeServices", {
811 cluster: outputs.cluster.clusterName,
812 services: [service.serviceName],
813 })).json) as { services?: { taskDefinition?: string }[] };
814 expect(described.services?.[0]?.taskDefinition).toBe(service.taskDefinitionArn);
815 }).pipe(Effect.repeat({ schedule: Schedule.spaced("2 seconds"), times: 8 }));
816
817 const first = yield* stack.deploy(program);
818 yield* pollMarker({ port: MAIN_RELOAD_PORT, marker: "ecs-reload-main-v1", times: 60 });
819 yield* expectRecordedRevisionSettled(first);
820
821 // Control: a redeploy with no changes keeps the same revision.
822 const unchanged = yield* stack.deploy(program);
823 expect(unchanged.service.taskDefinitionArn).toBe(first.service.taskDefinitionArn);
824 yield* expectRecordedRevisionSettled(unchanged);
825
826 yield* stack.destroy();
827 yield* assertFamilyTornDown({
828 clusterName: first.cluster.clusterName,
829 taskDefinitionArn: first.service.taskDefinitionArn,
830 containerName: first.service.containerName!,
831 });
832 }),
833 { timeout: 300_000 },
834 );
835
836 /**
837 * A PROP-driven update — no file event — must roll the service's running
838 * containers onto the new task-definition revision. Regression: restart
839 * logic lived only in the file-watch trigger, so an engine reconcile
840 * (env change, inline-dockerfile edit) registered a new revision and
841 * `updateService`d onto it while the container kept serving the old one
842 * until the next source edit (`onReconciled` in DevWatchProvider).
843 */
844 test.provider(
845 "rolls a service task on a prop-only env update",
846 (stack) =>
847 Effect.gen(function* () {
848 yield* stack.destroy();
849
850 const clone = yield* cloneFixture(`${import.meta.dirname}/fixtures/ecs-env`, {
851 prefix: "ecs-env-",
852 });
853
854 const declare = (env: string) =>
855 Effect.gen(function* () {
856 const cluster = yield* AWS.ECS.Cluster("EcsEnvCluster");
857 const service = yield* AWS.ECS.Service("EcsEnvService", {
858 cluster,
859 context: clone,
860 port: ENV_PORT,
861 cpu: 256,
862 memory: 512,
863 networkMode: "bridge",
864 requiresCompatibilities: ["EC2"],
865 launchType: "EC2",
866 desiredCount: 1,
867 runtimePlatform: hostRuntimePlatform,
868 deploymentStabilizationTimeout: "3 minutes",
869 env: { ROLL_ENV: env },
870 });
871 return { cluster, service };
872 });
873
874 const outputs = yield* stack.deploy(declare("roll-env-v1"));
875 yield* pollMarker({ port: ENV_PORT, marker: "roll-env-v1", path: "/env.txt", times: 90 });
876
877 // The prop change: same fixture bytes, only the env differs. The
878 // engine registers a new revision; the running container must roll.
879 const swapStartedAt = Date.now();
880 const updated = yield* stack.deploy(declare("roll-env-v2"));
881 expect(updated.service.taskDefinitionArn).not.toBe(outputs.service.taskDefinitionArn);
882 yield* pollMarker({ port: ENV_PORT, marker: "roll-env-v2", path: "/env.txt", times: 90 });
883 yield* Effect.log(`prop-only service roll observed in ${Date.now() - swapStartedAt}ms`);
884
885 yield* stack.destroy();
886 yield* assertFamilyTornDown({
887 clusterName: outputs.cluster.clusterName,
888 taskDefinitionArn: updated.service.taskDefinitionArn,
889 containerName: updated.service.containerName!,
890 });
891 }),
892 { timeout: 600_000 },
893 );
894 /**
895 * A `dockerfile` PATH that lives OUTSIDE the build context: the watcher
896 * must watch the Dockerfile's own directory in addition to the context
897 * (the `imageSourceTrigger` outside-context branch — previously never
898 * exercised by any test), and an edit to the Dockerfile itself must
899 * rebuild + roll with no deploy.
900 */
901 test.provider(
902 "hot reloads a service whose Dockerfile lives outside the build context",
903 (stack) =>
904 Effect.gen(function* () {
905 const fs = yield* FileSystem.FileSystem;
906 const path = yield* Path.Path;
907
908 yield* stack.destroy();
909
910 const clone = yield* cloneFixture(`${import.meta.dirname}/fixtures/ecs-ext`, {
911 prefix: "ecs-ext-",
912 });
913
914 const outputs = yield* stack.deploy(
915 Effect.gen(function* () {
916 const cluster = yield* AWS.ECS.Cluster("EcsExtCluster");
917 const service = yield* AWS.ECS.Service("EcsExtService", {
918 cluster,
919 context: path.join(clone, "site"),
920 dockerfile: path.join(clone, "Dockerfile.ecs"),
921 port: EXT_PORT,
922 cpu: 256,
923 memory: 512,
924 networkMode: "bridge",
925 requiresCompatibilities: ["EC2"],
926 launchType: "EC2",
927 desiredCount: 1,
928 runtimePlatform: hostRuntimePlatform,
929 deploymentStabilizationTimeout: "3 minutes",
930 });
931 return { cluster, service };
932 }),
933 );
934
935 yield* pollMarker({ port: EXT_PORT, marker: "ecs-ext-content-v1", times: 90 });
936 yield* pollMarker({
937 port: EXT_PORT,
938 marker: "ecs-ext-baked-v1",
939 path: "/baked.txt",
940 times: 60,
941 });
942
943 // Edit the OUT-OF-CONTEXT Dockerfile — no deploy.
944 const swapStartedAt = Date.now();
945 const dockerfile = yield* fs.readFileString(path.join(clone, "Dockerfile.ecs"));
946 yield* fs.writeFileString(
947 path.join(clone, "Dockerfile.ecs"),
948 dockerfile.replace("ecs-ext-baked-v1", "ecs-ext-baked-v2"),
949 );
950 yield* pollMarker({
951 port: EXT_PORT,
952 marker: "ecs-ext-baked-v2",
953 path: "/baked.txt",
954 times: 90,
955 });
956 yield* Effect.log(
957 `out-of-context Dockerfile reload observed in ${Date.now() - swapStartedAt}ms`,
958 );
959
960 // A context file edit still reloads too.
961 yield* fs.writeFileString(path.join(clone, "site", "index.html"), "ecs-ext-content-v2\n");
962 yield* pollMarker({ port: EXT_PORT, marker: "ecs-ext-content-v2", times: 90 });
963
964 yield* stack.destroy();
965 yield* assertFamilyTornDown({
966 clusterName: outputs.cluster.clusterName,
967 taskDefinitionArn: outputs.service.taskDefinitionArn,
968 containerName: outputs.service.containerName!,
969 });
970 }),
971 { timeout: 600_000 },
972 );
973 }); // describe.sequential("EcsDev")