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

main
ts 221 lines 8.41 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 SyntheticsBindingsFunctionLive, { SyntheticsBindingsFunction } from "./handler";
12
13 const testOptions = { providers: AWS.providers() };
14 const { test, beforeAll, afterAll } = Test.make(testOptions);
15 const sharedStack = Core.scratchStack(testOptions, "SyntheticsBindings");
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). Retry only
31 // 5xx; a genuine 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("500 millis"), Schedule.recurs(6)]),
46 }),
47 );
48
49 const getJson = (path: string) =>
50 send(HttpClientRequest.get(`${baseUrl}${path}`)).pipe(Effect.flatMap((r) => r.json));
51
52 // The role policy granting synthetics:* is attached moments before the
53 // tests — IAM propagation can lag ~10-30s, surfacing as AccessDenied from a
54 // route. Retry (bounded) until the grant lands.
55 const getJsonUntilGranted = (path: string) =>
56 getJson(path).pipe(
57 Effect.map((r) => r as { tag: string }),
58 Effect.repeat({
59 schedule: Schedule.spaced("5 seconds"),
60 until: (r): boolean => r.tag !== "AccessDeniedException",
61 times: 10,
62 }),
63 );
64
65 describe.sequential(
66 "Synthetics Bindings",
67 {
68 tags: [
69 "provider:aws",
70 "provider:aws:lambda",
71 "provider:aws:s3",
72 "provider:aws:synthetics",
73 "live",
74 ],
75 },
76 () => {
77 beforeAll(
78 Effect.gen(function* () {
79 yield* Effect.logInfo("Synthetics test setup: destroying previous resources");
80 yield* sharedStack.destroy();
81
82 yield* Effect.logInfo("Synthetics test setup: deploying fixture");
83 const attrs = yield* sharedStack.deploy(
84 Effect.gen(function* () {
85 return yield* SyntheticsBindingsFunction;
86 }).pipe(Effect.provide(SyntheticsBindingsFunctionLive)),
87 );
88
89 expect(attrs.functionUrl).toBeTruthy();
90 baseUrl = attrs.functionUrl!.replace(/\/+$/, "");
91 functionArn = attrs.functionArn;
92
93 const readinessUrl = `${baseUrl}/bindings`;
94 yield* Effect.logInfo(`Synthetics test setup: probing readiness at ${readinessUrl}`);
95 yield* HttpClient.get(readinessUrl).pipe(
96 Effect.flatMap((response) =>
97 response.status === 200
98 ? Effect.succeed(response)
99 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
100 ),
101 Effect.tapError((error) =>
102 Effect.logWarning(`Synthetics test setup: fixture not ready yet (${String(error)})`),
103 ),
104 Effect.retry({ schedule: readinessPolicy }),
105 );
106 }),
107 { timeout: 420_000 },
108 );
109
110 afterAll(process.env.NO_DESTROY ? Effect.void : sharedStack.destroy(), { timeout: 420_000 });
111
112 describe("binding registration", () => {
113 test.provider("all 5 capabilities initialize in the runtime", (_stack) =>
114 Effect.gen(function* () {
115 const response = (yield* getJson("/bindings")) as { bound: string[] };
116 expect(response.bound).toHaveLength(5);
117 expect(response.bound).toContain("getCanary");
118 expect(response.bound).toContain("getCanaryRuns");
119 expect(response.bound).toContain("startCanary");
120 expect(response.bound).toContain("stopCanary");
121 expect(response.bound).toContain("describeCanariesLastRun");
122 }),
123 );
124 });
125
126 describe("GetCanary", () => {
127 test.provider(
128 "reads the bound canary's state (name injected)",
129 (_stack) =>
130 Effect.gen(function* () {
131 const response = (yield* getJsonUntilGranted("/canary")) as {
132 tag: string;
133 state?: string;
134 };
135 expect(response.tag).toBe("ok");
136 // Never started → READY (STOPPED once a run has completed).
137 expect(["READY", "STOPPED", "RUNNING", "STARTING"]).toContain(response.state);
138 }),
139 { timeout: 120_000 },
140 );
141 });
142
143 describe("GetCanaryRuns", () => {
144 test.provider("lists runs on the bound canary", (_stack) =>
145 Effect.gen(function* () {
146 const response = (yield* getJsonUntilGranted("/runs")) as { tag: string; count?: number };
147 expect(response.tag).toBe("ok");
148 // A never-started canary has no runs; a zero count still proves the
149 // grant + name injection round-tripped.
150 expect(response.count).toBeGreaterThanOrEqual(0);
151 }),
152 );
153 });
154
155 describe("DescribeCanariesLastRun", () => {
156 test.provider("reads last runs account-wide", (_stack) =>
157 Effect.gen(function* () {
158 const response = (yield* getJsonUntilGranted("/last-run")) as {
159 tag: string;
160 count?: number;
161 };
162 expect(response.tag).toBe("ok");
163 // Canaries that have never run report no last-run entry — a zero
164 // count still proves synthetics:DescribeCanariesLastRun round-trips.
165 expect(response.count).toBeGreaterThanOrEqual(0);
166 }),
167 );
168 });
169
170 describe("StopCanary", () => {
171 test.provider("typed rejection when the canary is not running (grant proven)", (_stack) =>
172 Effect.gen(function* () {
173 // The canary was deployed stopped (READY); stopping it is a
174 // ConflictException — the typed tag proves synthetics:StopCanary
175 // reached the API.
176 const response = (yield* getJsonUntilGranted("/stop")) as { tag: string };
177 expect(["ok", "ConflictException"]).toContain(response.tag);
178 }),
179 );
180 });
181
182 describe("StartCanary", () => {
183 test.provider(
184 "starts the canary for its single scheduled run",
185 (_stack) =>
186 Effect.gen(function* () {
187 const response = (yield* getJsonUntilGranted("/start")) as { tag: string };
188 expect(response.tag).toBe("ok");
189 // A one-shot canary can traverse READY -> RUNNING -> READY between
190 // state polls. Prove the accepted start by observing its run record
191 // instead of relying on a transient control-plane state.
192 const started = yield* getJson("/runs").pipe(
193 Effect.map((r) => r as { tag: string; count?: number }),
194 Effect.repeat({
195 schedule: Schedule.spaced("2 seconds"),
196 until: (r): boolean => r.tag === "ok" && (r.count ?? 0) > 0,
197 times: 25,
198 }),
199 );
200 expect(started.tag).toBe("ok");
201 expect(started.count).toBeGreaterThan(0);
202 }),
203 { timeout: 120_000 },
204 );
205 });
206
207 describe("consumeCanaryEvents", { tags: ["provider:aws:eventbridge"] }, () => {
208 test.provider("the deploy created an EventBridge rule targeting the function", (_stack) =>
209 Effect.gen(function* () {
210 // Out-of-band via distilled: the fixture's consumeCanaryEvents
211 // must have materialized as a rule on the default bus with the
212 // Lambda as target.
213 const { RuleNames } = yield* eventbridge.listRuleNamesByTarget({
214 TargetArn: functionArn,
215 });
216 expect((RuleNames ?? []).length).toBeGreaterThanOrEqual(1);
217 }),
218 );
219 });
220 },
221 );