@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 412 lines 15.8 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 Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12
13 export class NeptuneDBInstanceNotReady extends Data.TaggedError("NeptuneDBInstanceNotReady")<{
14 readonly message: string;
15 readonly cause?: unknown;
16 }> {}
17
18 export interface DBInstanceProps {
19 /**
20 * Instance identifier. If omitted, Alchemy generates one.
21 */
22 dbInstanceIdentifier?: string;
23 /**
24 * Neptune cluster the instance belongs to. Required — every Neptune
25 * instance is a cluster member. Immutable — forces replacement.
26 */
27 dbClusterIdentifier: string;
28 /**
29 * Instance class such as `db.r6g.large`, `db.t4g.medium`, or
30 * `db.serverless` (requires the cluster to have a
31 * `serverlessV2ScalingConfiguration`). In-place modify.
32 */
33 dbInstanceClass: string;
34 /**
35 * Database engine. Neptune only supports `neptune`.
36 * Changing the engine forces replacement.
37 * @default "neptune"
38 */
39 engine?: string;
40 /**
41 * Availability zone. Immutable — forces replacement.
42 */
43 availabilityZone?: string;
44 /**
45 * Weekly maintenance window, e.g. `Mon:00:00-Mon:03:00`. In-place modify.
46 */
47 preferredMaintenanceWindow?: string;
48 /**
49 * Auto minor version upgrades. In-place modify.
50 */
51 autoMinorVersionUpgrade?: boolean;
52 /**
53 * Promotion tier inside the cluster (0-15). In-place modify.
54 */
55 promotionTier?: number;
56 /**
57 * DB (instance-level) parameter group name. In-place modify.
58 */
59 dbParameterGroupName?: string;
60 /**
61 * User-defined tags.
62 */
63 tags?: Record<string, string>;
64 }
65
66 export interface DBInstance extends Resource<
67 "AWS.Neptune.DBInstance",
68 DBInstanceProps,
69 {
70 /** Identifier of the instance. */
71 dbInstanceIdentifier: string;
72 /** ARN of the instance. */
73 dbInstanceArn: string;
74 /** Identifier of the cluster the instance belongs to. */
75 dbClusterIdentifier: string | undefined;
76 /** Instance endpoint host name. */
77 endpointAddress: string | undefined;
78 /** Port the instance listens on. */
79 endpointPort: number | undefined;
80 /** Compute class of the instance (e.g. `db.r5.large`, `db.serverless`). */
81 dbInstanceClass: string | undefined;
82 /** Database engine (`neptune`). */
83 engine: string | undefined;
84 /** Running engine version. */
85 engineVersion: string | undefined;
86 /** Current lifecycle status (e.g. `creating`, `available`). */
87 status: string | undefined;
88 /** Failover promotion priority of the instance. */
89 promotionTier: number | undefined;
90 /** Name of the subnet group the instance is placed in. */
91 dbSubnetGroupName: string | undefined;
92 /** Availability Zone the instance runs in. */
93 availabilityZone: string | undefined;
94 /** Weekly window during which maintenance may occur. */
95 preferredMaintenanceWindow: string | undefined;
96 /** Whether storage is encrypted at rest. */
97 storageEncrypted: boolean | undefined;
98 /** KMS key encrypting the instance's storage. */
99 kmsKeyId: string | undefined;
100 /** Immutable, region-unique identifier of the instance. */
101 dbiResourceId: string | undefined;
102 /** Whether minor engine upgrades are applied automatically. */
103 autoMinorVersionUpgrade: boolean | undefined;
104 /** Tags on the instance (user + internal Alchemy tags). */
105 tags: Record<string, string>;
106 },
107 never,
108 Providers
109 > {}
110
111 /**
112 * An Amazon Neptune instance — a compute member of a Neptune
113 * {@link DBCluster}. Storage, backup, and endpoints are managed at the
114 * cluster level; the instance contributes CPU/RAM and can serve as a writer
115 * or reader. Provisioning takes several minutes.
116 *
117 * Mutable fields (`dbInstanceClass`, `promotionTier`, maintenance window)
118 * are reconciled in place; immutable fields (`engine`,
119 * `dbClusterIdentifier`, `availabilityZone`) force a replacement.
120 * ### Adding an Instance
121 * **Example:** A Neptune writer instance
122 * ```typescript
123 * const writer = yield* DBInstance("Writer", {
124 * dbClusterIdentifier: cluster.dbClusterIdentifier,
125 * dbInstanceClass: "db.t4g.medium",
126 * });
127 * ```
128 *
129 * **Example:** A serverless instance
130 * ```typescript
131 * const writer = yield* DBInstance("Writer", {
132 * dbClusterIdentifier: cluster.dbClusterIdentifier,
133 * dbInstanceClass: "db.serverless",
134 * });
135 * ```
136 *
137 * @resource
138 */
139 export const DBInstance = Resource<DBInstance>("AWS.Neptune.DBInstance");
140
141 const toTagRecord = (
142 tags: Array<{ Key?: string; Value?: string }> | undefined,
143 ): Record<string, string> =>
144 Object.fromEntries(
145 (tags ?? [])
146 .filter(
147 (tag): tag is { Key: string; Value: string } =>
148 typeof tag.Key === "string" && typeof tag.Value === "string",
149 )
150 .map((tag) => [tag.Key, tag.Value]),
151 );
152
153 const toAttrs = ({
154 instance,
155 tags,
156 }: {
157 instance: neptune.DBInstance;
158 tags: Record<string, string>;
159 }): DBInstance["Attributes"] => ({
160 dbInstanceIdentifier: instance.DBInstanceIdentifier ?? "",
161 dbInstanceArn: instance.DBInstanceArn ?? "",
162 dbClusterIdentifier: instance.DBClusterIdentifier,
163 endpointAddress: instance.Endpoint?.Address,
164 endpointPort: instance.Endpoint?.Port,
165 dbInstanceClass: instance.DBInstanceClass,
166 engine: instance.Engine,
167 engineVersion: instance.EngineVersion,
168 status: instance.DBInstanceStatus,
169 promotionTier: instance.PromotionTier,
170 dbSubnetGroupName: instance.DBSubnetGroup?.DBSubnetGroupName,
171 availabilityZone: instance.AvailabilityZone,
172 preferredMaintenanceWindow: instance.PreferredMaintenanceWindow,
173 storageEncrypted: instance.StorageEncrypted,
174 kmsKeyId: instance.KmsKeyId,
175 dbiResourceId: instance.DbiResourceId,
176 autoMinorVersionUpgrade: instance.AutoMinorVersionUpgrade,
177 tags,
178 });
179
180 export const DBInstanceProvider = () =>
181 Provider.effect(
182 DBInstance,
183 Effect.gen(function* () {
184 const toIdentifier = (id: string, props: DBInstanceProps) =>
185 props.dbInstanceIdentifier
186 ? Effect.succeed(props.dbInstanceIdentifier)
187 : createPhysicalName({ id, maxLength: 63 });
188
189 const readInstance = Effect.fn(function* (instanceId: string) {
190 const response = yield* neptune
191 .describeDBInstances({
192 DBInstanceIdentifier: instanceId,
193 })
194 .pipe(Effect.catchTag("DBInstanceNotFoundFault", () => Effect.undefined));
195 return response?.DBInstances?.[0];
196 });
197
198 const readTags = Effect.fn(function* (arn: string | undefined) {
199 if (!arn) return {} as Record<string, string>;
200 const response = yield* neptune
201 .listTagsForResource({ ResourceName: arn })
202 .pipe(Effect.catchTag("DBInstanceNotFoundFault", () => Effect.undefined));
203 return toTagRecord(response?.TagList);
204 });
205
206 // Bounded readiness wait. Gate on `DBInstanceStatus === "available"` so a
207 // follow-on `modifyDBInstance` doesn't hit `InvalidDBInstanceStateFault`.
208 // Neptune instances (serverless in particular) routinely take 10-20
209 // minutes to leave `creating`; budget ~25 min (100 * 15s).
210 const waitForInstance = Effect.fn(function* (instanceId: string) {
211 const readinessPolicy = Schedule.max([Schedule.fixed("15 seconds"), Schedule.recurs(100)]);
212 return yield* readInstance(instanceId).pipe(
213 Effect.flatMap((instance) => {
214 if (!instance?.DBInstanceArn) {
215 return Effect.fail(
216 new NeptuneDBInstanceNotReady({ message: `DB instance '${instanceId}' not found` }),
217 );
218 }
219 const status = instance.DBInstanceStatus;
220 if (
221 status !== "available" &&
222 status !== "incompatible-parameters" &&
223 status !== "incompatible-restore"
224 ) {
225 return Effect.fail(
226 new NeptuneDBInstanceNotReady({
227 message: `DB instance '${instanceId}' not available (status: ${status})`,
228 }),
229 );
230 }
231 return Effect.succeed(instance);
232 }),
233 Effect.retry({ schedule: readinessPolicy }),
234 );
235 });
236
237 return {
238 stables: ["dbInstanceArn", "dbInstanceIdentifier"],
239 // AWS account/region collection: the RDS-family control plane serves
240 // instances for every engine, so filter to `engine = neptune`. Tags
241 // are not surfaced inline — emit an empty tag map rather than a
242 // per-item `listTagsForResource` fan-out.
243 list: () =>
244 neptune.describeDBInstances
245 .pages({ Filters: [{ Name: "engine", Values: ["neptune"] }] })
246 .pipe(
247 Stream.runCollect,
248 Effect.map((chunk) =>
249 Array.from(chunk).flatMap((page) =>
250 (page.DBInstances ?? [])
251 .filter(
252 (
253 instance,
254 ): instance is typeof instance & {
255 DBInstanceArn: string;
256 } => instance.DBInstanceArn != null,
257 )
258 .map((instance) => toAttrs({ instance, tags: {} })),
259 ),
260 ),
261 Effect.catchTag("DBInstanceNotFoundFault", () =>
262 Effect.succeed([] as DBInstance["Attributes"][]),
263 ),
264 ),
265 diff: Effect.fn(function* ({ id, olds, news }) {
266 if (!isResolved(news)) return undefined;
267 if (
268 (yield* toIdentifier(id, olds ?? ({} as DBInstanceProps))) !==
269 (yield* toIdentifier(id, news))
270 ) {
271 return { action: "replace" } as const;
272 }
273 // Immutable props — any change forces a fresh instance.
274 if (
275 olds !== undefined &&
276 ((olds.engine ?? "neptune") !== (news.engine ?? "neptune") ||
277 olds.dbClusterIdentifier !== news.dbClusterIdentifier ||
278 olds.availabilityZone !== news.availabilityZone)
279 ) {
280 return { action: "replace" } as const;
281 }
282 }),
283 read: Effect.fn(function* ({ id, olds, output }) {
284 const identifier =
285 output?.dbInstanceIdentifier ??
286 (yield* toIdentifier(
287 id,
288 olds ??
289 ({
290 dbClusterIdentifier: "",
291 dbInstanceClass: "",
292 } as DBInstanceProps),
293 ));
294 const instance = yield* readInstance(identifier);
295 if (!instance?.DBInstanceArn) {
296 return undefined;
297 }
298 const tags = yield* readTags(instance.DBInstanceArn);
299 return toAttrs({ instance, tags });
300 }),
301 reconcile: Effect.fn(function* ({ id, news, output, session }) {
302 const identifier = output?.dbInstanceIdentifier ?? (yield* toIdentifier(id, news));
303 const internalTags = yield* createInternalTags(id);
304 const desiredTags = { ...internalTags, ...news.tags };
305
306 // Observe — fetch live instance state.
307 let observed = yield* readInstance(identifier);
308
309 // Ensure — create if missing. Tolerate
310 // `DBInstanceAlreadyExistsFault` as a race with a peer reconciler.
311 if (!observed?.DBInstanceArn) {
312 yield* neptune
313 .createDBInstance({
314 DBInstanceIdentifier: identifier,
315 DBClusterIdentifier: news.dbClusterIdentifier,
316 DBInstanceClass: news.dbInstanceClass,
317 Engine: news.engine ?? "neptune",
318 AvailabilityZone: news.availabilityZone,
319 PreferredMaintenanceWindow: news.preferredMaintenanceWindow,
320 AutoMinorVersionUpgrade: news.autoMinorVersionUpgrade,
321 PromotionTier: news.promotionTier,
322 DBParameterGroupName: news.dbParameterGroupName,
323 Tags: Object.entries(desiredTags).map(([Key, Value]) => ({
324 Key,
325 Value,
326 })),
327 })
328 .pipe(Effect.catchTag("DBInstanceAlreadyExistsFault", () => Effect.void));
329
330 observed = yield* waitForInstance(identifier);
331 } else {
332 // Wait for the instance to settle before any modify so the call
333 // doesn't hit `InvalidDBInstanceStateFault`.
334 observed = yield* waitForInstance(identifier);
335
336 // syncCoreSettings — single `modifyDBInstance` carrying scalar
337 // in-place fields. Only emit a field when the desired value differs
338 // from the observed cloud state.
339 const core: neptune.ModifyDBInstanceMessage = {
340 DBInstanceIdentifier: identifier,
341 ApplyImmediately: true,
342 };
343 let coreDirty = false;
344 const setIf = <K extends keyof neptune.ModifyDBInstanceMessage>(
345 key: K,
346 desired: neptune.ModifyDBInstanceMessage[K] | undefined,
347 observedValue: unknown,
348 ) => {
349 if (desired !== undefined && desired !== observedValue) {
350 core[key] = desired;
351 coreDirty = true;
352 }
353 };
354 setIf("DBInstanceClass", news.dbInstanceClass, observed.DBInstanceClass); // prettier-ignore
355 setIf("PreferredMaintenanceWindow", news.preferredMaintenanceWindow, observed.PreferredMaintenanceWindow); // prettier-ignore
356 setIf("AutoMinorVersionUpgrade", news.autoMinorVersionUpgrade, observed.AutoMinorVersionUpgrade); // prettier-ignore
357 setIf("PromotionTier", news.promotionTier, observed.PromotionTier);
358 setIf("DBParameterGroupName", news.dbParameterGroupName, observed.DBParameterGroups?.[0]?.DBParameterGroupName); // prettier-ignore
359 if (coreDirty) {
360 yield* neptune.modifyDBInstance(core);
361 observed = yield* waitForInstance(identifier);
362 }
363 }
364
365 const dbInstanceArn = observed.DBInstanceArn ?? "";
366
367 // Sync tags — diff observed cloud tags against desired.
368 const observedTags = yield* readTags(dbInstanceArn);
369 const { removed, upsert } = diffTags(observedTags, desiredTags);
370 if (upsert.length > 0 && dbInstanceArn) {
371 yield* neptune.addTagsToResource({
372 ResourceName: dbInstanceArn,
373 Tags: upsert,
374 });
375 }
376 if (removed.length > 0 && dbInstanceArn) {
377 yield* neptune.removeTagsFromResource({
378 ResourceName: dbInstanceArn,
379 TagKeys: removed,
380 });
381 }
382
383 yield* session.note(dbInstanceArn || identifier);
384 return toAttrs({ instance: observed, tags: desiredTags });
385 }),
386 delete: Effect.fn(function* ({ output }) {
387 yield* neptune
388 .deleteDBInstance({
389 DBInstanceIdentifier: output.dbInstanceIdentifier,
390 SkipFinalSnapshot: true,
391 })
392 .pipe(Effect.catchTag("DBInstanceNotFoundFault", () => Effect.void));
393 // Block until the instance is fully gone so a dependent cluster or
394 // subnet group is not torn down while Neptune still references it.
395 yield* Effect.repeat(
396 neptune
397 .describeDBInstances({
398 DBInstanceIdentifier: output.dbInstanceIdentifier,
399 })
400 .pipe(
401 Effect.as(true),
402 Effect.catchTag("DBInstanceNotFoundFault", () => Effect.succeed(false)),
403 ),
404 {
405 schedule: Schedule.max([Schedule.fixed("15 seconds"), Schedule.recurs(40)]),
406 until: (exists) => exists === false,
407 },
408 ).pipe(Effect.catch(() => Effect.void));
409 }),
410 };
411 }),
412 );