The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Lambda from "@alchemy.run/aws/Lambda"; |
| 2 | import * as S3 from "@alchemy.run/aws/S3"; |
| 3 | import * as Textract from "@alchemy.run/aws/Textract"; |
| 4 | import * as Duration from "effect/Duration"; |
| 5 | import * as Effect from "effect/Effect"; |
| 6 | import { HttpServerRequest } from "effect/http/HttpServerRequest"; |
| 7 | import * as HttpServerResponse from "effect/http/HttpServerResponse"; |
| 8 | import * as Layer from "effect/Layer"; |
| 9 | import * as Schedule from "effect/Schedule"; |
| 10 | import path from "pathe"; |
| 11 | import { HELLO_PNG_BASE64 } from "./constants.ts"; |
| 12 | |
| 13 | const main = path.resolve(import.meta.dirname, "handler.ts"); |
| 14 | |
| 15 | // Deterministic checked-in test input, decoded once at module init. |
| 16 | const pngBytes = Buffer.from(HELLO_PNG_BASE64, "base64"); |
| 17 | |
| 18 | /** Key of the seeded input object the async Start* routes analyze. */ |
| 19 | export const INPUT_KEY = "textract/hello.png"; |
| 20 | |
| 21 | export class TextractTestFunction extends Lambda.Function<Lambda.Function>()( |
| 22 | "TextractTestFunction", |
| 23 | ) {} |
| 24 | |
| 25 | export default TextractTestFunction.make( |
| 26 | { |
| 27 | main, |
| 28 | functionUrl: true, |
| 29 | // Each sync analysis inference takes a few seconds; routes run several. |
| 30 | timeout: Duration.seconds(60), |
| 31 | // The bundled Textract schema graph is large — give headroom over the |
| 32 | // 128 MB default. |
| 33 | memorySize: 512, |
| 34 | }, |
| 35 | Effect.gen(function* () { |
| 36 | const bucket = yield* S3.Bucket("TextractInputBucket", { |
| 37 | forceDestroy: true, |
| 38 | }); |
| 39 | const adapter = yield* Textract.Adapter("TextractTestAdapter", { |
| 40 | featureTypes: ["QUERIES"], |
| 41 | description: "alchemy textract bindings fixture", |
| 42 | }); |
| 43 | |
| 44 | // Seeding route writes the input object; Textract's async Start* APIs |
| 45 | // read the S3 input with the CALLER's credentials, so the function |
| 46 | // itself also needs s3:GetObject on the bucket. |
| 47 | const putObject = yield* S3.PutObject(bucket); |
| 48 | yield* S3.GetObject(bucket); |
| 49 | |
| 50 | // --- synchronous analysis --- |
| 51 | const analyzeDocument = yield* Textract.AnalyzeDocument(); |
| 52 | const analyzeExpense = yield* Textract.AnalyzeExpense(); |
| 53 | const analyzeID = yield* Textract.AnalyzeID(); |
| 54 | |
| 55 | // --- asynchronous jobs --- |
| 56 | const startDocumentTextDetection = yield* Textract.StartDocumentTextDetection(); |
| 57 | const getDocumentTextDetection = yield* Textract.GetDocumentTextDetection(); |
| 58 | const startDocumentAnalysis = yield* Textract.StartDocumentAnalysis(); |
| 59 | const getDocumentAnalysis = yield* Textract.GetDocumentAnalysis(); |
| 60 | const startExpenseAnalysis = yield* Textract.StartExpenseAnalysis(); |
| 61 | const getExpenseAnalysis = yield* Textract.GetExpenseAnalysis(); |
| 62 | const startLendingAnalysis = yield* Textract.StartLendingAnalysis(); |
| 63 | const getLendingAnalysis = yield* Textract.GetLendingAnalysis(); |
| 64 | const getLendingAnalysisSummary = yield* Textract.GetLendingAnalysisSummary(); |
| 65 | |
| 66 | // --- adapter management --- |
| 67 | const listAdapters = yield* Textract.ListAdapters(); |
| 68 | const getAdapter = yield* Textract.GetAdapter(adapter); |
| 69 | const listAdapterVersions = yield* Textract.ListAdapterVersions(adapter); |
| 70 | const getAdapterVersion = yield* Textract.GetAdapterVersion(adapter); |
| 71 | const createAdapterVersion = yield* Textract.CreateAdapterVersion(adapter); |
| 72 | const deleteAdapterVersion = yield* Textract.DeleteAdapterVersion(adapter); |
| 73 | |
| 74 | const BucketName = yield* bucket.bucketName; |
| 75 | |
| 76 | const lineTexts = (blocks: { BlockType?: string; Text?: string }[]) => |
| 77 | blocks.filter((b) => b.BlockType === "LINE").map((b) => b.Text); |
| 78 | |
| 79 | // Textract's adapter management APIs throttle at ~1 TPS; bounded backoff |
| 80 | // absorbs the bursts the adapter routes emit. |
| 81 | const throttleRetry = <A, E extends { readonly _tag: string }>(effect: Effect.Effect<A, E>) => |
| 82 | effect.pipe( |
| 83 | Effect.retry({ |
| 84 | while: (e): boolean => |
| 85 | e._tag === "ProvisionedThroughputExceededException" || e._tag === "ThrottlingException", |
| 86 | schedule: Schedule.exponential("1 second"), |
| 87 | times: 5, |
| 88 | }), |
| 89 | ); |
| 90 | |
| 91 | return { |
| 92 | fetch: Effect.gen(function* () { |
| 93 | const request = yield* HttpServerRequest; |
| 94 | const url = new URL(request.originalUrl); |
| 95 | const pathname = url.pathname; |
| 96 | const jobId = url.searchParams.get("jobId") ?? ""; |
| 97 | // BucketName is an Output accessor — resolve it per invocation. |
| 98 | const Bucket = yield* BucketName; |
| 99 | const s3Input = { |
| 100 | S3Object: { Bucket, Name: INPUT_KEY }, |
| 101 | }; |
| 102 | |
| 103 | // Cheap readiness route — no AWS call. |
| 104 | if (request.method === "GET" && pathname === "/ping") { |
| 105 | return yield* HttpServerResponse.json({ ok: true }); |
| 106 | } |
| 107 | |
| 108 | if (request.method === "POST" && pathname === "/seed") { |
| 109 | yield* putObject({ |
| 110 | Key: INPUT_KEY, |
| 111 | Body: pngBytes, |
| 112 | ContentType: "image/png", |
| 113 | }); |
| 114 | return yield* HttpServerResponse.json({ seeded: true }); |
| 115 | } |
| 116 | |
| 117 | // --- synchronous analysis --- |
| 118 | if (request.method === "GET" && pathname === "/analyze-document") { |
| 119 | const result = yield* analyzeDocument({ |
| 120 | Document: { Bytes: pngBytes }, |
| 121 | FeatureTypes: ["TABLES", "FORMS"], |
| 122 | }); |
| 123 | return yield* HttpServerResponse.json({ |
| 124 | pages: result.DocumentMetadata?.Pages, |
| 125 | lines: lineTexts(result.Blocks ?? []), |
| 126 | }); |
| 127 | } |
| 128 | |
| 129 | if (request.method === "GET" && pathname === "/analyze-expense") { |
| 130 | const result = yield* analyzeExpense({ |
| 131 | Document: { Bytes: pngBytes }, |
| 132 | }); |
| 133 | return yield* HttpServerResponse.json({ |
| 134 | pages: result.DocumentMetadata?.Pages, |
| 135 | expenseDocuments: result.ExpenseDocuments?.length ?? 0, |
| 136 | }); |
| 137 | } |
| 138 | |
| 139 | if (request.method === "GET" && pathname === "/analyze-id") { |
| 140 | const result = yield* analyzeID({ |
| 141 | DocumentPages: [{ Bytes: pngBytes }], |
| 142 | }); |
| 143 | return yield* HttpServerResponse.json({ |
| 144 | pages: result.DocumentMetadata?.Pages, |
| 145 | identityDocuments: result.IdentityDocuments?.length ?? 0, |
| 146 | }); |
| 147 | } |
| 148 | |
| 149 | // --- asynchronous jobs --- |
| 150 | if (request.method === "POST" && pathname === "/start-text-detection") { |
| 151 | const result = yield* startDocumentTextDetection({ |
| 152 | DocumentLocation: s3Input, |
| 153 | }); |
| 154 | return yield* HttpServerResponse.json({ jobId: result.JobId }); |
| 155 | } |
| 156 | |
| 157 | if (request.method === "GET" && pathname === "/get-text-detection") { |
| 158 | const result = yield* getDocumentTextDetection({ JobId: jobId }); |
| 159 | return yield* HttpServerResponse.json({ |
| 160 | jobStatus: result.JobStatus, |
| 161 | lines: lineTexts(result.Blocks ?? []), |
| 162 | }); |
| 163 | } |
| 164 | |
| 165 | if (request.method === "POST" && pathname === "/start-analysis") { |
| 166 | const result = yield* startDocumentAnalysis({ |
| 167 | DocumentLocation: s3Input, |
| 168 | FeatureTypes: ["TABLES"], |
| 169 | }); |
| 170 | return yield* HttpServerResponse.json({ jobId: result.JobId }); |
| 171 | } |
| 172 | |
| 173 | if (request.method === "GET" && pathname === "/get-analysis") { |
| 174 | const result = yield* getDocumentAnalysis({ JobId: jobId }); |
| 175 | return yield* HttpServerResponse.json({ |
| 176 | jobStatus: result.JobStatus, |
| 177 | blocks: result.Blocks?.length ?? 0, |
| 178 | }); |
| 179 | } |
| 180 | |
| 181 | if (request.method === "POST" && pathname === "/start-expense") { |
| 182 | const result = yield* startExpenseAnalysis({ |
| 183 | DocumentLocation: s3Input, |
| 184 | }); |
| 185 | return yield* HttpServerResponse.json({ jobId: result.JobId }); |
| 186 | } |
| 187 | |
| 188 | if (request.method === "GET" && pathname === "/get-expense") { |
| 189 | const result = yield* getExpenseAnalysis({ JobId: jobId }); |
| 190 | return yield* HttpServerResponse.json({ |
| 191 | jobStatus: result.JobStatus, |
| 192 | expenseDocuments: result.ExpenseDocuments?.length ?? 0, |
| 193 | }); |
| 194 | } |
| 195 | |
| 196 | if (request.method === "POST" && pathname === "/start-lending") { |
| 197 | const result = yield* startLendingAnalysis({ |
| 198 | DocumentLocation: s3Input, |
| 199 | }); |
| 200 | return yield* HttpServerResponse.json({ jobId: result.JobId }); |
| 201 | } |
| 202 | |
| 203 | if (request.method === "GET" && pathname === "/get-lending") { |
| 204 | const result = yield* getLendingAnalysis({ JobId: jobId }); |
| 205 | return yield* HttpServerResponse.json({ |
| 206 | jobStatus: result.JobStatus, |
| 207 | results: result.Results?.length ?? 0, |
| 208 | }); |
| 209 | } |
| 210 | |
| 211 | if (request.method === "GET" && pathname === "/get-lending-summary") { |
| 212 | const result = yield* getLendingAnalysisSummary({ JobId: jobId }); |
| 213 | return yield* HttpServerResponse.json({ |
| 214 | jobStatus: result.JobStatus, |
| 215 | documentGroups: result.Summary?.DocumentGroups?.length ?? 0, |
| 216 | }); |
| 217 | } |
| 218 | |
| 219 | // --- adapter management --- |
| 220 | if (request.method === "GET" && pathname === "/adapters") { |
| 221 | const info = yield* throttleRetry(getAdapter()); |
| 222 | const listed = yield* throttleRetry(listAdapters()); |
| 223 | const versions = yield* throttleRetry(listAdapterVersions()); |
| 224 | return yield* HttpServerResponse.json({ |
| 225 | adapterName: info.AdapterName, |
| 226 | featureTypes: info.FeatureTypes, |
| 227 | listed: (listed.Adapters ?? []).map((a) => a.AdapterName), |
| 228 | versionsCount: versions.AdapterVersions?.length ?? 0, |
| 229 | }); |
| 230 | } |
| 231 | |
| 232 | // Typed-error probes — well-formed-but-nonexistent identifiers drive |
| 233 | // the typed not-found/validation paths. An IAM gap would surface |
| 234 | // AccessDeniedException (a 500 through the handler's orDie), so a |
| 235 | // typed tag here proves the grant end-to-end. |
| 236 | if (request.method === "GET" && pathname === "/adapter-version-probes") { |
| 237 | const getVersionProbe = yield* throttleRetry( |
| 238 | getAdapterVersion({ AdapterVersion: "999" }), |
| 239 | ).pipe( |
| 240 | Effect.map(() => "unexpected-success"), |
| 241 | Effect.catchTag(["ResourceNotFoundException", "ValidationException"], (e) => |
| 242 | Effect.succeed(e._tag), |
| 243 | ), |
| 244 | ); |
| 245 | // DeleteAdapterVersion is idempotent — deleting a nonexistent |
| 246 | // version returns success, which proves the grant just as well. |
| 247 | const deleteVersionProbe = yield* throttleRetry( |
| 248 | deleteAdapterVersion({ AdapterVersion: "999" }), |
| 249 | ).pipe( |
| 250 | Effect.map(() => "success"), |
| 251 | Effect.catchTag( |
| 252 | ["ResourceNotFoundException", "ValidationException", "ConflictException"], |
| 253 | (e) => Effect.succeed(e._tag), |
| 254 | ), |
| 255 | ); |
| 256 | const createVersionProbe = yield* throttleRetry( |
| 257 | createAdapterVersion({ |
| 258 | DatasetConfig: { |
| 259 | ManifestS3Object: { |
| 260 | Bucket, |
| 261 | Name: "missing-manifest.jsonl", |
| 262 | }, |
| 263 | }, |
| 264 | OutputConfig: { |
| 265 | S3Bucket: Bucket, |
| 266 | S3Prefix: "adapter-training/", |
| 267 | }, |
| 268 | }), |
| 269 | ).pipe( |
| 270 | Effect.map(() => "unexpected-success"), |
| 271 | Effect.catchTag( |
| 272 | [ |
| 273 | "InvalidS3ObjectException", |
| 274 | "InvalidParameterException", |
| 275 | "ValidationException", |
| 276 | "LimitExceededException", |
| 277 | ], |
| 278 | (e) => Effect.succeed(e._tag), |
| 279 | ), |
| 280 | ); |
| 281 | return yield* HttpServerResponse.json({ |
| 282 | getVersionProbe, |
| 283 | deleteVersionProbe, |
| 284 | createVersionProbe, |
| 285 | }); |
| 286 | } |
| 287 | |
| 288 | return yield* HttpServerResponse.json( |
| 289 | { error: "Not found", method: request.method, pathname }, |
| 290 | { status: 404 }, |
| 291 | ); |
| 292 | }).pipe(Effect.orDie), |
| 293 | }; |
| 294 | }).pipe( |
| 295 | Effect.provide( |
| 296 | Layer.mergeAll( |
| 297 | S3.PutObjectHttp, |
| 298 | S3.GetObjectHttp, |
| 299 | Textract.AnalyzeDocumentHttp, |
| 300 | Textract.AnalyzeExpenseHttp, |
| 301 | Textract.AnalyzeIDHttp, |
| 302 | Textract.StartDocumentTextDetectionHttp, |
| 303 | Textract.GetDocumentTextDetectionHttp, |
| 304 | Textract.StartDocumentAnalysisHttp, |
| 305 | Textract.GetDocumentAnalysisHttp, |
| 306 | Textract.StartExpenseAnalysisHttp, |
| 307 | Textract.GetExpenseAnalysisHttp, |
| 308 | Textract.StartLendingAnalysisHttp, |
| 309 | Textract.GetLendingAnalysisHttp, |
| 310 | Textract.GetLendingAnalysisSummaryHttp, |
| 311 | Textract.ListAdaptersHttp, |
| 312 | Textract.GetAdapterHttp, |
| 313 | Textract.ListAdapterVersionsHttp, |
| 314 | Textract.GetAdapterVersionHttp, |
| 315 | Textract.CreateAdapterVersionHttp, |
| 316 | Textract.DeleteAdapterVersionHttp, |
| 317 | ), |
| 318 | ), |
| 319 | ), |
| 320 | ); |