@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, 06:00 UTC

main
ts 257 lines 8.95 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 eventbridge from "@distilled.cloud/aws/eventbridge";
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 SageMakerTestFunctionLive, { SageMakerTestFunction } from "./handler";
12
13 const testOptions = { providers: AWS.providers() };
14 const { test, beforeAll, afterAll } = Test.make(testOptions);
15 const sharedStack = Core.scratchStack(testOptions, "SageMakerBindings");
16
17 const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(75)]);
18
19 let baseUrl: string;
20 let functionArn: string;
21
22 class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
23 readonly status: number;
24 readonly body: string;
25 }> {}
26
27 // Retry only transient 5xx (cold re-inits under parallel-suite load);
28 // genuine 4xx/assertion failures surface immediately.
29 const send = (request: HttpClientRequest.HttpClientRequest) =>
30 HttpClient.execute(request).pipe(
31 Effect.flatMap((response) =>
32 response.status >= 500
33 ? response.text.pipe(
34 Effect.flatMap((body) =>
35 Effect.fail(new TransientUpstream({ status: response.status, body })),
36 ),
37 )
38 : Effect.succeed(response),
39 ),
40 Effect.retry({
41 while: (e) => e._tag === "TransientUpstream",
42 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(6)]),
43 }),
44 );
45
46 const postJson = (path: string, body: unknown) =>
47 send(
48 HttpClientRequest.post(`${baseUrl}${path}`).pipe(HttpClientRequest.bodyJsonUnsafe(body)),
49 ).pipe(Effect.flatMap((r) => r.json));
50
51 const getJson = (path: string) =>
52 send(HttpClientRequest.get(`${baseUrl}${path}`)).pipe(Effect.flatMap((r) => r.json));
53
54 describe(
55 "SageMaker FeatureStore Bindings",
56 {
57 tags: [
58 "provider:aws",
59 "provider:aws:batch",
60 "provider:aws:lambda",
61 "provider:aws:sagemaker",
62 "live",
63 ],
64 },
65 () => {
66 beforeAll(
67 Effect.gen(function* () {
68 yield* Effect.logInfo("SageMaker bindings: destroying previous stack");
69 yield* sharedStack.destroy();
70
71 yield* Effect.logInfo("SageMaker bindings: deploying fixture");
72 const attrs = yield* sharedStack.deploy(
73 Effect.gen(function* () {
74 return yield* SageMakerTestFunction;
75 }).pipe(Effect.provide(SageMakerTestFunctionLive)),
76 );
77
78 expect(attrs.functionUrl).toBeTruthy();
79 baseUrl = attrs.functionUrl!.replace(/\/+$/, "");
80 functionArn = attrs.functionArn;
81
82 yield* Effect.logInfo(`SageMaker bindings: probing readiness at ${baseUrl}/health`);
83 yield* HttpClient.get(`${baseUrl}/health`).pipe(
84 Effect.flatMap((response) =>
85 response.status === 200
86 ? Effect.succeed(response)
87 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
88 ),
89 Effect.retry({ schedule: readinessPolicy }),
90 );
91 }),
92 { timeout: 480_000 },
93 );
94
95 afterAll(sharedStack.destroy(), { timeout: 300_000 });
96
97 describe("binding registration", () => {
98 test.provider("all six capabilities initialize in the runtime", () =>
99 Effect.gen(function* () {
100 const response = (yield* getJson("/bindings")) as { bound: string[] };
101 expect(response.bound.sort()).toEqual(
102 [
103 "batchGetRecord",
104 "batchWriteRecord",
105 "deleteRecord",
106 "getRecord",
107 "listRecords",
108 "putRecord",
109 ].sort(),
110 );
111 }),
112 );
113 });
114
115 describe("PutRecord", () => {
116 test.provider(
117 "writes a record to the online store",
118 () =>
119 Effect.gen(function* () {
120 const body = (yield* postJson("/put-record", { userId: "user-put-1", clicks: 7 })) as {
121 success: boolean;
122 };
123 expect(body.success).toBe(true);
124 }),
125 { timeout: 60_000 },
126 );
127 });
128
129 describe("GetRecord", () => {
130 test.provider(
131 "reads back a written record",
132 () =>
133 Effect.gen(function* () {
134 yield* postJson("/put-record", { userId: "user-roundtrip-1", clicks: 42 });
135
136 const body = (yield* getJson("/get-record?userId=user-roundtrip-1")) as {
137 record: { FeatureName?: string; ValueAsString?: string }[];
138 };
139 const byName = Object.fromEntries(
140 body.record.map((f) => [f.FeatureName, f.ValueAsString]),
141 );
142 expect(byName.user_id).toBe("user-roundtrip-1");
143 expect(byName.clicks).toBe("42");
144 }),
145 { timeout: 60_000 },
146 );
147
148 test.provider(
149 "returns an empty record for an unknown identifier",
150 () =>
151 Effect.gen(function* () {
152 const body = (yield* getJson("/get-record?userId=user-never-written")) as {
153 record: unknown[];
154 };
155 expect(body.record).toEqual([]);
156 }),
157 { timeout: 60_000 },
158 );
159 });
160
161 describe("DeleteRecord", () => {
162 test.provider(
163 "soft-deletes a written record (GetRecord no longer returns it)",
164 () =>
165 Effect.gen(function* () {
166 yield* postJson("/put-record", { userId: "user-delete-1", clicks: 1 });
167 yield* postJson("/delete-record", { userId: "user-delete-1" });
168
169 // Online-store deletes are read-after-write consistent in practice;
170 // allow a short bounded window regardless.
171 const body = yield* getJson("/get-record?userId=user-delete-1").pipe(
172 Effect.repeat({
173 schedule: Schedule.spaced("2 seconds"),
174 until: (b): boolean => (b as { record: unknown[] }).record.length === 0,
175 times: 8,
176 }),
177 );
178 expect((body as { record: unknown[] }).record).toEqual([]);
179 }),
180 { timeout: 60_000 },
181 );
182 });
183
184 describe("BatchWriteRecord + BatchGetRecord", () => {
185 test.provider(
186 "bulk-writes records and reads them back in one batch",
187 () =>
188 Effect.gen(function* () {
189 const write = (yield* postJson("/batch-write-record", {
190 records: [
191 { userId: "user-batch-1", clicks: 11 },
192 { userId: "user-batch-2", clicks: 22 },
193 ],
194 })) as { errors: unknown[]; unprocessed: unknown[] };
195 expect(write.errors).toEqual([]);
196 expect(write.unprocessed).toEqual([]);
197
198 const read = (yield* postJson("/batch-get-record", {
199 userIds: ["user-batch-1", "user-batch-2", "user-batch-missing"],
200 })) as {
201 records: {
202 userId: string;
203 record: { FeatureName?: string; ValueAsString?: string }[];
204 }[];
205 errors: unknown[];
206 };
207 expect(read.errors).toEqual([]);
208 const byUser = Object.fromEntries(
209 read.records.map((r) => [
210 r.userId,
211 Object.fromEntries(r.record.map((f) => [f.FeatureName, f.ValueAsString])),
212 ]),
213 );
214 expect(byUser["user-batch-1"]?.clicks).toBe("11");
215 expect(byUser["user-batch-2"]?.clicks).toBe("22");
216 expect(byUser["user-batch-missing"]).toBeUndefined();
217 }),
218 { timeout: 60_000 },
219 );
220 });
221
222 describe("ListRecords", () => {
223 test.provider(
224 "lists the identifiers of stored records",
225 () =>
226 Effect.gen(function* () {
227 yield* postJson("/put-record", { userId: "user-list-1", clicks: 3 });
228
229 const body = yield* getJson("/list-records").pipe(
230 Effect.repeat({
231 schedule: Schedule.spaced("2 seconds"),
232 until: (b): boolean =>
233 (b as { identifiers: string[] }).identifiers.includes("user-list-1"),
234 times: 8,
235 }),
236 );
237 expect((body as { identifiers: string[] }).identifiers).toContain("user-list-1");
238 }),
239 { timeout: 60_000 },
240 );
241 });
242
243 describe("consumeSageMakerEvents", { tags: ["provider:aws:eventbridge"] }, () => {
244 test.provider("the deploy created an EventBridge rule targeting the function", () =>
245 Effect.gen(function* () {
246 // Out-of-band via distilled: the fixture's consumeSageMakerEvents
247 // must have materialized as a rule on the default bus with the
248 // Lambda as target.
249 const { RuleNames } = yield* eventbridge.listRuleNamesByTarget({
250 TargetArn: functionArn,
251 });
252 expect((RuleNames ?? []).length).toBeGreaterThanOrEqual(1);
253 }),
254 );
255 });
256 },
257 );