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

main
ts 113 lines 5.38 KB
Raw
1 /** @effect-diagnostics anyUnknownInErrorContext:off */
2
3 /**
4 * The `alchemy dev` provider for `AWS.ECS.Task`: deploys the task
5 * definition (image, roles, log group, ECR repository) into the floci
6 * emulator and hot-swaps running tasks on file change.
7 *
8 * Built on the shared dev-watch skeleton
9 * ([DevWatchProvider](../Local/DevWatchProvider.ts)); this file supplies
10 * only the Task-specific parts:
11 *
12 * - **Watch triggers** by image source ({@link imageSourceTrigger}):
13 * `main` re-uses the deploy's exact rolldown module graph via
14 * `Bundle.watch`; `context` fs-watches the Docker build context;
15 * registry `image` refs have nothing local to watch.
16 * - **Swap mechanism** — every trigger re-runs the LIVE reconcile against
17 * the emulator: the image pipeline is content-addressed, so a real change
18 * builds and pushes a NEW `<repositoryUri>:<hash>` tag and registers a
19 * new task definition revision (an unchanged hash is a cheap no-op).
20 * - **Task restart** lives in the skeleton's `onReconciled` hook — NOT in
21 * the watch loop — so it also fires for engine-driven reconciles.
22 * Prop-only changes (an inline `dockerfile` edit, a new env var) never
23 * produce a file event: before the hook, they registered a new revision
24 * and running tasks kept serving the old one until the next source edit.
25 * RUNNING standalone tasks of the family (launched via `RunTask`) are
26 * stopped and re-run on the new revision — service-managed tasks belong
27 * to [FlociServiceProvider](./FlociServiceProvider.ts).
28 */
29
30 import * as Effect from "effect/Effect";
31 import * as Stream from "effect/Stream";
32 import { makeImageSource, type ImageSourceLike } from "../ECR/ImageSource.ts";
33 import { flociProvidersUrl, makeDevWatchProvider } from "../Local/DevWatchProvider.ts";
34 import { imageSourceTrigger, restartFamilyTasks } from "./EcsDevWatch.ts";
35 import { Task, TaskProvider, taskImageInput, type TaskProps } from "./Task.ts";
36
37 export const FlociTaskProvider = () =>
38 makeDevWatchProvider<Task, TaskProps, Task["Attributes"]>(Task, flociProvidersUrl(), {
39 liveProvider: () => TaskProvider(),
40 // The restart surface of the watch loop: everything that changes WHAT
41 // the watcher builds or WHERE it publishes/runs.
42 watchConfigOf: (news, attrs) => {
43 const source = news as ImageSourceLike;
44 return {
45 family: attrs.taskFamily,
46 repositoryName: attrs.repositoryName,
47 main: source.main,
48 handler: source.handler,
49 // Secrets stay out, as in the image hash: rotating one does not rebuild.
50 build: source.build === undefined ? undefined : { ...source.build, secrets: undefined },
51 isExternal: news.isExternal,
52 context: source.context,
53 dockerfile: source.dockerfile,
54 image: source.image,
55 port: news.port,
56 runtimePlatform: news.runtimePlatform,
57 };
58 },
59 // Mirrors the live diff's replacement rule: the family (taskName, or
60 // the id-derived generated name) is the identity.
61 replaceOn: ({ olds, news }) =>
62 Effect.sync(() =>
63 (olds.taskName ?? null) !== (news.taskName ?? null)
64 ? { action: "replace" as const }
65 : undefined,
66 ),
67 // Fires on every reconcile — watcher-triggered AND engine-driven
68 // (prop changes never produce a file event, so restarting only from
69 // the watch loop left running tasks on the old revision).
70 onReconciled: ({ previous, attrs }) =>
71 Effect.gen(function* () {
72 if (previous?.taskDefinitionArn === attrs.taskDefinitionArn) return;
73 const startedAt = Date.now();
74 const restarted = yield* restartFamilyTasks({
75 family: attrs.taskFamily,
76 nextTaskDefinitionArn: attrs.taskDefinitionArn,
77 serviceManaged: false,
78 });
79 yield* Effect.logInfo(
80 `task definition swapped (${restarted} task(s) restarted) in ${Date.now() - startedAt}ms`,
81 );
82 }).pipe(Effect.catchCause((cause) => Effect.logWarning(`task restart failed`, cause))),
83 startWatch: (ctx) =>
84 Effect.gen(function* () {
85 const imageSource = yield* makeImageSource;
86 const trigger = yield* imageSourceTrigger({
87 id: ctx.id,
88 source: ctx.news as ImageSourceLike,
89 isExternal: ctx.news.isExternal,
90 });
91 yield* trigger.pipe(
92 // The reconcile registers the new revision; the `onReconciled`
93 // hook (shared with engine-driven updates) restarts the tasks.
94 Stream.runForEach(() =>
95 // The staleness check runs under the per-id lock: an engine
96 // reconcile holding the lock may publish exactly this content
97 // first, and a pre-lock check against the older attrs would
98 // still re-register and reap the revision the engine recorded.
99 ctx
100 .rerunReconcileIfStale((current) =>
101 Effect.gen(function* () {
102 const hash = yield* imageSource.hash(taskImageInput(ctx.news));
103 // Bundle.watch emits its initial build too. Re-registering
104 // unchanged content would delete the ARN just returned by
105 // deploy before callers can launch a task with it.
106 return hash === undefined || hash !== current.code.hash;
107 }),
108 )
109 .pipe(Effect.catchCause((cause) => Effect.logWarning(`image swap failed`, cause))),
110 ),
111 );
112 }),
113 });