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

main
ts 241 lines 8.39 KB
Raw
1 import * as finspace from "@distilled.cloud/aws/finspace";
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 type { Providers } from "../Providers.ts";
11
12 export class KxDatabaseInvalidProps extends Data.TaggedError("KxDatabaseInvalidProps")<{
13 readonly message: string;
14 readonly cause?: unknown;
15 }> {}
16
17 export class KxDatabaseUnexpectedResponse extends Data.TaggedError("KxDatabaseUnexpectedResponse")<{
18 readonly message: string;
19 readonly cause?: unknown;
20 }> {}
21
22 export interface KxDatabaseProps {
23 /**
24 * Identifier of the kdb environment the database lives in. Changing it
25 * replaces the database.
26 */
27 environmentId: string;
28 /**
29 * Name of the kdb database. Changing it replaces the database.
30 * @default ${app}-${id}-${stage}-${suffix}
31 */
32 databaseName?: string;
33 /**
34 * A description of the database.
35 */
36 description?: string;
37 /**
38 * Tags to associate with the database.
39 */
40 tags?: Record<string, string>;
41 }
42
43 export interface KxDatabase extends Resource<
44 "AWS.FinSpace.KxDatabase",
45 KxDatabaseProps,
46 {
47 /**
48 * Identifier of the kdb environment the database lives in.
49 */
50 environmentId: string;
51 /**
52 * The database's name.
53 */
54 databaseName: string;
55 /**
56 * ARN of the database.
57 */
58 databaseArn: string;
59 /**
60 * The database's description.
61 */
62 description: string | undefined;
63 /**
64 * Current tags reported for the database.
65 */
66 tags: Record<string, string>;
67 },
68 never,
69 Providers
70 > {}
71
72 /**
73 * A kdb database inside an Amazon FinSpace Managed kdb environment — the
74 * versioned, changeset-based store that kdb clusters mount and query.
75 *
76 * ### Creating kdb Databases
77 * **Example:** Basic kdb Database
78 * ```typescript
79 * import * as AWS from "@alchemy.run/aws";
80 *
81 * const env = yield* AWS.FinSpace.KxEnvironment("Kdb", { kmsKeyId });
82 * const db = yield* AWS.FinSpace.KxDatabase("Ticks", {
83 * environmentId: env.environmentId,
84 * description: "tick data",
85 * });
86 * ```
87 *
88 * @resource
89 */
90 export const KxDatabase = Resource<KxDatabase>("AWS.FinSpace.KxDatabase");
91
92 const createDatabaseName = (id: string, props: { databaseName?: string | undefined }) =>
93 props.databaseName
94 ? Effect.succeed(props.databaseName)
95 : createPhysicalName({ id, maxLength: 63 });
96
97 const fetchDatabaseTags = Effect.fn(function* (arn: string) {
98 const response = yield* finspace
99 .listTagsForResource({ resourceArn: arn })
100 .pipe(
101 Effect.catchTag(
102 ["ResourceNotFoundException", "InvalidRequestException"],
103 () => Effect.undefined,
104 ),
105 );
106 return Object.fromEntries(
107 Object.entries(response?.tags ?? {}).flatMap(([key, value]) =>
108 value === undefined ? [] : [[key, value] as const],
109 ),
110 );
111 });
112
113 const readDatabase = Effect.fn(function* (environmentId: string, databaseName: string) {
114 const response = yield* finspace
115 .getKxDatabase({ environmentId, databaseName })
116 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
117 if (!response) return undefined;
118 const databaseArn = response.databaseArn ?? "";
119 const attrs: KxDatabase["Attributes"] = {
120 environmentId: response.environmentId ?? environmentId,
121 databaseName: response.databaseName ?? databaseName,
122 databaseArn,
123 description: response.description,
124 tags: databaseArn ? yield* fetchDatabaseTags(databaseArn) : {},
125 };
126 return attrs;
127 });
128
129 export const KxDatabaseProvider = () =>
130 Provider.effect(
131 KxDatabase,
132 Effect.gen(function* () {
133 return {
134 stables: ["environmentId", "databaseName", "databaseArn"],
135 // Databases are keyed by their parent kdb environment — there is no
136 // account-wide enumeration without an environment id.
137 list: () => Effect.succeed([]),
138 read: Effect.fn(function* ({ id, olds, output }) {
139 const environmentId = output?.environmentId ?? olds?.environmentId;
140 if (environmentId === undefined) return undefined;
141 const databaseName = output?.databaseName ?? (yield* createDatabaseName(id, olds ?? {}));
142 const attrs = yield* readDatabase(environmentId, databaseName);
143 if (!attrs) return undefined;
144 return (yield* hasAlchemyTags(id, attrs.tags as Tags)) ? attrs : Unowned(attrs);
145 }),
146 diff: Effect.fn(function* ({ id, news, olds }) {
147 if (!isResolved(news)) return;
148 if (olds === undefined) return;
149 const oldName = yield* createDatabaseName(id, olds);
150 const newName = yield* createDatabaseName(id, news);
151 if (olds.environmentId !== news.environmentId || oldName !== newName) {
152 return { action: "replace" } as const;
153 }
154 }),
155 reconcile: Effect.fn(function* ({ id, news, output, session }) {
156 if (!news) {
157 return yield* new KxDatabaseInvalidProps({
158 message: "FinSpace KxDatabase requires props",
159 });
160 }
161 const environmentId = news.environmentId;
162 const databaseName = output?.databaseName ?? (yield* createDatabaseName(id, news));
163 const internalTags = yield* createInternalTags(id);
164 const desiredTags = { ...internalTags, ...news.tags };
165 // One idempotency token per reconcile, reused across create+update.
166 const clientToken = yield* Effect.sync(() => crypto.randomUUID());
167
168 // Observe — cloud state is authoritative.
169 let attrs = yield* readDatabase(environmentId, databaseName);
170
171 // Ensure — create if missing; tolerate an AlreadyExists race.
172 if (attrs === undefined) {
173 yield* finspace
174 .createKxDatabase({
175 environmentId,
176 databaseName,
177 description: news.description,
178 tags: desiredTags,
179 clientToken,
180 })
181 .pipe(Effect.catchTag("ResourceAlreadyExistsException", () => Effect.undefined));
182 yield* session.note(`Created kdb database ${databaseName}`);
183 attrs = yield* readDatabase(environmentId, databaseName);
184 if (attrs === undefined) {
185 return yield* new KxDatabaseUnexpectedResponse({
186 message: `failed to read created kdb database ${databaseName}`,
187 });
188 }
189 }
190
191 // Sync description — only call UpdateKxDatabase on drift.
192 if (news.description !== undefined && news.description !== attrs.description) {
193 yield* finspace.updateKxDatabase({
194 environmentId,
195 databaseName,
196 description: news.description,
197 clientToken,
198 });
199 yield* session.note(`Updated kdb database ${databaseName}`);
200 }
201
202 // Sync tags — diff against observed cloud tags.
203 if (attrs.databaseArn) {
204 const { removed, upsert } = diffTags(attrs.tags, desiredTags);
205 if (removed.length > 0) {
206 yield* finspace.untagResource({
207 resourceArn: attrs.databaseArn,
208 tagKeys: removed,
209 });
210 }
211 if (upsert.length > 0) {
212 yield* finspace.tagResource({
213 resourceArn: attrs.databaseArn,
214 tags: Object.fromEntries(upsert.map(({ Key, Value }) => [Key, Value])),
215 });
216 }
217 }
218
219 yield* session.note(attrs.databaseArn);
220
221 const final = yield* readDatabase(environmentId, databaseName);
222 if (!final) {
223 return yield* new KxDatabaseUnexpectedResponse({
224 message: `failed to read reconciled kdb database ${databaseName}`,
225 });
226 }
227 return final;
228 }),
229 delete: Effect.fn(function* ({ output }) {
230 const clientToken = yield* Effect.sync(() => crypto.randomUUID());
231 yield* finspace
232 .deleteKxDatabase({
233 environmentId: output.environmentId,
234 databaseName: output.databaseName,
235 clientToken,
236 })
237 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
238 }),
239 };
240 }),
241 );