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

main
ts 243 lines 9.28 KB
Raw
1 import * as neptune from "@distilled.cloud/aws/neptune";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, diffTags } from "alchemy/Tags";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import type { SubnetId } from "../EC2/Subnet.ts";
11 import type { Providers } from "../Providers.ts";
12
13 export class NeptuneDBSubnetGroupUnexpectedResponse extends Data.TaggedError(
14 "NeptuneDBSubnetGroupUnexpectedResponse",
15 )<{
16 readonly message: string;
17 readonly cause?: unknown;
18 }> {}
19
20 export interface DBSubnetGroupProps {
21 /**
22 * Name of the DB subnet group. If omitted, a deterministic name is generated.
23 */
24 dbSubnetGroupName?: string;
25 /**
26 * Description for the subnet group.
27 * @default "Managed by Alchemy"
28 */
29 description?: string;
30 /**
31 * Subnets the Neptune cluster may use. Must span at least two
32 * Availability Zones.
33 */
34 subnetIds: SubnetId[];
35 /**
36 * User-defined tags for the subnet group.
37 */
38 tags?: Record<string, string>;
39 }
40
41 export interface DBSubnetGroup extends Resource<
42 "AWS.Neptune.DBSubnetGroup",
43 DBSubnetGroupProps,
44 {
45 /** Name of the subnet group. */
46 dbSubnetGroupName: string;
47 /** ARN of the subnet group. */
48 dbSubnetGroupArn: string | undefined;
49 /** ID of the VPC the subnets belong to. */
50 vpcId: string | undefined;
51 /** IDs of the subnets in the group. */
52 subnetIds: string[];
53 /** Status of the subnet group (e.g. `Complete`). */
54 status: string | undefined;
55 /** Tags on the subnet group (user + internal Alchemy tags). */
56 tags: Record<string, string>;
57 },
58 never,
59 Providers
60 > {}
61
62 /**
63 * An Amazon Neptune DB subnet group — the set of VPC subnets a Neptune
64 * cluster and its instances are placed into. Neptune is VPC-only, so a
65 * subnet group spanning at least two Availability Zones is required before a
66 * cluster can be created.
67 * ### Creating a Subnet Group
68 * **Example:** Multi-AZ subnet group
69 * ```typescript
70 * const subnetGroup = yield* DBSubnetGroup("NeptuneSubnets", {
71 * subnetIds: [subnetA.subnetId, subnetB.subnetId],
72 * });
73 * ```
74 *
75 * @resource
76 */
77 export const DBSubnetGroup = Resource<DBSubnetGroup>("AWS.Neptune.DBSubnetGroup");
78
79 export const DBSubnetGroupProvider = () =>
80 Provider.effect(
81 DBSubnetGroup,
82 Effect.gen(function* () {
83 const toName = (id: string, props: DBSubnetGroupProps) =>
84 props.dbSubnetGroupName
85 ? Effect.succeed(props.dbSubnetGroupName)
86 : createPhysicalName({ id, maxLength: 255 });
87
88 const readGroup = Effect.fn(function* (groupName: string) {
89 const response = yield* neptune
90 .describeDBSubnetGroups({
91 DBSubnetGroupName: groupName,
92 })
93 .pipe(Effect.catchTag("DBSubnetGroupNotFoundFault", () => Effect.undefined));
94 return response?.DBSubnetGroups?.[0];
95 });
96
97 return {
98 stables: ["dbSubnetGroupArn", "dbSubnetGroupName", "vpcId"],
99 diff: Effect.fn(function* ({ id, olds, news }) {
100 if (!isResolved(news)) return undefined;
101 if ((yield* toName(id, olds ?? { subnetIds: [] })) !== (yield* toName(id, news))) {
102 return { action: "replace" } as const;
103 }
104 }),
105 read: Effect.fn(function* ({ id, olds, output }) {
106 const name =
107 output?.dbSubnetGroupName ??
108 (yield* toName(id, olds ?? ({ subnetIds: [] } as DBSubnetGroupProps)));
109 const group = yield* readGroup(name);
110 if (!group?.DBSubnetGroupName) {
111 return undefined;
112 }
113
114 return {
115 dbSubnetGroupName: group.DBSubnetGroupName,
116 dbSubnetGroupArn: group.DBSubnetGroupArn,
117 vpcId: group.VpcId,
118 subnetIds: (group.Subnets ?? []).flatMap((subnet) =>
119 subnet.SubnetIdentifier ? [subnet.SubnetIdentifier] : [],
120 ),
121 status: group.SubnetGroupStatus,
122 tags: output?.tags ?? {},
123 };
124 }),
125 reconcile: Effect.fn(function* ({ id, news, output, session }) {
126 const dbSubnetGroupName = output?.dbSubnetGroupName ?? (yield* toName(id, news));
127 const internalTags = yield* createInternalTags(id);
128 const desiredTags = { ...internalTags, ...news.tags };
129
130 // Observe — fetch live subnet-group state.
131 let observed = yield* readGroup(dbSubnetGroupName);
132
133 // Ensure — create if missing. Tolerate
134 // `DBSubnetGroupAlreadyExistsFault` as a race with a peer
135 // reconciler by re-reading.
136 if (!observed?.DBSubnetGroupName) {
137 yield* neptune
138 .createDBSubnetGroup({
139 DBSubnetGroupName: dbSubnetGroupName,
140 DBSubnetGroupDescription: news.description ?? "Managed by Alchemy",
141 SubnetIds: news.subnetIds,
142 Tags: Object.entries(desiredTags).map(([Key, Value]) => ({
143 Key,
144 Value,
145 })),
146 })
147 .pipe(Effect.catchTag("DBSubnetGroupAlreadyExistsFault", () => Effect.void));
148 observed = yield* readGroup(dbSubnetGroupName);
149 if (!observed?.DBSubnetGroupName) {
150 return yield* new NeptuneDBSubnetGroupUnexpectedResponse({
151 message: `Failed to create DB subnet group '${dbSubnetGroupName}'`,
152 });
153 }
154 } else {
155 // Sync description and subnet membership — `modifyDBSubnetGroup`
156 // accepts the full desired set and is idempotent for unchanged
157 // input.
158 yield* neptune.modifyDBSubnetGroup({
159 DBSubnetGroupName: dbSubnetGroupName,
160 DBSubnetGroupDescription: news.description ?? "Managed by Alchemy",
161 SubnetIds: news.subnetIds,
162 });
163 observed = yield* readGroup(dbSubnetGroupName);
164 if (!observed?.DBSubnetGroupName) {
165 return yield* new NeptuneDBSubnetGroupUnexpectedResponse({
166 message: `DB subnet group '${dbSubnetGroupName}' not found after update`,
167 });
168 }
169 }
170
171 const dbSubnetGroupArn = observed.DBSubnetGroupArn;
172
173 // Sync tags — diff prior recorded tags against desired (describe
174 // does not surface tags inline).
175 const observedTags = output?.tags ?? {};
176 const { removed, upsert } = diffTags(observedTags, desiredTags);
177 if (upsert.length > 0 && dbSubnetGroupArn) {
178 yield* neptune.addTagsToResource({
179 ResourceName: dbSubnetGroupArn,
180 Tags: upsert,
181 });
182 }
183 if (removed.length > 0 && dbSubnetGroupArn) {
184 yield* neptune.removeTagsFromResource({
185 ResourceName: dbSubnetGroupArn,
186 TagKeys: removed,
187 });
188 }
189
190 yield* session.note(dbSubnetGroupArn ?? dbSubnetGroupName);
191 return {
192 dbSubnetGroupName: observed.DBSubnetGroupName,
193 dbSubnetGroupArn,
194 vpcId: observed.VpcId,
195 subnetIds: (observed.Subnets ?? []).flatMap((subnet) =>
196 subnet.SubnetIdentifier ? [subnet.SubnetIdentifier] : [],
197 ),
198 status: observed.SubnetGroupStatus,
199 tags: desiredTags,
200 };
201 }),
202 list: () =>
203 // AWS account/region collection: `describeDBSubnetGroups` is
204 // paginated (items field `DBSubnetGroups`). Subnet groups are shared
205 // across the RDS-family engines (RDS/DocumentDB/Neptune), so this
206 // enumerates all of them — mirroring the DocDB provider. `read` does
207 // not hydrate tags from the cloud (it returns the cached
208 // `output.tags`), so we mirror that here with an empty tag map.
209 neptune.describeDBSubnetGroups.pages({}).pipe(
210 Stream.runCollect,
211 Effect.map((chunk) =>
212 Array.from(chunk).flatMap((page) =>
213 (page.DBSubnetGroups ?? []).flatMap((group) =>
214 // `default` is the RDS-family subnet group AWS auto-creates
215 // for the default VPC — never ours, never census/nuke it.
216 group.DBSubnetGroupName && group.DBSubnetGroupName !== "default"
217 ? [
218 {
219 dbSubnetGroupName: group.DBSubnetGroupName,
220 dbSubnetGroupArn: group.DBSubnetGroupArn,
221 vpcId: group.VpcId,
222 subnetIds: (group.Subnets ?? []).flatMap((subnet) =>
223 subnet.SubnetIdentifier ? [subnet.SubnetIdentifier] : [],
224 ),
225 status: group.SubnetGroupStatus,
226 tags: {} as Record<string, string>,
227 },
228 ]
229 : [],
230 ),
231 ),
232 ),
233 ),
234 delete: Effect.fn(function* ({ output }) {
235 yield* neptune
236 .deleteDBSubnetGroup({
237 DBSubnetGroupName: output.dbSubnetGroupName,
238 })
239 .pipe(Effect.catchTag("DBSubnetGroupNotFoundFault", () => Effect.void));
240 }),
241 };
242 }),
243 );