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

main
ts 280 lines 10.5 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { describe, expect } from "@alchemy.run/test";
3 import * as Test from "@alchemy.run/test/Alchemy";
4 import * as Core from "@alchemy.run/test/Core";
5 import * as sqs from "@distilled.cloud/aws/sqs";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as HttpClient from "effect/http/HttpClient";
9 import * as HttpClientRequest from "effect/http/HttpClientRequest";
10 import * as Schedule from "effect/Schedule";
11 import B2biTestFunctionLive, { B2biTestFunction, EVENTS_QUEUE } from "./handler";
12
13 const testOptions = { providers: AWS.providers() };
14 const { test, beforeAll, afterAll } = Test.make(testOptions);
15 const sharedStack = Core.scratchStack(testOptions, "B2biBindings");
16
17 // Lambda function URL cold-start (DNS, IAM propagation, init) can take well
18 // over 60s on a fresh deploy.
19 const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(75)]);
20
21 let baseUrl: string;
22
23 class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
24 readonly status: number;
25 readonly body: string;
26 }> {}
27
28 // The shared Lambda fixture occasionally answers a transient 5xx under load
29 // (cold re-init, IAM propagation on the freshly attached policy that the
30 // handler's `Effect.orDie` surfaces as a 500). Retry only 5xx; a genuine
31 // 4xx/assertion failure surfaces immediately.
32 const send = (request: HttpClientRequest.HttpClientRequest) =>
33 HttpClient.execute(request).pipe(
34 Effect.flatMap((response) =>
35 response.status >= 500
36 ? response.text.pipe(
37 Effect.flatMap((body) =>
38 Effect.fail(new TransientUpstream({ status: response.status, body })),
39 ),
40 )
41 : Effect.succeed(response),
42 ),
43 Effect.retry({
44 while: (e) => e._tag === "TransientUpstream",
45 schedule: Schedule.max([Schedule.exponential("2 seconds"), Schedule.recurs(6)]),
46 }),
47 );
48
49 class TransformationEventNotObserved extends Data.TaggedError("TransformationEventNotObserved")<{
50 readonly transformerJobId: string;
51 }> {
52 override get message() {
53 return `No B2BI transformation event was observed for job ${this.transformerJobId}`;
54 }
55 }
56
57 const runTransformerJob = Effect.fn(function* () {
58 const response = (yield* send(HttpClientRequest.post(`${baseUrl}/transformer-job`)).pipe(
59 Effect.flatMap((r) => r.json),
60 )) as {
61 transformerJobId: string;
62 status: string;
63 message: string | null;
64 outputFiles: { bucketName?: string; key?: string }[];
65 error?: string;
66 };
67 expect(response.error).toBeUndefined();
68 expect(response.transformerJobId).toBeTruthy();
69 expect(response.status).toBe("succeeded");
70 expect(response.outputFiles.length).toBeGreaterThan(0);
71 yield* Effect.logInfo(
72 `B2BI job ${response.transformerJobId}: ${response.status}; ${response.message ?? "no message"}`,
73 );
74 return response;
75 });
76
77 describe.sequential(
78 "B2BI Bindings",
79 {
80 tags: [
81 "provider:aws",
82 "provider:aws:b2bi",
83 "provider:aws:iam",
84 "provider:aws:lambda",
85 "provider:aws:s3",
86 "provider:aws:sqs",
87 "live",
88 ],
89 },
90 () => {
91 beforeAll(
92 Effect.gen(function* () {
93 yield* Effect.logInfo("B2BI test setup: destroying previous resources");
94 yield* sharedStack.destroy();
95
96 yield* Effect.logInfo("B2BI test setup: deploying fixture");
97 const { functionUrl } = yield* sharedStack.deploy(
98 Effect.gen(function* () {
99 return yield* B2biTestFunction;
100 }).pipe(Effect.provide(B2biTestFunctionLive)),
101 );
102
103 expect(functionUrl).toBeTruthy();
104 baseUrl = functionUrl!.replace(/\/+$/, "");
105
106 const readinessUrl = `${baseUrl}/bindings`;
107 yield* Effect.logInfo(`B2BI test setup: probing readiness at ${readinessUrl}`);
108 yield* HttpClient.get(readinessUrl).pipe(
109 Effect.flatMap((response) =>
110 response.status === 200
111 ? Effect.succeed(response)
112 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
113 ),
114 Effect.tapError((error) =>
115 Effect.logWarning(`B2BI test setup: fixture not ready yet (${String(error)})`),
116 ),
117 Effect.retry({ schedule: readinessPolicy }),
118 );
119 }),
120 { timeout: 300_000 },
121 );
122
123 afterAll.skipIf(!!process.env.NO_DESTROY)(sharedStack.destroy(), { timeout: 180_000 });
124
125 describe("binding registration", () => {
126 test.provider("all 8 capabilities initialize in the runtime", (_stack) =>
127 Effect.gen(function* () {
128 const response = yield* send(HttpClientRequest.get(`${baseUrl}/bindings`)).pipe(
129 Effect.flatMap((r) => r.json),
130 );
131 expect((response as any).bound).toHaveLength(8);
132 }),
133 );
134 });
135
136 describe("TestMapping", () => {
137 test.provider("maps JSON content with a JSONATA template", (_stack) =>
138 Effect.gen(function* () {
139 const response = (yield* send(HttpClientRequest.post(`${baseUrl}/test-mapping`)).pipe(
140 Effect.flatMap((r) => r.json),
141 )) as { mappedFileContent: string };
142 // B2BI returns the mapped output as text (observed live: a JSON
143 // string literal of the pretty-printed document) — unwrap however
144 // many string layers it arrives in.
145 const parseDeep = (value: unknown): unknown =>
146 typeof value === "string" ? parseDeep(JSON.parse(value)) : value;
147 expect(parseDeep(response.mappedFileContent)).toEqual({ name: "acme" });
148 }),
149 );
150 });
151
152 describe("CreateStarterMappingTemplate", () => {
153 test.provider(
154 "scaffolds a JSONATA template for X12 850",
155 (_stack) =>
156 Effect.gen(function* () {
157 const response = (yield* send(
158 HttpClientRequest.post(`${baseUrl}/starter-template`),
159 ).pipe(Effect.flatMap((r) => r.json))) as { templateLength: number; error?: string };
160 expect(response.error).toBeUndefined();
161 expect(response.templateLength).toBeGreaterThan(0);
162 }),
163 { timeout: 60_000 },
164 );
165 });
166
167 describe("GenerateMapping", () => {
168 test.provider(
169 "generates a mapping template from sample documents",
170 (_stack) =>
171 Effect.gen(function* () {
172 const response = (yield* send(
173 HttpClientRequest.post(`${baseUrl}/generate-mapping`),
174 ).pipe(Effect.flatMap((r) => r.json))) as {
175 templateLength: number;
176 bedrockAccessDenied: boolean;
177 error?: string;
178 };
179 expect(response.error).toBeUndefined();
180 if (response.bedrockAccessDenied) {
181 // Bedrock model access for B2BI's mapping model is only
182 // intermittently entitled in the testing account (the same call
183 // succeeds on other runs — cross-region model routing). The
184 // typed rejection ("AccessDeniedException: Access denied when
185 // invoking Bedrock's InvokeModel API") still proves the
186 // b2bi:GenerateMapping + bedrock:InvokeModel grants end-to-end —
187 // an IAM gap would deny b2bi:GenerateMapping itself.
188 expect(response.templateLength).toBe(0);
189 } else {
190 expect(response.templateLength).toBeGreaterThan(0);
191 }
192 }),
193 { timeout: 120_000 },
194 );
195 });
196
197 describe("TestParsing", () => {
198 test.provider(
199 "parses an X12 850 from S3 into JSON",
200 (_stack) =>
201 Effect.gen(function* () {
202 const response = (yield* send(HttpClientRequest.post(`${baseUrl}/test-parsing`)).pipe(
203 Effect.flatMap((r) => r.json),
204 )) as { parsed: any; error?: string };
205 expect(response.error).toBeUndefined();
206 // The parsed representation carries the interchange/transaction data.
207 expect(JSON.stringify(response.parsed)).toContain("850");
208 }),
209 { timeout: 60_000 },
210 );
211 });
212
213 describe("TestConversion", () => {
214 test.provider(
215 "converts parsed JSON back into an X12 document",
216 (_stack) =>
217 Effect.gen(function* () {
218 const response = (yield* send(
219 HttpClientRequest.post(`${baseUrl}/test-conversion`),
220 ).pipe(Effect.flatMap((r) => r.json))) as {
221 convertedLength: number;
222 startsWithIsa: boolean;
223 error?: string;
224 };
225 expect(response.error).toBeUndefined();
226 expect(response.convertedLength).toBeGreaterThan(0);
227 expect(response.startsWithIsa).toBe(true);
228 }),
229 { timeout: 60_000 },
230 );
231 });
232
233 describe("StartTransformerJob + GetTransformerJob", () => {
234 test.provider("runs a transformer job to completion", () => runTransformerJob(), {
235 timeout: 120_000,
236 });
237 });
238
239 describe("consumeTransformationEvents", () => {
240 test.provider(
241 "delivers the completed job's EventBridge event to the sink queue",
242 () =>
243 Effect.gen(function* () {
244 const response = yield* runTransformerJob();
245 const { QueueUrl } = yield* sqs.getQueueUrl({ QueueName: EVENTS_QUEUE });
246 const event = yield* sqs
247 .receiveMessage({ QueueUrl: QueueUrl!, WaitTimeSeconds: 5, MaxNumberOfMessages: 10 })
248 .pipe(
249 Effect.flatMap((result) => {
250 const event = (result.Messages ?? [])
251 .map(
252 (message) =>
253 JSON.parse(message.Body ?? "{}") as {
254 detailType?: string;
255 transformerJobId?: string;
256 },
257 )
258 .find((body) => body.transformerJobId === response.transformerJobId);
259 return event
260 ? Effect.succeed(event)
261 : Effect.fail(
262 new TransformationEventNotObserved({
263 transformerJobId: response.transformerJobId,
264 }),
265 );
266 }),
267 Effect.retry({
268 while: (error) => error._tag === "TransformationEventNotObserved",
269 // Ten five-second long polls plus nine one-second delays.
270 schedule: Schedule.spaced("1 second"),
271 times: 9,
272 }),
273 );
274 expect(event.detailType).toBe("Transformation Completed");
275 }),
276 { timeout: 240_000 },
277 );
278 });
279 },
280 );