@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 455 lines 16.1 KB
Raw
1 import * as influxdb from "@distilled.cloud/aws/timestream-influxdb";
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, type Tags } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Redacted from "effect/Redacted";
11 import * as Schedule from "effect/Schedule";
12 import * as EffectStream from "effect/Stream";
13 import type { Providers } from "../Providers.ts";
14
15 export class DbInstanceInvalidProps extends Data.TaggedError("DbInstanceInvalidProps")<{
16 readonly message: string;
17 readonly cause?: unknown;
18 }> {}
19
20 export class DbInstanceUnexpectedResponse extends Data.TaggedError("DbInstanceUnexpectedResponse")<{
21 readonly message: string;
22 readonly cause?: unknown;
23 }> {}
24
25 export type DbInstanceStatus = influxdb.Status;
26
27 export interface DbInstanceProps {
28 /**
29 * Name that uniquely identifies the DB instance. Must be 3–40 characters,
30 * start with a letter, and contain only lowercase letters, numbers, and
31 * hyphens.
32 * @default ${app}-${stage}-${id}
33 */
34 name?: string;
35 /**
36 * The compute instance type to run InfluxDB on (e.g. `db.influx.medium`).
37 */
38 dbInstanceType: influxdb.DbInstanceType;
39 /**
40 * The amount of storage to allocate, in GiB.
41 */
42 allocatedStorage: number;
43 /**
44 * The IDs of the VPC subnets the DB instance is attached to.
45 */
46 vpcSubnetIds: string[];
47 /**
48 * The VPC security group IDs to associate with the DB instance.
49 */
50 vpcSecurityGroupIds: string[];
51 /**
52 * The initial InfluxDB admin password. Stored in AWS Secrets Manager by
53 * Timestream; supplied only at creation. Must be alphanumeric
54 * (`[a-zA-Z0-9]+`, 8-64 characters). Pass a redacted value, e.g.
55 * `Redacted.make("SuperSecretPassword1")`.
56 */
57 password: Redacted.Redacted<string>;
58 /**
59 * The initial InfluxDB admin username.
60 * @default "admin"
61 */
62 username?: string;
63 /**
64 * The name of the initial InfluxDB organization.
65 */
66 organization?: string;
67 /**
68 * The name of the initial InfluxDB bucket.
69 */
70 bucket?: string;
71 /**
72 * The storage tier (IOPS profile) for the DB instance.
73 */
74 dbStorageType?: influxdb.DbStorageType;
75 /**
76 * Whether the DB instance has a public IP and is reachable from the internet.
77 * @default false
78 */
79 publiclyAccessible?: boolean;
80 /**
81 * Single- or multi-AZ deployment.
82 * @default "SINGLE_AZ"
83 */
84 deploymentType?: influxdb.DeploymentType;
85 /**
86 * The identifier of an InfluxDB parameter group to associate.
87 */
88 dbParameterGroupIdentifier?: string;
89 /**
90 * Log delivery (S3) configuration for InfluxDB engine logs.
91 */
92 logDeliveryConfiguration?: influxdb.LogDeliveryConfiguration;
93 /**
94 * The port InfluxDB listens on.
95 * @default 8086
96 */
97 port?: number;
98 /**
99 * The network protocol (IPv4 or dual-stack).
100 */
101 networkType?: influxdb.NetworkType;
102 /**
103 * Tags to associate with the DB instance.
104 */
105 tags?: Record<string, string>;
106 }
107
108 export interface DbInstance extends Resource<
109 "AWS.Timestream.DbInstance",
110 DbInstanceProps,
111 {
112 /**
113 * Service-assigned unique identifier for the DB instance.
114 */
115 id: string;
116 /**
117 * The DB instance's name.
118 */
119 name: string;
120 /**
121 * ARN of the DB instance.
122 */
123 arn: string;
124 /**
125 * Current lifecycle status of the DB instance.
126 */
127 status: DbInstanceStatus | undefined;
128 /**
129 * The connection endpoint (host) for the DB instance.
130 */
131 endpoint: string | undefined;
132 /**
133 * The port InfluxDB is listening on.
134 */
135 port: number | undefined;
136 /**
137 * ARN of the Secrets Manager secret holding the InfluxDB auth parameters.
138 */
139 influxAuthParametersSecretArn: string | undefined;
140 /**
141 * The compute instance type backing the DB instance.
142 */
143 dbInstanceType: influxdb.DbInstanceType | undefined;
144 /**
145 * The allocated storage, in GiB.
146 */
147 allocatedStorage: number | undefined;
148 /**
149 * The subnets the DB instance is attached to.
150 */
151 vpcSubnetIds: string[];
152 /**
153 * Current tags reported for the DB instance.
154 */
155 tags: Record<string, string>;
156 },
157 never,
158 Providers
159 > {}
160
161 /**
162 * An Amazon Timestream for InfluxDB DB instance — a managed, single-tenant
163 * InfluxDB engine for time-series workloads.
164 *
165 * `DbInstance` owns the instance's lifecycle and its mutable configuration
166 * (instance type, storage, port, parameter group, log delivery, deployment
167 * type, and tags). Networking (subnets, security groups), the initial
168 * credentials, organization, and bucket are fixed at creation.
169 *
170 * :::caution
171 * Provisioning a DB instance takes ~15–20 minutes and incurs EC2-backed cost.
172 * :::
173 * ### Creating DB Instances
174 * **Example:** Basic InfluxDB Instance
175 * ```typescript
176 * import * as Timestream from "@alchemy.run/aws/Timestream";
177 *
178 * const influx = yield* Timestream.DbInstance("Influx", {
179 * name: "my-influx",
180 * dbInstanceType: "db.influx.medium",
181 * allocatedStorage: 20,
182 * vpcSubnetIds: [subnetA.subnetId, subnetB.subnetId],
183 * vpcSecurityGroupIds: [securityGroup.groupId],
184 * password: Redacted.make("SuperSecretPassword1"),
185 * });
186 * ```
187 *
188 * @resource
189 */
190 export const DbInstance = Resource<DbInstance>("AWS.Timestream.DbInstance");
191
192 const createInstanceName = (id: string, props: { name?: string | undefined }) =>
193 Effect.gen(function* () {
194 if (props.name) {
195 return props.name;
196 }
197 return yield* createPhysicalName({ id, maxLength: 40 });
198 });
199
200 const toAttrs = (
201 instance: influxdb.GetDbInstanceOutput,
202 tags: Record<string, string>,
203 ): DbInstance["Attributes"] => ({
204 id: instance.id,
205 name: instance.name,
206 arn: instance.arn,
207 status: instance.status,
208 endpoint: instance.endpoint,
209 port: instance.port,
210 influxAuthParametersSecretArn: instance.influxAuthParametersSecretArn,
211 dbInstanceType: instance.dbInstanceType,
212 allocatedStorage: instance.allocatedStorage,
213 vpcSubnetIds: instance.vpcSubnetIds,
214 tags,
215 });
216
217 const fetchTags = Effect.fn(function* (arn: string) {
218 const response = yield* influxdb
219 .listTagsForResource({ resourceArn: arn })
220 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
221 const tags = response?.tags ?? {};
222 return Object.fromEntries(
223 Object.entries(tags).filter((entry): entry is [string, string] => typeof entry[1] === "string"),
224 );
225 });
226
227 const readInstanceById = Effect.fn(function* (identifier: string) {
228 const instance = yield* influxdb
229 .getDbInstance({ identifier })
230 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
231 if (!instance) return undefined;
232 return toAttrs(instance, yield* fetchTags(instance.arn));
233 });
234
235 const findInstanceByName = Effect.fn(function* (name: string) {
236 const summaries = yield* influxdb.listDbInstances.pages({}).pipe(
237 EffectStream.runCollect,
238 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.items ?? [])),
239 );
240 const match = summaries.find((summary) => summary.name === name);
241 if (!match) return undefined;
242 return yield* readInstanceById(match.id);
243 });
244
245 /**
246 * A DB instance still transitioning toward the awaited status — retried by
247 * {@link waitForStatus}'s bounded schedule.
248 */
249 class DbInstanceNotReady extends Data.TaggedError("DbInstanceNotReady")<{
250 readonly identifier: string;
251 readonly status: string | undefined;
252 }> {}
253
254 /**
255 * A DB instance whose asynchronous provisioning converged to a terminal
256 * failure status (`FAILED` / `REBOOT_FAILED`).
257 */
258 export class DbInstanceProvisioningFailed extends Data.TaggedError("DbInstanceProvisioningFailed")<{
259 readonly identifier: string;
260 readonly status: string;
261 }> {}
262
263 // Explicitly-typed retry wrapper — an inline `Effect.retry` in provider
264 // lifecycle code leaks `Retry.Return`'s conditional type into declaration
265 // emit and widens the provider layer to `unknown` for every consumer of
266 // `AWS.providers()`.
267 const retryWhileNotReady = <A, E extends { readonly _tag: string }, R>(
268 self: Effect.Effect<A, E, R>,
269 ): Effect.Effect<A, E, R> =>
270 Effect.retry(self, {
271 // ParseError: a CREATING instance can transiently decode incompletely
272 // while fields are still being populated — treat it as not-ready.
273 while: (e) => e._tag === "DbInstanceNotReady" || e._tag === "ParseError",
274 // Provisioning is slow (~15–20 min); poll every 20s up to ~30 min.
275 schedule: Schedule.max([Schedule.spaced("20 seconds"), Schedule.recurs(90)]),
276 });
277
278 const waitForStatus = (identifier: string, target: "AVAILABLE" | "DELETED") =>
279 retryWhileNotReady(
280 Effect.gen(function* () {
281 const instance = yield* influxdb
282 .getDbInstance({ identifier })
283 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
284 if (target === "DELETED") {
285 if (instance === undefined) return;
286 return yield* new DbInstanceNotReady({ identifier, status: instance.status });
287 }
288 if (instance?.status === "AVAILABLE") return;
289 if (instance?.status === "FAILED" || instance?.status === "REBOOT_FAILED") {
290 return yield* new DbInstanceProvisioningFailed({
291 identifier,
292 status: instance.status,
293 });
294 }
295 return yield* new DbInstanceNotReady({ identifier, status: instance?.status });
296 }),
297 );
298
299 export const DbInstanceProvider = () =>
300 Provider.effect(
301 DbInstance,
302 Effect.gen(function* () {
303 return {
304 stables: ["id", "arn", "name"],
305 list: () =>
306 Effect.gen(function* () {
307 const summaries = yield* influxdb.listDbInstances.pages({}).pipe(
308 EffectStream.runCollect,
309 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.items ?? [])),
310 );
311 const hydrated = yield* Effect.forEach(
312 summaries,
313 (summary) => readInstanceById(summary.id),
314 { concurrency: 5 },
315 );
316 return hydrated.filter(
317 (attrs): attrs is DbInstance["Attributes"] => attrs !== undefined,
318 );
319 }),
320 read: Effect.fn(function* ({ id, olds, output }) {
321 const state = output?.id
322 ? yield* readInstanceById(output.id)
323 : yield* findInstanceByName(yield* createInstanceName(id, olds ?? {}));
324 if (!state) return undefined;
325 return (yield* hasAlchemyTags(id, state.tags as Tags)) ? state : Unowned(state);
326 }),
327 diff: Effect.fn(function* ({ id, news, olds = {} }) {
328 if (!isResolved(news)) return;
329 const oldName = yield* createInstanceName(id, olds);
330 const newName = yield* createInstanceName(id, news);
331 // Name and the networking/credential aspects are immutable — changing
332 // any of them requires a replacement.
333 const arraysDiffer = (a?: string[], b?: string[]) =>
334 JSON.stringify([...(a ?? [])].sort()) !== JSON.stringify([...(b ?? [])].sort());
335 if (
336 oldName !== newName ||
337 arraysDiffer(olds.vpcSubnetIds, news.vpcSubnetIds) ||
338 arraysDiffer(olds.vpcSecurityGroupIds, news.vpcSecurityGroupIds) ||
339 olds.username !== news.username ||
340 olds.organization !== news.organization ||
341 olds.bucket !== news.bucket ||
342 olds.publiclyAccessible !== news.publiclyAccessible ||
343 olds.networkType !== news.networkType
344 ) {
345 return { action: "replace" } as const;
346 }
347 }),
348 reconcile: Effect.fn(function* ({ id, news, output, session }) {
349 if (!news) {
350 return yield* new DbInstanceInvalidProps({
351 message: "Timestream DbInstance requires props",
352 });
353 }
354 const name = output?.name ?? (yield* createInstanceName(id, news));
355 const internalTags = yield* createInternalTags(id);
356 const desiredTags = { ...internalTags, ...news.tags };
357
358 // Observe — prefer the cached id; fall back to a name lookup so a
359 // create whose state failed to persist is adopted rather than
360 // duplicated.
361 let state = output?.id
362 ? yield* readInstanceById(output.id)
363 : yield* findInstanceByName(name);
364
365 // Ensure — create if missing, then wait for AVAILABLE.
366 if (state === undefined) {
367 const created = yield* influxdb.createDbInstance({
368 name,
369 dbInstanceType: news.dbInstanceType,
370 allocatedStorage: news.allocatedStorage,
371 vpcSubnetIds: news.vpcSubnetIds,
372 vpcSecurityGroupIds: news.vpcSecurityGroupIds,
373 password: Redacted.value(news.password),
374 username: news.username,
375 organization: news.organization,
376 bucket: news.bucket,
377 dbStorageType: news.dbStorageType,
378 publiclyAccessible: news.publiclyAccessible,
379 deploymentType: news.deploymentType,
380 dbParameterGroupIdentifier: news.dbParameterGroupIdentifier,
381 logDeliveryConfiguration: news.logDeliveryConfiguration,
382 port: news.port,
383 networkType: news.networkType,
384 tags: desiredTags,
385 });
386 yield* session.note(`Creating DB instance ${name} (${created.id})...`);
387 yield* waitForStatus(created.id, "AVAILABLE");
388 state = yield* readInstanceById(created.id);
389 if (state === undefined) {
390 return yield* new DbInstanceUnexpectedResponse({
391 message: `failed to read created DB instance ${name}`,
392 });
393 }
394 }
395
396 // Sync mutable settings via UpdateDbInstance. It is a partial upsert;
397 // only send it when a mutable aspect drifted from observed state.
398 const needsUpdate =
399 (news.dbInstanceType !== undefined && news.dbInstanceType !== state.dbInstanceType) ||
400 (news.allocatedStorage !== undefined &&
401 news.allocatedStorage !== state.allocatedStorage) ||
402 (news.port !== undefined && news.port !== state.port) ||
403 news.dbParameterGroupIdentifier !== undefined ||
404 news.logDeliveryConfiguration !== undefined ||
405 news.deploymentType !== undefined ||
406 news.dbStorageType !== undefined;
407 if (needsUpdate) {
408 yield* influxdb.updateDbInstance({
409 identifier: state.id,
410 dbInstanceType: news.dbInstanceType,
411 allocatedStorage: news.allocatedStorage,
412 port: news.port,
413 dbParameterGroupIdentifier: news.dbParameterGroupIdentifier,
414 logDeliveryConfiguration: news.logDeliveryConfiguration,
415 deploymentType: news.deploymentType,
416 dbStorageType: news.dbStorageType,
417 });
418 yield* waitForStatus(state.id, "AVAILABLE");
419 yield* session.note(`Updated DB instance ${name}`);
420 }
421
422 // Sync tags — diff against observed cloud tags.
423 const { removed, upsert } = diffTags(state.tags, desiredTags);
424 if (removed.length > 0) {
425 yield* influxdb.untagResource({
426 resourceArn: state.arn,
427 tagKeys: removed,
428 });
429 }
430 if (upsert.length > 0) {
431 yield* influxdb.tagResource({
432 resourceArn: state.arn,
433 tags: Object.fromEntries(upsert.map(({ Key, Value }) => [Key, Value])),
434 });
435 }
436
437 yield* session.note(state.arn);
438
439 const final = yield* readInstanceById(state.id);
440 if (!final) {
441 return yield* new DbInstanceUnexpectedResponse({
442 message: `failed to read reconciled DB instance ${name}`,
443 });
444 }
445 return final;
446 }),
447 delete: Effect.fn(function* ({ output }) {
448 yield* influxdb
449 .deleteDbInstance({ identifier: output.id })
450 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
451 yield* waitForStatus(output.id, "DELETED");
452 }),
453 };
454 }),
455 );