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
| 1 | import * as healthlake from "@distilled.cloud/aws/healthlake"; |
| 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 type { Providers } from "../Providers.ts"; |
| 12 | |
| 13 | export class FHIRDatastoreNotReady extends Data.TaggedError("FHIRDatastoreNotReady")<{ |
| 14 | readonly message: string; |
| 15 | readonly cause?: unknown; |
| 16 | }> {} |
| 17 | |
| 18 | export interface FHIRDatastoreIdentityProviderProps { |
| 19 | /** |
| 20 | * Authorization strategy for the data store — `"AWS_AUTH"` (SigV4, the |
| 21 | * default), `"SMART_ON_FHIR"` or `"SMART_ON_FHIR_V1"`. |
| 22 | */ |
| 23 | authorizationStrategy: healthlake.AuthorizationStrategy; |
| 24 | /** |
| 25 | * Whether fine-grained (SMART on FHIR scope based) authorization is |
| 26 | * enabled. |
| 27 | * @default false |
| 28 | */ |
| 29 | fineGrainedAuthorizationEnabled?: boolean; |
| 30 | /** |
| 31 | * JSON metadata elements the identity provider uses in its authorization |
| 32 | * flow (issuer, authorization/token endpoints, etc.). |
| 33 | */ |
| 34 | metadata?: string; |
| 35 | /** |
| 36 | * ARN of the Lambda function the data store invokes to decode SMART on |
| 37 | * FHIR access tokens. |
| 38 | */ |
| 39 | idpLambdaArn?: string; |
| 40 | } |
| 41 | |
| 42 | export interface FHIRDatastoreProps { |
| 43 | /** |
| 44 | * Name of the data store. Names do not have to be unique within an |
| 45 | * account; the data store is identified by its auto-assigned id. Updated |
| 46 | * in place. |
| 47 | * @default a deterministic physical name derived from app, stage and logical id |
| 48 | */ |
| 49 | datastoreName?: string; |
| 50 | /** |
| 51 | * FHIR release version supported by the data store. Only `"R4"` is |
| 52 | * currently supported. Changing this replaces the data store. |
| 53 | * @default "R4" |
| 54 | */ |
| 55 | datastoreTypeVersion?: healthlake.FHIRVersion; |
| 56 | /** |
| 57 | * Customer-managed KMS key (id, ARN or alias) used to encrypt the data |
| 58 | * store at rest. Changing this replaces the data store. |
| 59 | * @default an AWS-owned KMS key |
| 60 | */ |
| 61 | kmsKeyId?: string; |
| 62 | /** |
| 63 | * Preload the data store with synthetic sample data on creation — |
| 64 | * `"SYNTHEA"` loads ~100k synthetic patient records. Changing this |
| 65 | * replaces the data store. |
| 66 | * @default no preloaded data |
| 67 | */ |
| 68 | preloadDataType?: healthlake.PreloadDataType; |
| 69 | /** |
| 70 | * Identity provider configuration for SMART on FHIR authorization. |
| 71 | * Updated in place. |
| 72 | * @default AWS_AUTH (SigV4) |
| 73 | */ |
| 74 | identityProviderConfiguration?: FHIRDatastoreIdentityProviderProps; |
| 75 | /** |
| 76 | * User-defined tags for the data store. |
| 77 | */ |
| 78 | tags?: Record<string, string>; |
| 79 | } |
| 80 | |
| 81 | export interface FHIRDatastore extends Resource< |
| 82 | "AWS.HealthLake.FHIRDatastore", |
| 83 | FHIRDatastoreProps, |
| 84 | { |
| 85 | /** The unique ID of the datastore. */ |
| 86 | datastoreId: string; |
| 87 | /** The ARN of the datastore. */ |
| 88 | datastoreArn: string; |
| 89 | /** The name of the datastore. */ |
| 90 | datastoreName: string; |
| 91 | /** The current status of the datastore (`ACTIVE`, `CREATING`, ...). */ |
| 92 | datastoreStatus: string; |
| 93 | /** The FHIR REST API endpoint of the datastore. */ |
| 94 | datastoreEndpoint: string; |
| 95 | /** The FHIR version of the datastore (`R4`). */ |
| 96 | datastoreTypeVersion: string; |
| 97 | /** The tags applied to the datastore. */ |
| 98 | tags: Record<string, string>; |
| 99 | }, |
| 100 | never, |
| 101 | Providers |
| 102 | > {} |
| 103 | |
| 104 | /** |
| 105 | * An AWS HealthLake FHIR-enabled data store — a HIPAA-eligible, managed |
| 106 | * store for FHIR R4 health data with a FHIR REST endpoint plus bulk |
| 107 | * import/export. |
| 108 | * |
| 109 | * Data stores take roughly 15-30 minutes to provision (`CREATING` → |
| 110 | * `ACTIVE`) and are billed while they exist; deletion is also asynchronous |
| 111 | * (`DELETING` → gone). Destroy data stores you are not using. |
| 112 | * ### Creating a Data Store |
| 113 | * **Example:** Basic FHIR R4 Data Store |
| 114 | * ```typescript |
| 115 | * const datastore = yield* FHIRDatastore("Records", {}); |
| 116 | * ``` |
| 117 | * |
| 118 | * **Example:** Data Store Preloaded with Synthetic Data |
| 119 | * ```typescript |
| 120 | * const datastore = yield* FHIRDatastore("Sandbox", { |
| 121 | * preloadDataType: "SYNTHEA", |
| 122 | * }); |
| 123 | * ``` |
| 124 | * |
| 125 | * ### Encryption |
| 126 | * **Example:** Data Store Encrypted with a Customer-Managed KMS Key |
| 127 | * ```typescript |
| 128 | * const key = yield* KMS.Key("RecordsKey", { |
| 129 | * description: "healthlake data store key", |
| 130 | * }); |
| 131 | * const datastore = yield* FHIRDatastore("Records", { |
| 132 | * kmsKeyId: key.keyArn, |
| 133 | * }); |
| 134 | * ``` |
| 135 | * |
| 136 | * @resource |
| 137 | */ |
| 138 | export const FHIRDatastore = Resource<FHIRDatastore>("AWS.HealthLake.FHIRDatastore"); |
| 139 | |
| 140 | const DEFAULT_FHIR_VERSION: healthlake.FHIRVersion = "R4"; |
| 141 | |
| 142 | const toIdpConfig = ( |
| 143 | props: FHIRDatastoreIdentityProviderProps | undefined, |
| 144 | ): healthlake.IdentityProviderConfiguration | undefined => |
| 145 | props === undefined |
| 146 | ? undefined |
| 147 | : { |
| 148 | AuthorizationStrategy: props.authorizationStrategy, |
| 149 | FineGrainedAuthorizationEnabled: props.fineGrainedAuthorizationEnabled, |
| 150 | Metadata: props.metadata, |
| 151 | IdpLambdaArn: props.idpLambdaArn, |
| 152 | }; |
| 153 | |
| 154 | const sameIdpConfig = ( |
| 155 | observed: healthlake.IdentityProviderConfiguration | undefined, |
| 156 | desired: healthlake.IdentityProviderConfiguration, |
| 157 | ): boolean => |
| 158 | observed !== undefined && |
| 159 | observed.AuthorizationStrategy === desired.AuthorizationStrategy && |
| 160 | (observed.FineGrainedAuthorizationEnabled ?? false) === |
| 161 | (desired.FineGrainedAuthorizationEnabled ?? false) && |
| 162 | observed.Metadata === desired.Metadata && |
| 163 | observed.IdpLambdaArn === desired.IdpLambdaArn; |
| 164 | |
| 165 | export const FHIRDatastoreProvider = () => |
| 166 | Provider.effect( |
| 167 | FHIRDatastore, |
| 168 | Effect.gen(function* () { |
| 169 | const toName = (id: string, props: Partial<FHIRDatastoreProps>) => |
| 170 | props.datastoreName |
| 171 | ? Effect.succeed(props.datastoreName) |
| 172 | : createPhysicalName({ id, maxLength: 256 }); |
| 173 | |
| 174 | const readDatastoreTags = Effect.fn(function* (arn: string) { |
| 175 | const response = yield* healthlake |
| 176 | .listTagsForResource({ ResourceARN: arn }) |
| 177 | .pipe(Effect.orElseSucceed(() => ({ Tags: [] }))); |
| 178 | const tags: Record<string, string> = {}; |
| 179 | for (const tag of response.Tags ?? []) { |
| 180 | tags[tag.Key] = tag.Value; |
| 181 | } |
| 182 | return tags; |
| 183 | }); |
| 184 | |
| 185 | // Describe by id; typed not-found → undefined. A data store in |
| 186 | // DELETED status still describes for a while — callers decide how to |
| 187 | // treat terminal/transitional statuses. |
| 188 | const readDatastore = Effect.fn(function* (datastoreId: string) { |
| 189 | const response = yield* healthlake |
| 190 | .describeFHIRDatastore({ DatastoreId: datastoreId }) |
| 191 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)); |
| 192 | return response?.DatastoreProperties; |
| 193 | }); |
| 194 | |
| 195 | const isGoneOrGoing = (properties: healthlake.DatastoreProperties | undefined) => |
| 196 | properties === undefined || |
| 197 | properties.DatastoreStatus === "DELETED" || |
| 198 | properties.DatastoreStatus === "DELETING"; |
| 199 | |
| 200 | // Data store ids are auto-assigned; recover an existing instance from |
| 201 | // its deterministic name (bounded pagination, name-filtered). |
| 202 | const findByName = Effect.fn(function* (name: string) { |
| 203 | let nextToken: string | undefined; |
| 204 | for (let page = 0; page < 20; page++) { |
| 205 | const response = yield* healthlake.listFHIRDatastores({ |
| 206 | Filter: { DatastoreName: name }, |
| 207 | NextToken: nextToken, |
| 208 | }); |
| 209 | const match = (response.DatastorePropertiesList ?? []).find( |
| 210 | (properties) => !isGoneOrGoing(properties), |
| 211 | ); |
| 212 | if (match !== undefined) return match; |
| 213 | nextToken = response.NextToken; |
| 214 | if (!nextToken) break; |
| 215 | } |
| 216 | return undefined; |
| 217 | }); |
| 218 | |
| 219 | // Bounded readiness wait. Provisioning typically completes in 15-30 |
| 220 | // minutes; budget ~35 min (70 * 30s). Terminal failure statuses stop |
| 221 | // the wait immediately. |
| 222 | const waitForActive = Effect.fn(function* (datastoreId: string) { |
| 223 | const properties = yield* readDatastore(datastoreId).pipe( |
| 224 | Effect.repeat({ |
| 225 | schedule: Schedule.max([Schedule.fixed("30 seconds"), Schedule.recurs(70)]), |
| 226 | until: (p) => |
| 227 | p === undefined || |
| 228 | p.DatastoreStatus === "ACTIVE" || |
| 229 | p.DatastoreStatus === "CREATE_FAILED" || |
| 230 | p.DatastoreStatus === "UPDATE_FAILED" || |
| 231 | p.DatastoreStatus === "DELETED", |
| 232 | }), |
| 233 | ); |
| 234 | if (properties === undefined || properties.DatastoreStatus !== "ACTIVE") { |
| 235 | const cause = properties?.ErrorCause?.ErrorMessage; |
| 236 | return yield* new FHIRDatastoreNotReady({ |
| 237 | message: `HealthLake data store '${datastoreId}' did not become ACTIVE (status: ${ |
| 238 | properties?.DatastoreStatus ?? "gone" |
| 239 | }${cause ? `: ${cause}` : ""})`, |
| 240 | }); |
| 241 | } |
| 242 | return properties; |
| 243 | }); |
| 244 | |
| 245 | // Wait for a data store to leave a transitional state (CREATING / |
| 246 | // UPDATING) so delete does not hit ConflictException. |
| 247 | const waitUntilSettled = Effect.fn(function* (datastoreId: string) { |
| 248 | return yield* readDatastore(datastoreId).pipe( |
| 249 | Effect.repeat({ |
| 250 | schedule: Schedule.max([Schedule.fixed("30 seconds"), Schedule.recurs(70)]), |
| 251 | until: (p) => |
| 252 | p === undefined || |
| 253 | (p.DatastoreStatus !== "CREATING" && p.DatastoreStatus !== "UPDATING"), |
| 254 | }), |
| 255 | ); |
| 256 | }); |
| 257 | |
| 258 | // Deletion is asynchronous (DELETING → gone); wait until the data |
| 259 | // store is fully gone. Budget ~35 min (70 * 30s). |
| 260 | const waitUntilGone = Effect.fn(function* (datastoreId: string) { |
| 261 | const properties = yield* readDatastore(datastoreId).pipe( |
| 262 | Effect.repeat({ |
| 263 | schedule: Schedule.max([Schedule.fixed("30 seconds"), Schedule.recurs(70)]), |
| 264 | until: (p) => p === undefined || p.DatastoreStatus === "DELETED", |
| 265 | }), |
| 266 | ); |
| 267 | if (properties !== undefined && properties.DatastoreStatus !== "DELETED") { |
| 268 | return yield* new FHIRDatastoreNotReady({ |
| 269 | message: `HealthLake data store '${datastoreId}' still exists after deletion (status: ${properties.DatastoreStatus})`, |
| 270 | }); |
| 271 | } |
| 272 | }); |
| 273 | |
| 274 | const toAttrs = Effect.fn(function* (properties: healthlake.DatastoreProperties) { |
| 275 | return { |
| 276 | datastoreId: properties.DatastoreId, |
| 277 | datastoreArn: properties.DatastoreArn, |
| 278 | datastoreName: properties.DatastoreName ?? "", |
| 279 | datastoreStatus: properties.DatastoreStatus, |
| 280 | datastoreEndpoint: properties.DatastoreEndpoint, |
| 281 | datastoreTypeVersion: properties.DatastoreTypeVersion, |
| 282 | tags: yield* readDatastoreTags(properties.DatastoreArn), |
| 283 | }; |
| 284 | }); |
| 285 | |
| 286 | return { |
| 287 | stables: ["datastoreId", "datastoreArn", "datastoreEndpoint", "datastoreTypeVersion"], |
| 288 | |
| 289 | diff: Effect.fn(function* ({ olds, news }) { |
| 290 | if (!isResolved(news)) return undefined; |
| 291 | const n = news ?? {}; |
| 292 | const o = olds ?? {}; |
| 293 | // Create-only properties force a replacement. |
| 294 | if ( |
| 295 | (n.datastoreTypeVersion ?? DEFAULT_FHIR_VERSION) !== |
| 296 | (o.datastoreTypeVersion ?? DEFAULT_FHIR_VERSION) |
| 297 | ) { |
| 298 | return { action: "replace" } as const; |
| 299 | } |
| 300 | if (n.kmsKeyId !== o.kmsKeyId) { |
| 301 | return { action: "replace" } as const; |
| 302 | } |
| 303 | if (n.preloadDataType !== o.preloadDataType) { |
| 304 | return { action: "replace" } as const; |
| 305 | } |
| 306 | }), |
| 307 | |
| 308 | read: Effect.fn(function* ({ id, olds, output }) { |
| 309 | let properties = output?.datastoreId |
| 310 | ? yield* readDatastore(output.datastoreId) |
| 311 | : undefined; |
| 312 | if (isGoneOrGoing(properties)) { |
| 313 | const name = yield* toName(id, olds ?? {}); |
| 314 | properties = yield* findByName(name); |
| 315 | } |
| 316 | if (properties === undefined) return undefined; |
| 317 | const attrs = yield* toAttrs(properties); |
| 318 | return (yield* hasAlchemyTags(id, attrs.tags)) ? attrs : Unowned(attrs); |
| 319 | }), |
| 320 | |
| 321 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 322 | const props = news!; |
| 323 | const name = yield* toName(id, props); |
| 324 | const internalTags = yield* createInternalTags(id); |
| 325 | const desiredTags = { ...internalTags, ...props.tags }; |
| 326 | |
| 327 | // 1. Observe — cloud state is authoritative; output is only an |
| 328 | // id cache. A deleted/deleting instance is treated as missing. |
| 329 | let observed = output?.datastoreId ? yield* readDatastore(output.datastoreId) : undefined; |
| 330 | if (isGoneOrGoing(observed)) { |
| 331 | observed = yield* findByName(name); |
| 332 | } |
| 333 | |
| 334 | // 2. Ensure — create if missing, then wait (bounded) for ACTIVE. |
| 335 | // ClientToken is an idempotency token filled in by distilled. |
| 336 | if (observed === undefined) { |
| 337 | const created = yield* healthlake.createFHIRDatastore({ |
| 338 | DatastoreName: name, |
| 339 | DatastoreTypeVersion: props.datastoreTypeVersion ?? DEFAULT_FHIR_VERSION, |
| 340 | SseConfiguration: props.kmsKeyId |
| 341 | ? { |
| 342 | KmsEncryptionConfig: { |
| 343 | CmkType: "CUSTOMER_MANAGED_KMS_KEY", |
| 344 | KmsKeyId: props.kmsKeyId, |
| 345 | }, |
| 346 | } |
| 347 | : undefined, |
| 348 | PreloadDataConfig: props.preloadDataType |
| 349 | ? { PreloadDataType: props.preloadDataType } |
| 350 | : undefined, |
| 351 | IdentityProviderConfiguration: toIdpConfig(props.identityProviderConfiguration), |
| 352 | Tags: Object.entries(desiredTags).map(([Key, Value]) => ({ |
| 353 | Key, |
| 354 | Value, |
| 355 | })), |
| 356 | }); |
| 357 | observed = yield* waitForActive(created.DatastoreId); |
| 358 | } else if (observed.DatastoreStatus !== "ACTIVE") { |
| 359 | // Mid-flight provisioning or a prior update still converging. |
| 360 | observed = yield* waitForActive(observed.DatastoreId); |
| 361 | } |
| 362 | |
| 363 | // 3. Sync mutable aspects — compute the update delta from |
| 364 | // OBSERVED state; skip the API entirely on no-op. |
| 365 | const update: healthlake.UpdateFHIRDatastoreRequest = { |
| 366 | DatastoreId: observed.DatastoreId, |
| 367 | }; |
| 368 | let mutated = false; |
| 369 | if (observed.DatastoreName !== name) { |
| 370 | update.DatastoreName = name; |
| 371 | mutated = true; |
| 372 | } |
| 373 | const desiredIdp = toIdpConfig(props.identityProviderConfiguration); |
| 374 | if ( |
| 375 | desiredIdp !== undefined && |
| 376 | !sameIdpConfig(observed.IdentityProviderConfiguration, desiredIdp) |
| 377 | ) { |
| 378 | update.IdentityProviderConfiguration = desiredIdp; |
| 379 | mutated = true; |
| 380 | } |
| 381 | if (mutated) { |
| 382 | yield* healthlake.updateFHIRDatastore(update); |
| 383 | observed = yield* waitForActive(observed.DatastoreId); |
| 384 | } |
| 385 | |
| 386 | // 3b. Sync tags — diff against OBSERVED cloud tags. |
| 387 | const observedTags = yield* readDatastoreTags(observed.DatastoreArn); |
| 388 | const { removed, upsert } = diffTags(observedTags, desiredTags); |
| 389 | if (upsert.length > 0) { |
| 390 | yield* healthlake.tagResource({ |
| 391 | ResourceARN: observed.DatastoreArn, |
| 392 | Tags: upsert, |
| 393 | }); |
| 394 | } |
| 395 | if (removed.length > 0) { |
| 396 | yield* healthlake.untagResource({ |
| 397 | ResourceARN: observed.DatastoreArn, |
| 398 | TagKeys: removed, |
| 399 | }); |
| 400 | } |
| 401 | |
| 402 | yield* session.note(observed.DatastoreId); |
| 403 | return yield* toAttrs(observed); |
| 404 | }), |
| 405 | |
| 406 | delete: Effect.fn(function* ({ output }) { |
| 407 | const datastoreId = output.datastoreId; |
| 408 | // A data store mid-create/update rejects deletion with |
| 409 | // ConflictException — wait (bounded) for it to settle first. |
| 410 | const settled = yield* waitUntilSettled(datastoreId).pipe( |
| 411 | Effect.orElseSucceed(() => undefined), |
| 412 | ); |
| 413 | if (settled === undefined || settled.DatastoreStatus === "DELETED") { |
| 414 | return; |
| 415 | } |
| 416 | if (settled.DatastoreStatus !== "DELETING") { |
| 417 | yield* healthlake.deleteFHIRDatastore({ DatastoreId: datastoreId }).pipe( |
| 418 | Effect.retry({ |
| 419 | while: (e) => e._tag === "ConflictException", |
| 420 | schedule: Schedule.max([Schedule.fixed("15 seconds"), Schedule.recurs(10)]), |
| 421 | }), |
| 422 | Effect.catchTag("ResourceNotFoundException", () => Effect.undefined), |
| 423 | ); |
| 424 | } |
| 425 | // Deletion is asynchronous — wait until the data store is gone so |
| 426 | // dependent resources (e.g. the KMS key) can be deleted next. |
| 427 | yield* waitUntilGone(datastoreId); |
| 428 | }), |
| 429 | |
| 430 | list: () => |
| 431 | Effect.gen(function* () { |
| 432 | // Bounded hand-rolled pagination. |
| 433 | const datastores: healthlake.DatastoreProperties[] = []; |
| 434 | let nextToken: string | undefined; |
| 435 | for (let page = 0; page < 20; page++) { |
| 436 | const response = yield* healthlake.listFHIRDatastores({ |
| 437 | NextToken: nextToken, |
| 438 | }); |
| 439 | datastores.push(...(response.DatastorePropertiesList ?? [])); |
| 440 | nextToken = response.NextToken; |
| 441 | if (!nextToken) break; |
| 442 | } |
| 443 | return yield* Effect.forEach( |
| 444 | datastores.filter((properties) => !isGoneOrGoing(properties)), |
| 445 | (properties) => toAttrs(properties), |
| 446 | { concurrency: 4 }, |
| 447 | ); |
| 448 | }), |
| 449 | }; |
| 450 | }), |
| 451 | ); |