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

main
ts 273 lines 10.6 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { AWSEnvironment } from "@alchemy.run/aws/Environment";
3 import { describe, expect } from "@alchemy.run/test";
4 import * as Test from "@alchemy.run/test/Alchemy";
5 import * as Core from "@alchemy.run/test/Core";
6 import * as healthlake from "@distilled.cloud/aws/healthlake";
7 import * as s3 from "@distilled.cloud/aws/s3";
8 import * as Effect from "effect/Effect";
9 import * as HttpClient from "effect/http/HttpClient";
10 import * as Schedule from "effect/Schedule";
11 import HealthLakeTestFunctionLive, { HealthLakeTestFunction, IMPORT_PREFIX } from "./handler";
12
13 const testOptions = { providers: AWS.providers() };
14 const { test } = Test.make(testOptions);
15
16 // A well-formed-but-nonexistent data store id (32 hex chars) the ungated
17 // probes are driven against.
18 const NONEXISTENT_DATASTORE = "0123456789abcdef0123456789abcdef";
19 const NONEXISTENT_JOB = "0123456789abcdef0123456789abcdef";
20
21 // ---------------------------------------------------------------------------
22 // Ungated typed-error probes: every job operation the six bindings wrap is
23 // exercised directly through distilled against a nonexistent data store, and
24 // must answer with the typed not-found tag the bindings' consumers handle.
25 // These prove the distilled error unions (and request serialization) at
26 // near-zero cost on every CI pass, while the full runtime fixture below is
27 // gated behind the 15-30 minute data store provisioning.
28 // ---------------------------------------------------------------------------
29
30 describe(
31 "HealthLake job operations (typed-error probes)",
32 { tags: ["provider:aws", "provider:aws:healthlake", "live"] },
33 () => {
34 test.provider(
35 "describeFHIRImportJob on a nonexistent datastore fails with ResourceNotFoundException",
36 () =>
37 Effect.gen(function* () {
38 const error = yield* Effect.flip(
39 healthlake.describeFHIRImportJob({
40 DatastoreId: NONEXISTENT_DATASTORE,
41 JobId: NONEXISTENT_JOB,
42 }),
43 );
44 expect(error._tag).toBe("ResourceNotFoundException");
45 }),
46 );
47
48 test.provider(
49 "describeFHIRExportJob on a nonexistent datastore fails with ResourceNotFoundException",
50 () =>
51 Effect.gen(function* () {
52 const error = yield* Effect.flip(
53 healthlake.describeFHIRExportJob({
54 DatastoreId: NONEXISTENT_DATASTORE,
55 JobId: NONEXISTENT_JOB,
56 }),
57 );
58 expect(error._tag).toBe("ResourceNotFoundException");
59 }),
60 );
61
62 test.provider(
63 "listFHIRImportJobs on a nonexistent datastore fails with ResourceNotFoundException",
64 () =>
65 Effect.gen(function* () {
66 const error = yield* Effect.flip(
67 healthlake.listFHIRImportJobs({ DatastoreId: NONEXISTENT_DATASTORE }),
68 );
69 expect(error._tag).toBe("ResourceNotFoundException");
70 }),
71 );
72
73 test.provider(
74 "listFHIRExportJobs on a nonexistent datastore fails with ResourceNotFoundException",
75 () =>
76 Effect.gen(function* () {
77 const error = yield* Effect.flip(
78 healthlake.listFHIRExportJobs({ DatastoreId: NONEXISTENT_DATASTORE }),
79 );
80 expect(error._tag).toBe("ResourceNotFoundException");
81 }),
82 );
83
84 test.provider("startFHIRExportJob on a nonexistent datastore fails with a typed tag", () =>
85 Effect.gen(function* () {
86 const { accountId } = yield* AWSEnvironment.current;
87 const error = yield* Effect.flip(
88 healthlake.startFHIRExportJob({
89 DatastoreId: NONEXISTENT_DATASTORE,
90 DataAccessRoleArn: `arn:aws:iam::${accountId}:role/alchemy-probe-nonexistent`,
91 OutputDataConfig: {
92 S3Configuration: {
93 S3Uri: "s3://alchemy-probe-nonexistent/export/",
94 KmsKeyId: `arn:aws:kms:us-east-1:${accountId}:key/00000000-0000-0000-0000-000000000000`,
95 },
96 },
97 }),
98 );
99 expect([
100 "ResourceNotFoundException",
101 "ValidationException",
102 "AccessDeniedException",
103 ]).toContain(error._tag);
104 }),
105 );
106
107 test.provider("startFHIRImportJob on a nonexistent datastore fails with a typed tag", () =>
108 Effect.gen(function* () {
109 const { accountId } = yield* AWSEnvironment.current;
110 const error = yield* Effect.flip(
111 healthlake.startFHIRImportJob({
112 DatastoreId: NONEXISTENT_DATASTORE,
113 DataAccessRoleArn: `arn:aws:iam::${accountId}:role/alchemy-probe-nonexistent`,
114 InputDataConfig: { S3Uri: "s3://alchemy-probe-nonexistent/in/" },
115 JobOutputDataConfig: {
116 S3Configuration: {
117 S3Uri: "s3://alchemy-probe-nonexistent/out/",
118 KmsKeyId: `arn:aws:kms:us-east-1:${accountId}:key/00000000-0000-0000-0000-000000000000`,
119 },
120 },
121 }),
122 );
123 expect([
124 "ResourceNotFoundException",
125 "ValidationException",
126 "AccessDeniedException",
127 ]).toContain(error._tag);
128 }),
129 );
130 },
131 );
132
133 // ---------------------------------------------------------------------------
134 // Full runtime fixture: a Lambda bound to all six job bindings against a live
135 // FHIR data store. A data store takes ~15-30 minutes to provision and bills
136 // while it exists, so this is gated behind AWS_TEST_HEALTHLAKE=1 (same gate
137 // as the FHIRDatastore lifecycle test) and always destroys what it created.
138 // ---------------------------------------------------------------------------
139
140 const sharedStack = Core.scratchStack(testOptions, "HealthLakeBindings");
141
142 // A single synthetic FHIR R4 Patient in NDJSON form — the smallest valid
143 // import payload.
144 const PATIENT_NDJSON = JSON.stringify({
145 resourceType: "Patient",
146 id: "alchemy-bindings-patient",
147 name: [{ family: "Alchemy", given: ["Bindings"] }],
148 gender: "unknown",
149 });
150
151 test.provider.skipIf(!process.env.AWS_TEST_HEALTHLAKE)(
152 "import + export job bindings against a live FHIR data store",
153 () =>
154 Effect.gen(function* () {
155 yield* sharedStack.destroy();
156
157 yield* Effect.gen(function* () {
158 const { functionUrl } = yield* sharedStack.deploy(
159 Effect.gen(function* () {
160 return yield* HealthLakeTestFunction;
161 }).pipe(Effect.provide(HealthLakeTestFunctionLive)),
162 );
163 expect(functionUrl).toBeTruthy();
164 const baseUrl = functionUrl!.replace(/\/+$/, "");
165
166 const getJson = (path: string) =>
167 HttpClient.get(`${baseUrl}${path}`).pipe(
168 Effect.flatMap((response) =>
169 response.status >= 500
170 ? Effect.fail(new Error(`transient upstream ${response.status}`))
171 : Effect.succeed(response),
172 ),
173 Effect.retry({
174 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(10)]),
175 }),
176 Effect.flatMap((r) => r.json),
177 );
178
179 // All six capabilities initialized in the runtime.
180 const bindings = (yield* getJson("/bindings")) as { bound: string[] };
181 expect(bindings.bound).toHaveLength(6);
182
183 // Upload the smallest valid import payload out-of-band.
184 const config = (yield* getJson("/config")) as { bucketName: string };
185 yield* s3.putObject({
186 Bucket: config.bucketName,
187 Key: `${IMPORT_PREFIX}patient.ndjson`,
188 Body: new TextEncoder().encode(PATIENT_NDJSON),
189 ContentType: "application/x-ndjson",
190 });
191
192 // StartFHIRImportJob — proves DatastoreId + DataAccessRoleArn
193 // injection and the iam:PassRole grant.
194 const importJob = (yield* getJson("/import")) as {
195 jobId?: string;
196 status?: string;
197 errorTag?: string;
198 };
199 expect(importJob.errorTag).toBeUndefined();
200 expect(importJob.jobId).toBeTruthy();
201 expect(importJob.status).toBe("SUBMITTED");
202
203 // DescribeFHIRImportJob — the job is observable immediately.
204 const describedImport = (yield* getJson(`/describe-import?jobId=${importJob.jobId}`)) as {
205 status?: string;
206 errorTag?: string;
207 };
208 expect(describedImport.errorTag).toBeUndefined();
209 expect(describedImport.status).toBeTruthy();
210
211 // ListFHIRImportJobs sees it.
212 const imports = (yield* getJson("/list-imports")) as { count: number };
213 expect(imports.count).toBeGreaterThanOrEqual(1);
214
215 // Wait (bounded) for the import to leave the submitted/in-progress
216 // states so the concurrent export below is not rejected.
217 yield* getJson(`/describe-import?jobId=${importJob.jobId}`).pipe(
218 Effect.map((r) => (r as { status: string }).status),
219 Effect.repeat({
220 schedule: Schedule.spaced("15 seconds"),
221 until: (status): boolean =>
222 status !== "SUBMITTED" && status !== "QUEUED" && status !== "IN_PROGRESS",
223 times: 60,
224 }),
225 );
226
227 // StartFHIRExportJob + DescribeFHIRExportJob + ListFHIRExportJobs.
228 const exportJob = (yield* getJson("/export")) as {
229 jobId?: string;
230 status?: string;
231 errorTag?: string;
232 };
233 expect(exportJob.errorTag).toBeUndefined();
234 expect(exportJob.jobId).toBeTruthy();
235 expect(exportJob.status).toBe("SUBMITTED");
236
237 const describedExport = (yield* getJson(`/describe-export?jobId=${exportJob.jobId}`)) as {
238 status?: string;
239 errorTag?: string;
240 };
241 expect(describedExport.errorTag).toBeUndefined();
242 expect(describedExport.status).toBeTruthy();
243
244 const exports = (yield* getJson("/list-exports")) as { count: number };
245 expect(exports.count).toBeGreaterThanOrEqual(1);
246
247 // Wait (bounded) for the export to finish so the bucket/data store
248 // are quiescent before destroy.
249 yield* getJson(`/describe-export?jobId=${exportJob.jobId}`).pipe(
250 Effect.map((r) => (r as { status: string }).status),
251 Effect.repeat({
252 schedule: Schedule.spaced("15 seconds"),
253 until: (status): boolean =>
254 status !== "SUBMITTED" && status !== "QUEUED" && status !== "IN_PROGRESS",
255 times: 60,
256 }),
257 );
258 }).pipe(Effect.ensuring(sharedStack.destroy().pipe(Effect.orDie)));
259 }),
260 // data store create (~15-30 min) + import + export + delete wait, one test.
261 {
262 tags: [
263 "provider:aws",
264 "provider:aws:healthlake",
265 "provider:aws:iam",
266 "provider:aws:kms",
267 "provider:aws:lambda",
268 "provider:aws:s3",
269 "live",
270 ],
271 timeout: 5_400_000,
272 },
273 );