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

main
ts 444 lines 16.3 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 * as Schedule from "effect/Schedule";
11 import * as EffectStream from "effect/Stream";
12 import type { Providers } from "../Providers.ts";
13
14 export class KxEnvironmentInvalidProps extends Data.TaggedError("KxEnvironmentInvalidProps")<{
15 readonly message: string;
16 readonly cause?: unknown;
17 }> {}
18
19 export class KxEnvironmentUnexpectedResponse extends Data.TaggedError(
20 "KxEnvironmentUnexpectedResponse",
21 )<{
22 readonly message: string;
23 readonly cause?: unknown;
24 }> {}
25
26 export type KxEnvironmentStatus = finspace.EnvironmentStatus;
27 export type TransitGatewayConfiguration = finspace.TransitGatewayConfiguration;
28 export type CustomDNSServer = finspace.CustomDNSServer;
29
30 export interface KxEnvironmentProps {
31 /**
32 * Name of the kdb environment.
33 * @default ${app}-${id}-${stage}-${suffix}
34 */
35 name?: string;
36 /**
37 * A description of the kdb environment.
38 */
39 description?: string;
40 /**
41 * The KMS key id used to encrypt data in the environment. Required;
42 * changing it replaces the environment.
43 */
44 kmsKeyId: string;
45 /**
46 * Transit gateway to attach so on-prem kdb clients can reach the
47 * environment. Attached once via `UpdateKxEnvironmentNetwork` after the
48 * environment is created; FinSpace does not support changing an attached
49 * network, so changing an existing configuration replaces the environment.
50 */
51 transitGatewayConfiguration?: TransitGatewayConfiguration;
52 /**
53 * Custom DNS servers to resolve on-prem hostnames from inside the
54 * environment. Attached together with `transitGatewayConfiguration`;
55 * changing an existing configuration replaces the environment.
56 */
57 customDNSConfiguration?: CustomDNSServer[];
58 /**
59 * Tags to associate with the environment.
60 */
61 tags?: Record<string, string>;
62 }
63
64 export interface KxEnvironment extends Resource<
65 "AWS.FinSpace.KxEnvironment",
66 KxEnvironmentProps,
67 {
68 /**
69 * Service-assigned unique identifier of the kdb environment.
70 */
71 environmentId: string;
72 /**
73 * ARN of the kdb environment.
74 */
75 environmentArn: string;
76 /**
77 * The environment's name.
78 */
79 name: string;
80 /**
81 * Current lifecycle status of the environment.
82 */
83 status: KxEnvironmentStatus | undefined;
84 /**
85 * ID of the KMS key encrypting the environment.
86 */
87 kmsKeyId: string | undefined;
88 /**
89 * The environment's description.
90 */
91 description: string | undefined;
92 /**
93 * The transit gateway attached to the environment, if any.
94 */
95 transitGatewayConfiguration: TransitGatewayConfiguration | undefined;
96 /**
97 * The custom DNS servers configured on the environment, if any.
98 */
99 customDNSConfiguration: CustomDNSServer[] | undefined;
100 /**
101 * Current tags reported for the environment.
102 */
103 tags: Record<string, string>;
104 },
105 never,
106 Providers
107 > {}
108
109 /**
110 * An Amazon FinSpace Managed kdb environment — the account-level container
111 * that kdb databases, clusters, users, volumes and scaling groups live in.
112 *
113 * :::caution
114 * kdb environment provisioning is slow (tens of minutes) and the service is
115 * gated to onboarded accounts. Live lifecycle tests are gated behind
116 * `AWS_TEST_FINSPACE=1`.
117 * :::
118 * ### Creating kdb Environments
119 * **Example:** Basic kdb Environment
120 * ```typescript
121 * import * as AWS from "@alchemy.run/aws";
122 *
123 * const key = yield* AWS.KMS.Key("KdbKey", {});
124 * const env = yield* AWS.FinSpace.KxEnvironment("Kdb", {
125 * kmsKeyId: key.keyArn,
126 * description: "managed kdb environment",
127 * });
128 * ```
129 *
130 * ### Connecting to On-Prem Networks
131 * **Example:** Attach a Transit Gateway
132 * ```typescript
133 * const env = yield* AWS.FinSpace.KxEnvironment("Kdb", {
134 * kmsKeyId: key.keyArn,
135 * transitGatewayConfiguration: {
136 * transitGatewayID: "tgw-0123456789abcdef0",
137 * routableCIDRSpace: "10.0.0.0/16",
138 * },
139 * customDNSConfiguration: [
140 * { customDNSServerName: "dns.corp.example", customDNSServerIP: "10.0.0.2" },
141 * ],
142 * });
143 * ```
144 *
145 * @resource
146 */
147 export const KxEnvironment = Resource<KxEnvironment>("AWS.FinSpace.KxEnvironment");
148
149 const createKxEnvironmentName = (id: string, props: { name?: string | undefined }) =>
150 props.name ? Effect.succeed(props.name) : createPhysicalName({ id, maxLength: 255 });
151
152 const fetchKxTags = Effect.fn(function* (arn: string) {
153 const response = yield* finspace
154 .listTagsForResource({ resourceArn: arn })
155 .pipe(
156 Effect.catchTag(
157 ["ResourceNotFoundException", "InvalidRequestException"],
158 () => Effect.undefined,
159 ),
160 );
161 return Object.fromEntries(
162 Object.entries(response?.tags ?? {}).flatMap(([key, value]) =>
163 value === undefined ? [] : [[key, value] as const],
164 ),
165 );
166 });
167
168 const isGone = (status: KxEnvironmentStatus | undefined) =>
169 status === "DELETED" || status === "DELETING" || status === "DELETE_REQUESTED";
170
171 const sameJson = (a: unknown, b: unknown) =>
172 JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
173
174 interface KxEnvironmentView {
175 environmentId?: string;
176 environmentArn?: string;
177 name?: string;
178 status?: KxEnvironmentStatus;
179 kmsKeyId?: string;
180 description?: string;
181 transitGatewayConfiguration?: TransitGatewayConfiguration;
182 customDNSConfiguration?: CustomDNSServer[];
183 }
184
185 const toKxAttributes = Effect.fn(function* (env: KxEnvironmentView, fallbackId: string) {
186 const environmentArn = env.environmentArn ?? "";
187 const attrs: KxEnvironment["Attributes"] = {
188 environmentId: env.environmentId ?? fallbackId,
189 environmentArn,
190 name: env.name ?? "",
191 status: env.status,
192 kmsKeyId: env.kmsKeyId,
193 description: env.description,
194 transitGatewayConfiguration: env.transitGatewayConfiguration,
195 customDNSConfiguration: env.customDNSConfiguration
196 ? [...env.customDNSConfiguration]
197 : undefined,
198 tags: environmentArn ? yield* fetchKxTags(environmentArn) : {},
199 };
200 return attrs;
201 });
202
203 const readKxEnvironmentById = Effect.fn(function* (environmentId: string) {
204 const response = yield* finspace
205 .getKxEnvironment({ environmentId })
206 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
207 if (!response || isGone(response.status)) return undefined;
208 return response;
209 });
210
211 const findKxEnvironmentByName = Effect.fn(function* (name: string) {
212 const environments = yield* finspace.listKxEnvironments.items({}).pipe(
213 EffectStream.runCollect,
214 Effect.map((chunk) => Array.from(chunk)),
215 );
216 return environments.find((env) => env.name === name && !isGone(env.status));
217 });
218
219 /**
220 * A kdb environment still transitioning toward the awaited status — retried
221 * by the bounded schedule in {@link waitForKxEnvironmentStatus}.
222 */
223 class KxEnvironmentNotReady extends Data.TaggedError("KxEnvironmentNotReady")<{
224 readonly environmentId: string;
225 readonly status: string | undefined;
226 }> {}
227
228 /**
229 * A kdb environment whose asynchronous provisioning converged to the
230 * terminal `FAILED_CREATION` status.
231 */
232 export class KxEnvironmentProvisioningFailed extends Data.TaggedError(
233 "KxEnvironmentProvisioningFailed",
234 )<{
235 readonly environmentId: string;
236 readonly status: string | undefined;
237 }> {}
238
239 // Explicitly-typed retry wrapper — an inline `Effect.retry` in provider
240 // lifecycle code leaks `Retry.Return`'s conditional type into declaration
241 // emit and widens the provider layer to `unknown` for every consumer of
242 // `AWS.providers()`.
243 const retryWhileNotReady = <A, E extends { readonly _tag: string }, R>(
244 self: Effect.Effect<A, E, R>,
245 ): Effect.Effect<A, E, R> =>
246 Effect.retry(self, {
247 while: (e) => e._tag === "KxEnvironmentNotReady",
248 // kdb environment provisioning is slow; poll every 20s up to ~40 min.
249 schedule: Schedule.max([Schedule.spaced("20 seconds"), Schedule.recurs(120)]),
250 });
251
252 // Deleting an environment that is still creating/updating surfaces as a
253 // Conflict — bounded retry through it. Explicitly typed for the same
254 // declaration-emit reason as retryWhileNotReady.
255 const retryThroughConflict = <A, E extends { readonly _tag: string }, R>(
256 self: Effect.Effect<A, E, R>,
257 ): Effect.Effect<A, E, R> =>
258 Effect.retry(self, {
259 while: (e) => e._tag === "ConflictException",
260 schedule: Schedule.max([Schedule.spaced("15 seconds"), Schedule.recurs(8)]),
261 });
262
263 const waitForKxEnvironmentStatus = (environmentId: string, target: "CREATED" | "DELETED") =>
264 retryWhileNotReady(
265 Effect.gen(function* () {
266 const response = yield* finspace
267 .getKxEnvironment({ environmentId })
268 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
269 const status = response?.status;
270 if (target === "DELETED") {
271 if (response === undefined || isGone(status)) return;
272 return yield* new KxEnvironmentNotReady({ environmentId, status });
273 }
274 if (status === "CREATED") return;
275 if (status === "FAILED_CREATION") {
276 return yield* new KxEnvironmentProvisioningFailed({ environmentId, status });
277 }
278 return yield* new KxEnvironmentNotReady({ environmentId, status });
279 }),
280 );
281
282 export const KxEnvironmentProvider = () =>
283 Provider.effect(
284 KxEnvironment,
285 Effect.gen(function* () {
286 return {
287 stables: ["environmentId", "environmentArn"],
288 list: () =>
289 Effect.gen(function* () {
290 const environments = yield* finspace.listKxEnvironments.items({}).pipe(
291 EffectStream.runCollect,
292 Effect.map((chunk) => Array.from(chunk)),
293 );
294 return yield* Effect.forEach(
295 environments.filter((env) => !isGone(env.status)),
296 (env) => toKxAttributes(env, env.environmentId ?? ""),
297 { concurrency: 5 },
298 );
299 }),
300 read: Effect.fn(function* ({ id, olds, output }) {
301 const env = output?.environmentId
302 ? yield* readKxEnvironmentById(output.environmentId)
303 : yield* findKxEnvironmentByName(yield* createKxEnvironmentName(id, olds ?? {}));
304 if (!env) return undefined;
305 const attrs = yield* toKxAttributes(env, output?.environmentId ?? "");
306 return (yield* hasAlchemyTags(id, attrs.tags as Tags)) ? attrs : Unowned(attrs);
307 }),
308 diff: Effect.fn(function* ({ news, olds }) {
309 if (!isResolved(news)) return;
310 if (olds === undefined) return;
311 // The KMS key is fixed at creation.
312 if (olds.kmsKeyId !== news.kmsKeyId) {
313 return { action: "replace" } as const;
314 }
315 // FinSpace does not support changing or detaching an attached
316 // network (UpdateKxEnvironmentNetwork is attach-once).
317 const hadNetwork =
318 olds.transitGatewayConfiguration !== undefined ||
319 olds.customDNSConfiguration !== undefined;
320 if (
321 hadNetwork &&
322 (!sameJson(olds.transitGatewayConfiguration, news.transitGatewayConfiguration) ||
323 !sameJson(olds.customDNSConfiguration, news.customDNSConfiguration))
324 ) {
325 return { action: "replace" } as const;
326 }
327 }),
328 reconcile: Effect.fn(function* ({ id, news, output, session }) {
329 if (!news) {
330 return yield* new KxEnvironmentInvalidProps({
331 message: "FinSpace KxEnvironment requires props",
332 });
333 }
334 const name = yield* createKxEnvironmentName(id, news);
335 const internalTags = yield* createInternalTags(id);
336 const desiredTags = { ...internalTags, ...news.tags };
337
338 // Observe — prefer the cached id; fall back to a name lookup so a
339 // create whose state failed to persist is adopted, not duplicated.
340 let env: KxEnvironmentView | undefined = output?.environmentId
341 ? yield* readKxEnvironmentById(output.environmentId)
342 : yield* findKxEnvironmentByName(name);
343
344 // Ensure — create if missing, then wait for CREATED.
345 if (env === undefined) {
346 const created = yield* finspace.createKxEnvironment({
347 name,
348 description: news.description,
349 kmsKeyId: news.kmsKeyId,
350 tags: desiredTags,
351 });
352 if (!created.environmentId) {
353 return yield* new KxEnvironmentUnexpectedResponse({
354 message: `CreateKxEnvironment for '${name}' returned no id`,
355 });
356 }
357 yield* session.note(`Creating kdb environment ${name} (${created.environmentId})...`);
358 yield* waitForKxEnvironmentStatus(created.environmentId, "CREATED");
359 env = yield* readKxEnvironmentById(created.environmentId);
360 if (env === undefined) {
361 return yield* new KxEnvironmentUnexpectedResponse({
362 message: `failed to read created kdb environment ${name}`,
363 });
364 }
365 }
366 const environmentId = env.environmentId;
367 if (environmentId === undefined) {
368 return yield* new KxEnvironmentUnexpectedResponse({
369 message: `kdb environment '${name}' has no environmentId`,
370 });
371 }
372
373 // Sync network — UpdateKxEnvironmentNetwork is attach-once: apply
374 // only when a network is desired and none is observed. (Changing
375 // an attached network is a replacement — see diff.)
376 const wantsNetwork =
377 news.transitGatewayConfiguration !== undefined ||
378 news.customDNSConfiguration !== undefined;
379 const hasNetwork =
380 env.transitGatewayConfiguration !== undefined ||
381 (env.customDNSConfiguration !== undefined && env.customDNSConfiguration.length > 0);
382 if (wantsNetwork && !hasNetwork) {
383 yield* finspace.updateKxEnvironmentNetwork({
384 environmentId,
385 transitGatewayConfiguration: news.transitGatewayConfiguration,
386 customDNSConfiguration: news.customDNSConfiguration,
387 });
388 yield* session.note(`Attaching network to kdb environment ${name}...`);
389 yield* waitForKxEnvironmentStatus(environmentId, "CREATED");
390 env = (yield* readKxEnvironmentById(environmentId)) ?? env;
391 }
392
393 // Sync mutable settings — only call UpdateKxEnvironment on drift.
394 const needsUpdate =
395 name !== env.name ||
396 (news.description !== undefined && news.description !== env.description);
397 if (needsUpdate) {
398 yield* finspace.updateKxEnvironment({
399 environmentId,
400 name,
401 description: news.description,
402 });
403 yield* session.note(`Updated kdb environment ${name}`);
404 }
405
406 // Sync tags — diff against observed cloud tags.
407 const attrs = yield* toKxAttributes(env, environmentId);
408 if (attrs.environmentArn) {
409 const { removed, upsert } = diffTags(attrs.tags, desiredTags);
410 if (removed.length > 0) {
411 yield* finspace.untagResource({
412 resourceArn: attrs.environmentArn,
413 tagKeys: removed,
414 });
415 }
416 if (upsert.length > 0) {
417 yield* finspace.tagResource({
418 resourceArn: attrs.environmentArn,
419 tags: Object.fromEntries(upsert.map(({ Key, Value }) => [Key, Value])),
420 });
421 }
422 }
423
424 yield* session.note(attrs.environmentArn);
425
426 const final = yield* readKxEnvironmentById(environmentId);
427 if (!final) {
428 return yield* new KxEnvironmentUnexpectedResponse({
429 message: `failed to read reconciled kdb environment ${name}`,
430 });
431 }
432 return yield* toKxAttributes(final, environmentId);
433 }),
434 delete: Effect.fn(function* ({ output }) {
435 yield* retryThroughConflict(
436 finspace
437 .deleteKxEnvironment({ environmentId: output.environmentId })
438 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void)),
439 );
440 yield* waitForKxEnvironmentStatus(output.environmentId, "DELETED");
441 }),
442 };
443 }),
444 );