@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 263 lines 9.42 KB
Raw
1 import * as TSW from "@distilled.cloud/aws/timestream-write";
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 EffectStream from "effect/Stream";
11 import { AWSEnvironment, type AccountID } from "../Environment.ts";
12 import type { Providers } from "../Providers.ts";
13 import type { RegionID } from "../Region.ts";
14 import { withWriteEndpoint } from "./internal.ts";
15
16 export class TimestreamDatabaseUnexpectedResponse extends Data.TaggedError(
17 "TimestreamDatabaseUnexpectedResponse",
18 )<{
19 readonly message: string;
20 readonly cause?: unknown;
21 }> {}
22
23 export type DatabaseArn = `arn:aws:timestream:${RegionID}:${AccountID}:database/${string}`;
24
25 export interface DatabaseProps {
26 /**
27 * Name of the Timestream database. Must be unique within the account and
28 * region and between 3 and 256 characters.
29 * @default ${app}-${stage}-${id}
30 */
31 databaseName?: string;
32 /**
33 * The ID (or ARN/alias) of the KMS key used to encrypt data at rest. When
34 * omitted, Timestream provisions and manages an AWS-owned KMS key.
35 */
36 kmsKeyId?: string;
37 /**
38 * Tags to associate with the database.
39 */
40 tags?: Record<string, string>;
41 }
42
43 export interface Database extends Resource<
44 "AWS.Timestream.Database",
45 DatabaseProps,
46 {
47 /**
48 * The database's physical name.
49 */
50 databaseName: string;
51 /**
52 * ARN of the database.
53 */
54 databaseArn: DatabaseArn;
55 /**
56 * The KMS key backing encryption at rest.
57 */
58 kmsKeyId: string | undefined;
59 /**
60 * Number of tables in the database.
61 */
62 tableCount: number | undefined;
63 /**
64 * Current tags reported for the database.
65 */
66 tags: Record<string, string>;
67 },
68 never,
69 Providers
70 > {}
71
72 /**
73 * An Amazon Timestream for LiveAnalytics database — the top-level container for
74 * time-series {@link Table}s.
75 *
76 * `Database` owns the database's lifecycle and its mutable configuration: the
77 * KMS key used for encryption at rest and its tags. A database name is
78 * auto-generated from the app, stage, and logical ID unless you provide one.
79 *
80 * :::note
81 * Timestream for LiveAnalytics is closed to new AWS customers. Accounts that
82 * were not already onboarded receive `TimestreamNotOnboarded` (a specialized
83 * `AccessDenied`) on every operation.
84 * :::
85 * ### Creating Databases
86 * **Example:** Basic Database
87 * ```typescript
88 * import * as Timestream from "@alchemy.run/aws/Timestream";
89 *
90 * const database = yield* Timestream.Database("Metrics");
91 * ```
92 *
93 * **Example:** Database with a Customer-Managed KMS Key
94 * ```typescript
95 * const database = yield* Timestream.Database("SecureMetrics", {
96 * kmsKeyId: "alias/my-timestream-key",
97 * tags: { Environment: "production" },
98 * });
99 * ```
100 *
101 * @resource
102 */
103 export const Database = Resource<Database>("AWS.Timestream.Database");
104
105 const createDatabaseName = (id: string, props: { databaseName?: string | undefined }) =>
106 Effect.gen(function* () {
107 if (props.databaseName) {
108 return props.databaseName;
109 }
110 return yield* createPhysicalName({ id, maxLength: 256 });
111 });
112
113 const toTagRecord = (
114 tags: Array<{ Key: string; Value: string }> | undefined,
115 ): Record<string, string> => Object.fromEntries((tags ?? []).map((tag) => [tag.Key, tag.Value]));
116
117 const readDatabase = Effect.fn(function* (databaseName: string) {
118 const response = yield* withWriteEndpoint(
119 TSW.describeDatabase({ DatabaseName: databaseName }),
120 ).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
121 if (!response?.Database) {
122 return undefined;
123 }
124 const database = response.Database;
125 const tagsResponse = yield* withWriteEndpoint(
126 TSW.listTagsForResource({ ResourceARN: database.Arn! }),
127 ).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
128 if (!tagsResponse) {
129 return undefined;
130 }
131 return {
132 databaseName: database.DatabaseName!,
133 databaseArn: database.Arn as DatabaseArn,
134 kmsKeyId: database.KmsKeyId,
135 tableCount: database.TableCount,
136 tags: toTagRecord(tagsResponse.Tags),
137 } satisfies Database["Attributes"];
138 });
139
140 export const DatabaseProvider = () =>
141 Provider.effect(
142 Database,
143 Effect.gen(function* () {
144 return {
145 stables: ["databaseName", "databaseArn"],
146 // Enumerate every Timestream database in the ambient account/region.
147 // `listDatabases` is paginated; collect every page and hydrate each
148 // into the exact `read` Attributes shape. A database that vanishes
149 // between listing and hydration is dropped (typed NotFound handled in
150 // `readDatabase`).
151 list: () =>
152 Effect.gen(function* () {
153 const names = yield* withWriteEndpoint(
154 TSW.listDatabases.pages({}).pipe(EffectStream.runCollect),
155 ).pipe(
156 Effect.map((chunk) =>
157 Array.from(chunk).flatMap((page) =>
158 (page.Databases ?? []).flatMap((db) =>
159 db.DatabaseName ? [db.DatabaseName] : [],
160 ),
161 ),
162 ),
163 );
164 const hydrated = yield* Effect.forEach(names, (name) => readDatabase(name), {
165 concurrency: 10,
166 });
167 return hydrated.filter((attrs): attrs is Database["Attributes"] => attrs !== undefined);
168 }),
169 read: Effect.fn(function* ({ id, olds, output }) {
170 const databaseName = output?.databaseName ?? (yield* createDatabaseName(id, olds ?? {}));
171 const state = yield* readDatabase(databaseName);
172 if (!state) return undefined;
173 return (yield* hasAlchemyTags(id, state.tags as Tags)) ? state : Unowned(state);
174 }),
175 diff: Effect.fn(function* ({ id, news = {}, olds = {} }) {
176 if (!isResolved(news)) return;
177 const oldName = yield* createDatabaseName(id, olds);
178 const newName = yield* createDatabaseName(id, news);
179 if (oldName !== newName) {
180 return { action: "replace" } as const;
181 }
182 }),
183 reconcile: Effect.fn(function* ({ id, news = {}, output, session }) {
184 const { accountId, region } = yield* AWSEnvironment.current;
185 const databaseName = output?.databaseName ?? (yield* createDatabaseName(id, news));
186 const databaseArn =
187 `arn:aws:timestream:${region}:${accountId}:database/${databaseName}` as DatabaseArn;
188 const internalTags = yield* createInternalTags(id);
189 const desiredTags = { ...internalTags, ...news.tags };
190
191 // Observe — cloud state is authoritative; output is only a name cache.
192 let state = yield* readDatabase(databaseName);
193
194 // Ensure — create if missing. Tolerate a ConflictException as a race
195 // with a peer reconciler and fall through to sync.
196 if (state === undefined) {
197 yield* withWriteEndpoint(
198 TSW.createDatabase({
199 DatabaseName: databaseName,
200 KmsKeyId: news.kmsKeyId,
201 Tags: Object.entries(desiredTags).map(([Key, Value]) => ({
202 Key,
203 Value,
204 })),
205 }),
206 ).pipe(Effect.catchTag("ConflictException", () => Effect.void));
207 yield* session.note(`Creating database ${databaseName}...`);
208 state = yield* readDatabase(databaseName);
209 if (state === undefined) {
210 return yield* new TimestreamDatabaseUnexpectedResponse({
211 message: `failed to read created database ${databaseName}`,
212 });
213 }
214 }
215
216 // Sync KMS key — only when the user pinned one and it drifted.
217 if (news.kmsKeyId !== undefined && state.kmsKeyId !== news.kmsKeyId) {
218 yield* withWriteEndpoint(
219 TSW.updateDatabase({
220 DatabaseName: databaseName,
221 KmsKeyId: news.kmsKeyId,
222 }),
223 );
224 yield* session.note(`Updated KMS key for ${databaseName}`);
225 }
226
227 // Sync tags — diff against observed cloud tags.
228 const { removed, upsert } = diffTags(state.tags, desiredTags);
229 if (removed.length > 0) {
230 yield* withWriteEndpoint(
231 TSW.untagResource({
232 ResourceARN: databaseArn,
233 TagKeys: removed,
234 }),
235 );
236 }
237 if (upsert.length > 0) {
238 yield* withWriteEndpoint(
239 TSW.tagResource({
240 ResourceARN: databaseArn,
241 Tags: upsert.map(({ Key, Value }) => ({ Key, Value })),
242 }),
243 );
244 }
245
246 yield* session.note(databaseArn);
247
248 const final = yield* readDatabase(databaseName);
249 if (!final) {
250 return yield* new TimestreamDatabaseUnexpectedResponse({
251 message: `failed to read reconciled database ${databaseName}`,
252 });
253 }
254 return final;
255 }),
256 delete: Effect.fn(function* ({ output }) {
257 yield* withWriteEndpoint(TSW.deleteDatabase({ DatabaseName: output.databaseName })).pipe(
258 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
259 );
260 }),
261 };
262 }),
263 );