@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 285 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 lambda from "@distilled.cloud/aws/lambda";
6 import * as s3 from "@distilled.cloud/aws/s3";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as HttpClient from "effect/http/HttpClient";
10 import * as HttpClientRequest from "effect/http/HttpClientRequest";
11 import * as Schedule from "effect/Schedule";
12 import EntityResolutionTestFunctionLive, {
13 EntityResolutionTestFunction,
14 FIXTURE_BUCKET_NAME,
15 } from "./handler";
16
17 const testOptions = { providers: AWS.providers() };
18 const { test, beforeAll, afterAll } = Test.make(testOptions);
19 const sharedStack = Core.scratchStack(testOptions, "EntityResolutionBindings");
20
21 // Lambda function URL cold-start (DNS, IAM propagation, init) can take well
22 // over 60s on a fresh deploy.
23 const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(75)]);
24
25 let baseUrl: string;
26 let functionArn: string;
27
28 class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
29 readonly status: number;
30 readonly body: string;
31 }> {}
32
33 class FunctionStillExists extends Data.TaggedError("FunctionStillExists") {}
34 class BucketStillExists extends Data.TaggedError("BucketStillExists") {}
35
36 // The shared Lambda fixture occasionally answers a transient 5xx under load
37 // (cold re-init, IAM propagation on the freshly attached policy that the
38 // handler's `Effect.orDie` surfaces as a 500). Retry only 5xx; a genuine
39 // 4xx/assertion failure surfaces immediately.
40 const send = (request: HttpClientRequest.HttpClientRequest) =>
41 HttpClient.execute(request).pipe(
42 Effect.flatMap((response) =>
43 response.status >= 500
44 ? response.text.pipe(
45 Effect.flatMap((body) =>
46 Effect.fail(new TransientUpstream({ status: response.status, body })),
47 ),
48 )
49 : Effect.succeed(response),
50 ),
51 Effect.retry({
52 while: (e) => e._tag === "TransientUpstream",
53 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(6)]),
54 }),
55 );
56
57 const getJson = (path: string) =>
58 send(HttpClientRequest.get(`${baseUrl}${path}`)).pipe(Effect.flatMap((r) => r.json));
59
60 const postJson = (path: string) =>
61 send(HttpClientRequest.post(`${baseUrl}${path}`)).pipe(Effect.flatMap((r) => r.json));
62
63 describe.sequential(
64 "EntityResolution Bindings",
65 {
66 tags: [
67 "provider:aws",
68 "provider:aws:batch",
69 "provider:aws:entityresolution",
70 "provider:aws:glue",
71 "provider:aws:iam",
72 "provider:aws:lambda",
73 "provider:aws:s3",
74 "live",
75 ],
76 },
77 () => {
78 beforeAll(
79 Effect.gen(function* () {
80 yield* Effect.logInfo("EntityResolution bindings setup: destroying previous resources");
81 yield* sharedStack.destroy();
82
83 yield* Effect.logInfo("EntityResolution bindings setup: deploying fixture");
84 const attrs = yield* sharedStack.deploy(
85 Effect.gen(function* () {
86 return yield* EntityResolutionTestFunction;
87 }).pipe(Effect.provide(EntityResolutionTestFunctionLive)),
88 );
89
90 expect(attrs.functionUrl).toBeTruthy();
91 baseUrl = attrs.functionUrl!.replace(/\/+$/, "");
92 functionArn = attrs.functionArn;
93
94 const readinessUrl = `${baseUrl}/bindings`;
95 yield* Effect.logInfo(
96 `EntityResolution bindings setup: probing readiness at ${readinessUrl}`,
97 );
98 yield* HttpClient.get(readinessUrl).pipe(
99 Effect.flatMap((response) =>
100 response.status === 200
101 ? Effect.succeed(response)
102 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
103 ),
104 Effect.tapError((error) =>
105 Effect.logWarning(
106 `EntityResolution bindings setup: fixture not ready yet (${String(error)})`,
107 ),
108 ),
109 Effect.retry({ schedule: readinessPolicy }),
110 );
111 }),
112 { timeout: 240_000 },
113 );
114
115 afterAll.skipIf(!!process.env.NO_DESTROY)(
116 Effect.gen(function* () {
117 yield* sharedStack.destroy();
118 // Assert gone (skipped when beforeAll never got far enough to deploy):
119 // the fixture Lambda answers with the typed not-found tag and the
120 // fixed-name fixture bucket no longer heads. afterAll runs outside
121 // `test.provider`'s layer, so raw distilled calls need the provider
122 // layer (credentials, region) supplied explicitly.
123 if (functionArn) {
124 yield* Core.withProviders(
125 Effect.gen(function* () {
126 yield* lambda.getFunction({ FunctionName: functionArn }).pipe(
127 Effect.flatMap(() => Effect.fail(new FunctionStillExists())),
128 Effect.retry({
129 while: (error) => error._tag === "FunctionStillExists",
130 schedule: Schedule.exponential("500 millis"),
131 times: 8,
132 }),
133 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
134 );
135 yield* s3.headBucket({ Bucket: FIXTURE_BUCKET_NAME }).pipe(
136 Effect.flatMap(() => Effect.fail(new BucketStillExists())),
137 Effect.retry({
138 while: (error) => error._tag === "BucketStillExists",
139 schedule: Schedule.exponential("500 millis"),
140 times: 8,
141 }),
142 Effect.catchTag("NotFound", () => Effect.void),
143 );
144 }),
145 testOptions,
146 sharedStack.name,
147 );
148 }
149 }),
150 { timeout: 240_000 },
151 );
152
153 describe("binding registration", () => {
154 test.provider("all nine capabilities initialize in the runtime", (_stack) =>
155 Effect.gen(function* () {
156 const response = (yield* getJson("/bindings")) as { bound: string[] };
157 expect(response.bound).toHaveLength(9);
158 }),
159 );
160 });
161
162 describe("ListMatchingJobs / ListIdMappingJobs", () => {
163 test.provider(
164 "both workflow-scoped listings answer (fresh workflows have no jobs)",
165 (_stack) =>
166 Effect.gen(function* () {
167 const response = (yield* getJson("/jobs")) as {
168 matchingJobs: number;
169 idMappingJobs: number;
170 };
171 expect(response.matchingJobs).toBe(0);
172 expect(response.idMappingJobs).toBe(0);
173 }),
174 );
175 });
176
177 describe("GetMatchingJob / GetIdMappingJob", () => {
178 test.provider("a bogus job id surfaces the typed ResourceNotFoundException", (_stack) =>
179 Effect.gen(function* () {
180 const response = (yield* getJson("/jobs/not-found")) as {
181 matching: string;
182 idMapping: string;
183 };
184 expect(response.matching).toBe("ResourceNotFoundException");
185 expect(response.idMapping).toBe("ResourceNotFoundException");
186 }),
187 );
188 });
189
190 describe("GetMatchId", () => {
191 test.provider("an unprocessed record answers with no match id", (_stack) =>
192 Effect.gen(function* () {
193 const response = (yield* postJson("/match-id")) as {
194 result: string;
195 matchId: string | null;
196 matchRule: string | null;
197 message: string | null;
198 };
199 // Either an empty lookup succeeds or the service rejects real-time
200 // lookups on a never-run workflow with a typed tag — both prove the
201 // grant + typed plumbing (an IAM gap would be a 500).
202 expect(
203 ["ok", "ValidationException", "ResourceNotFoundException"],
204 response.message ?? undefined,
205 ).toContain(response.result);
206 expect(response.matchId).toBeNull();
207 }),
208 );
209 });
210
211 describe("GenerateMatchId", () => {
212 test.provider("real-time generation matches two records by email", (_stack) =>
213 Effect.gen(function* () {
214 const response = (yield* postJson("/generate-match-id")) as {
215 result: string;
216 matchGroups?: number;
217 failedRecords?: number;
218 message?: string | null;
219 };
220 // Either the account supports real-time generation on this
221 // workflow (both records land in one match group) or the service
222 // rejects it with a typed tag — both prove the grant + plumbing
223 // (an IAM gap would be a 500).
224 expect(
225 ["ok", "ValidationException", "ResourceNotFoundException"],
226 response.message ?? undefined,
227 ).toContain(response.result);
228 if (response.result === "ok") {
229 expect(response.matchGroups).toBeGreaterThanOrEqual(1);
230 }
231 }),
232 );
233 });
234
235 describe("BatchDeleteUniqueId", () => {
236 test.provider("deleting unknown unique ids answers per-id results", (_stack) =>
237 Effect.gen(function* () {
238 const response = (yield* postJson("/delete-unique-ids")) as {
239 result: string;
240 status?: string;
241 deleted?: number;
242 errors?: number;
243 message?: string | null;
244 };
245 expect(
246 ["ok", "ValidationException", "ResourceNotFoundException"],
247 response.message ?? undefined,
248 ).toContain(response.result);
249 }),
250 );
251 });
252
253 // The batch job runs take many minutes and cannot be cancelled — only
254 // exercised when explicitly opted in.
255 describe("StartMatchingJob / StartIdMappingJob (gated)", () => {
256 test.provider.skipIf(!process.env.AWS_TEST_ENTITYRESOLUTION_RUN)(
257 "starts a matching job through the binding",
258 (_stack) =>
259 Effect.gen(function* () {
260 const response = (yield* postJson("/start-matching-job")) as {
261 jobId: string;
262 status: string;
263 };
264 expect(response.jobId).toBeTruthy();
265 expect(["QUEUED", "RUNNING"]).toContain(response.status);
266 }),
267 { timeout: 120_000 },
268 );
269
270 test.provider.skipIf(!process.env.AWS_TEST_ENTITYRESOLUTION_RUN)(
271 "starts an id mapping job through the binding",
272 (_stack) =>
273 Effect.gen(function* () {
274 const response = (yield* postJson("/start-id-mapping-job")) as {
275 jobId: string;
276 status: string;
277 };
278 expect(response.jobId).toBeTruthy();
279 expect(["QUEUED", "RUNNING"]).toContain(response.status);
280 }),
281 { timeout: 120_000 },
282 );
283 });
284 },
285 );