@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 402 lines 14.4 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 type { Providers } from "../Providers.ts";
12
13 export class EnvironmentUnexpectedResponse extends Data.TaggedError(
14 "EnvironmentUnexpectedResponse",
15 )<{
16 readonly message: string;
17 readonly cause?: unknown;
18 }> {}
19
20 export type EnvironmentStatus = finspace.EnvironmentStatus;
21 export type FederationMode = finspace.FederationMode;
22 export type FederationParameters = finspace.FederationParameters;
23 export type SuperuserParameters = finspace.SuperuserParameters;
24
25 export interface EnvironmentProps {
26 /**
27 * Name of the FinSpace environment.
28 * @default ${app}-${id}-${stage}-${suffix}
29 */
30 name?: string;
31 /**
32 * A description of the environment.
33 */
34 description?: string;
35 /**
36 * The KMS key id used to encrypt data in the environment. Changing it
37 * replaces the environment.
38 */
39 kmsKeyId?: string;
40 /**
41 * Authentication mode for the environment — `FEDERATED` (SAML) or `LOCAL`.
42 */
43 federationMode?: FederationMode;
44 /**
45 * SAML federation configuration, required when `federationMode` is
46 * `FEDERATED`.
47 */
48 federationParameters?: FederationParameters;
49 /**
50 * Configuration of the superuser created with the environment. Only used
51 * at creation; changing it replaces the environment.
52 */
53 superuserParameters?: SuperuserParameters;
54 /**
55 * ARNs of the sample data bundles to install. Only used at creation;
56 * changing it replaces the environment.
57 */
58 dataBundles?: string[];
59 /**
60 * Tags to associate with the environment.
61 */
62 tags?: Record<string, string>;
63 }
64
65 export interface Environment extends Resource<
66 "AWS.FinSpace.Environment",
67 EnvironmentProps,
68 {
69 /**
70 * Service-assigned unique identifier of the environment.
71 */
72 environmentId: string;
73 /**
74 * ARN of the environment.
75 */
76 environmentArn: string;
77 /**
78 * The environment's name.
79 */
80 name: string;
81 /**
82 * Current lifecycle status of the environment.
83 */
84 status: EnvironmentStatus | undefined;
85 /**
86 * Sign-in URL for the web application of the environment.
87 */
88 environmentUrl: string | undefined;
89 /**
90 * URL of the integrated SageMaker Studio domain.
91 */
92 sageMakerStudioDomainUrl: string | undefined;
93 /**
94 * ID of the KMS key encrypting the environment.
95 */
96 kmsKeyId: string | undefined;
97 /**
98 * AWS account ID of the dedicated service account associated with the
99 * environment.
100 */
101 dedicatedServiceAccountId: string | undefined;
102 /**
103 * Current tags reported for the environment.
104 */
105 tags: Record<string, string>;
106 },
107 never,
108 Providers
109 > {}
110
111 /**
112 * An Amazon FinSpace environment — a managed data management and analytics
113 * workspace for the financial services industry.
114 *
115 * :::caution
116 * FinSpace is closed to new customers and environment provisioning takes
117 * ~20 minutes and bills while it exists. Live lifecycle tests are gated
118 * behind `AWS_TEST_FINSPACE=1`.
119 * :::
120 * ### Creating Environments
121 * **Example:** Basic Environment
122 * ```typescript
123 * import * as AWS from "@alchemy.run/aws";
124 *
125 * const env = yield* AWS.FinSpace.Environment("Analytics", {
126 * description: "research analytics environment",
127 * });
128 * ```
129 *
130 * **Example:** Federated Environment
131 * ```typescript
132 * const env = yield* AWS.FinSpace.Environment("Analytics", {
133 * federationMode: "FEDERATED",
134 * federationParameters: {
135 * samlMetadataURL: "https://idp.example.com/metadata.xml",
136 * federationProviderName: "idp.example.com",
137 * applicationCallBackURL: "https://example.com/callback",
138 * },
139 * });
140 * ```
141 *
142 * @resource
143 */
144 export const Environment = Resource<Environment>("AWS.FinSpace.Environment");
145
146 const createEnvironmentName = (id: string, props: { name?: string | undefined }) =>
147 props.name ? Effect.succeed(props.name) : createPhysicalName({ id, maxLength: 255 });
148
149 const fetchTags = Effect.fn(function* (arn: string) {
150 const response = yield* finspace
151 .listTagsForResource({ resourceArn: arn })
152 .pipe(
153 Effect.catchTag(
154 ["ResourceNotFoundException", "InvalidRequestException"],
155 () => Effect.undefined,
156 ),
157 );
158 return Object.fromEntries(
159 Object.entries(response?.tags ?? {}).flatMap(([key, value]) =>
160 value === undefined ? [] : [[key, value] as const],
161 ),
162 );
163 });
164
165 const toAttributes = Effect.fn(function* (env: finspace.Environment, fallbackId: string) {
166 const environmentId = env.environmentId ?? fallbackId;
167 const environmentArn = env.environmentArn ?? "";
168 const attrs: Environment["Attributes"] = {
169 environmentId,
170 environmentArn,
171 name: env.name ?? "",
172 status: env.status,
173 environmentUrl: env.environmentUrl,
174 sageMakerStudioDomainUrl: env.sageMakerStudioDomainUrl,
175 kmsKeyId: env.kmsKeyId,
176 dedicatedServiceAccountId: env.dedicatedServiceAccountId,
177 tags: environmentArn ? yield* fetchTags(environmentArn) : {},
178 };
179 return attrs;
180 });
181
182 const isGone = (status: EnvironmentStatus | undefined) =>
183 status === "DELETED" || status === "DELETING" || status === "DELETE_REQUESTED";
184
185 const readEnvironmentById = Effect.fn(function* (environmentId: string) {
186 const response = yield* finspace
187 .getEnvironment({ environmentId })
188 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
189 const env = response?.environment;
190 if (!env || isGone(env.status)) return undefined;
191 return env;
192 });
193
194 // listEnvironments is not marked paginated in the Smithy model — paginate by
195 // hand, page-bounded, treating an absent/empty nextToken as terminal.
196 const listAllEnvironments = Effect.gen(function* () {
197 const environments: finspace.Environment[] = [];
198 let nextToken: string | undefined;
199 for (let page = 0; page < 20; page++) {
200 const response = yield* finspace.listEnvironments({ nextToken });
201 environments.push(...(response.environments ?? []));
202 if (!response.nextToken) break;
203 nextToken = response.nextToken;
204 }
205 return environments;
206 });
207
208 const findEnvironmentByName = Effect.fn(function* (name: string) {
209 const environments = yield* listAllEnvironments;
210 return environments.find((env) => env.name === name && !isGone(env.status));
211 });
212
213 /**
214 * An environment still transitioning toward the awaited status — retried by
215 * the bounded schedule in {@link waitForEnvironmentStatus}.
216 */
217 class EnvironmentNotReady extends Data.TaggedError("EnvironmentNotReady")<{
218 readonly environmentId: string;
219 readonly status: string | undefined;
220 }> {}
221
222 /**
223 * An environment whose asynchronous provisioning converged to the terminal
224 * `FAILED_CREATION` status.
225 */
226 export class EnvironmentProvisioningFailed extends Data.TaggedError(
227 "EnvironmentProvisioningFailed",
228 )<{
229 readonly environmentId: string;
230 readonly status: string | undefined;
231 }> {}
232
233 // Explicitly-typed retry wrapper — an inline `Effect.retry` in provider
234 // lifecycle code leaks `Retry.Return`'s conditional type into declaration
235 // emit and widens the provider layer to `unknown` for every consumer of
236 // `AWS.providers()`.
237 const retryWhileNotReady = <A, E extends { readonly _tag: string }, R>(
238 self: Effect.Effect<A, E, R>,
239 ): Effect.Effect<A, E, R> =>
240 Effect.retry(self, {
241 while: (e) => e._tag === "EnvironmentNotReady",
242 // Environment provisioning is slow (~20 min); poll every 20s up to ~40 min.
243 schedule: Schedule.max([Schedule.spaced("20 seconds"), Schedule.recurs(120)]),
244 });
245
246 const waitForEnvironmentStatus = (environmentId: string, target: "CREATED" | "DELETED") =>
247 retryWhileNotReady(
248 Effect.gen(function* () {
249 const response = yield* finspace
250 .getEnvironment({ environmentId })
251 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
252 const status = response?.environment?.status;
253 if (target === "DELETED") {
254 if (response === undefined || isGone(status)) return;
255 return yield* new EnvironmentNotReady({ environmentId, status });
256 }
257 if (status === "CREATED") return;
258 if (status === "FAILED_CREATION" || status === "SUSPENDED") {
259 return yield* new EnvironmentProvisioningFailed({ environmentId, status });
260 }
261 return yield* new EnvironmentNotReady({ environmentId, status });
262 }),
263 );
264
265 export const EnvironmentProvider = () =>
266 Provider.effect(
267 Environment,
268 Effect.gen(function* () {
269 return {
270 stables: ["environmentId", "environmentArn"],
271 list: () =>
272 Effect.gen(function* () {
273 const environments = yield* listAllEnvironments;
274 const hydrated = yield* Effect.forEach(
275 environments.filter((env) => !isGone(env.status)),
276 (env) => toAttributes(env, env.environmentId ?? ""),
277 { concurrency: 5 },
278 );
279 return hydrated;
280 }),
281 read: Effect.fn(function* ({ id, olds, output }) {
282 const env = output?.environmentId
283 ? yield* readEnvironmentById(output.environmentId)
284 : yield* findEnvironmentByName(yield* createEnvironmentName(id, olds ?? {}));
285 if (!env) return undefined;
286 const attrs = yield* toAttributes(env, output?.environmentId ?? "");
287 return (yield* hasAlchemyTags(id, attrs.tags as Tags)) ? attrs : Unowned(attrs);
288 }),
289 diff: Effect.fn(function* ({ news, olds }) {
290 if (!isResolved(news)) return;
291 if (olds === undefined) return;
292 // KMS key, superuser and data bundles are fixed at creation.
293 if (
294 olds.kmsKeyId !== news.kmsKeyId ||
295 JSON.stringify(olds.superuserParameters) !== JSON.stringify(news.superuserParameters) ||
296 JSON.stringify(olds.dataBundles) !== JSON.stringify(news.dataBundles)
297 ) {
298 return { action: "replace" } as const;
299 }
300 }),
301 reconcile: Effect.fn(function* ({ id, news, output, session }) {
302 const props = news ?? {};
303 const name = yield* createEnvironmentName(id, props);
304 const internalTags = yield* createInternalTags(id);
305 const desiredTags = { ...internalTags, ...props.tags };
306
307 // Observe — prefer the cached id; fall back to a name lookup so a
308 // create whose state failed to persist is adopted, not duplicated.
309 let env = output?.environmentId
310 ? yield* readEnvironmentById(output.environmentId)
311 : yield* findEnvironmentByName(name);
312
313 // Ensure — create if missing, then wait for CREATED.
314 if (env === undefined) {
315 const created = yield* finspace.createEnvironment({
316 name,
317 description: props.description,
318 kmsKeyId: props.kmsKeyId,
319 federationMode: props.federationMode,
320 federationParameters: props.federationParameters,
321 superuserParameters: props.superuserParameters,
322 dataBundles: props.dataBundles,
323 tags: desiredTags,
324 });
325 if (!created.environmentId) {
326 return yield* new EnvironmentUnexpectedResponse({
327 message: `CreateEnvironment for '${name}' returned no id`,
328 });
329 }
330 yield* session.note(
331 `Creating FinSpace environment ${name} (${created.environmentId})...`,
332 );
333 yield* waitForEnvironmentStatus(created.environmentId, "CREATED");
334 env = yield* readEnvironmentById(created.environmentId);
335 if (env === undefined) {
336 return yield* new EnvironmentUnexpectedResponse({
337 message: `failed to read created environment ${name}`,
338 });
339 }
340 }
341 const environmentId = env.environmentId;
342 if (environmentId === undefined) {
343 return yield* new EnvironmentUnexpectedResponse({
344 message: `environment '${name}' has no environmentId`,
345 });
346 }
347
348 // Sync mutable settings — only call UpdateEnvironment on drift.
349 const needsUpdate =
350 name !== env.name ||
351 (props.description !== undefined && props.description !== env.description) ||
352 (props.federationMode !== undefined && props.federationMode !== env.federationMode);
353 if (needsUpdate) {
354 yield* finspace.updateEnvironment({
355 environmentId,
356 name,
357 description: props.description,
358 federationMode: props.federationMode,
359 federationParameters: props.federationParameters,
360 });
361 yield* session.note(`Updated FinSpace environment ${name}`);
362 }
363
364 // Sync tags — diff against observed cloud tags.
365 const attrs = yield* toAttributes(env, environmentId);
366 if (attrs.environmentArn) {
367 const { removed, upsert } = diffTags(attrs.tags, desiredTags);
368 if (removed.length > 0) {
369 yield* finspace.untagResource({
370 resourceArn: attrs.environmentArn,
371 tagKeys: removed,
372 });
373 }
374 if (upsert.length > 0) {
375 yield* finspace.tagResource({
376 resourceArn: attrs.environmentArn,
377 tags: Object.fromEntries(upsert.map(({ Key, Value }) => [Key, Value])),
378 });
379 }
380 }
381
382 yield* session.note(attrs.environmentArn);
383
384 const final = yield* readEnvironmentById(environmentId);
385 if (!final) {
386 return yield* new EnvironmentUnexpectedResponse({
387 message: `failed to read reconciled environment ${name}`,
388 });
389 }
390 return yield* toAttributes(final, environmentId);
391 }),
392 delete: Effect.fn(function* ({ output }) {
393 yield* finspace
394 .deleteEnvironment({ environmentId: output.environmentId })
395 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
396 // Deletion is irreversible once initiated; wait until the service
397 // reports it gone (DELETE_REQUESTED/DELETING/DELETED or NotFound).
398 yield* waitForEnvironmentStatus(output.environmentId, "DELETED");
399 }),
400 };
401 }),
402 );