@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 236 lines 8.72 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 SchemasTestFunctionLive, { SchemasTestFunction } from "./handler";
12
13 const testOptions = { providers: AWS.providers() };
14 const { test, beforeAll, afterAll } = Test.make(testOptions);
15 const sharedStack = Core.scratchStack(testOptions, "SchemasBindings");
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 let functionArn: string;
23
24 class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
25 readonly status: number;
26 readonly body: string;
27 }> {}
28
29 // The shared Lambda fixture occasionally answers a transient 5xx under load
30 // (cold re-init, IAM propagation on the freshly attached policy that the
31 // handler's `Effect.orDie` surfaces as a 500). Retry only 5xx; a genuine
32 // 4xx/assertion failure surfaces immediately.
33 const send = (request: HttpClientRequest.HttpClientRequest) =>
34 HttpClient.execute(request).pipe(
35 Effect.flatMap((response) =>
36 response.status >= 500
37 ? response.text.pipe(
38 Effect.flatMap((body) =>
39 Effect.fail(new TransientUpstream({ status: response.status, body })),
40 ),
41 )
42 : Effect.succeed(response),
43 ),
44 Effect.retry({
45 while: (e) => e._tag === "TransientUpstream",
46 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(6)]),
47 }),
48 );
49
50 const getJson = (path: string) =>
51 send(HttpClientRequest.get(`${baseUrl}${path}`)).pipe(Effect.flatMap((r) => r.json));
52
53 const postJson = (path: string) =>
54 send(HttpClientRequest.post(`${baseUrl}${path}`)).pipe(Effect.flatMap((r) => r.json));
55
56 describe.sequential(
57 "Schemas Bindings",
58 {
59 tags: [
60 "provider:aws",
61 "provider:aws:eventbridge",
62 "provider:aws:lambda",
63 "provider:aws:schemas",
64 "live",
65 ],
66 },
67 () => {
68 beforeAll(
69 Effect.gen(function* () {
70 yield* Effect.logInfo("Schemas test setup: destroying previous resources");
71 yield* sharedStack.destroy();
72
73 yield* Effect.logInfo("Schemas test setup: deploying fixture");
74 const attrs = yield* sharedStack.deploy(
75 Effect.gen(function* () {
76 return yield* SchemasTestFunction;
77 }).pipe(Effect.provide(SchemasTestFunctionLive)),
78 );
79
80 expect(attrs.functionUrl).toBeTruthy();
81 baseUrl = attrs.functionUrl!.replace(/\/+$/, "");
82 functionArn = attrs.functionArn;
83
84 const readinessUrl = `${baseUrl}/bindings`;
85 yield* Effect.logInfo(`Schemas test setup: probing readiness at ${readinessUrl}`);
86 yield* HttpClient.get(readinessUrl).pipe(
87 Effect.flatMap((response) =>
88 response.status === 200
89 ? Effect.succeed(response)
90 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
91 ),
92 Effect.tapError((error) =>
93 Effect.logWarning(`Schemas test setup: fixture not ready yet (${String(error)})`),
94 ),
95 Effect.retry({ schedule: readinessPolicy }),
96 );
97 }),
98 { timeout: 240_000 },
99 );
100
101 afterAll.skipIf(!!process.env.NO_DESTROY)(sharedStack.destroy(), { timeout: 120_000 });
102
103 describe("binding registration", () => {
104 test.provider("all ten capabilities initialize in the runtime", (_stack) =>
105 Effect.gen(function* () {
106 const response = (yield* getJson("/bindings")) as { bound: string[] };
107 expect(response.bound).toHaveLength(10);
108 }),
109 );
110 });
111
112 describe("DescribeSchema", () => {
113 test.provider(
114 "reads the bound schema's document (injected registry + schema names)",
115 (_stack) =>
116 Effect.gen(function* () {
117 const response = (yield* getJson("/schema")) as {
118 name: string;
119 type: string;
120 version: string;
121 hasContent: boolean;
122 };
123 expect(response.name).toBeTruthy();
124 expect(response.type).toBe("OpenApi3");
125 expect(response.version).toBe("1");
126 expect(response.hasContent).toBe(true);
127 }),
128 );
129 });
130
131 describe("ExportSchema", () => {
132 test.provider("surfaces the typed ForbiddenException for custom-registry schemas", (_stack) =>
133 Effect.gen(function* () {
134 // AWS only allows exporting discovered / AWS-managed schemas. The
135 // call reaching the API and failing with the typed tag proves the
136 // binding + IAM wiring end-to-end.
137 const response = (yield* getJson("/export")) as { outcome: string; message?: string };
138 expect(response.outcome).toBe("forbidden");
139 expect(response.message).toContain("export");
140 }),
141 );
142 });
143
144 describe("ListSchemaVersions", () => {
145 test.provider("lists the schema's single published version", (_stack) =>
146 Effect.gen(function* () {
147 const response = (yield* getJson("/versions")) as { versions: string[] };
148 expect(response.versions).toContain("1");
149 }),
150 );
151 });
152
153 describe("SearchSchemas", () => {
154 test.provider(
155 "finds the schema by keyword in the bound registry",
156 (_stack) =>
157 Effect.gen(function* () {
158 // Search indexing lags schema creation by a few seconds.
159 const response = yield* getJson("/search").pipe(
160 Effect.map((r) => r as { names: string[] }),
161 Effect.repeat({
162 schedule: Schedule.spaced("3 seconds"),
163 until: (r): boolean => (r.names ?? []).length > 0,
164 times: 15,
165 }),
166 );
167 expect(response.names.length).toBeGreaterThanOrEqual(1);
168 }),
169 { timeout: 90_000 },
170 );
171 });
172
173 describe("GetDiscoveredSchema", () => {
174 test.provider("infers a schema from a sample event envelope", (_stack) =>
175 Effect.gen(function* () {
176 const response = (yield* postJson("/discover")) as { hasContent: boolean };
177 expect(response.hasContent).toBe(true);
178 }),
179 );
180 });
181
182 describe("PutCodeBinding / DescribeCodeBinding / GetCodeBindingSource", () => {
183 test.provider(
184 "generates a code-binding package and downloads it",
185 (_stack) =>
186 Effect.gen(function* () {
187 // Kick off async generation.
188 const put = (yield* postJson("/codebinding")) as { status: string };
189 expect(["CREATE_IN_PROGRESS", "CREATE_COMPLETE"]).toContain(put.status);
190
191 // Poll until generation completes (usually well under 30s).
192 const status = yield* getJson("/codebinding").pipe(
193 Effect.map((r) => (r as { status: string }).status),
194 Effect.repeat({
195 schedule: Schedule.spaced("3 seconds"),
196 until: (s): boolean => s === "CREATE_COMPLETE",
197 times: 20,
198 }),
199 );
200 expect(status).toBe("CREATE_COMPLETE");
201
202 // The generated zip streams back as Body.
203 const source = (yield* getJson("/codebinding/source")) as { bytes: number };
204 expect(source.bytes).toBeGreaterThan(0);
205 }),
206 { timeout: 120_000 },
207 );
208 });
209
210 describe("StopDiscoverer / StartDiscoverer", () => {
211 test.provider("pauses and resumes the bound discoverer (injected discoverer id)", (_stack) =>
212 Effect.gen(function* () {
213 const stopped = (yield* postJson("/discoverer/stop")) as { state: string };
214 expect(stopped.state).toBe("STOPPED");
215
216 const started = (yield* postJson("/discoverer/start")) as { state: string };
217 expect(started.state).toBe("STARTED");
218 }),
219 );
220 });
221
222 describe("consumeSchemaEvents", () => {
223 test.provider("the deploy created an EventBridge rule targeting the function", (_stack) =>
224 Effect.gen(function* () {
225 // Out-of-band via distilled: the fixture's consumeSchemaEvents
226 // must have materialized as a rule on the default bus with the
227 // Lambda as target.
228 const { RuleNames } = yield* eventbridge.listRuleNamesByTarget({
229 TargetArn: functionArn,
230 });
231 expect((RuleNames ?? []).length).toBeGreaterThanOrEqual(1);
232 }),
233 );
234 });
235 },
236 );