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

main
ts 166 lines 6.45 KB
Raw
1 import * as logs from "@distilled.cloud/aws/cloudwatch-logs";
2 import * as imagebuilder from "@distilled.cloud/aws/imagebuilder";
3 import { deepEqual, isResolved } from "alchemy/Diff";
4 import type { Input } from "alchemy/Input";
5 import * as Output from "alchemy/Output";
6 import { diffTags } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Option from "effect/Option";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import { AWSEnvironment } from "../Environment.ts";
12
13 /**
14 * Plan-time replacement check for immutable Image Builder versions
15 * (components, image recipes). `news` may still carry unresolved Outputs
16 * at plan time — e.g. the build-version ARN of a component being replaced
17 * in the same deploy — so compare per key and skip only the keys that are
18 * unresolved. A resolved change on an immutable key (like a
19 * `semanticVersion` bump) must still plan a replacement; drift hidden
20 * behind an unresolved key is caught by the provider's reconcile
21 * immutability guard.
22 */
23 export const immutableVersionKeysChanged = <Props extends object>(
24 olds: Props,
25 news: Input<Props>,
26 keys: readonly (keyof Props)[],
27 ): boolean => {
28 // The whole props object itself may be an unresolved expression — no
29 // per-key comparison is possible; defer to the reconcile guard.
30 if (Output.isExpr(news) || Effect.isEffect(news)) return false;
31 const desired = news as { [K in keyof Props]: Input<Props[K]> };
32 return keys.some((key) => {
33 const value = desired[key];
34 return isResolved(value) && !deepEqual(olds[key], value);
35 });
36 };
37
38 /**
39 * Image Builder rejects deletion of a resource that another resource still
40 * references (e.g. a component referenced by a not-yet-deleted recipe, or a
41 * recipe referenced by a pipeline) with `ResourceDependencyException`.
42 * During a replacement the engine deletes the displaced resources without
43 * ordering guarantees, so retry through the window while the dependents are
44 * deleted (bounded).
45 */
46 export const retryWhileDependedOn = <A, E extends { _tag: string }, R>(
47 self: Effect.Effect<A, E, R>,
48 ): Effect.Effect<A, E, R> =>
49 Effect.retry(self, {
50 while: (e) => e._tag === "ResourceDependencyException",
51 schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(12)]),
52 });
53
54 /**
55 * Delete one exact CloudWatch log group that Image Builder auto-created for
56 * an Alchemy-owned recipe or pipeline. Callers derive the name from their
57 * owned resource output; this helper never scans or deletes by broad prefix.
58 */
59 export const deleteImageBuilderLogGroup = Effect.fn(function* (logGroupName: string) {
60 yield* logs.deleteLogGroup({ logGroupName }).pipe(
61 Effect.retry({
62 while: (error) =>
63 error._tag === "OperationAbortedException" || error._tag === "ServiceUnavailableException",
64 schedule: Schedule.max([Schedule.fixed("500 millis"), Schedule.recurs(10)]),
65 }),
66 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
67 );
68
69 for (let attempt = 0; attempt < 20; attempt++) {
70 const present = yield* logs.describeLogGroups.items({ logGroupNamePrefix: logGroupName }).pipe(
71 Stream.filter((group) => group.logGroupName === logGroupName),
72 Stream.runHead,
73 Effect.map(Option.isSome),
74 );
75 if (!present) return;
76 yield* Effect.sleep("500 millis");
77 }
78 return yield* Effect.die(
79 new Error(
80 `Image Builder log group ${logGroupName} remained observable 10 seconds after delete`,
81 ),
82 );
83 });
84
85 /**
86 * Convert an Image Builder wire tag map (values may be undefined) into a
87 * plain string record.
88 */
89 export const toTagRecord = (
90 tags: { [key: string]: string | undefined } | undefined,
91 ): Record<string, string> =>
92 Object.fromEntries(
93 Object.entries(tags ?? {}).filter(
94 (entry): entry is [string, string] => typeof entry[1] === "string",
95 ),
96 );
97
98 /**
99 * Read the observed tags of an Image Builder resource. Tag reads are
100 * best-effort — a failure (e.g. a race with deletion) reports no tags.
101 */
102 export const readImageBuilderTags = Effect.fn(function* (arn: string) {
103 const response = yield* imagebuilder
104 .listTagsForResource({ resourceArn: arn })
105 .pipe(Effect.orElseSucceed(() => undefined));
106 return toTagRecord(response?.tags);
107 });
108
109 /**
110 * Sync tags on an Image Builder resource: diff the OBSERVED cloud tags
111 * against the desired set and apply only the delta.
112 */
113 export const syncImageBuilderTags = Effect.fn(function* (
114 arn: string,
115 desiredTags: Record<string, string>,
116 ) {
117 const observedTags = yield* readImageBuilderTags(arn);
118 const { removed, upsert } = diffTags(observedTags, desiredTags);
119 if (upsert.length > 0) {
120 yield* imagebuilder.tagResource({
121 resourceArn: arn,
122 tags: Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value])),
123 });
124 }
125 if (removed.length > 0) {
126 yield* imagebuilder.untagResource({ resourceArn: arn, tagKeys: removed });
127 }
128 });
129
130 /**
131 * Construct the deterministic ARN of an Image Builder resource in the
132 * ambient account/region. Image Builder lowercases resource names in ARNs.
133 *
134 * @param resourceType e.g. `image-recipe`, `infrastructure-configuration`
135 * @param resourcePath the name (plus `/{version}` segments where relevant)
136 */
137 export const imageBuilderArn = Effect.fn(function* (resourceType: string, resourcePath: string) {
138 const { accountId, region } = yield* AWSEnvironment.current;
139 return `arn:aws:imagebuilder:${region}:${accountId}:${resourceType}/${resourcePath.toLowerCase()}`;
140 });
141
142 /**
143 * Structural drift check between the desired value the user specified and
144 * the observed cloud value. `undefined` desired values are "unspecified"
145 * (no drift — the service fills defaults we must not fight). Objects are
146 * compared as subsets: every key the user specified must match; extra
147 * observed keys (server defaults) are ignored. Arrays compare length +
148 * element-wise.
149 */
150 export const driftedFrom = (observed: unknown, desired: unknown): boolean => {
151 if (desired === undefined) return false;
152 if (observed === undefined) return true;
153 if (Array.isArray(desired)) {
154 if (!Array.isArray(observed) || observed.length !== desired.length) {
155 return true;
156 }
157 return desired.some((item, index) => driftedFrom(observed[index], item));
158 }
159 if (typeof desired === "object" && desired !== null) {
160 if (typeof observed !== "object" || observed === null) return true;
161 return Object.entries(desired).some(([key, value]) =>
162 driftedFrom((observed as Record<string, unknown>)[key], value),
163 );
164 }
165 return observed !== desired;
166 };