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

main
ts 288 lines 10.9 KB
Raw
1 import * as redshift from "@distilled.cloud/aws/redshift";
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 * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Schedule from "effect/Schedule";
11 import * as Stream from "effect/Stream";
12 import type { SubnetId } from "../EC2/Subnet.ts";
13 import { AWSEnvironment } from "../Environment.ts";
14 import type { Providers } from "../Providers.ts";
15 import { applyRedshiftTagDelta, redshiftArn, sameStringSet, toTagRecord } from "./internal.ts";
16
17 export class ClusterSubnetGroupUnexpectedResponse extends Data.TaggedError(
18 "ClusterSubnetGroupUnexpectedResponse",
19 )<{
20 readonly message: string;
21 readonly cause?: unknown;
22 }> {}
23
24 export interface ClusterSubnetGroupProps {
25 /**
26 * Name of the cluster subnet group. Must contain no more than 255
27 * lowercase alphanumeric characters or hyphens and must not be `default`.
28 * If omitted, a deterministic physical name is generated. Changing the
29 * name replaces the subnet group.
30 */
31 clusterSubnetGroupName?: string;
32 /**
33 * Human-readable description of the subnet group.
34 * @default "Managed by Alchemy"
35 */
36 description?: string;
37 /**
38 * VPC subnet IDs the subnet group spans. Redshift places cluster nodes
39 * into these subnets; span at least two Availability Zones so the cluster
40 * can relocate during maintenance.
41 */
42 subnetIds: SubnetId[];
43 /**
44 * User-defined tags for the subnet group.
45 */
46 tags?: Record<string, string>;
47 }
48
49 export interface ClusterSubnetGroup extends Resource<
50 "AWS.Redshift.ClusterSubnetGroup",
51 ClusterSubnetGroupProps,
52 {
53 /**
54 * Name of the subnet group.
55 */
56 clusterSubnetGroupName: string;
57 /**
58 * ARN of the subnet group.
59 */
60 clusterSubnetGroupArn: string;
61 /**
62 * Description of the subnet group.
63 */
64 description: string | undefined;
65 /**
66 * ID of the VPC the subnets belong to.
67 */
68 vpcId: string | undefined;
69 /**
70 * IDs of the subnets in the group.
71 */
72 subnetIds: string[];
73 /**
74 * Status of the subnet group (e.g. `"Complete"`).
75 */
76 subnetGroupStatus: string | undefined;
77 /**
78 * Tags on the subnet group (including internal Alchemy tags).
79 */
80 tags: Record<string, string>;
81 },
82 never,
83 Providers
84 > {}
85
86 /**
87 * An Amazon Redshift cluster subnet group — the set of VPC subnets a
88 * provisioned Redshift cluster's nodes are placed into.
89 *
90 * Subnet groups are free and provision instantly. A {@link Cluster}
91 * references one by name via `clusterSubnetGroupName`.
92 * ### Creating a Cluster Subnet Group
93 * **Example:** Subnet Group Spanning Two Subnets
94 * ```typescript
95 * const subnetGroup = yield* Redshift.ClusterSubnetGroup("WarehouseSubnets", {
96 * description: "Subnets for the analytics warehouse",
97 * subnetIds: [subnetA.subnetId, subnetB.subnetId],
98 * });
99 * ```
100 * **Example:** Tagged Subnet Group
101 * ```typescript
102 * const subnetGroup = yield* Redshift.ClusterSubnetGroup("WarehouseSubnets", {
103 * subnetIds: [subnetA.subnetId, subnetB.subnetId],
104 * tags: { team: "analytics" },
105 * });
106 * ```
107 *
108 * @resource
109 */
110 export const ClusterSubnetGroup = Resource<ClusterSubnetGroup>("AWS.Redshift.ClusterSubnetGroup");
111
112 /**
113 * Retry an effect while the subnet group is still held by a cluster that is
114 * mid-deletion (`InvalidClusterSubnetGroupStateFault`), bounded to ~10
115 * minutes — a Redshift cluster releases its subnet group only once its own
116 * deletion completes, several minutes after `deleteCluster` returns.
117 *
118 * Expressed as an explicitly-typed module-scope helper: inlining
119 * `Effect.retry` in a lifecycle operation leaves `Retry.Return`'s
120 * conditional type unresolved in the provider's inferred layer type, which
121 * declaration emit widens to an `unknown` R — poisoning `AWS.providers()`
122 * for every downstream consumer.
123 */
124 const retryWhileSubnetGroupInUse = <A, E extends { _tag: string }, R>(
125 self: Effect.Effect<A, E, R>,
126 ): Effect.Effect<A, E, R> =>
127 Effect.retry(self, {
128 while: (e) => e._tag === "InvalidClusterSubnetGroupStateFault",
129 schedule: Schedule.max([Schedule.fixed("15 seconds"), Schedule.recurs(40)]),
130 });
131
132 export const ClusterSubnetGroupProvider = () =>
133 Provider.effect(
134 ClusterSubnetGroup,
135 Effect.gen(function* () {
136 const toName = (id: string, props: Partial<ClusterSubnetGroupProps>) =>
137 props.clusterSubnetGroupName
138 ? Effect.succeed(props.clusterSubnetGroupName)
139 : createPhysicalName({ id, maxLength: 255, lowercase: true });
140
141 const readGroup = Effect.fn(function* (name: string) {
142 const response = yield* redshift
143 .describeClusterSubnetGroups({ ClusterSubnetGroupName: name })
144 .pipe(Effect.catchTag("ClusterSubnetGroupNotFoundFault", () => Effect.undefined));
145 return response?.ClusterSubnetGroups?.[0];
146 });
147
148 const toAttrs = Effect.fn(function* (group: redshift.ClusterSubnetGroup) {
149 const { accountId, region } = yield* AWSEnvironment.current;
150 if (!group.ClusterSubnetGroupName) {
151 return yield* new ClusterSubnetGroupUnexpectedResponse({
152 message: "Cluster subnet group is missing its name",
153 });
154 }
155 return {
156 clusterSubnetGroupName: group.ClusterSubnetGroupName,
157 clusterSubnetGroupArn: redshiftArn(
158 region,
159 accountId,
160 "subnetgroup",
161 group.ClusterSubnetGroupName,
162 ),
163 description: group.Description,
164 vpcId: group.VpcId,
165 subnetIds: (group.Subnets ?? []).flatMap((subnet) =>
166 subnet.SubnetIdentifier ? [subnet.SubnetIdentifier] : [],
167 ),
168 subnetGroupStatus: group.SubnetGroupStatus,
169 tags: toTagRecord(group.Tags),
170 };
171 });
172
173 return {
174 stables: ["clusterSubnetGroupName", "clusterSubnetGroupArn", "vpcId"],
175
176 diff: Effect.fn(function* ({ id, olds, news }) {
177 if (!isResolved(news)) return undefined;
178 if ((yield* toName(id, olds ?? {})) !== (yield* toName(id, news ?? {}))) {
179 return { action: "replace" } as const;
180 }
181 }),
182
183 read: Effect.fn(function* ({ id, olds, output }) {
184 const name = output?.clusterSubnetGroupName ?? (yield* toName(id, olds ?? {}));
185 const group = yield* readGroup(name);
186 if (!group?.ClusterSubnetGroupName) return undefined;
187 const attrs = yield* toAttrs(group);
188 return (yield* hasAlchemyTags(id, attrs.tags)) ? attrs : Unowned(attrs);
189 }),
190
191 reconcile: Effect.fn(function* ({ id, news, output, session }) {
192 const name = output?.clusterSubnetGroupName ?? (yield* toName(id, news));
193 const internalTags = yield* createInternalTags(id);
194 const desiredTags = { ...internalTags, ...news.tags };
195 const description = news.description ?? "Managed by Alchemy";
196
197 // 1. Observe — cloud state is authoritative.
198 let observed = yield* readGroup(name);
199
200 // 2. Ensure — create if missing; tolerate AlreadyExists as a race
201 // with a peer reconciler by re-reading.
202 if (!observed?.ClusterSubnetGroupName) {
203 yield* redshift
204 .createClusterSubnetGroup({
205 ClusterSubnetGroupName: name,
206 Description: description,
207 SubnetIds: news.subnetIds,
208 Tags: Object.entries(desiredTags).map(([Key, Value]) => ({
209 Key,
210 Value,
211 })),
212 })
213 .pipe(Effect.catchTag("ClusterSubnetGroupAlreadyExistsFault", () => Effect.void));
214 observed = yield* readGroup(name);
215 if (!observed?.ClusterSubnetGroupName) {
216 return yield* new ClusterSubnetGroupUnexpectedResponse({
217 message: `Failed to create cluster subnet group '${name}'`,
218 });
219 }
220 }
221
222 // 3. Sync — diff OBSERVED description/subnets against desired;
223 // modifyClusterSubnetGroup replaces the whole subnet list.
224 const observedSubnets = (observed.Subnets ?? []).flatMap((subnet) =>
225 subnet.SubnetIdentifier ? [subnet.SubnetIdentifier] : [],
226 );
227 if (
228 observed.Description !== description ||
229 !sameStringSet(observedSubnets, news.subnetIds)
230 ) {
231 yield* redshift.modifyClusterSubnetGroup({
232 ClusterSubnetGroupName: name,
233 Description: description,
234 SubnetIds: news.subnetIds,
235 });
236 observed = yield* readGroup(name);
237 if (!observed?.ClusterSubnetGroupName) {
238 return yield* new ClusterSubnetGroupUnexpectedResponse({
239 message: `Cluster subnet group '${name}' not found after update`,
240 });
241 }
242 }
243
244 // 3b. Sync tags — diff against OBSERVED cloud tags (describe
245 // surfaces them inline).
246 const { accountId, region } = yield* AWSEnvironment.current;
247 const arn = redshiftArn(region, accountId, "subnetgroup", name);
248 const { removed, upsert } = diffTags(toTagRecord(observed.Tags), desiredTags);
249 yield* applyRedshiftTagDelta({ arn, upsert, removed });
250
251 yield* session.note(arn);
252 const attrs = yield* toAttrs(observed);
253 return { ...attrs, tags: desiredTags };
254 }),
255
256 delete: Effect.fn(function* ({ output }) {
257 // A cluster deleting out of this group holds it until the
258 // cluster's own deletion completes — retry through that window.
259 yield* retryWhileSubnetGroupInUse(
260 redshift
261 .deleteClusterSubnetGroup({
262 ClusterSubnetGroupName: output.clusterSubnetGroupName,
263 })
264 .pipe(Effect.catchTag("ClusterSubnetGroupNotFoundFault", () => Effect.undefined)),
265 );
266 }),
267
268 list: () =>
269 // Top-level account/region collection: exhaustively paginate
270 // describeClusterSubnetGroups; tags come inline on each group.
271 redshift.describeClusterSubnetGroups.pages({}).pipe(
272 Stream.runCollect,
273 Effect.map((chunk) =>
274 Array.from(chunk).flatMap((page) =>
275 (page.ClusterSubnetGroups ?? []).filter(
276 (group) =>
277 group.ClusterSubnetGroupName !== undefined &&
278 // `default` is auto-created by Redshift for the default
279 // VPC — never ours, never census/nuke it.
280 group.ClusterSubnetGroupName !== "default",
281 ),
282 ),
283 ),
284 Effect.flatMap(Effect.forEach((group) => toAttrs(group), { concurrency: 4 })),
285 ),
286 };
287 }),
288 );