@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, 06:00 UTC

main
ts 526 lines 19.8 KB
Raw
1 import * as docdbelastic from "@distilled.cloud/aws/docdb-elastic";
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 { toWireDays } from "alchemy/Util/Duration";
9 import * as Data from "effect/Data";
10 import type * as Duration from "effect/Duration";
11 import * as Effect from "effect/Effect";
12 import * as Redacted from "effect/Redacted";
13 import * as Schedule from "effect/Schedule";
14 import * as Stream from "effect/Stream";
15 import type { Providers } from "../Providers.ts";
16
17 export class DocDBElasticClusterNotReady extends Data.TaggedError("DocDBElasticClusterNotReady")<{
18 readonly message: string;
19 readonly cause?: unknown;
20 }> {}
21
22 export class DocDBElasticClusterUnexpectedResponse extends Data.TaggedError(
23 "DocDBElasticClusterUnexpectedResponse",
24 )<{
25 readonly message: string;
26 readonly cause?: unknown;
27 }> {}
28
29 export interface ClusterProps {
30 /**
31 * Name of the elastic cluster. If omitted, a deterministic physical name
32 * is generated. Changing the name replaces the cluster.
33 */
34 clusterName?: string;
35 /**
36 * Name of the administrator account for the elastic cluster. Changing the
37 * admin user name replaces the cluster.
38 */
39 adminUserName: string;
40 /**
41 * Password for the administrator account. Must be 8-100 printable ASCII
42 * characters (no `/`, `"` or `@`). The cloud never reports the current
43 * password, so password rotation is detected by comparing against the
44 * previously deployed value.
45 */
46 adminUserPassword: Redacted.Redacted<string>;
47 /**
48 * Authentication type — `"PLAIN_TEXT"` (the password is the literal
49 * credential) or `"SECRET_ARN"` (the password is a Secrets Manager ARN).
50 * @default "PLAIN_TEXT"
51 */
52 authType?: string;
53 /**
54 * Capacity of each shard in vCPUs. Valid values: 2, 4, 8, 16, 32, 64.
55 * Updated in place.
56 * @default 2
57 */
58 shardCapacity?: number;
59 /**
60 * Number of shards in the cluster (1-32). Updated in place.
61 * @default 1
62 */
63 shardCount?: number;
64 /**
65 * Number of replica instances per shard (1-16).
66 * @default 1
67 */
68 shardInstanceCount?: number;
69 /**
70 * VPC security groups that control network access to the cluster
71 * endpoint.
72 * @default the VPC's default security group
73 */
74 vpcSecurityGroupIds?: string[];
75 /**
76 * VPC subnet IDs the cluster spans. Must cover at least two Availability
77 * Zones (three for production workloads).
78 * @default the default VPC's subnets
79 */
80 subnetIds?: string[];
81 /**
82 * Customer-managed KMS key for encryption at rest. Changing the key
83 * replaces the cluster.
84 * @default AWS-owned key
85 */
86 kmsKeyId?: string;
87 /**
88 * Weekly maintenance window, e.g. `"sun:23:00-mon:01:30"` (UTC).
89 */
90 preferredMaintenanceWindow?: string;
91 /**
92 * How long automatic snapshots are retained, e.g. `"7 days"` or
93 * `Duration.days(7)`. Rounded to whole days (1-35) on the wire.
94 */
95 backupRetentionPeriod?: Duration.Input;
96 /**
97 * Daily window (UTC, `HH:MM-HH:MM`) when automatic snapshots are taken.
98 */
99 preferredBackupWindow?: string;
100 /**
101 * User-defined tags for the cluster.
102 */
103 tags?: Record<string, string>;
104 }
105
106 export interface Cluster extends Resource<
107 "AWS.DocDBElastic.Cluster",
108 ClusterProps,
109 {
110 /** The name of the elastic cluster. */
111 clusterName: string;
112 /** The ARN of the elastic cluster. */
113 clusterArn: string;
114 /** The current status of the cluster, e.g. `ACTIVE`. */
115 status: string;
116 /** The MongoDB-compatible connection endpoint. */
117 clusterEndpoint: string | undefined;
118 /** The administrator username. */
119 adminUserName: string;
120 /** The authentication type (`PLAIN_TEXT` or `SECRET_ARN`). */
121 authType: string;
122 /** vCPU capacity of each shard (2, 4, 8, 16, 32, or 64). */
123 shardCapacity: number;
124 /** Number of shards in the cluster. */
125 shardCount: number;
126 /** Number of replica instances per shard. */
127 shardInstanceCount: number | undefined;
128 /** The VPC security groups attached to the cluster. */
129 vpcSecurityGroupIds: string[];
130 /** The subnets the cluster is deployed into. */
131 subnetIds: string[];
132 /** The KMS key used for encryption at rest. */
133 kmsKeyId: string;
134 /** The weekly window during which maintenance can occur. */
135 preferredMaintenanceWindow: string;
136 /** Number of days automated backups are retained. */
137 backupRetentionPeriod: number | undefined;
138 /** The daily window during which automated backups run. */
139 preferredBackupWindow: string | undefined;
140 /** The tags attached to the cluster. */
141 tags: Record<string, string>;
142 },
143 never,
144 Providers
145 > {}
146
147 /**
148 * An Amazon DocumentDB elastic cluster — a MongoDB-compatible, sharded
149 * document database that scales workloads to millions of reads/writes per
150 * second without managing instances.
151 *
152 * Elastic clusters take roughly 8-10 minutes to provision and bill per
153 * shard-vCPU-hour while they exist. They are reachable only from inside a
154 * VPC. Destroy clusters you are not using.
155 * ### Creating a Cluster
156 * **Example:** Minimal Elastic Cluster
157 * ```typescript
158 * const cluster = yield* Cluster("Documents", {
159 * adminUserName: "admin",
160 * adminUserPassword: Redacted.make("super-secret-password"),
161 * shardCapacity: 2,
162 * shardCount: 1,
163 * });
164 * ```
165 *
166 * **Example:** Cluster Pinned to Specific Subnets
167 * ```typescript
168 * const cluster = yield* Cluster("Documents", {
169 * adminUserName: "admin",
170 * adminUserPassword: Redacted.make("super-secret-password"),
171 * shardCapacity: 2,
172 * shardCount: 1,
173 * subnetIds: [subnetA.subnetId, subnetB.subnetId],
174 * vpcSecurityGroupIds: [securityGroup.securityGroupId],
175 * backupRetentionPeriod: "1 day",
176 * });
177 * ```
178 *
179 * @resource
180 */
181 export const Cluster = Resource<Cluster>("AWS.DocDBElastic.Cluster");
182
183 const DEFAULT_AUTH_TYPE = "PLAIN_TEXT";
184 const DEFAULT_SHARD_CAPACITY = 2;
185 const DEFAULT_SHARD_COUNT = 1;
186
187 /** True when two string sets are equal ignoring order and duplicates. */
188 const sameStringSet = (
189 a: readonly string[] | undefined,
190 b: readonly string[] | undefined,
191 ): boolean => {
192 const left = [...new Set(a ?? [])].sort();
193 const right = [...new Set(b ?? [])].sort();
194 return left.length === right.length && left.every((v, i) => v === right[i]);
195 };
196
197 const toTagRecord = (
198 tags: { [key: string]: string | undefined } | undefined,
199 ): Record<string, string> =>
200 Object.fromEntries(
201 Object.entries(tags ?? {}).filter((entry): entry is [string, string] => entry[1] !== undefined),
202 );
203
204 export const ClusterProvider = () =>
205 Provider.effect(
206 Cluster,
207 Effect.gen(function* () {
208 const toName = (id: string, props: Partial<ClusterProps>) =>
209 props.clusterName
210 ? Effect.succeed(props.clusterName)
211 : createPhysicalName({ id, maxLength: 50, lowercase: true });
212
213 const getByArn = Effect.fn(function* (arn: string) {
214 const response = yield* docdbelastic
215 .getCluster({ clusterArn: arn })
216 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
217 return response?.cluster;
218 });
219
220 // Elastic clusters are addressed by ARN (which embeds a server-side
221 // UUID), so a name-based lookup scans the paginated list.
222 const findByName = Effect.fn(function* (name: string) {
223 const matches = yield* docdbelastic.listClusters.items({}).pipe(
224 Stream.filter((cluster) => cluster.clusterName === name),
225 Stream.take(1),
226 Stream.runCollect,
227 );
228 const summary = Array.from(matches)[0];
229 if (summary === undefined) return undefined;
230 return yield* getByArn(summary.clusterArn);
231 });
232
233 const readCluster = Effect.fn(function* (name: string, arn: string | undefined) {
234 if (arn !== undefined) {
235 const cluster = yield* getByArn(arn);
236 if (cluster !== undefined) return cluster;
237 }
238 return yield* findByName(name);
239 });
240
241 const readTags = Effect.fn(function* (arn: string) {
242 const response = yield* docdbelastic
243 .listTagsForResource({ resourceArn: arn })
244 .pipe(Effect.orElseSucceed(() => undefined));
245 return toTagRecord(response?.tags);
246 });
247
248 // Bounded readiness wait. Elastic cluster provisioning/modification
249 // typically completes in 8-10 minutes; budget ~20 min (80 * 15s).
250 const waitForActive = Effect.fn(function* (name: string, arn: string | undefined) {
251 const policy = Schedule.max([Schedule.fixed("15 seconds"), Schedule.recurs(80)]);
252 return yield* readCluster(name, arn).pipe(
253 Effect.flatMap((cluster) => {
254 if (cluster === undefined) {
255 return Effect.fail(
256 new DocDBElasticClusterNotReady({ message: `Elastic cluster '${name}' not found` }),
257 );
258 }
259 if (cluster.status !== "ACTIVE") {
260 return Effect.fail(
261 new DocDBElasticClusterNotReady({
262 message: `Elastic cluster '${name}' not active (status: ${cluster.status})`,
263 }),
264 );
265 }
266 return Effect.succeed(cluster);
267 }),
268 Effect.retry({ schedule: policy }),
269 );
270 });
271
272 const toAttrs = Effect.fn(function* (cluster: docdbelastic.Cluster) {
273 return {
274 clusterName: cluster.clusterName,
275 clusterArn: cluster.clusterArn,
276 status: cluster.status,
277 clusterEndpoint: cluster.clusterEndpoint,
278 adminUserName: cluster.adminUserName,
279 authType: cluster.authType,
280 shardCapacity: cluster.shardCapacity,
281 shardCount: cluster.shardCount,
282 shardInstanceCount: cluster.shardInstanceCount,
283 vpcSecurityGroupIds: [...cluster.vpcSecurityGroupIds],
284 subnetIds: [...cluster.subnetIds],
285 kmsKeyId: cluster.kmsKeyId,
286 preferredMaintenanceWindow: cluster.preferredMaintenanceWindow,
287 backupRetentionPeriod: cluster.backupRetentionPeriod,
288 preferredBackupWindow: cluster.preferredBackupWindow,
289 tags: yield* readTags(cluster.clusterArn),
290 };
291 });
292
293 return {
294 stables: ["clusterName", "clusterArn"],
295
296 diff: Effect.fn(function* ({ id, olds, news }) {
297 if (!isResolved(news)) return undefined;
298 const n = news;
299 const o = olds;
300 if (n === undefined || o === undefined) return undefined;
301 if ((yield* toName(id, o)) !== (yield* toName(id, n))) {
302 return { action: "replace" } as const;
303 }
304 // Create-only properties force a replacement.
305 if (n.adminUserName !== o.adminUserName) {
306 return { action: "replace" } as const;
307 }
308 if ((n.kmsKeyId ?? undefined) !== (o.kmsKeyId ?? undefined)) {
309 return { action: "replace" } as const;
310 }
311 }),
312
313 read: Effect.fn(function* ({ id, olds, output }) {
314 const name =
315 output?.clusterName ??
316 (yield* toName(
317 id,
318 olds ?? {
319 adminUserName: "",
320 adminUserPassword: Redacted.make(""),
321 },
322 ));
323 const cluster = yield* readCluster(name, output?.clusterArn);
324 if (cluster === undefined) return undefined;
325 const attrs = yield* toAttrs(cluster);
326 return (yield* hasAlchemyTags(id, attrs.tags)) ? attrs : Unowned(attrs);
327 }),
328
329 reconcile: Effect.fn(function* ({ id, news, olds, output, session }) {
330 const props = news!;
331 const name = output?.clusterName ?? (yield* toName(id, props));
332 const internalTags = yield* createInternalTags(id);
333 const desiredTags = { ...internalTags, ...props.tags };
334
335 // 1. Observe — cloud state is authoritative; output is only an
336 // ARN cache.
337 let observed = yield* readCluster(name, output?.clusterArn);
338 let created = false;
339
340 // 2. Ensure — create if missing; tolerate a create race
341 // (ConflictException) by re-reading.
342 if (observed === undefined) {
343 const response = yield* docdbelastic
344 .createCluster({
345 clusterName: name,
346 adminUserName: props.adminUserName,
347 adminUserPassword: props.adminUserPassword,
348 authType: props.authType ?? DEFAULT_AUTH_TYPE,
349 shardCapacity: props.shardCapacity ?? DEFAULT_SHARD_CAPACITY,
350 shardCount: props.shardCount ?? DEFAULT_SHARD_COUNT,
351 shardInstanceCount: props.shardInstanceCount,
352 vpcSecurityGroupIds: props.vpcSecurityGroupIds,
353 subnetIds: props.subnetIds,
354 kmsKeyId: props.kmsKeyId,
355 preferredMaintenanceWindow: props.preferredMaintenanceWindow,
356 backupRetentionPeriod: toWireDays(props.backupRetentionPeriod),
357 preferredBackupWindow: props.preferredBackupWindow,
358 tags: desiredTags,
359 })
360 .pipe(Effect.catchTag("ConflictException", () => Effect.undefined));
361 observed = response?.cluster ?? (yield* findByName(name));
362 created = true;
363 }
364 if (observed === undefined) {
365 return yield* new DocDBElasticClusterUnexpectedResponse({
366 message: `Elastic cluster '${name}' not found after create`,
367 });
368 }
369 const arn = observed.clusterArn;
370
371 // Provisioning and in-flight modifications both surface as a
372 // non-ACTIVE status; wait (bounded) so update calls do not hit
373 // ConflictException.
374 observed = yield* waitForActive(name, arn);
375
376 // 3. Sync — compute the update delta from OBSERVED state.
377 const update: docdbelastic.UpdateClusterInput = { clusterArn: arn };
378 let mutated = false;
379 if (props.shardCapacity !== undefined && props.shardCapacity !== observed.shardCapacity) {
380 update.shardCapacity = props.shardCapacity;
381 mutated = true;
382 }
383 if (props.shardCount !== undefined && props.shardCount !== observed.shardCount) {
384 update.shardCount = props.shardCount;
385 mutated = true;
386 }
387 if (
388 props.shardInstanceCount !== undefined &&
389 props.shardInstanceCount !== observed.shardInstanceCount
390 ) {
391 update.shardInstanceCount = props.shardInstanceCount;
392 mutated = true;
393 }
394 if (
395 props.vpcSecurityGroupIds !== undefined &&
396 !sameStringSet(props.vpcSecurityGroupIds, observed.vpcSecurityGroupIds)
397 ) {
398 update.vpcSecurityGroupIds = props.vpcSecurityGroupIds;
399 mutated = true;
400 }
401 if (
402 props.subnetIds !== undefined &&
403 !sameStringSet(props.subnetIds, observed.subnetIds)
404 ) {
405 update.subnetIds = props.subnetIds;
406 mutated = true;
407 }
408 if (
409 props.preferredMaintenanceWindow !== undefined &&
410 props.preferredMaintenanceWindow !== observed.preferredMaintenanceWindow
411 ) {
412 update.preferredMaintenanceWindow = props.preferredMaintenanceWindow;
413 mutated = true;
414 }
415 const desiredRetentionDays = toWireDays(props.backupRetentionPeriod);
416 if (
417 desiredRetentionDays !== undefined &&
418 desiredRetentionDays !== observed.backupRetentionPeriod
419 ) {
420 update.backupRetentionPeriod = desiredRetentionDays;
421 mutated = true;
422 }
423 if (
424 props.preferredBackupWindow !== undefined &&
425 props.preferredBackupWindow !== observed.preferredBackupWindow
426 ) {
427 update.preferredBackupWindow = props.preferredBackupWindow;
428 mutated = true;
429 }
430 if ((props.authType ?? DEFAULT_AUTH_TYPE) !== observed.authType) {
431 update.authType = props.authType ?? DEFAULT_AUTH_TYPE;
432 update.adminUserPassword = props.adminUserPassword;
433 mutated = true;
434 } else if (
435 // The cloud never reports the password; the previously deployed
436 // value is the only diff baseline (skipped right after create —
437 // the password was just applied).
438 !created &&
439 olds !== undefined &&
440 Redacted.value(props.adminUserPassword) !== Redacted.value(olds.adminUserPassword)
441 ) {
442 update.adminUserPassword = props.adminUserPassword;
443 mutated = true;
444 }
445 if (mutated) {
446 yield* docdbelastic.updateCluster(update);
447 observed = yield* waitForActive(name, arn);
448 }
449
450 // 3b. Sync tags — diff against OBSERVED cloud tags.
451 const observedTags = yield* readTags(arn);
452 const { removed, upsert } = diffTags(observedTags, desiredTags);
453 if (upsert.length > 0) {
454 yield* docdbelastic.tagResource({
455 resourceArn: arn,
456 tags: Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value])),
457 });
458 }
459 if (removed.length > 0) {
460 yield* docdbelastic.untagResource({
461 resourceArn: arn,
462 tagKeys: removed,
463 });
464 }
465
466 yield* session.note(name);
467 return yield* toAttrs(observed);
468 }),
469
470 delete: Effect.fn(function* ({ output }) {
471 // A cluster mid-create/modify rejects deletion with
472 // ConflictException — retry (bounded) while it settles. A cluster
473 // already deleting (or gone) is success.
474 //
475 // Only an ACTIVE cluster is deletable: STOPPING, STOPPED and
476 // STARTING all reject DeleteCluster with a ValidationException
477 // ("Can't delete the cluster because it is in STOPPED state"). Wait
478 // (bounded) for a stop/start to settle, then start a STOPPED
479 // cluster and wait for ACTIVE before deleting it.
480 const settled = yield* getByArn(output.clusterArn).pipe(
481 Effect.repeat({
482 schedule: Schedule.spaced("15 seconds"),
483 until: (cluster) =>
484 cluster === undefined ||
485 (cluster.status !== "STOPPING" && cluster.status !== "STARTING"),
486 times: 60,
487 }),
488 );
489 if (settled === undefined || settled.status === "DELETING") {
490 return;
491 }
492 if (settled.status === "STOPPED") {
493 yield* docdbelastic
494 .startCluster({ clusterArn: output.clusterArn })
495 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
496 yield* waitForActive(settled.clusterName, output.clusterArn);
497 }
498 yield* docdbelastic.deleteCluster({ clusterArn: output.clusterArn }).pipe(
499 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
500 Effect.retry({
501 while: (e) => e._tag === "ConflictException",
502 schedule: Schedule.max([Schedule.fixed("15 seconds"), Schedule.recurs(60)]),
503 }),
504 );
505 }),
506
507 list: () =>
508 docdbelastic.listClusters.items({}).pipe(
509 Stream.runCollect,
510 Effect.flatMap((summaries) =>
511 Effect.forEach(
512 Array.from(summaries),
513 (summary) =>
514 getByArn(summary.clusterArn).pipe(
515 Effect.flatMap((cluster) =>
516 cluster === undefined ? Effect.undefined : toAttrs(cluster),
517 ),
518 ),
519 { concurrency: 4 },
520 ),
521 ),
522 Effect.map((attrs) => attrs.filter((a): a is NonNullable<typeof a> => a !== undefined)),
523 ),
524 };
525 }),
526 );