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

main
ts 274 lines 10.2 KB
Raw
1 import * as IAM from "@alchemy.run/aws/IAM";
2 import * as Lambda from "@alchemy.run/aws/Lambda";
3 import * as MedicalImaging from "@alchemy.run/aws/MedicalImaging";
4 import * as S3 from "@alchemy.run/aws/S3";
5 import * as Duration from "effect/Duration";
6 import * as Effect from "effect/Effect";
7 import { HttpServerRequest } from "effect/http/HttpServerRequest";
8 import * as HttpServerResponse from "effect/http/HttpServerResponse";
9 import * as Layer from "effect/Layer";
10 import path from "pathe";
11
12 const main = path.resolve(import.meta.dirname, "handler.ts");
13
14 /** S3 prefix the gated test uploads DICOM input to before calling `/import`. */
15 export const IMPORT_PREFIX = "dicom-input/";
16
17 export class MedicalImagingTestFunction extends Lambda.Function<Lambda.Function>()(
18 "MedicalImagingTestFunction",
19 ) {}
20
21 /**
22 * Every route answers `{ …fields }` on success or `{ errorTag }` when the
23 * operation fails with a TYPED error — the test asserts on concrete fields
24 * (or a typed tag), which proves the binding wiring, the identifier/role
25 * injection, and the IAM grants (a missing grant surfaces as
26 * `AccessDeniedException`, not `ResourceNotFoundException`). An untyped
27 * error crashes into a 500.
28 */
29 const errorTagged = <A, E extends { _tag: string }, R>(
30 effect: Effect.Effect<A, E, R>,
31 ): Effect.Effect<A | { errorTag: string }, never, R> =>
32 effect.pipe(
33 Effect.map((a): A | { errorTag: string } => a),
34 Effect.catch((e) => Effect.succeed({ errorTag: e._tag })),
35 );
36
37 // A well-formed (32 hex chars) but nonexistent image set id — image-set
38 // routes prove wiring + IAM by observing the typed not-found tag.
39 const NONEXISTENT_IMAGE_SET = "0123456789abcdef0123456789abcdef";
40
41 /**
42 * Data-store-scoped binding fixture: deploys a real HealthImaging data
43 * store (provisions in a few minutes — gated behind
44 * AWS_TEST_MEDICAL_IMAGING) plus the import supporting cast (S3 bucket,
45 * HealthImaging data-access role) and a Lambda bound to all eleven
46 * data-plane bindings.
47 */
48 export default MedicalImagingTestFunction.make(
49 {
50 main,
51 functionUrl: true,
52 timeout: Duration.seconds(30),
53 },
54 Effect.gen(function* () {
55 const bucket = yield* S3.Bucket("MedicalImagingBindingsBucket", {
56 forceDestroy: true,
57 });
58
59 // The data-access role HealthImaging assumes to read the DICOM P10
60 // input and write the import manifests. Fixture-only wide grants; the
61 // interesting IAM (the scoped medical-imaging:* + iam:PassRole
62 // statements) is what the bindings attach to the Lambda itself.
63 const role = yield* IAM.Role("MedicalImagingBindingsRole", {
64 assumeRolePolicyDocument: {
65 Version: "2012-10-17",
66 Statement: [
67 {
68 Effect: "Allow",
69 Principal: { Service: "medical-imaging.amazonaws.com" },
70 Action: ["sts:AssumeRole"],
71 },
72 ],
73 },
74 inlinePolicies: {
75 DataAccess: {
76 Version: "2012-10-17",
77 Statement: [
78 {
79 Effect: "Allow",
80 Action: ["s3:GetObject", "s3:PutObject", "s3:ListBucket"],
81 Resource: ["*"],
82 },
83 ],
84 },
85 },
86 });
87
88 const datastore = yield* MedicalImaging.Datastore("BindingsStore", {
89 tags: { fixture: "medical-imaging-bindings" },
90 });
91
92 const startImport = yield* MedicalImaging.StartDICOMImportJob(datastore, role);
93 const getImportJob = yield* MedicalImaging.GetDICOMImportJob(datastore);
94 const listImportJobs = yield* MedicalImaging.ListDICOMImportJobs(datastore);
95 const searchImageSets = yield* MedicalImaging.SearchImageSets(datastore);
96 const getImageSet = yield* MedicalImaging.GetImageSet(datastore);
97 const getImageSetMetadata = yield* MedicalImaging.GetImageSetMetadata(datastore);
98 const getImageFrame = yield* MedicalImaging.GetImageFrame(datastore);
99 const listImageSetVersions = yield* MedicalImaging.ListImageSetVersions(datastore);
100 const updateImageSetMetadata = yield* MedicalImaging.UpdateImageSetMetadata(datastore);
101 const copyImageSet = yield* MedicalImaging.CopyImageSet(datastore);
102 const deleteImageSet = yield* MedicalImaging.DeleteImageSet(datastore);
103
104 const bound = {
105 startImport,
106 getImportJob,
107 listImportJobs,
108 searchImageSets,
109 getImageSet,
110 getImageSetMetadata,
111 getImageFrame,
112 listImageSetVersions,
113 updateImageSetMetadata,
114 copyImageSet,
115 deleteImageSet,
116 };
117
118 const BucketName = yield* bucket.bucketName;
119
120 return {
121 fetch: Effect.gen(function* () {
122 const request = yield* HttpServerRequest;
123 const url = new URL(request.originalUrl);
124 const pathname = url.pathname;
125 const bucketName = yield* BucketName;
126 const imageSetId = url.searchParams.get("imageSetId") ?? NONEXISTENT_IMAGE_SET;
127
128 if (request.method === "GET" && pathname === "/bindings") {
129 return yield* HttpServerResponse.json({
130 bound: Object.keys(bound),
131 });
132 }
133
134 if (request.method === "GET" && pathname === "/config") {
135 return yield* HttpServerResponse.json({ bucketName });
136 }
137
138 // StartDICOMImportJob — proves datastoreId + dataAccessRoleArn
139 // injection and the iam:PassRole grant.
140 if (request.method === "GET" && pathname === "/import") {
141 const clientToken = yield* Effect.sync(() => crypto.randomUUID());
142 const result = yield* errorTagged(
143 startImport({
144 clientToken,
145 inputS3Uri: `s3://${bucketName}/${IMPORT_PREFIX}`,
146 outputS3Uri: `s3://${bucketName}/dicom-output/`,
147 }),
148 );
149 return yield* HttpServerResponse.json(
150 "errorTag" in result ? result : { jobId: result.jobId, status: result.jobStatus },
151 );
152 }
153
154 if (request.method === "GET" && pathname === "/describe-import") {
155 const jobId = url.searchParams.get("jobId") ?? "";
156 const result = yield* errorTagged(getImportJob({ jobId }));
157 return yield* HttpServerResponse.json(
158 "errorTag" in result ? result : { status: result.jobProperties.jobStatus },
159 );
160 }
161
162 if (request.method === "GET" && pathname === "/list-imports") {
163 const result = yield* errorTagged(listImportJobs());
164 return yield* HttpServerResponse.json(
165 "errorTag" in result ? result : { count: result.jobSummaries.length },
166 );
167 }
168
169 if (request.method === "GET" && pathname === "/search") {
170 const result = yield* errorTagged(searchImageSets());
171 return yield* HttpServerResponse.json(
172 "errorTag" in result ? result : { count: result.imageSetsMetadataSummaries.length },
173 );
174 }
175
176 if (request.method === "GET" && pathname === "/get-image-set") {
177 const result = yield* errorTagged(getImageSet({ imageSetId }));
178 return yield* HttpServerResponse.json(
179 "errorTag" in result
180 ? result
181 : { state: result.imageSetState, versionId: result.versionId },
182 );
183 }
184
185 if (request.method === "GET" && pathname === "/get-metadata") {
186 const result = yield* errorTagged(getImageSetMetadata({ imageSetId }));
187 return yield* HttpServerResponse.json(
188 "errorTag" in result ? result : { contentType: result.contentType ?? "unknown" },
189 );
190 }
191
192 if (request.method === "GET" && pathname === "/get-frame") {
193 const result = yield* errorTagged(
194 getImageFrame({
195 imageSetId,
196 imageFrameInformation: {
197 imageFrameId: NONEXISTENT_IMAGE_SET,
198 },
199 }),
200 );
201 return yield* HttpServerResponse.json(
202 "errorTag" in result ? result : { contentType: result.contentType ?? "unknown" },
203 );
204 }
205
206 if (request.method === "GET" && pathname === "/versions") {
207 const result = yield* errorTagged(listImageSetVersions({ imageSetId }));
208 return yield* HttpServerResponse.json(
209 "errorTag" in result ? result : { count: result.imageSetPropertiesList.length },
210 );
211 }
212
213 if (request.method === "GET" && pathname === "/update-metadata") {
214 const result = yield* errorTagged(
215 updateImageSetMetadata({
216 imageSetId,
217 latestVersionId: "1",
218 updateImageSetMetadataUpdates: { revertToVersionId: "1" },
219 }),
220 );
221 return yield* HttpServerResponse.json(
222 "errorTag" in result ? result : { versionId: result.latestVersionId },
223 );
224 }
225
226 if (request.method === "GET" && pathname === "/copy") {
227 const result = yield* errorTagged(
228 copyImageSet({
229 sourceImageSetId: imageSetId,
230 copyImageSetInformation: {
231 sourceImageSet: { latestVersionId: "1" },
232 },
233 }),
234 );
235 return yield* HttpServerResponse.json(
236 "errorTag" in result
237 ? result
238 : {
239 imageSetId: result.destinationImageSetProperties.imageSetId,
240 },
241 );
242 }
243
244 if (request.method === "GET" && pathname === "/delete-image-set") {
245 const result = yield* errorTagged(deleteImageSet({ imageSetId }));
246 return yield* HttpServerResponse.json(
247 "errorTag" in result ? result : { status: result.imageSetWorkflowStatus },
248 );
249 }
250
251 return yield* HttpServerResponse.json(
252 { error: "Not found", method: request.method, pathname },
253 { status: 404 },
254 );
255 }).pipe(Effect.orDie),
256 };
257 }).pipe(
258 Effect.provide(
259 Layer.mergeAll(
260 MedicalImaging.StartDICOMImportJobHttp,
261 MedicalImaging.GetDICOMImportJobHttp,
262 MedicalImaging.ListDICOMImportJobsHttp,
263 MedicalImaging.SearchImageSetsHttp,
264 MedicalImaging.GetImageSetHttp,
265 MedicalImaging.GetImageSetMetadataHttp,
266 MedicalImaging.GetImageFrameHttp,
267 MedicalImaging.ListImageSetVersionsHttp,
268 MedicalImaging.UpdateImageSetMetadataHttp,
269 MedicalImaging.CopyImageSetHttp,
270 MedicalImaging.DeleteImageSetHttp,
271 ),
272 ),
273 ),
274 );