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

main
ts 375 lines 14.3 KB
Raw
1 import * as medicalimaging from "@distilled.cloud/aws/medical-imaging";
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 } 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 Stream from "effect/Stream";
12 import type { Providers } from "../Providers.ts";
13
14 export interface DatastoreProps {
15 /**
16 * Name of the data store. If omitted, a deterministic physical name is
17 * generated. AWS HealthImaging has no update operation, so changing the
18 * name replaces the data store.
19 */
20 datastoreName?: string;
21 /**
22 * ARN of a customer-managed KMS key used to encrypt the data store at
23 * rest. Changing the key replaces the data store.
24 * @default AWS-owned key
25 */
26 kmsKeyArn?: string;
27 /**
28 * ARN of a Lambda authorizer used to gate data access. Changing the
29 * authorizer replaces the data store.
30 */
31 lambdaAuthorizerArn?: string;
32 /**
33 * Lossless compression format for stored image frames — `"HTJ2K"` or
34 * `"JPEG_2000_LOSSLESS"`. Changing the format replaces the data store.
35 * @default "HTJ2K"
36 */
37 losslessStorageFormat?: string;
38 /**
39 * User-defined tags for the data store.
40 */
41 tags?: Record<string, string>;
42 }
43
44 export interface Datastore extends Resource<
45 "AWS.MedicalImaging.Datastore",
46 DatastoreProps,
47 {
48 /** Server-assigned unique id of the data store. */
49 datastoreId: string;
50 /** Name of the data store. */
51 datastoreName: string;
52 /** ARN of the data store. */
53 datastoreArn: string;
54 /** Current lifecycle status (e.g. `CREATING`, `ACTIVE`). */
55 datastoreStatus: string;
56 /** ARN of the KMS key encrypting the data store, if customer-managed. */
57 kmsKeyArn: string | undefined;
58 /** Tags on the data store (user + internal Alchemy tags). */
59 tags: Record<string, string>;
60 },
61 never,
62 Providers
63 > {}
64
65 /**
66 * An AWS HealthImaging data store — a HIPAA-eligible store for DICOM P10
67 * medical images with sub-second image-frame retrieval.
68 *
69 * Data stores provision asynchronously (CREATING → ACTIVE, typically a few
70 * minutes) and must be empty (no image sets) before they can be deleted.
71 * HealthImaging has no update API, so every property except tags triggers a
72 * replacement.
73 * ### Creating a Data Store
74 * **Example:** Basic Data Store
75 * ```typescript
76 * const datastore = yield* Datastore("Imaging", {});
77 * ```
78 *
79 * **Example:** Data Store with a Customer-Managed KMS Key
80 * ```typescript
81 * const datastore = yield* Datastore("Imaging", {
82 * kmsKeyArn: key.keyArn,
83 * tags: { team: "radiology" },
84 * });
85 * ```
86 *
87 * ### Importing DICOM Data
88 * **Example:** Reference the Data Store Id
89 * ```typescript
90 * const datastore = yield* Datastore("Imaging", {});
91 * // startDICOMImportJob and image-set APIs address the store by id
92 * const id = datastore.datastoreId;
93 * ```
94 *
95 * @resource
96 */
97 export const Datastore = Resource<Datastore>("AWS.MedicalImaging.Datastore");
98
99 /**
100 * Raised when a data store never reaches `ACTIVE` (or its create fails)
101 * within the bounded provisioning wait.
102 */
103 export class DatastoreNotReady extends Data.TaggedError("DatastoreNotReady")<{
104 message: string;
105 }> {}
106
107 /**
108 * Raised when the HealthImaging API omits an expected field (e.g. the
109 * data store ARN) from a response.
110 */
111 export class DatastoreIncomplete extends Data.TaggedError("DatastoreIncomplete")<{
112 message: string;
113 }> {}
114
115 /** CreateDatastore requires a client token; derive it from the instance id
116 * so engine retries of the same instance are idempotent. */
117 const createToken = (instanceId: string): string =>
118 instanceId.replaceAll(/[^a-zA-Z0-9]/g, "").slice(0, 64) || "alchemy";
119
120 /** Provisioning typically completes in a few minutes; budget 40 × 15s. */
121 const retryWhileNotReady = <A, E extends { readonly _tag: string }, R>(
122 self: Effect.Effect<A, E, R>,
123 ): Effect.Effect<A, E, R> =>
124 Effect.retry(self, {
125 while: (e) => e._tag === "DatastoreNotReady",
126 schedule: Schedule.max([Schedule.fixed("15 seconds"), Schedule.recurs(40)]),
127 });
128
129 /** A data store mid-create rejects deletion with ConflictException — retry
130 * (bounded) while it settles. */
131 const retryWhileConflict = <A, E extends { readonly _tag: string }, R>(
132 self: Effect.Effect<A, E, R>,
133 ): Effect.Effect<A, E, R> =>
134 Effect.retry(self, {
135 while: (e) => e._tag === "ConflictException",
136 schedule: Schedule.max([Schedule.fixed("15 seconds"), Schedule.recurs(20)]),
137 });
138
139 const toTagRecord = (
140 tags: { [key: string]: string | undefined } | undefined,
141 ): Record<string, string> =>
142 Object.fromEntries(
143 Object.entries(tags ?? {}).filter((entry): entry is [string, string] => entry[1] !== undefined),
144 );
145
146 export const DatastoreProvider = () =>
147 Provider.effect(
148 Datastore,
149 Effect.gen(function* () {
150 const toName = (id: string, props: Partial<DatastoreProps>) =>
151 props.datastoreName
152 ? Effect.succeed(props.datastoreName)
153 : createPhysicalName({ id, maxLength: 64 });
154
155 const getById = Effect.fn(function* (datastoreId: string) {
156 const response = yield* medicalimaging
157 .getDatastore({ datastoreId })
158 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
159 const properties = response?.datastoreProperties;
160 if (properties === undefined) return undefined;
161 if (properties.datastoreStatus === "DELETED" || properties.datastoreStatus === "DELETING") {
162 return undefined;
163 }
164 return properties;
165 });
166
167 // Data stores are addressed by a server-generated id; a name-based
168 // lookup scans the paginated list (names are not unique — take the
169 // first live match).
170 const findByName = Effect.fn(function* (name: string) {
171 const matches = yield* medicalimaging.listDatastores.items({}).pipe(
172 Stream.filter(
173 (summary) =>
174 summary.datastoreName === name &&
175 summary.datastoreStatus !== "DELETED" &&
176 summary.datastoreStatus !== "DELETING",
177 ),
178 Stream.take(1),
179 Stream.runCollect,
180 );
181 const summary = Array.from(matches)[0];
182 if (summary === undefined) return undefined;
183 return yield* getById(summary.datastoreId);
184 });
185
186 const observe = Effect.fn(function* (datastoreId: string | undefined, name: string) {
187 if (datastoreId !== undefined) {
188 const properties = yield* getById(datastoreId);
189 if (properties !== undefined) return properties;
190 }
191 return yield* findByName(name);
192 });
193
194 const requireArn = Effect.fn(function* (properties: medicalimaging.DatastoreProperties) {
195 if (properties.datastoreArn === undefined) {
196 return yield* new DatastoreIncomplete({
197 message: `data store '${properties.datastoreId}' has no ARN in the GetDatastore response`,
198 });
199 }
200 return properties.datastoreArn;
201 });
202
203 const readTags = Effect.fn(function* (arn: string) {
204 const response = yield* medicalimaging
205 .listTagsForResource({ resourceArn: arn })
206 .pipe(Effect.orElseSucceed(() => undefined));
207 return toTagRecord(response?.tags);
208 });
209
210 const toAttrs = Effect.fn(function* (properties: medicalimaging.DatastoreProperties) {
211 const arn = yield* requireArn(properties);
212 return {
213 datastoreId: properties.datastoreId,
214 datastoreName: properties.datastoreName,
215 datastoreArn: arn,
216 datastoreStatus: properties.datastoreStatus as string,
217 kmsKeyArn: properties.kmsKeyArn,
218 tags: yield* readTags(arn),
219 };
220 });
221
222 const waitForActive = Effect.fn(function* (datastoreId: string) {
223 return yield* Effect.gen(function* () {
224 const properties = yield* getById(datastoreId);
225 if (properties === undefined) {
226 return yield* new DatastoreNotReady({
227 message: `data store '${datastoreId}' disappeared while waiting for ACTIVE`,
228 });
229 }
230 if (properties.datastoreStatus === "CREATE_FAILED") {
231 return yield* new DatastoreIncomplete({
232 message: `data store '${datastoreId}' failed to create (status: CREATE_FAILED)`,
233 });
234 }
235 if (properties.datastoreStatus !== "ACTIVE") {
236 return yield* new DatastoreNotReady({
237 message: `data store '${datastoreId}' not active (status: ${properties.datastoreStatus})`,
238 });
239 }
240 return properties;
241 }).pipe(retryWhileNotReady);
242 });
243
244 return {
245 stables: ["datastoreId", "datastoreArn", "datastoreName"],
246
247 diff: Effect.fn(function* ({ id, olds, news }) {
248 if (!isResolved(news)) return undefined;
249 const n = news;
250 const o = olds;
251 if (n === undefined || o === undefined) return undefined;
252 // HealthImaging has no UpdateDatastore — every property except
253 // tags is create-only and forces a replacement.
254 if ((yield* toName(id, o)) !== (yield* toName(id, n))) {
255 return { action: "replace" } as const;
256 }
257 if ((n.kmsKeyArn ?? undefined) !== (o.kmsKeyArn ?? undefined)) {
258 return { action: "replace" } as const;
259 }
260 if ((n.lambdaAuthorizerArn ?? undefined) !== (o.lambdaAuthorizerArn ?? undefined)) {
261 return { action: "replace" } as const;
262 }
263 if ((n.losslessStorageFormat ?? undefined) !== (o.losslessStorageFormat ?? undefined)) {
264 return { action: "replace" } as const;
265 }
266 // tags → default update
267 }),
268
269 read: Effect.fn(function* ({ id, olds, output }) {
270 const name = output?.datastoreName ?? (yield* toName(id, olds ?? {}));
271 const properties = yield* observe(output?.datastoreId, name);
272 if (properties === undefined) return undefined;
273 const attrs = yield* toAttrs(properties);
274 return (yield* hasAlchemyTags(id, attrs.tags)) ? attrs : Unowned(attrs);
275 }),
276
277 reconcile: Effect.fn(function* ({ id, news, output, session, instanceId }) {
278 const props = news!;
279 const name = output?.datastoreName ?? (yield* toName(id, props));
280 const internalTags = yield* createInternalTags(id);
281 const desiredTags = { ...props.tags, ...internalTags };
282
283 // 1. OBSERVE — cloud state is authoritative; output is only an
284 // id cache.
285 let observed = yield* observe(output?.datastoreId, name);
286
287 // 2. ENSURE — create if missing; a ConflictException is a create
288 // race (or a leftover CREATE_FAILED store), resolved by re-reading.
289 if (observed === undefined) {
290 const created = yield* medicalimaging
291 .createDatastore({
292 datastoreName: name,
293 clientToken: createToken(instanceId),
294 kmsKeyArn: props.kmsKeyArn,
295 lambdaAuthorizerArn: props.lambdaAuthorizerArn,
296 losslessStorageFormat: props.losslessStorageFormat,
297 tags: desiredTags,
298 })
299 .pipe(Effect.catchTag("ConflictException", () => Effect.undefined));
300 observed =
301 created !== undefined ? yield* getById(created.datastoreId) : yield* findByName(name);
302 }
303 if (observed === undefined) {
304 return yield* new DatastoreIncomplete({
305 message: `data store '${name}' not found after create`,
306 });
307 }
308
309 // Provisioning is async (CREATING → ACTIVE); wait bounded so tag
310 // syncs and dependents see an ACTIVE store.
311 observed = yield* waitForActive(observed.datastoreId);
312 const arn = yield* requireArn(observed);
313
314 // 3. SYNC TAGS — diff against OBSERVED cloud tags.
315 const observedTags = yield* readTags(arn);
316 const { removed, upsert } = diffTags(observedTags, desiredTags);
317 if (upsert.length > 0) {
318 yield* medicalimaging.tagResource({
319 resourceArn: arn,
320 tags: Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value])),
321 });
322 }
323 if (removed.length > 0) {
324 yield* medicalimaging.untagResource({
325 resourceArn: arn,
326 tagKeys: removed,
327 });
328 }
329
330 yield* session.note(observed.datastoreId);
331 return yield* toAttrs(observed);
332 }),
333
334 delete: Effect.fn(function* ({ output }) {
335 // Already deleting or gone is success; a store mid-create rejects
336 // deletion with ConflictException (retried, bounded). A non-empty
337 // store also raises ConflictException and surfaces the typed error
338 // once the retry budget is exhausted.
339 const observed = yield* medicalimaging
340 .getDatastore({ datastoreId: output.datastoreId })
341 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
342 const status = observed?.datastoreProperties.datastoreStatus;
343 if (status === undefined || status === "DELETING" || status === "DELETED") {
344 return;
345 }
346 yield* medicalimaging.deleteDatastore({ datastoreId: output.datastoreId }).pipe(
347 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
348 retryWhileConflict,
349 );
350 }),
351
352 list: () =>
353 medicalimaging.listDatastores.items({}).pipe(
354 Stream.filter(
355 (summary) =>
356 summary.datastoreStatus !== "DELETED" && summary.datastoreStatus !== "DELETING",
357 ),
358 Stream.runCollect,
359 Effect.flatMap((summaries) =>
360 Effect.forEach(
361 Array.from(summaries),
362 (summary) =>
363 getById(summary.datastoreId).pipe(
364 Effect.flatMap((properties) =>
365 properties === undefined ? Effect.undefined : toAttrs(properties),
366 ),
367 ),
368 { concurrency: 4 },
369 ),
370 ),
371 Effect.map((attrs) => attrs.filter((a): a is NonNullable<typeof a> => a !== undefined)),
372 ),
373 };
374 }),
375 );