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 BDA from "@alchemy.run/aws/BedrockDataAutomation"; |
| 2 | import * as Lambda from "@alchemy.run/aws/Lambda"; |
| 3 | import * as S3 from "@alchemy.run/aws/S3"; |
| 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 Stream from "effect/Stream"; |
| 10 | import path from "pathe"; |
| 11 | |
| 12 | const main = path.resolve(import.meta.dirname, "handler.ts"); |
| 13 | |
| 14 | const INPUT_KEY = "inputs/hello.pdf"; |
| 15 | |
| 16 | // Minimal single-page PDF, checked in as a constant (never generated at test |
| 17 | // time). The async invoke only needs a readable S3 object — the job's final |
| 18 | // verdict is irrelevant to the binding test. |
| 19 | const TINY_PDF = `%PDF-1.4 |
| 20 | 1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj |
| 21 | 2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj |
| 22 | 3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 612 792]/Resources<</Font<</F1 5 0 R>>>>/Contents 4 0 R>>endobj |
| 23 | 4 0 obj<</Length 46>>stream |
| 24 | BT /F1 24 Tf 72 720 Td (Hello Alchemy) Tj ET |
| 25 | endstream |
| 26 | endobj |
| 27 | 5 0 obj<</Type/Font/Subtype/Type1/BaseFont/Helvetica>>endobj |
| 28 | trailer<</Size 6/Root 1 0 R>> |
| 29 | %%EOF |
| 30 | `; |
| 31 | |
| 32 | // A deterministic, valid BDA blueprint schema (checked-in constant fixture). |
| 33 | const INVOICE_SCHEMA = JSON.stringify({ |
| 34 | $schema: "http://json-schema.org/draft-07/schema#", |
| 35 | description: "Extract invoice fields", |
| 36 | class: "invoice", |
| 37 | type: "object", |
| 38 | definitions: {}, |
| 39 | properties: { |
| 40 | invoice_number: { |
| 41 | type: "string", |
| 42 | inferenceType: "explicit", |
| 43 | instruction: "The invoice number", |
| 44 | }, |
| 45 | }, |
| 46 | }); |
| 47 | |
| 48 | export class BdaTestFunction extends Lambda.Function<Lambda.Function>()("BdaTestFunction") {} |
| 49 | |
| 50 | export default BdaTestFunction.make( |
| 51 | { |
| 52 | main, |
| 53 | functionUrl: true, |
| 54 | timeout: Duration.seconds(30), |
| 55 | }, |
| 56 | Effect.gen(function* () { |
| 57 | const project = yield* BDA.DataAutomationProject("BindingsProject", { |
| 58 | projectDescription: "alchemy bindings test project", |
| 59 | standardOutputConfiguration: { |
| 60 | document: { |
| 61 | extraction: { |
| 62 | granularity: { types: ["DOCUMENT"] }, |
| 63 | boundingBox: { state: "DISABLED" }, |
| 64 | }, |
| 65 | generativeField: { state: "DISABLED" }, |
| 66 | outputFormat: { |
| 67 | textFormat: { types: ["MARKDOWN"] }, |
| 68 | additionalFileFormat: { state: "DISABLED" }, |
| 69 | }, |
| 70 | }, |
| 71 | }, |
| 72 | }); |
| 73 | const blueprint = yield* BDA.Blueprint("BindingsBlueprint", { |
| 74 | type: "DOCUMENT", |
| 75 | schema: INVOICE_SCHEMA, |
| 76 | }); |
| 77 | const library = yield* BDA.DataAutomationLibrary("BindingsLibrary", { |
| 78 | libraryDescription: "alchemy bindings test library", |
| 79 | }); |
| 80 | // Bedrock Data Automation reads the input and writes the output with the |
| 81 | // CALLER's S3 permissions (forward access sessions), so the Lambda role |
| 82 | // needs GetObject + PutObject on the working bucket. |
| 83 | const bucket = yield* S3.Bucket("BindingsBucket", { forceDestroy: true }); |
| 84 | const bucketName = yield* bucket.bucketName; |
| 85 | |
| 86 | const putObject = yield* S3.PutObject(bucket); |
| 87 | const getObject = yield* S3.GetObject(bucket); |
| 88 | const invokeDataAutomationAsync = yield* BDA.InvokeDataAutomationAsync(project); |
| 89 | const invokeDataAutomation = yield* BDA.InvokeDataAutomation(project); |
| 90 | const getDataAutomationStatus = yield* BDA.GetDataAutomationStatus(); |
| 91 | const ingestLibraryEntities = yield* BDA.InvokeDataAutomationLibraryIngestionJob(library); |
| 92 | const getLibraryIngestionJob = yield* BDA.GetDataAutomationLibraryIngestionJob(library); |
| 93 | const listLibraryIngestionJobs = yield* BDA.ListDataAutomationLibraryIngestionJobs(library); |
| 94 | const getLibraryEntity = yield* BDA.GetDataAutomationLibraryEntity(library); |
| 95 | const listLibraryEntities = yield* BDA.ListDataAutomationLibraryEntities(library); |
| 96 | const createBlueprintVersion = yield* BDA.CreateBlueprintVersion(blueprint); |
| 97 | const copyBlueprintStage = yield* BDA.CopyBlueprintStage(blueprint); |
| 98 | const invokeBlueprintOptimizationAsync = yield* BDA.InvokeBlueprintOptimizationAsync(blueprint); |
| 99 | const getBlueprintOptimizationStatus = yield* BDA.GetBlueprintOptimizationStatus(); |
| 100 | |
| 101 | // Deploy-time: creates the EventBridge rule (default bus, source |
| 102 | // aws.bedrock) targeting this Function. Runtime firing needs a settled |
| 103 | // job with eventBridgeEnabled, so the test only verifies the |
| 104 | // subscription deploys. |
| 105 | yield* BDA.consumeDataAutomationJobEvents( |
| 106 | { kinds: ["succeeded", "client-error", "service-error"] }, |
| 107 | (events) => |
| 108 | Stream.runForEach(events, (event) => |
| 109 | Effect.log(`data automation job ${event.detail.job_id}: ${event.detail.job_status}`), |
| 110 | ), |
| 111 | ); |
| 112 | |
| 113 | const bound = { |
| 114 | putObject, |
| 115 | getObject, |
| 116 | invokeDataAutomationAsync, |
| 117 | invokeDataAutomation, |
| 118 | getDataAutomationStatus, |
| 119 | ingestLibraryEntities, |
| 120 | getLibraryIngestionJob, |
| 121 | listLibraryIngestionJobs, |
| 122 | getLibraryEntity, |
| 123 | listLibraryEntities, |
| 124 | createBlueprintVersion, |
| 125 | copyBlueprintStage, |
| 126 | invokeBlueprintOptimizationAsync, |
| 127 | getBlueprintOptimizationStatus, |
| 128 | }; |
| 129 | |
| 130 | return { |
| 131 | fetch: Effect.gen(function* () { |
| 132 | const request = yield* HttpServerRequest; |
| 133 | const url = new URL(request.originalUrl); |
| 134 | const pathname = url.pathname; |
| 135 | |
| 136 | if (request.method === "GET" && pathname === "/bindings") { |
| 137 | return yield* HttpServerResponse.json({ |
| 138 | bound: Object.keys(bound), |
| 139 | }); |
| 140 | } |
| 141 | |
| 142 | if (request.method === "POST" && pathname === "/invoke-async") { |
| 143 | // Uploads the fixture document, then submits an async job against |
| 144 | // the bound project. The response arrives before the job settles — |
| 145 | // the test asserts the invocation ARN shape and polls status once. |
| 146 | const profileArn = url.searchParams.get("profileArn")!; |
| 147 | // Double-yield: the init-scope yield gives an accessor; yielding |
| 148 | // it here resolves the physical bucket name at runtime. |
| 149 | const physicalBucket = yield* bucketName; |
| 150 | const result = yield* putObject({ |
| 151 | Key: INPUT_KEY, |
| 152 | Body: TINY_PDF, |
| 153 | ContentType: "application/pdf", |
| 154 | }).pipe( |
| 155 | Effect.flatMap(() => |
| 156 | invokeDataAutomationAsync({ |
| 157 | inputConfiguration: { |
| 158 | s3Uri: `s3://${physicalBucket}/${INPUT_KEY}`, |
| 159 | }, |
| 160 | outputConfiguration: { |
| 161 | s3Uri: `s3://${physicalBucket}/results/`, |
| 162 | }, |
| 163 | dataAutomationProfileArn: profileArn, |
| 164 | notificationConfiguration: { |
| 165 | eventBridgeConfiguration: { eventBridgeEnabled: true }, |
| 166 | }, |
| 167 | }), |
| 168 | ), |
| 169 | Effect.map((r) => ({ invocationArn: r.invocationArn })), |
| 170 | // Surface the typed failure to the test instead of a bare 500 — |
| 171 | // the assertion prints the tag + message on mismatch. |
| 172 | Effect.catch((e) => |
| 173 | Effect.succeed({ |
| 174 | invocationArn: undefined, |
| 175 | error: e._tag, |
| 176 | message: String((e as { message?: unknown }).message ?? ""), |
| 177 | }), |
| 178 | ), |
| 179 | ); |
| 180 | return yield* HttpServerResponse.json(result); |
| 181 | } |
| 182 | |
| 183 | if (request.method === "GET" && pathname === "/status") { |
| 184 | const invocationArn = url.searchParams.get("invocationArn")!; |
| 185 | const result = yield* getDataAutomationStatus({ invocationArn }); |
| 186 | return yield* HttpServerResponse.json({ status: result.status }); |
| 187 | } |
| 188 | |
| 189 | if (request.method === "POST" && pathname === "/invoke-sync-validation") { |
| 190 | // The sync API needs a SYNC project and a non-empty input; driving |
| 191 | // it through the typed ValidationException path proves the IAM |
| 192 | // grant + project injection end-to-end — an IAM gap would surface |
| 193 | // AccessDeniedException (a 500 through orDie) instead. |
| 194 | const profileArn = url.searchParams.get("profileArn")!; |
| 195 | const tag = yield* invokeDataAutomation({ |
| 196 | inputConfiguration: {}, |
| 197 | dataAutomationProfileArn: profileArn, |
| 198 | }).pipe( |
| 199 | Effect.map(() => "Invoked"), |
| 200 | Effect.catchTag("ValidationException", (e) => Effect.succeed(e._tag)), |
| 201 | ); |
| 202 | return yield* HttpServerResponse.json({ tag }); |
| 203 | } |
| 204 | |
| 205 | if (request.method === "POST" && pathname === "/library-ingest") { |
| 206 | // Starts an inline UPSERT ingestion job against the bound library. |
| 207 | // Results land in the fixture bucket with the caller's S3 |
| 208 | // permissions. |
| 209 | const physicalBucket = yield* bucketName; |
| 210 | const result = yield* ingestLibraryEntities({ |
| 211 | entityType: "VOCABULARY", |
| 212 | operationType: "UPSERT", |
| 213 | inputConfiguration: { |
| 214 | inlinePayload: { |
| 215 | upsertEntitiesInfo: [ |
| 216 | { |
| 217 | vocabulary: { |
| 218 | language: "EN", |
| 219 | phrases: [{ text: "Alchemy", displayAsText: "Alchemy" }], |
| 220 | }, |
| 221 | }, |
| 222 | ], |
| 223 | }, |
| 224 | }, |
| 225 | outputConfiguration: { |
| 226 | s3Uri: `s3://${physicalBucket}/library-results/`, |
| 227 | }, |
| 228 | }).pipe( |
| 229 | Effect.map((r) => ({ jobArn: r.jobArn })), |
| 230 | // Surface the FULL cause (typed failure or defect) to the test — |
| 231 | // the assertion prints it on mismatch. |
| 232 | Effect.catchCause((cause) => |
| 233 | Effect.succeed({ |
| 234 | jobArn: undefined, |
| 235 | error: "Cause", |
| 236 | message: String(cause), |
| 237 | }), |
| 238 | ), |
| 239 | ); |
| 240 | return yield* HttpServerResponse.json(result); |
| 241 | } |
| 242 | |
| 243 | if (request.method === "GET" && pathname === "/library-ingestion-job") { |
| 244 | const jobArn = url.searchParams.get("jobArn")!; |
| 245 | const result = yield* getLibraryIngestionJob({ jobArn }); |
| 246 | return yield* HttpServerResponse.json({ |
| 247 | status: result.job?.jobStatus, |
| 248 | }); |
| 249 | } |
| 250 | |
| 251 | if (request.method === "GET" && pathname === "/library-ingestion-jobs") { |
| 252 | const result = yield* listLibraryIngestionJobs({ maxResults: 25 }); |
| 253 | return yield* HttpServerResponse.json({ |
| 254 | count: (result.jobs ?? []).length, |
| 255 | }); |
| 256 | } |
| 257 | |
| 258 | if (request.method === "GET" && pathname === "/library-entities") { |
| 259 | const result = yield* listLibraryEntities({ |
| 260 | entityType: "VOCABULARY", |
| 261 | maxResults: 25, |
| 262 | }); |
| 263 | return yield* HttpServerResponse.json({ |
| 264 | count: (result.entities ?? []).length, |
| 265 | }); |
| 266 | } |
| 267 | |
| 268 | if (request.method === "GET" && pathname === "/library-entity-missing") { |
| 269 | // Proves bedrock:GetDataAutomationLibraryEntity + library injection |
| 270 | // via the typed not-found path — an IAM gap would surface |
| 271 | // AccessDeniedException (a 500 through orDie) instead of the tag. |
| 272 | const tag = yield* getLibraryEntity({ |
| 273 | entityType: "VOCABULARY", |
| 274 | entityId: "nonexistent-alchemy-probe", |
| 275 | }).pipe( |
| 276 | Effect.map(() => "Found"), |
| 277 | Effect.catchTag(["ResourceNotFoundException", "ValidationException"], (e) => |
| 278 | Effect.succeed(e._tag), |
| 279 | ), |
| 280 | Effect.catchCause((cause) => Effect.succeed(`Cause: ${String(cause)}`)), |
| 281 | ); |
| 282 | return yield* HttpServerResponse.json({ tag }); |
| 283 | } |
| 284 | |
| 285 | if (request.method === "POST" && pathname === "/blueprint-version") { |
| 286 | const result = yield* createBlueprintVersion({}).pipe( |
| 287 | Effect.map((r) => ({ |
| 288 | version: r.blueprint.blueprintVersion, |
| 289 | arn: r.blueprint.blueprintArn, |
| 290 | })), |
| 291 | Effect.catch((e) => |
| 292 | Effect.succeed({ |
| 293 | version: undefined, |
| 294 | arn: undefined, |
| 295 | error: e._tag, |
| 296 | message: String((e as { message?: unknown }).message ?? ""), |
| 297 | }), |
| 298 | ), |
| 299 | ); |
| 300 | return yield* HttpServerResponse.json(result); |
| 301 | } |
| 302 | |
| 303 | if (request.method === "POST" && pathname === "/copy-stage-validation") { |
| 304 | // The fixture blueprint only exists in LIVE, so copying from the |
| 305 | // (absent) DEVELOPMENT stage drives the typed error path without |
| 306 | // creating a second stage copy the stack would have to clean up. |
| 307 | const tag = yield* copyBlueprintStage({ |
| 308 | sourceStage: "DEVELOPMENT", |
| 309 | targetStage: "LIVE", |
| 310 | }).pipe( |
| 311 | Effect.map(() => "Copied"), |
| 312 | Effect.catchTag(["ResourceNotFoundException", "ValidationException"], (e) => |
| 313 | Effect.succeed(e._tag), |
| 314 | ), |
| 315 | Effect.catchCause((cause) => Effect.succeed(`Cause: ${String(cause)}`)), |
| 316 | ); |
| 317 | return yield* HttpServerResponse.json({ tag }); |
| 318 | } |
| 319 | |
| 320 | if (request.method === "POST" && pathname === "/optimize-validation") { |
| 321 | // An empty samples list is invalid (min 1 labeled pair), so this |
| 322 | // drives the typed ValidationException path — proving IAM + |
| 323 | // blueprint injection without starting (and paying for) a real |
| 324 | // optimization job. |
| 325 | const profileArn = url.searchParams.get("profileArn")!; |
| 326 | const physicalBucket = yield* bucketName; |
| 327 | const tag = yield* invokeBlueprintOptimizationAsync({ |
| 328 | samples: [], |
| 329 | outputConfiguration: { |
| 330 | s3Object: { |
| 331 | s3Uri: `s3://${physicalBucket}/optimization-results/`, |
| 332 | }, |
| 333 | }, |
| 334 | dataAutomationProfileArn: profileArn, |
| 335 | }).pipe( |
| 336 | Effect.map(() => "Invoked"), |
| 337 | Effect.catchTag("ValidationException", (e) => Effect.succeed(e._tag)), |
| 338 | Effect.catchCause((cause) => Effect.succeed(`Cause: ${String(cause)}`)), |
| 339 | ); |
| 340 | return yield* HttpServerResponse.json({ tag }); |
| 341 | } |
| 342 | |
| 343 | if (request.method === "GET" && pathname === "/optimization-status-missing") { |
| 344 | // Proves bedrock:GetBlueprintOptimizationStatus via the typed |
| 345 | // not-found path on a well-formed but nonexistent invocation ARN |
| 346 | // supplied by the test. |
| 347 | const invocationArn = url.searchParams.get("invocationArn")!; |
| 348 | const tag = yield* getBlueprintOptimizationStatus({ |
| 349 | invocationArn, |
| 350 | }).pipe( |
| 351 | Effect.map((r) => r.status ?? "Unknown"), |
| 352 | Effect.catchTag(["ResourceNotFoundException", "ValidationException"], (e) => |
| 353 | Effect.succeed(e._tag), |
| 354 | ), |
| 355 | Effect.catchCause((cause) => Effect.succeed(`Cause: ${String(cause)}`)), |
| 356 | ); |
| 357 | return yield* HttpServerResponse.json({ tag }); |
| 358 | } |
| 359 | |
| 360 | return yield* HttpServerResponse.json( |
| 361 | { error: "Not found", method: request.method, pathname }, |
| 362 | { status: 404 }, |
| 363 | ); |
| 364 | }).pipe(Effect.orDie), |
| 365 | }; |
| 366 | }).pipe( |
| 367 | Effect.provide( |
| 368 | Layer.mergeAll( |
| 369 | Lambda.EventSource, |
| 370 | S3.PutObjectHttp, |
| 371 | S3.GetObjectHttp, |
| 372 | BDA.InvokeDataAutomationAsyncHttp, |
| 373 | BDA.InvokeDataAutomationHttp, |
| 374 | BDA.GetDataAutomationStatusHttp, |
| 375 | BDA.InvokeDataAutomationLibraryIngestionJobHttp, |
| 376 | BDA.GetDataAutomationLibraryIngestionJobHttp, |
| 377 | BDA.ListDataAutomationLibraryIngestionJobsHttp, |
| 378 | BDA.GetDataAutomationLibraryEntityHttp, |
| 379 | BDA.ListDataAutomationLibraryEntitiesHttp, |
| 380 | BDA.CreateBlueprintVersionHttp, |
| 381 | BDA.CopyBlueprintStageHttp, |
| 382 | BDA.InvokeBlueprintOptimizationAsyncHttp, |
| 383 | BDA.GetBlueprintOptimizationStatusHttp, |
| 384 | ), |
| 385 | ), |
| 386 | ), |
| 387 | ); |