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

main
ts 408 lines 15.7 KB
Raw
1 import * as codedeploy from "@distilled.cloud/aws/codedeploy";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags";
8 import { toWireMinutes } from "alchemy/Util/Duration";
9 import type * as Duration from "effect/Duration";
10 import * as Effect from "effect/Effect";
11 import * as Schedule from "effect/Schedule";
12 import { AWSEnvironment } from "../Environment.ts";
13 import type { Providers } from "../Providers.ts";
14
15 /**
16 * Blue/green deployment behaviour for a deployment group. Mirrors the wire
17 * `BlueGreenDeploymentConfiguration` with `Duration.Input` wait times
18 * (CodeDeploy's wire unit for both is whole minutes).
19 */
20 export interface BlueGreenDeploymentConfigurationProps {
21 /**
22 * What happens to the original (blue) instances after a successful
23 * blue/green deployment.
24 */
25 terminateBlueInstancesOnDeploymentSuccess?: {
26 /**
27 * `TERMINATE` the blue instances (after `terminationWaitTime`) or
28 * `KEEP_ALIVE` them deregistered from the load balancer.
29 */
30 action?: codedeploy.InstanceAction;
31 /**
32 * How long to wait after a successful deployment before terminating
33 * the blue instances. Wire unit: whole minutes.
34 */
35 terminationWaitTime?: Duration.Input;
36 };
37 /**
38 * How traffic is rerouted to the green fleet once it is provisioned.
39 */
40 deploymentReadyOption?: {
41 /**
42 * `CONTINUE_DEPLOYMENT` reroutes automatically; `STOP_DEPLOYMENT`
43 * waits for {@link ContinueDeployment} (up to `waitTime`).
44 */
45 actionOnTimeout?: codedeploy.DeploymentReadyAction;
46 /**
47 * How long to wait for a manual continue before the deployment stops
48 * (only with `actionOnTimeout: "STOP_DEPLOYMENT"`). Wire unit: whole
49 * minutes.
50 */
51 waitTime?: Duration.Input;
52 };
53 /**
54 * How the green fleet's instances are provisioned (discover existing or
55 * copy the Auto Scaling group).
56 */
57 greenFleetProvisioningOption?: codedeploy.GreenFleetProvisioningOption;
58 }
59
60 /** Convert the blue/green props to the CodeDeploy wire shape (minutes). */
61 const toWireBlueGreen = (
62 props: BlueGreenDeploymentConfigurationProps | undefined,
63 ): codedeploy.BlueGreenDeploymentConfiguration | undefined =>
64 props === undefined
65 ? undefined
66 : {
67 terminateBlueInstancesOnDeploymentSuccess:
68 props.terminateBlueInstancesOnDeploymentSuccess === undefined
69 ? undefined
70 : {
71 action: props.terminateBlueInstancesOnDeploymentSuccess.action,
72 terminationWaitTimeInMinutes: toWireMinutes(
73 props.terminateBlueInstancesOnDeploymentSuccess.terminationWaitTime,
74 ),
75 },
76 deploymentReadyOption:
77 props.deploymentReadyOption === undefined
78 ? undefined
79 : {
80 actionOnTimeout: props.deploymentReadyOption.actionOnTimeout,
81 waitTimeInMinutes: toWireMinutes(props.deploymentReadyOption.waitTime),
82 },
83 greenFleetProvisioningOption: props.greenFleetProvisioningOption,
84 };
85
86 export interface DeploymentGroupProps {
87 /**
88 * Name of the CodeDeploy application that owns the group. Pass an
89 * `Application`'s `applicationName` attribute. Immutable — changing it
90 * replaces the deployment group.
91 */
92 applicationName: string;
93 /**
94 * Name of the deployment group (1-100 chars). If omitted a deterministic
95 * physical name is generated. Changing the name replaces the group.
96 */
97 deploymentGroupName?: string;
98 /**
99 * ARN of the IAM service role that grants CodeDeploy access to the target
100 * compute resources. Required.
101 */
102 serviceRoleArn: string;
103 /**
104 * Name of the deployment configuration (predefined like
105 * `CodeDeployDefault.LambdaAllAtOnce`, or a custom `DeploymentConfig`).
106 */
107 deploymentConfigName?: string;
108 /**
109 * How the deployment routes traffic (in-place vs. blue/green).
110 */
111 deploymentStyle?: codedeploy.DeploymentStyle;
112 /**
113 * Automatic rollback behaviour on deployment failure or alarm.
114 */
115 autoRollbackConfiguration?: codedeploy.AutoRollbackConfiguration;
116 /**
117 * CloudWatch alarms that can stop a deployment.
118 */
119 alarmConfiguration?: codedeploy.AlarmConfiguration;
120 /**
121 * Load-balancer configuration used for traffic shifting.
122 */
123 loadBalancerInfo?: codedeploy.LoadBalancerInfo;
124 /**
125 * Blue/green deployment configuration (green-fleet provisioning, traffic
126 * ready-options, blue-instance termination). Wait times accept
127 * `Duration.Input` (e.g. `"5 minutes"`).
128 */
129 blueGreenDeploymentConfiguration?: BlueGreenDeploymentConfigurationProps;
130 /**
131 * EC2 tag filters selecting the instances to deploy to (EC2/on-prem
132 * `Server` platform).
133 */
134 ec2TagFilters?: codedeploy.EC2TagFilter[];
135 /**
136 * Auto Scaling group names to deploy to (EC2/on-prem `Server` platform).
137 */
138 autoScalingGroups?: string[];
139 /**
140 * ECS services (cluster + service) targeted by blue/green ECS deployments.
141 */
142 ecsServices?: codedeploy.ECSService[];
143 /**
144 * SNS/notification triggers fired on deployment lifecycle events.
145 */
146 triggerConfigurations?: codedeploy.TriggerConfig[];
147 /**
148 * User-defined tags.
149 */
150 tags?: Record<string, string>;
151 }
152
153 export interface DeploymentGroup extends Resource<
154 "AWS.CodeDeploy.DeploymentGroup",
155 DeploymentGroupProps,
156 {
157 /** Physical name of the deployment group. */
158 deploymentGroupName: string;
159 /** Unique CodeDeploy-assigned deployment-group ID. */
160 deploymentGroupId: string;
161 /** ARN of the deployment group. */
162 deploymentGroupArn: string;
163 /** Name of the application this group belongs to. */
164 applicationName: string;
165 /** ARN of the service role CodeDeploy assumes for deployments. */
166 serviceRoleArn: string;
167 },
168 never,
169 Providers
170 > {}
171
172 /**
173 * An AWS CodeDeploy deployment group — the set of target instances/functions
174 * plus the deployment configuration for one {@link Application}. For the
175 * `Lambda` compute platform a group ties a service role and a deployment
176 * config (e.g. `CodeDeployDefault.LambdaAllAtOnce`) to an application.
177 *
178 * ### Creating a Deployment Group
179 * **Example:** Lambda Deployment Group
180 * ```typescript
181 * const app = yield* CodeDeploy.Application("api", { computePlatform: "Lambda" });
182 * const group = yield* CodeDeploy.DeploymentGroup("prod", {
183 * applicationName: app.applicationName,
184 * serviceRoleArn: role.roleArn,
185 * deploymentConfigName: "CodeDeployDefault.LambdaAllAtOnce",
186 * deploymentStyle: {
187 * deploymentType: "BLUE_GREEN",
188 * deploymentOption: "WITH_TRAFFIC_CONTROL",
189 * },
190 * autoRollbackConfiguration: {
191 * enabled: true,
192 * events: ["DEPLOYMENT_FAILURE"],
193 * },
194 * });
195 * ```
196 *
197 * @resource
198 */
199 export const DeploymentGroup = Resource<DeploymentGroup>("AWS.CodeDeploy.DeploymentGroup");
200
201 /** Build the ARN for a CodeDeploy deployment group. */
202 const deploymentGroupArn = (
203 region: string,
204 account: string,
205 appName: string,
206 groupName: string,
207 ): string => `arn:aws:codedeploy:${region}:${account}:deploymentgroup:${appName}/${groupName}`;
208
209 /**
210 * Retry an effect while CodeDeploy reports that it cannot yet assume the
211 * service role. A freshly-created IAM role's trust relationship is eventually
212 * consistent, so `InvalidRoleException` immediately after role creation is a
213 * transient propagation error, not a permanent failure. Wrapped in an
214 * explicitly-typed helper so the retry's conditional type never widens the
215 * provider layer in declaration emit (see PATTERNS §7).
216 */
217 const retryThroughRolePropagation = <A, E extends { _tag: string }, R>(
218 effect: Effect.Effect<A, E, R>,
219 ): Effect.Effect<A, E, R> =>
220 effect.pipe(
221 Effect.retry({
222 while: (e: E) => e._tag === "InvalidRoleException",
223 schedule: Schedule.max([Schedule.fixed(2000), Schedule.recurs(15)]),
224 }),
225 );
226
227 /** Convert a CodeDeploy wire tag list into a plain record. */
228 const toTagRecord = (
229 tags: ReadonlyArray<{ Key?: string; Value?: string }> | undefined,
230 ): Record<string, string> =>
231 Object.fromEntries(
232 (tags ?? [])
233 .filter(
234 (tag): tag is { Key: string; Value: string } =>
235 typeof tag.Key === "string" && typeof tag.Value === "string",
236 )
237 .map((tag) => [tag.Key, tag.Value]),
238 );
239
240 export const DeploymentGroupProvider = () =>
241 Provider.effect(
242 DeploymentGroup,
243 Effect.gen(function* () {
244 const toName = (id: string, props: Partial<DeploymentGroupProps>) =>
245 props.deploymentGroupName
246 ? Effect.succeed(props.deploymentGroupName)
247 : createPhysicalName({ id, maxLength: 100 });
248
249 const getGroup = Effect.fn(function* (appName: string, groupName: string) {
250 const response = yield* codedeploy
251 .getDeploymentGroup({
252 applicationName: appName,
253 deploymentGroupName: groupName,
254 })
255 .pipe(
256 Effect.catchTag(
257 ["DeploymentGroupDoesNotExistException", "ApplicationDoesNotExistException"],
258 () => Effect.undefined,
259 ),
260 );
261 return response?.deploymentGroupInfo;
262 });
263
264 const syncTags = Effect.fn(function* (arn: string, desiredTags: Record<string, string>) {
265 const observed = yield* codedeploy
266 .listTagsForResource({ ResourceArn: arn })
267 .pipe(Effect.orElseSucceed(() => undefined));
268 const { removed, upsert } = diffTags(toTagRecord(observed?.Tags), desiredTags);
269 if (upsert.length > 0) {
270 yield* codedeploy.tagResource({ ResourceArn: arn, Tags: upsert });
271 }
272 if (removed.length > 0) {
273 yield* codedeploy.untagResource({
274 ResourceArn: arn,
275 TagKeys: removed,
276 });
277 }
278 });
279
280 return {
281 stables: ["deploymentGroupName", "deploymentGroupId", "applicationName"],
282
283 diff: Effect.fn(function* ({ id, olds, news }) {
284 if (!isResolved(news)) return undefined;
285 if ((yield* toName(id, olds ?? {})) !== (yield* toName(id, news ?? {}))) {
286 return { action: "replace" } as const;
287 }
288 // The parent application is immutable — replace on change.
289 if ((news?.applicationName ?? "") !== (olds?.applicationName ?? "")) {
290 return { action: "replace" } as const;
291 }
292 }),
293
294 read: Effect.fn(function* ({ id, olds, output }) {
295 const { accountId, region } = yield* AWSEnvironment.current;
296 const appName = output?.applicationName ?? olds?.applicationName;
297 if (appName === undefined) return undefined;
298 const name = output?.deploymentGroupName ?? (yield* toName(id, olds ?? {}));
299 const group = yield* getGroup(appName, name);
300 if (group?.deploymentGroupId === undefined) return undefined;
301 const arn = deploymentGroupArn(region, accountId, appName, name);
302 const attrs = {
303 deploymentGroupName: group.deploymentGroupName ?? name,
304 deploymentGroupId: group.deploymentGroupId,
305 deploymentGroupArn: arn,
306 applicationName: group.applicationName ?? appName,
307 serviceRoleArn: group.serviceRoleArn ?? "",
308 };
309 const tags = yield* codedeploy.listTagsForResource({ ResourceArn: arn }).pipe(
310 Effect.map((res) => toTagRecord(res.Tags)),
311 Effect.orElseSucceed(() => ({})),
312 );
313 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
314 }),
315
316 reconcile: Effect.fn(function* ({ id, news, output, session }) {
317 const { accountId, region } = yield* AWSEnvironment.current;
318 const appName = news.applicationName;
319 const name = output?.deploymentGroupName ?? (yield* toName(id, news));
320 const arn = deploymentGroupArn(region, accountId, appName, name);
321 const internalTags = yield* createInternalTags(id);
322 const desiredTags = { ...internalTags, ...news.tags };
323
324 // 1. Observe — cloud state is authoritative.
325 let group = yield* getGroup(appName, name);
326
327 // 2. Ensure — create if missing; otherwise converge via update.
328 if (group?.deploymentGroupId === undefined) {
329 yield* retryThroughRolePropagation(
330 codedeploy.createDeploymentGroup({
331 applicationName: appName,
332 deploymentGroupName: name,
333 serviceRoleArn: news.serviceRoleArn,
334 deploymentConfigName: news.deploymentConfigName,
335 deploymentStyle: news.deploymentStyle,
336 autoRollbackConfiguration: news.autoRollbackConfiguration,
337 alarmConfiguration: news.alarmConfiguration,
338 loadBalancerInfo: news.loadBalancerInfo,
339 blueGreenDeploymentConfiguration: toWireBlueGreen(
340 news.blueGreenDeploymentConfiguration,
341 ),
342 ec2TagFilters: news.ec2TagFilters,
343 autoScalingGroups: news.autoScalingGroups,
344 ecsServices: news.ecsServices,
345 triggerConfigurations: news.triggerConfigurations,
346 tags: Object.entries(desiredTags).map(([Key, Value]) => ({
347 Key,
348 Value,
349 })),
350 }),
351 ).pipe(
352 Effect.catchTag("DeploymentGroupAlreadyExistsException", () => Effect.undefined),
353 );
354 group = yield* getGroup(appName, name);
355 } else {
356 // 3. Sync — converge mutable configuration in place.
357 yield* codedeploy.updateDeploymentGroup({
358 applicationName: appName,
359 currentDeploymentGroupName: name,
360 serviceRoleArn: news.serviceRoleArn,
361 deploymentConfigName: news.deploymentConfigName,
362 deploymentStyle: news.deploymentStyle,
363 autoRollbackConfiguration: news.autoRollbackConfiguration,
364 alarmConfiguration: news.alarmConfiguration,
365 loadBalancerInfo: news.loadBalancerInfo,
366 blueGreenDeploymentConfiguration: toWireBlueGreen(
367 news.blueGreenDeploymentConfiguration,
368 ),
369 ec2TagFilters: news.ec2TagFilters,
370 autoScalingGroups: news.autoScalingGroups,
371 ecsServices: news.ecsServices,
372 triggerConfigurations: news.triggerConfigurations,
373 });
374 group = yield* getGroup(appName, name);
375 }
376
377 // 3b. Sync tags — diff against OBSERVED cloud tags.
378 yield* syncTags(arn, desiredTags);
379
380 // 4. Return fresh attributes.
381 yield* session.note(name);
382 return {
383 deploymentGroupName: group?.deploymentGroupName ?? name,
384 deploymentGroupId: group?.deploymentGroupId ?? "",
385 deploymentGroupArn: arn,
386 applicationName: group?.applicationName ?? appName,
387 serviceRoleArn: group?.serviceRoleArn ?? news.serviceRoleArn,
388 };
389 }),
390
391 delete: Effect.fn(function* ({ output, olds }) {
392 const appName = output.applicationName || olds?.applicationName;
393 if (appName === undefined) return;
394 // DeleteDeploymentGroup is idempotent — deleting a non-existent
395 // group (or one under a deleted application) succeeds; its typed
396 // error union has no not-found variants.
397 yield* codedeploy.deleteDeploymentGroup({
398 applicationName: appName,
399 deploymentGroupName: output.deploymentGroupName,
400 });
401 }),
402
403 // Deployment groups are scoped to an application; there is no global
404 // enumeration without knowing the application name.
405 list: () => Effect.succeed([]),
406 };
407 }),
408 );