@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 233 lines 10 KB
Raw
1 /** @effect-diagnostics anyUnknownInErrorContext:off */
2
3 /**
4 * The `alchemy dev` provider for `AWS.ECS.Service`: deploys the service
5 * (and, for the image-owning forms, its synthesized task definition) into
6 * the floci emulator and hot-swaps the service's running tasks on file
7 * change.
8 *
9 * Built on the shared dev-watch skeleton
10 * ([DevWatchProvider](../Local/DevWatchProvider.ts)); this file supplies
11 * only the Service-specific parts:
12 *
13 * - **Watch triggers** ({@link imageSourceTrigger}) apply to the
14 * image-owning forms (`main` / `context` / `image`). A BYO `task:`
15 * reference owns its image on the `AWS.ECS.Task` resource, so the
16 * service watcher has nothing to build — hot reload of the referenced
17 * task flows through [FlociTaskProvider](./FlociTaskProvider.ts) plus a
18 * redeploy to roll the service.
19 * - **Swap mechanism** — a trigger re-runs the LIVE reconcile: the
20 * content-addressed image pipeline pushes a new `<repositoryUri>:<hash>`
21 * tag, registers a new task definition revision, and `updateService`
22 * points the service at it. Floci swaps the service's task definition in
23 * place WITHOUT restarting running containers (probed), so the
24 * old-revision tasks are stopped and the floci service scheduler
25 * relaunches them on the new revision (~6s observed end-to-end for a
26 * container relaunch).
27 * - **Task roll** lives in the skeleton's `onReconciled` hook — NOT in the
28 * watch loop — so it also fires for engine-driven reconciles. Prop-only
29 * changes (an inline `dockerfile` edit, a new env var) never produce a
30 * file event: before the hook, they registered a new revision and
31 * `updateService`d onto it, but the running containers kept serving the
32 * old one until the next source edit.
33 */
34
35 import * as ecs from "@distilled.cloud/aws/ecs";
36 import { deepEqual } from "alchemy/Diff";
37 import { registerRpcErrorClasses } from "alchemy/Local/RpcSerialization";
38 import * as Effect from "effect/Effect";
39 import * as Schedule from "effect/Schedule";
40 import * as Stream from "effect/Stream";
41 import { makeImageSource, type ImageSourceLike } from "../ECR/ImageSource.ts";
42 import { flociProvidersUrl, makeDevWatchProvider } from "../Local/DevWatchProvider.ts";
43 import { imageSourceTrigger, restartFamilyTasks } from "./EcsDevWatch.ts";
44 import {
45 MissingListenerCertificate,
46 MissingRuleListener,
47 MixedListenerOwnership,
48 MixedLoadBalancerProtocols,
49 NetworkListenerRuleUnsupported,
50 OwnedOnlyLoadBalancerOption,
51 RequestCountScalingRequiresLoadBalancer,
52 Service,
53 ServiceDidNotStabilize,
54 ServiceHealthTargetNotFound,
55 ServiceHostedZoneNotFound,
56 ServiceProvider,
57 ServiceRuleActionConflict,
58 serviceImageInput,
59 UnsupportedListenerProtocol,
60 type ServiceProps,
61 } from "./Service.ts";
62
63 // This provider runs in the RPC sidecar; register its typed failures so
64 // callers receive instances of the real classes.
65 registerRpcErrorClasses(
66 MissingListenerCertificate,
67 MissingRuleListener,
68 MixedListenerOwnership,
69 MixedLoadBalancerProtocols,
70 NetworkListenerRuleUnsupported,
71 OwnedOnlyLoadBalancerOption,
72 RequestCountScalingRequiresLoadBalancer,
73 ServiceDidNotStabilize,
74 ServiceHealthTargetNotFound,
75 ServiceHostedZoneNotFound,
76 ServiceRuleActionConflict,
77 UnsupportedListenerProtocol,
78 );
79
80 /** Cluster ARN from either form of the `cluster` prop (see ServiceProvider). */
81 const clusterArnOfProps = (cluster: ServiceProps["cluster"] | undefined): string | undefined =>
82 typeof cluster === "string"
83 ? cluster
84 : typeof (cluster as { clusterArn?: unknown } | undefined)?.clusterArn === "string"
85 ? (cluster as { clusterArn: string }).clusterArn
86 : undefined;
87
88 /** The truly-immutable post-create fields (mirrors the live diff). */
89 const immutableFieldsOf = (props: ServiceProps) => ({
90 usesStrategy: !!props.capacityProviderStrategy,
91 schedulingStrategy: props.schedulingStrategy ?? "REPLICA",
92 deploymentControllerType: props.deploymentController?.type ?? "ECS",
93 enableECSManagedTags: props.enableECSManagedTags ?? true,
94 role: props.role,
95 });
96
97 /** The BYO task reference, when the props use the `task:` form. */
98 const taskRefOf = (props: ServiceProps) => ("task" in props ? props.task : undefined);
99
100 export const FlociServiceProvider = () =>
101 makeDevWatchProvider<Service, ServiceProps, Service["Attributes"]>(Service, flociProvidersUrl(), {
102 liveProvider: () => ServiceProvider(),
103 watchConfigOf: (news, attrs) => {
104 const source = news as ImageSourceLike;
105 return {
106 serviceName: attrs.serviceName,
107 clusterArn: attrs.clusterArn,
108 taskFamily: attrs.taskFamily,
109 byoTaskDefinitionArn: taskRefOf(news)?.taskDefinitionArn,
110 main: source.main,
111 handler: source.handler,
112 // Secrets stay out, as in the image hash: rotating one does not rebuild.
113 build: source.build === undefined ? undefined : { ...source.build, secrets: undefined },
114 isExternal: news.isExternal,
115 context: source.context,
116 dockerfile: source.dockerfile,
117 image: source.image,
118 port: (news as { port?: number }).port,
119 runtimePlatform: (news as { runtimePlatform?: unknown }).runtimePlatform,
120 };
121 },
122 // Mirrors the live diff's cheap replacement rules (never building):
123 // serviceName is the identity, a service can't move clusters, and the
124 // immutable post-create flags replace delete-first.
125 replaceOn: ({ olds, news }) =>
126 Effect.sync(() => {
127 if ((olds.serviceName ?? null) !== (news.serviceName ?? null)) {
128 return { action: "replace" as const, deleteFirst: true };
129 }
130 const oldCluster = clusterArnOfProps(olds.cluster);
131 const newCluster = clusterArnOfProps(news.cluster);
132 if (oldCluster !== undefined && newCluster !== undefined && oldCluster !== newCluster) {
133 return { action: "replace" as const, deleteFirst: true };
134 }
135 if (!deepEqual(immutableFieldsOf(olds), immutableFieldsOf(news))) {
136 return { action: "replace" as const, deleteFirst: true };
137 }
138 return undefined;
139 }),
140 // The live update waits for the service to stabilize on its new
141 // revision, but floci swaps the revision in place and keeps the old
142 // tasks running, so (with a fixed host port) the new task can never
143 // start and the wait times out. While the reconcile waits, stop the
144 // old-revision tasks as soon as the service points at the new one.
145 whileReconciling: ({ previous }) =>
146 Effect.gen(function* () {
147 if (
148 previous?.taskFamily === undefined ||
149 previous.taskDefinitionArn === undefined ||
150 previous.clusterArn === undefined
151 ) {
152 return;
153 }
154 const family = previous.taskFamily;
155 let rolled = previous.taskDefinitionArn;
156 yield* Effect.gen(function* () {
157 const described = yield* ecs.describeServices({
158 cluster: previous.clusterArn,
159 services: [previous.serviceName],
160 });
161 const current = described.services?.[0]?.taskDefinition;
162 if (current === undefined || current === rolled) return;
163 yield* restartFamilyTasks({
164 family,
165 nextTaskDefinitionArn: current,
166 serviceManaged: true,
167 });
168 rolled = current;
169 }).pipe(Effect.repeat(Schedule.spaced("2 seconds")));
170 }),
171 // Fires on every reconcile — watcher-triggered AND engine-driven
172 // (prop changes never produce a file event, so rolling only from the
173 // watch loop left the service's containers on the old revision).
174 onReconciled: ({ previous, attrs }) =>
175 Effect.gen(function* () {
176 if (
177 attrs.taskFamily === undefined ||
178 attrs.taskDefinitionArn === undefined ||
179 previous?.taskDefinitionArn === attrs.taskDefinitionArn
180 ) {
181 return;
182 }
183 const startedAt = Date.now();
184 // `updateService` (inside the reconcile) pointed the service at
185 // the new revision, but floci's in-place swap keeps the old
186 // containers running — stop them so the scheduler relaunches on
187 // the new revision.
188 const restarted = yield* restartFamilyTasks({
189 family: attrs.taskFamily,
190 nextTaskDefinitionArn: attrs.taskDefinitionArn,
191 serviceManaged: true,
192 });
193 yield* Effect.logInfo(
194 `task definition swapped (${restarted} service task(s) rolling) in ${Date.now() - startedAt}ms`,
195 );
196 }).pipe(Effect.catchCause((cause) => Effect.logWarning(`service roll failed`, cause))),
197 startWatch: (ctx) =>
198 Effect.gen(function* () {
199 if (taskRefOf(ctx.news) !== undefined) {
200 // BYO task reference: the image (and its hot reload) belongs to
201 // the referenced `AWS.ECS.Task` resource.
202 return;
203 }
204 const imageSource = yield* makeImageSource;
205 const trigger = yield* imageSourceTrigger({
206 id: ctx.id,
207 source: ctx.news as ImageSourceLike,
208 isExternal: ctx.news.isExternal,
209 });
210 yield* trigger.pipe(
211 // The reconcile registers the new revision and `updateService`s
212 // onto it; the `onReconciled` hook (shared with engine-driven
213 // updates) rolls the running tasks.
214 Stream.runForEach(() =>
215 // The staleness check runs under the per-id lock, against the
216 // freshest attrs (see FlociTaskProvider).
217 ctx
218 .rerunReconcileIfStale((current) =>
219 Effect.gen(function* () {
220 const hash = yield* imageSource.hash(serviceImageInput(ctx.news));
221 // Bundle.watch emits its initial build too. Re-reconciling
222 // unchanged content would register another revision and
223 // roll the running tasks for nothing.
224 return (
225 hash === undefined || current.code === undefined || hash !== current.code.hash
226 );
227 }),
228 )
229 .pipe(Effect.catchCause((cause) => Effect.logWarning(`image swap failed`, cause))),
230 ),
231 );
232 }),
233 });