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

main
ts 238 lines 8.55 KB
Raw
1 import * as memorydb from "@distilled.cloud/aws/memorydb";
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 { Providers } from "../Providers.ts";
13 import { readMemoryDbTags, sameStringSet } from "./internal.ts";
14
15 export class MemoryDBSubnetGroupUnexpectedResponse extends Data.TaggedError(
16 "MemoryDBSubnetGroupUnexpectedResponse",
17 )<{
18 readonly message: string;
19 readonly cause?: unknown;
20 }> {}
21
22 export interface SubnetGroupProps {
23 /**
24 * Name of the subnet group. Must be 1-40 characters. If omitted, a
25 * deterministic physical name is generated. Changing the name replaces the
26 * subnet group.
27 */
28 subnetGroupName?: string;
29 /**
30 * Human-readable description of the subnet group.
31 */
32 description?: string;
33 /**
34 * VPC subnet IDs the subnet group spans. MemoryDB places cluster nodes into
35 * these subnets, so they should cover at least two Availability Zones for a
36 * multi-AZ cluster.
37 */
38 subnetIds: string[];
39 /**
40 * User-defined tags for the subnet group.
41 */
42 tags?: Record<string, string>;
43 }
44
45 export interface SubnetGroup extends Resource<
46 "AWS.MemoryDB.SubnetGroup",
47 SubnetGroupProps,
48 {
49 /** Name of the subnet group. */
50 subnetGroupName: string;
51 /** ARN of the subnet group. */
52 subnetGroupArn: string;
53 /** Description of the subnet group. */
54 description: string | undefined;
55 /** ID of the VPC the subnets belong to. */
56 vpcId: string | undefined;
57 /** IDs of the subnets in the group. */
58 subnetIds: string[];
59 /** Tags on the subnet group (user + internal Alchemy tags). */
60 tags: Record<string, string>;
61 },
62 never,
63 Providers
64 > {}
65
66 /**
67 * A MemoryDB subnet group — the set of VPC subnets a MemoryDB cluster's nodes
68 * are placed into.
69 *
70 * Subnet groups are free and provision instantly. A cluster references one by
71 * name via `subnetGroupName`.
72 * ### Creating a Subnet Group
73 * **Example:** Subnet Group Spanning Two Subnets
74 * ```typescript
75 * const subnetGroup = yield* SubnetGroup("CacheSubnets", {
76 * description: "MemoryDB cluster subnets",
77 * subnetIds: [subnetA.subnetId, subnetB.subnetId],
78 * });
79 * ```
80 *
81 * @resource
82 */
83 export const SubnetGroup = Resource<SubnetGroup>("AWS.MemoryDB.SubnetGroup");
84
85 export const SubnetGroupProvider = () =>
86 Provider.effect(
87 SubnetGroup,
88 Effect.gen(function* () {
89 const toName = (id: string, props: SubnetGroupProps) =>
90 props.subnetGroupName
91 ? Effect.succeed(props.subnetGroupName)
92 : createPhysicalName({ id, maxLength: 40, lowercase: true });
93
94 const readGroup = Effect.fn(function* (name: string) {
95 const response = yield* memorydb
96 .describeSubnetGroups({ SubnetGroupName: name })
97 .pipe(Effect.catchTag("SubnetGroupNotFoundFault", () => Effect.undefined));
98 return response?.SubnetGroups?.[0];
99 });
100
101 const toAttrs = Effect.fn(function* (group: memorydb.SubnetGroup) {
102 if (!group.Name || !group.ARN) {
103 return yield* new MemoryDBSubnetGroupUnexpectedResponse({
104 message: `Subnet group '${group.Name}' is missing its ARN`,
105 });
106 }
107 return {
108 subnetGroupName: group.Name,
109 subnetGroupArn: group.ARN,
110 description: group.Description,
111 vpcId: group.VpcId,
112 subnetIds: (group.Subnets ?? [])
113 .map((s) => s.Identifier)
114 .filter((id): id is string => id !== undefined),
115 tags: yield* readMemoryDbTags(group.ARN),
116 };
117 });
118
119 return {
120 stables: ["subnetGroupName", "subnetGroupArn"],
121
122 diff: Effect.fn(function* ({ id, olds, news }) {
123 if (!isResolved(news)) return undefined;
124 if (
125 (yield* toName(id, olds ?? { subnetIds: [] })) !==
126 (yield* toName(id, news ?? { subnetIds: [] }))
127 ) {
128 return { action: "replace" } as const;
129 }
130 }),
131
132 read: Effect.fn(function* ({ id, olds, output }) {
133 const name = output?.subnetGroupName ?? (yield* toName(id, olds ?? { subnetIds: [] }));
134 const group = yield* readGroup(name);
135 if (!group?.ARN) return undefined;
136 const attrs = yield* toAttrs(group);
137 return (yield* hasAlchemyTags(id, attrs.tags)) ? attrs : Unowned(attrs);
138 }),
139
140 reconcile: Effect.fn(function* ({ id, news, output, session }) {
141 const props = news ?? { subnetIds: [] };
142 const name = output?.subnetGroupName ?? (yield* toName(id, props));
143 const internalTags = yield* createInternalTags(id);
144 const desiredTags = { ...internalTags, ...props.tags };
145
146 // 1. Observe — cloud state is authoritative.
147 let observed = yield* readGroup(name);
148
149 // 2. Ensure — create if missing; tolerate AlreadyExists as a race.
150 if (observed === undefined) {
151 yield* memorydb
152 .createSubnetGroup({
153 SubnetGroupName: name,
154 Description: props.description,
155 SubnetIds: props.subnetIds,
156 Tags: Object.entries(desiredTags).map(([Key, Value]) => ({
157 Key,
158 Value,
159 })),
160 })
161 .pipe(Effect.catchTag("SubnetGroupAlreadyExistsFault", () => Effect.void));
162 observed = yield* readGroup(name);
163 }
164 if (observed === undefined) {
165 return yield* new MemoryDBSubnetGroupUnexpectedResponse({
166 message: `Subnet group '${name}' not found after create`,
167 });
168 }
169
170 // 3. Sync — apply description / subnet delta from OBSERVED state.
171 const update: memorydb.UpdateSubnetGroupRequest = {
172 SubnetGroupName: name,
173 };
174 let mutated = false;
175 if (props.description !== undefined && props.description !== observed.Description) {
176 update.Description = props.description;
177 mutated = true;
178 }
179 const observedSubnets = (observed.Subnets ?? [])
180 .map((s) => s.Identifier)
181 .filter((s): s is string => s !== undefined);
182 if (!sameStringSet(props.subnetIds, observedSubnets)) {
183 update.SubnetIds = props.subnetIds;
184 mutated = true;
185 }
186 if (mutated) {
187 const response = yield* memorydb.updateSubnetGroup(update);
188 observed = response.SubnetGroup ?? observed;
189 }
190
191 // 3b. Sync tags — diff against OBSERVED cloud tags.
192 const arn = observed.ARN;
193 if (arn) {
194 const observedTags = yield* readMemoryDbTags(arn);
195 const { removed, upsert } = diffTags(observedTags, desiredTags);
196 if (upsert.length > 0) {
197 yield* memorydb.tagResource({ ResourceArn: arn, Tags: upsert });
198 }
199 if (removed.length > 0) {
200 yield* memorydb.untagResource({
201 ResourceArn: arn,
202 TagKeys: removed,
203 });
204 }
205 }
206
207 yield* session.note(name);
208 return yield* toAttrs(observed);
209 }),
210
211 delete: Effect.fn(function* ({ output }) {
212 // A subnet group still attached to a cluster rejects deletion with
213 // SubnetGroupInUseFault — retry (bounded) while the cluster releases
214 // it. NotFound is success (idempotent delete).
215 yield* memorydb.deleteSubnetGroup({ SubnetGroupName: output.subnetGroupName }).pipe(
216 Effect.catchTag("SubnetGroupNotFoundFault", () => Effect.void),
217 Effect.retry({
218 while: (e) => e._tag === "SubnetGroupInUseFault",
219 schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(12)]),
220 }),
221 );
222 }),
223
224 list: () =>
225 memorydb.describeSubnetGroups.pages({}).pipe(
226 Stream.runCollect,
227 Effect.map((chunk) =>
228 Array.from(chunk).flatMap((page) =>
229 (page.SubnetGroups ?? []).filter(
230 (group) => group.Name !== undefined && group.ARN !== undefined,
231 ),
232 ),
233 ),
234 Effect.flatMap(Effect.forEach((group) => toAttrs(group), { concurrency: 4 })),
235 ),
236 };
237 }),
238 );