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

main
ts 254 lines 10.2 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 logs from "@distilled.cloud/aws/cloudwatch-logs";
6 import * as eventbridge from "@distilled.cloud/aws/eventbridge";
7 import * as im from "@distilled.cloud/aws/internetmonitor";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as HttpClient from "effect/http/HttpClient";
11 import * as HttpClientRequest from "effect/http/HttpClientRequest";
12 import * as Schedule from "effect/Schedule";
13 import * as Stream from "effect/Stream";
14 import InternetMonitorBindingsFunctionLive, { InternetMonitorBindingsFunction } from "./handler";
15
16 const testOptions = { providers: AWS.providers() };
17 const { test, beforeAll, afterAll } = Test.make(testOptions);
18 const sharedStack = Core.scratchStack(testOptions, "InternetMonitorBindings");
19
20 // Lambda function URL cold-start (DNS, IAM propagation, init) can take well
21 // over 60s on a fresh deploy.
22 const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(75)]);
23
24 let baseUrl: string;
25 let functionArn: string;
26
27 // beforeAll/afterAll hooks run outside `test.provider`'s layer, so raw
28 // distilled calls need the provider layer (credentials, region) supplied
29 // explicitly.
30 const aws = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
31 Core.withProviders(effect, testOptions, sharedStack.name);
32
33 // Names of all monitors owned by this suite's scratch stack (matched by the
34 // internal `alchemy::stack` ownership tag), read fresh from the cloud.
35 const listStackMonitors = aws(
36 im.listMonitors.items({}).pipe(
37 Stream.runCollect,
38 Effect.flatMap((monitors) =>
39 Effect.forEach(
40 Array.from(monitors),
41 (monitor) =>
42 im.getMonitor({ MonitorName: monitor.MonitorName }).pipe(
43 Effect.map((r) =>
44 r.Tags?.["alchemy::stack"] === sharedStack.name ? [monitor.MonitorName] : [],
45 ),
46 // Tolerate delete races between list and get.
47 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed([] as string[])),
48 ),
49 { concurrency: 4 },
50 ),
51 ),
52 Effect.map((names) => names.flat()),
53 ),
54 );
55
56 class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
57 readonly status: number;
58 readonly body: string;
59 }> {}
60
61 // The shared Lambda fixture occasionally answers a transient 5xx under load
62 // (cold re-init, IAM propagation on the freshly attached policy). Retry only
63 // 5xx; a genuine 4xx/assertion failure surfaces immediately.
64 const send = (request: HttpClientRequest.HttpClientRequest) =>
65 HttpClient.execute(request).pipe(
66 Effect.flatMap((response) =>
67 response.status >= 500
68 ? response.text.pipe(
69 Effect.flatMap((body) =>
70 Effect.fail(new TransientUpstream({ status: response.status, body })),
71 ),
72 )
73 : Effect.succeed(response),
74 ),
75 Effect.retry({
76 while: (e) => e._tag === "TransientUpstream",
77 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(6)]),
78 }),
79 );
80
81 const getJson = (path: string) =>
82 send(HttpClientRequest.get(`${baseUrl}${path}`)).pipe(Effect.flatMap((r) => r.json));
83
84 describe.sequential(
85 "InternetMonitor Bindings",
86 { tags: ["provider:aws", "provider:aws:internetmonitor", "provider:aws:lambda", "live"] },
87 () => {
88 beforeAll(
89 Effect.gen(function* () {
90 yield* Effect.logInfo("InternetMonitor test setup: destroying previous resources");
91 yield* sharedStack.destroy();
92
93 yield* Effect.logInfo("InternetMonitor test setup: deploying fixture");
94 const attrs = yield* sharedStack.deploy(
95 Effect.gen(function* () {
96 return yield* InternetMonitorBindingsFunction;
97 }).pipe(Effect.provide(InternetMonitorBindingsFunctionLive)),
98 );
99
100 expect(attrs.functionUrl).toBeTruthy();
101 baseUrl = attrs.functionUrl!.replace(/\/+$/, "");
102 functionArn = attrs.functionArn;
103
104 const readinessUrl = `${baseUrl}/bindings`;
105 yield* Effect.logInfo(`InternetMonitor test setup: probing readiness at ${readinessUrl}`);
106 yield* HttpClient.get(readinessUrl).pipe(
107 Effect.flatMap((response) =>
108 response.status === 200
109 ? Effect.succeed(response)
110 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
111 ),
112 Effect.tapError((error) =>
113 Effect.logWarning(
114 `InternetMonitor test setup: fixture not ready yet (${String(error)})`,
115 ),
116 ),
117 Effect.retry({ schedule: readinessPolicy }),
118 );
119 }),
120 { timeout: 300_000 },
121 );
122
123 afterAll(
124 Effect.gen(function* () {
125 if (process.env.NO_DESTROY) return;
126 // Capture our monitor names before destroy so the log-group reap can
127 // be verified per-monitor afterwards.
128 const owned = yield* listStackMonitors;
129 yield* sharedStack.destroy();
130 // Zero-orphan proof: no monitor tagged with this stack remains.
131 const remaining = yield* listStackMonitors;
132 expect(remaining).toEqual([]);
133 // And the auto-created /aws/internet-monitor/{name}/* log groups were
134 // reaped by the provider delete.
135 const remainingLogGroups = yield* aws(
136 Effect.forEach(owned, (name) =>
137 logs
138 .describeLogGroups({ logGroupNamePrefix: `/aws/internet-monitor/${name}` })
139 .pipe(Effect.map((r) => (r.logGroups ?? []).map((g) => g.logGroupName))),
140 ),
141 );
142 expect(remainingLogGroups.flat()).toEqual([]);
143 }),
144 { timeout: 300_000 },
145 );
146
147 describe("binding registration", () => {
148 test.provider("all 8 capabilities initialize in the runtime", (_stack) =>
149 Effect.gen(function* () {
150 const response = (yield* getJson("/bindings")) as { bound: string[] };
151 expect(response.bound).toHaveLength(8);
152 expect(response.bound).toContain("listHealthEvents");
153 expect(response.bound).toContain("startQuery");
154 expect(response.bound).toContain("listInternetEvents");
155 }),
156 );
157 });
158
159 describe("ListHealthEvents", () => {
160 test.provider("lists health events on the bound monitor (name injected)", (_stack) =>
161 Effect.gen(function* () {
162 const response = (yield* getJson("/health-events")) as { count: number };
163 // A fresh empty monitor has no health events; a zero count still
164 // proves the grant + monitor-name injection round-tripped.
165 expect(response.count).toBeGreaterThanOrEqual(0);
166 }),
167 );
168 });
169
170 describe("GetHealthEvent", () => {
171 test.provider("typed rejection for a nonexistent event id (grant proven)", (_stack) =>
172 Effect.gen(function* () {
173 const response = (yield* getJson("/health-events/typed-probe")) as { tag: string };
174 // Any typed tag except AccessDenied proves the IAM grant reached
175 // the monitor-scoped API.
176 expect(response.tag).not.toBe("AccessDeniedException");
177 }),
178 );
179 });
180
181 describe("ListInternetEvents", () => {
182 test.provider("lists global internet events (account-level)", (_stack) =>
183 Effect.gen(function* () {
184 const response = (yield* getJson("/internet-events")) as { count: number };
185 expect(response.count).toBeGreaterThanOrEqual(0);
186 }),
187 );
188 });
189
190 describe("GetInternetEvent", () => {
191 test.provider("typed rejection for a nonexistent event id (grant proven)", (_stack) =>
192 Effect.gen(function* () {
193 const response = (yield* getJson("/internet-event/typed-probe")) as { tag: string };
194 expect(response.tag).not.toBe("AccessDeniedException");
195 }),
196 );
197 });
198
199 describe("StartQuery / GetQueryStatus / GetQueryResults / StopQuery", () => {
200 test.provider(
201 "runs a MEASUREMENTS query end-to-end on the bound monitor",
202 (_stack) =>
203 Effect.gen(function* () {
204 type QueryResponse = {
205 step: string;
206 tag?: string;
207 error?: string;
208 queryId?: string;
209 status?: string;
210 fields?: number;
211 rows?: number;
212 stopTag?: string;
213 };
214 // The role policy granting internetmonitor:* is attached moments
215 // before this test — IAM propagation can lag ~10-30s, surfacing as
216 // AccessDeniedException from a step. Retry (bounded) until the
217 // grant lands; any other failure surfaces immediately.
218 const response = yield* getJson("/query").pipe(
219 Effect.map((r) => r as QueryResponse),
220 Effect.repeat({
221 schedule: Schedule.spaced("5 seconds"),
222 until: (r): boolean => r.tag !== "AccessDeniedException",
223 times: 10,
224 }),
225 );
226 // On a step failure the route reports { step, tag, error } — log
227 // the full payload so the exact typed failure is never elided.
228 yield* Effect.logInfo(`/query response: ${JSON.stringify(response)}`);
229 expect(response).toMatchObject({ step: "ok" });
230 expect(response.queryId).toBeTruthy();
231 // An empty monitor's query still runs to a terminal state.
232 expect(["SUCCEEDED", "FAILED", "CANCELED"]).toContain(response.status);
233 expect(response.rows).toBeGreaterThanOrEqual(0);
234 expect(response.stopTag).not.toBe("AccessDeniedException");
235 }),
236 { timeout: 180_000 },
237 );
238 });
239
240 describe("consumeHealthEvents", { tags: ["provider:aws:eventbridge"] }, () => {
241 test.provider("the deploy created an EventBridge rule targeting the function", (_stack) =>
242 Effect.gen(function* () {
243 // Out-of-band via distilled: the fixture's consumeHealthEvents
244 // must have materialized as a rule on the default bus with the
245 // Lambda as target.
246 const { RuleNames } = yield* eventbridge.listRuleNamesByTarget({
247 TargetArn: functionArn,
248 });
249 expect((RuleNames ?? []).length).toBeGreaterThanOrEqual(1);
250 }),
251 );
252 });
253 },
254 );