The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as AWS from "@alchemy.run/aws"; |
| 2 | import type { PolicyStatement } from "@alchemy.run/aws/IAM"; |
| 3 | import * as Cause from "effect/Cause"; |
| 4 | import * as Context from "effect/Context"; |
| 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 * as Schedule from "effect/Schedule"; |
| 11 | import * as Stream from "effect/Stream"; |
| 12 | |
| 13 | // Deterministic bucket for EDI input/output. B2BI accesses the bucket as the |
| 14 | // service principal, authorized by the bucket policy below. |
| 15 | const stageSuffix = process.env.ALCHEMY_TEST_STAGE |
| 16 | ? `-${process.env.ALCHEMY_TEST_STAGE.toLowerCase().replaceAll("_", "-")}` |
| 17 | : ""; |
| 18 | export const BUCKET = `alchemy-test-b2bi-bindings${stageSuffix}`; |
| 19 | const BUCKET_ARN = `arn:aws:s3:::${BUCKET}`; |
| 20 | |
| 21 | // Deterministic queue name so the test can look up the queue URL out-of-band |
| 22 | // (sqs.getQueueUrl) and observe delivered transformation events. |
| 23 | export const EVENTS_QUEUE = `alchemy-b2bi-bindings-events${stageSuffix}`; |
| 24 | |
| 25 | // A minimal, valid X12 850 (purchase order), version 4010 — checked in as a |
| 26 | // constant fixture, never generated at test time. |
| 27 | export const SAMPLE_850_EDI = [ |
| 28 | "ISA*00* *00* *ZZ*SENDERID *ZZ*RECEIVERID *210101*1253*U*00401*000000001*0*T*>~", |
| 29 | "GS*PO*SENDERID*RECEIVERID*20210101*1253*1*X*004010~", |
| 30 | "ST*850*0001~", |
| 31 | "BEG*00*SA*XX-1234**20210101~", |
| 32 | "REF*DP*038~", |
| 33 | "PO1*1*10*EA*9.25*TE*CB*065322-117~", |
| 34 | "CTT*1~", |
| 35 | "SE*6*0001~", |
| 36 | "GE*1*1~", |
| 37 | "IEA*1*000000001~", |
| 38 | "", |
| 39 | ].join("\n"); |
| 40 | |
| 41 | const b2biBucketPolicy: PolicyStatement[] = [ |
| 42 | { |
| 43 | Effect: "Allow", |
| 44 | Principal: { Service: "b2bi.amazonaws.com" }, |
| 45 | Action: [ |
| 46 | "s3:GetObject", |
| 47 | "s3:GetObjectAttributes", |
| 48 | "s3:PutObject", |
| 49 | "s3:DeleteObject", |
| 50 | "s3:ListBucket", |
| 51 | "s3:GetBucketLocation", |
| 52 | "s3:AbortMultipartUpload", |
| 53 | ], |
| 54 | Resource: [BUCKET_ARN, `${BUCKET_ARN}/*`], |
| 55 | }, |
| 56 | ]; |
| 57 | |
| 58 | export class B2biTestFunction extends AWS.Lambda.Function<AWS.Lambda.Function>()( |
| 59 | "B2biTestFunction", |
| 60 | ) {} |
| 61 | |
| 62 | /** |
| 63 | * Shared infrastructure for the B2BI bindings fixture: the EDI S3 bucket, |
| 64 | * an ACTIVE inbound X12 850 transformer, and an SQS sink queue where the |
| 65 | * transformation-event consume loop forwards events so the test can observe |
| 66 | * them out-of-band. |
| 67 | */ |
| 68 | export class B2biFixtures extends Context.Service< |
| 69 | B2biFixtures, |
| 70 | { |
| 71 | bucket: AWS.S3.Bucket; |
| 72 | transformer: AWS.B2BI.Transformer; |
| 73 | eventsQueue: AWS.SQS.Queue; |
| 74 | } |
| 75 | >()("B2biFixtures") {} |
| 76 | |
| 77 | export const B2biFixturesLive = Layer.effect( |
| 78 | B2biFixtures, |
| 79 | Effect.gen(function* () { |
| 80 | const bucket = yield* AWS.S3.Bucket("B2biData", { |
| 81 | bucketName: BUCKET, |
| 82 | forceDestroy: true, |
| 83 | policy: b2biBucketPolicy, |
| 84 | }); |
| 85 | const transformer = yield* AWS.B2BI.Transformer("BindingsTransformer", { |
| 86 | name: `alchemy-b2bi-bindings-transformer${stageSuffix}`, |
| 87 | status: "active", |
| 88 | inputConversion: { |
| 89 | fromFormat: "X12", |
| 90 | formatOptions: { |
| 91 | x12: { transactionSet: "X12_850", version: "VERSION_4010" }, |
| 92 | }, |
| 93 | }, |
| 94 | mapping: { |
| 95 | templateLanguage: "JSONATA", |
| 96 | template: '{ "orderId": "test" }', |
| 97 | }, |
| 98 | }); |
| 99 | const eventsQueue = yield* AWS.SQS.Queue("B2biEventsSink", { |
| 100 | queueName: EVENTS_QUEUE, |
| 101 | }); |
| 102 | return { bucket, transformer, eventsQueue }; |
| 103 | }), |
| 104 | ); |
| 105 | |
| 106 | export default B2biTestFunction.make( |
| 107 | { |
| 108 | main: import.meta.url, |
| 109 | functionUrl: true, |
| 110 | timeout: Duration.minutes(2), |
| 111 | }, |
| 112 | Effect.gen(function* () { |
| 113 | const { bucket, transformer, eventsQueue } = yield* B2biFixtures; |
| 114 | const BucketName = yield* bucket.bucketName; |
| 115 | |
| 116 | // --- data-plane bindings under test --- |
| 117 | const putObject = yield* AWS.S3.PutObject(bucket); |
| 118 | const startTransformerJob = yield* AWS.B2BI.StartTransformerJob(transformer); |
| 119 | const getTransformerJob = yield* AWS.B2BI.GetTransformerJob(transformer); |
| 120 | const testMapping = yield* AWS.B2BI.TestMapping(); |
| 121 | const testParsing = yield* AWS.B2BI.TestParsing(); |
| 122 | const testConversion = yield* AWS.B2BI.TestConversion(); |
| 123 | const generateMapping = yield* AWS.B2BI.GenerateMapping(); |
| 124 | const createStarterMappingTemplate = yield* AWS.B2BI.CreateStarterMappingTemplate(); |
| 125 | const eventsSink = yield* AWS.SQS.QueueSink(eventsQueue); |
| 126 | |
| 127 | // Event source under test: forward every B2BI transformation event to |
| 128 | // the sink queue where the test observes it out-of-band. |
| 129 | yield* AWS.B2BI.consumeTransformationEvents({}, (events) => |
| 130 | events.pipe( |
| 131 | Stream.map((event) => ({ |
| 132 | MessageBody: JSON.stringify({ |
| 133 | detailType: event["detail-type"], |
| 134 | transformerJobId: event.detail["transformer-job-id"] ?? null, |
| 135 | output: event.detail["output-file-s3-attributes"] ?? null, |
| 136 | }), |
| 137 | })), |
| 138 | Stream.run(eventsSink), |
| 139 | Effect.orDie, |
| 140 | ), |
| 141 | ); |
| 142 | |
| 143 | const bound = { |
| 144 | startTransformerJob, |
| 145 | getTransformerJob, |
| 146 | testMapping, |
| 147 | testParsing, |
| 148 | testConversion, |
| 149 | generateMapping, |
| 150 | createStarterMappingTemplate, |
| 151 | putObject, |
| 152 | }; |
| 153 | |
| 154 | const uploadSampleEdi = (key: string) => |
| 155 | putObject({ |
| 156 | Key: key, |
| 157 | Body: SAMPLE_850_EDI, |
| 158 | ContentType: "text/plain", |
| 159 | }); |
| 160 | |
| 161 | const parseSampleEdi = (key: string) => |
| 162 | uploadSampleEdi(key).pipe( |
| 163 | Effect.andThen(BucketName), |
| 164 | Effect.flatMap((bucketName) => |
| 165 | testParsing({ |
| 166 | inputFile: { bucketName, key }, |
| 167 | fileFormat: "JSON", |
| 168 | ediType: { |
| 169 | x12Details: { |
| 170 | transactionSet: "X12_850", |
| 171 | version: "VERSION_4010", |
| 172 | }, |
| 173 | }, |
| 174 | }), |
| 175 | ), |
| 176 | ); |
| 177 | |
| 178 | return { |
| 179 | fetch: Effect.gen(function* () { |
| 180 | const request = yield* HttpServerRequest; |
| 181 | const url = new URL(request.originalUrl); |
| 182 | const pathname = url.pathname; |
| 183 | |
| 184 | if (request.method === "GET" && pathname === "/bindings") { |
| 185 | return yield* HttpServerResponse.json({ |
| 186 | bound: Object.keys(bound), |
| 187 | }); |
| 188 | } |
| 189 | |
| 190 | if (request.method === "POST" && pathname === "/test-mapping") { |
| 191 | const result = yield* testMapping({ |
| 192 | inputFileContent: JSON.stringify({ customer: "acme" }), |
| 193 | mappingTemplate: '{ "name": customer }', |
| 194 | fileFormat: "JSON", |
| 195 | }); |
| 196 | return yield* HttpServerResponse.json({ |
| 197 | mappedFileContent: result.mappedFileContent, |
| 198 | }); |
| 199 | } |
| 200 | |
| 201 | if (request.method === "POST" && pathname === "/starter-template") { |
| 202 | const result = yield* createStarterMappingTemplate({ |
| 203 | mappingType: "JSONATA", |
| 204 | templateDetails: { |
| 205 | x12: { transactionSet: "X12_850", version: "VERSION_4010" }, |
| 206 | }, |
| 207 | }); |
| 208 | return yield* HttpServerResponse.json({ |
| 209 | templateLength: result.mappingTemplate.length, |
| 210 | }); |
| 211 | } |
| 212 | |
| 213 | if (request.method === "POST" && pathname === "/generate-mapping") { |
| 214 | // GenerateMapping invokes Bedrock with the caller's session and |
| 215 | // requires Bedrock MODEL ACCESS to be enabled (an account/region |
| 216 | // entitlement). In the testing account the call succeeds on some |
| 217 | // runs and is denied on others (cross-region model routing), so |
| 218 | // the typed Bedrock-model-access rejection is reported explicitly |
| 219 | // rather than treated as a binding failure. |
| 220 | const result = yield* generateMapping({ |
| 221 | inputFileContent: JSON.stringify({ |
| 222 | customer: "acme", |
| 223 | city: "portland", |
| 224 | }), |
| 225 | outputFileContent: JSON.stringify({ name: "acme" }), |
| 226 | mappingType: "JSONATA", |
| 227 | }).pipe( |
| 228 | Effect.map((r) => ({ |
| 229 | templateLength: r.mappingTemplate.length, |
| 230 | accuracy: r.mappingAccuracy ?? null, |
| 231 | bedrockAccessDenied: false, |
| 232 | })), |
| 233 | Effect.catchTag("AccessDeniedException", (e) => |
| 234 | String(e.message).includes("Bedrock") |
| 235 | ? Effect.succeed({ |
| 236 | templateLength: 0, |
| 237 | accuracy: null, |
| 238 | bedrockAccessDenied: true, |
| 239 | }) |
| 240 | : Effect.fail(e), |
| 241 | ), |
| 242 | ); |
| 243 | return yield* HttpServerResponse.json(result); |
| 244 | } |
| 245 | |
| 246 | if (request.method === "POST" && pathname === "/test-parsing") { |
| 247 | const result = yield* parseSampleEdi("test-parsing/sample-850.edi"); |
| 248 | return yield* HttpServerResponse.json({ |
| 249 | parsed: JSON.parse(result.parsedFileContent), |
| 250 | validationMessages: result.validationMessages ?? [], |
| 251 | }); |
| 252 | } |
| 253 | |
| 254 | if (request.method === "POST" && pathname === "/test-conversion") { |
| 255 | // Round-trip: parse the sample 850 into B2BI's JSON representation, |
| 256 | // then convert that JSON back into an X12 document. |
| 257 | const parsed = yield* parseSampleEdi("test-conversion/sample-850.edi"); |
| 258 | const result = yield* testConversion({ |
| 259 | source: { |
| 260 | fileFormat: "JSON", |
| 261 | inputFile: { fileContent: parsed.parsedFileContent }, |
| 262 | }, |
| 263 | target: { |
| 264 | fileFormat: "X12", |
| 265 | formatDetails: { |
| 266 | x12: { transactionSet: "X12_850", version: "VERSION_4010" }, |
| 267 | }, |
| 268 | }, |
| 269 | }); |
| 270 | return yield* HttpServerResponse.json({ |
| 271 | convertedLength: result.convertedFileContent.length, |
| 272 | startsWithIsa: result.convertedFileContent.startsWith("ISA"), |
| 273 | validationMessages: result.validationMessages ?? [], |
| 274 | }); |
| 275 | } |
| 276 | |
| 277 | if (request.method === "POST" && pathname === "/transformer-job") { |
| 278 | const bucketName = yield* BucketName; |
| 279 | yield* uploadSampleEdi("job-input/sample-850.edi"); |
| 280 | const started = yield* startTransformerJob({ |
| 281 | inputFile: { bucketName, key: "job-input/sample-850.edi" }, |
| 282 | outputLocation: { bucketName, key: "job-output/" }, |
| 283 | }); |
| 284 | // A freshly started job can briefly 404; retry the typed tag, then |
| 285 | // poll (bounded) until the job leaves `running`. |
| 286 | const job = yield* getTransformerJob({ |
| 287 | transformerJobId: started.transformerJobId, |
| 288 | }).pipe( |
| 289 | Effect.retry({ |
| 290 | while: (e) => e._tag === "ResourceNotFoundException", |
| 291 | schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(5)]), |
| 292 | }), |
| 293 | Effect.repeat({ |
| 294 | schedule: Schedule.spaced("2 seconds"), |
| 295 | until: (j): boolean => j.status !== "running", |
| 296 | times: 25, |
| 297 | }), |
| 298 | ); |
| 299 | return yield* HttpServerResponse.json({ |
| 300 | transformerJobId: started.transformerJobId, |
| 301 | status: job.status, |
| 302 | message: job.message ?? null, |
| 303 | outputFiles: job.outputFiles ?? [], |
| 304 | }); |
| 305 | } |
| 306 | |
| 307 | return yield* HttpServerResponse.json( |
| 308 | { error: "Not found", method: request.method, pathname }, |
| 309 | { status: 404 }, |
| 310 | ); |
| 311 | }).pipe( |
| 312 | // Surface every failure (typed error or defect) to the test as JSON |
| 313 | // instead of an opaque 500 — the test asserts `error` is absent. |
| 314 | Effect.catchCause((cause) => HttpServerResponse.json({ error: Cause.pretty(cause) })), |
| 315 | ), |
| 316 | }; |
| 317 | }).pipe( |
| 318 | Effect.provide( |
| 319 | Layer.provideMerge( |
| 320 | Layer.mergeAll( |
| 321 | AWS.Lambda.EventSource, |
| 322 | AWS.S3.PutObjectHttp, |
| 323 | AWS.SQS.QueueSinkHttp, |
| 324 | AWS.B2BI.StartTransformerJobHttp, |
| 325 | AWS.B2BI.GetTransformerJobHttp, |
| 326 | AWS.B2BI.TestMappingHttp, |
| 327 | AWS.B2BI.TestParsingHttp, |
| 328 | AWS.B2BI.TestConversionHttp, |
| 329 | AWS.B2BI.GenerateMappingHttp, |
| 330 | AWS.B2BI.CreateStarterMappingTemplateHttp, |
| 331 | B2biFixturesLive, |
| 332 | ), |
| 333 | Layer.mergeAll(AWS.SQS.SendMessageBatchHttp), |
| 334 | ), |
| 335 | ), |
| 336 | ), |
| 337 | ); |