@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, 04:45 UTC

main
ts 300 lines 12.8 KB
Raw
1 import * as ComprehendMedical from "@alchemy.run/aws/ComprehendMedical";
2 import * as Lambda from "@alchemy.run/aws/Lambda";
3 import * as Duration from "effect/Duration";
4 import * as Effect from "effect/Effect";
5 import { HttpServerRequest } from "effect/http/HttpServerRequest";
6 import * as HttpServerResponse from "effect/http/HttpServerResponse";
7 import * as Layer from "effect/Layer";
8 import path from "pathe";
9
10 const main = path.resolve(import.meta.dirname, "handler.ts");
11
12 // Well-formed (1-32 chars of [a-zA-Z0-9-]) but nonexistent job id — describe
13 // and stop must answer with the typed ResourceNotFoundException.
14 const FAKE_JOB_ID = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
15
16 export class ComprehendMedicalTestFunction extends Lambda.Function<Lambda.Function>()(
17 "ComprehendMedicalTestFunction",
18 ) {}
19
20 export default ComprehendMedicalTestFunction.make(
21 {
22 main,
23 functionUrl: true,
24 // Comprehend Medical inference can exceed Lambda's 3s default under load.
25 timeout: Duration.seconds(30),
26 },
27 Effect.gen(function* () {
28 const detectEntities = yield* ComprehendMedical.DetectEntitiesV2();
29 const detectPHI = yield* ComprehendMedical.DetectPHI();
30 const inferICD10CM = yield* ComprehendMedical.InferICD10CM();
31 const inferRxNorm = yield* ComprehendMedical.InferRxNorm();
32 const inferSNOMEDCT = yield* ComprehendMedical.InferSNOMEDCT();
33
34 const listEntitiesJobs = yield* ComprehendMedical.ListEntitiesDetectionV2Jobs();
35 const listICD10CMJobs = yield* ComprehendMedical.ListICD10CMInferenceJobs();
36 const listPHIJobs = yield* ComprehendMedical.ListPHIDetectionJobs();
37 const listRxNormJobs = yield* ComprehendMedical.ListRxNormInferenceJobs();
38 const listSNOMEDCTJobs = yield* ComprehendMedical.ListSNOMEDCTInferenceJobs();
39
40 const describeEntitiesJob = yield* ComprehendMedical.DescribeEntitiesDetectionV2Job();
41 const describeICD10CMJob = yield* ComprehendMedical.DescribeICD10CMInferenceJob();
42 const describePHIJob = yield* ComprehendMedical.DescribePHIDetectionJob();
43 const describeRxNormJob = yield* ComprehendMedical.DescribeRxNormInferenceJob();
44 const describeSNOMEDCTJob = yield* ComprehendMedical.DescribeSNOMEDCTInferenceJob();
45
46 const stopEntitiesJob = yield* ComprehendMedical.StopEntitiesDetectionV2Job();
47 const stopICD10CMJob = yield* ComprehendMedical.StopICD10CMInferenceJob();
48 const stopPHIJob = yield* ComprehendMedical.StopPHIDetectionJob();
49 const stopRxNormJob = yield* ComprehendMedical.StopRxNormInferenceJob();
50 const stopSNOMEDCTJob = yield* ComprehendMedical.StopSNOMEDCTInferenceJob();
51
52 const startEntitiesJob = yield* ComprehendMedical.StartEntitiesDetectionV2Job();
53 const startICD10CMJob = yield* ComprehendMedical.StartICD10CMInferenceJob();
54 const startPHIJob = yield* ComprehendMedical.StartPHIDetectionJob();
55 const startRxNormJob = yield* ComprehendMedical.StartRxNormInferenceJob();
56 const startSNOMEDCTJob = yield* ComprehendMedical.StartSNOMEDCTInferenceJob();
57 // The remaining start bindings attach their IAM statements at deploy
58 // time; the PHI start callable is the one exercised at runtime.
59 void startEntitiesJob;
60 void startICD10CMJob;
61 void startRxNormJob;
62 void startSNOMEDCTJob;
63
64 return {
65 fetch: Effect.gen(function* () {
66 const request = yield* HttpServerRequest;
67 const url = new URL(request.originalUrl);
68 const pathname = url.pathname;
69
70 // Cheap readiness route — no Comprehend Medical call.
71 if (request.method === "GET" && pathname === "/ping") {
72 return yield* HttpServerResponse.json({ ok: true });
73 }
74
75 if (request.method === "GET" && pathname === "/entities") {
76 const result = yield* detectEntities({
77 Text: "Patient takes 50 mg atenolol daily for hypertension.",
78 });
79 return yield* HttpServerResponse.json({
80 entities: (result.Entities ?? []).map((entity) => ({
81 text: entity.Text,
82 category: entity.Category,
83 type: entity.Type,
84 })),
85 modelVersion: result.ModelVersion,
86 });
87 }
88
89 if (request.method === "GET" && pathname === "/phi") {
90 const result = yield* detectPHI({
91 Text: "John Doe, age 47, was seen on 2024-01-03 at Seattle Clinic.",
92 });
93 return yield* HttpServerResponse.json({
94 entities: (result.Entities ?? []).map((entity) => ({
95 text: entity.Text,
96 type: entity.Type,
97 })),
98 });
99 }
100
101 if (request.method === "GET" && pathname === "/icd10") {
102 const result = yield* inferICD10CM({
103 Text: "Patient presents with type 2 diabetes and hypertension.",
104 });
105 return yield* HttpServerResponse.json({
106 entities: (result.Entities ?? []).map((entity) => ({
107 text: entity.Text,
108 codes: (entity.ICD10CMConcepts ?? []).map((concept) => ({
109 code: concept.Code,
110 description: concept.Description,
111 })),
112 })),
113 });
114 }
115
116 if (request.method === "GET" && pathname === "/rxnorm") {
117 const result = yield* inferRxNorm({
118 Text: "Patient takes 50 mg atenolol daily and 500 mg metformin twice a day.",
119 });
120 return yield* HttpServerResponse.json({
121 entities: (result.Entities ?? []).map((entity) => ({
122 text: entity.Text,
123 concepts: (entity.RxNormConcepts ?? []).map((concept) => ({
124 code: concept.Code,
125 description: concept.Description,
126 })),
127 })),
128 });
129 }
130
131 if (request.method === "GET" && pathname === "/snomed") {
132 const result = yield* inferSNOMEDCT({
133 Text: "Patient presents with type 2 diabetes and hypertension.",
134 });
135 return yield* HttpServerResponse.json({
136 entities: (result.Entities ?? []).map((entity) => ({
137 text: entity.Text,
138 concepts: (entity.SNOMEDCTConcepts ?? []).map((concept) => ({
139 code: concept.Code,
140 description: concept.Description,
141 })),
142 })),
143 });
144 }
145
146 // Exercises the five List* bindings — real calls, no side effects.
147 if (request.method === "GET" && pathname === "/jobs") {
148 const [entities, icd10cm, phi, rxnorm, snomedct] = yield* Effect.all(
149 [
150 listEntitiesJobs({}),
151 listICD10CMJobs({}),
152 listPHIJobs({}),
153 listRxNormJobs({}),
154 listSNOMEDCTJobs({}),
155 ],
156 { concurrency: 5 },
157 );
158 return yield* HttpServerResponse.json({
159 entities: entities.ComprehendMedicalAsyncJobPropertiesList?.length ?? 0,
160 icd10cm: icd10cm.ComprehendMedicalAsyncJobPropertiesList?.length ?? 0,
161 phi: phi.ComprehendMedicalAsyncJobPropertiesList?.length ?? 0,
162 rxnorm: rxnorm.ComprehendMedicalAsyncJobPropertiesList?.length ?? 0,
163 snomedct: snomedct.ComprehendMedicalAsyncJobPropertiesList?.length ?? 0,
164 });
165 }
166
167 // Exercises the Describe*/Stop* bindings against a nonexistent job:
168 // IAM authorizes first, so the typed ResourceNotFoundException proves
169 // both the wiring and the granted action.
170 if (request.method === "GET" && pathname === "/job-checks") {
171 const success = () => "Success" as string;
172 const tagOf = (e: { readonly _tag: string }) => Effect.succeed(e._tag as string);
173
174 const [describes, stops] = yield* Effect.all([
175 Effect.all(
176 [
177 describeEntitiesJob({ JobId: FAKE_JOB_ID }).pipe(
178 Effect.map(success),
179 Effect.catchTag("ResourceNotFoundException", tagOf),
180 ),
181 describeICD10CMJob({ JobId: FAKE_JOB_ID }).pipe(
182 Effect.map(success),
183 Effect.catchTag("ResourceNotFoundException", tagOf),
184 ),
185 describePHIJob({ JobId: FAKE_JOB_ID }).pipe(
186 Effect.map(success),
187 Effect.catchTag("ResourceNotFoundException", tagOf),
188 ),
189 describeRxNormJob({ JobId: FAKE_JOB_ID }).pipe(
190 Effect.map(success),
191 Effect.catchTag("ResourceNotFoundException", tagOf),
192 ),
193 describeSNOMEDCTJob({ JobId: FAKE_JOB_ID }).pipe(
194 Effect.map(success),
195 Effect.catchTag("ResourceNotFoundException", tagOf),
196 ),
197 ],
198 { concurrency: 5 },
199 ),
200 Effect.all(
201 [
202 stopEntitiesJob({ JobId: FAKE_JOB_ID }).pipe(
203 Effect.map(success),
204 Effect.catchTag("ResourceNotFoundException", tagOf),
205 ),
206 stopICD10CMJob({ JobId: FAKE_JOB_ID }).pipe(
207 Effect.map(success),
208 Effect.catchTag("ResourceNotFoundException", tagOf),
209 ),
210 stopPHIJob({ JobId: FAKE_JOB_ID }).pipe(
211 Effect.map(success),
212 Effect.catchTag("ResourceNotFoundException", tagOf),
213 ),
214 stopRxNormJob({ JobId: FAKE_JOB_ID }).pipe(
215 Effect.map(success),
216 Effect.catchTag("ResourceNotFoundException", tagOf),
217 ),
218 stopSNOMEDCTJob({ JobId: FAKE_JOB_ID }).pipe(
219 Effect.map(success),
220 Effect.catchTag("ResourceNotFoundException", tagOf),
221 ),
222 ],
223 { concurrency: 5 },
224 ),
225 ]);
226 return yield* HttpServerResponse.json({ describes, stops });
227 }
228
229 // Exercises a Start* binding: the request passes the
230 // comprehendmedical:StartPHIDetectionJob IAM check and fails typed on
231 // the same-account-but-nonexistent data-access role supplied by the
232 // test (DATA_ACCESS_ROLE_ARN_INVALID). An unauthorized caller would
233 // get AccessDeniedException instead — so InvalidRequestException
234 // proves the binding granted the Start action.
235 if (request.method === "GET" && pathname === "/job-start") {
236 const roleArn = url.searchParams.get("roleArn");
237 if (!roleArn) {
238 return yield* HttpServerResponse.json(
239 { error: "roleArn query parameter required" },
240 { status: 400 },
241 );
242 }
243 const outcome = yield* startPHIJob({
244 InputDataConfig: {
245 S3Bucket: "alchemy-nonexistent-input-bucket",
246 S3Key: "notes/",
247 },
248 OutputDataConfig: {
249 S3Bucket: "alchemy-nonexistent-output-bucket",
250 },
251 DataAccessRoleArn: roleArn,
252 LanguageCode: "en",
253 }).pipe(
254 Effect.map(() => ({ tag: "Success" })),
255 Effect.catchTag(
256 ["AccessDeniedException", "InvalidRequestException", "ResourceNotFoundException"],
257 (e) => Effect.succeed({ tag: e._tag as string }),
258 ),
259 );
260 return yield* HttpServerResponse.json(outcome);
261 }
262
263 return yield* HttpServerResponse.json(
264 { error: "Not found", method: request.method, pathname },
265 { status: 404 },
266 );
267 }).pipe(Effect.orDie),
268 };
269 }).pipe(
270 Effect.provide(
271 Layer.mergeAll(
272 ComprehendMedical.DetectEntitiesV2Http,
273 ComprehendMedical.DetectPHIHttp,
274 ComprehendMedical.InferICD10CMHttp,
275 ComprehendMedical.InferRxNormHttp,
276 ComprehendMedical.InferSNOMEDCTHttp,
277 ComprehendMedical.ListEntitiesDetectionV2JobsHttp,
278 ComprehendMedical.ListICD10CMInferenceJobsHttp,
279 ComprehendMedical.ListPHIDetectionJobsHttp,
280 ComprehendMedical.ListRxNormInferenceJobsHttp,
281 ComprehendMedical.ListSNOMEDCTInferenceJobsHttp,
282 ComprehendMedical.DescribeEntitiesDetectionV2JobHttp,
283 ComprehendMedical.DescribeICD10CMInferenceJobHttp,
284 ComprehendMedical.DescribePHIDetectionJobHttp,
285 ComprehendMedical.DescribeRxNormInferenceJobHttp,
286 ComprehendMedical.DescribeSNOMEDCTInferenceJobHttp,
287 ComprehendMedical.StopEntitiesDetectionV2JobHttp,
288 ComprehendMedical.StopICD10CMInferenceJobHttp,
289 ComprehendMedical.StopPHIDetectionJobHttp,
290 ComprehendMedical.StopRxNormInferenceJobHttp,
291 ComprehendMedical.StopSNOMEDCTInferenceJobHttp,
292 ComprehendMedical.StartEntitiesDetectionV2JobHttp,
293 ComprehendMedical.StartICD10CMInferenceJobHttp,
294 ComprehendMedical.StartPHIDetectionJobHttp,
295 ComprehendMedical.StartRxNormInferenceJobHttp,
296 ComprehendMedical.StartSNOMEDCTInferenceJobHttp,
297 ),
298 ),
299 ),
300 );