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