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

main
ts 327 lines 12.7 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 GreengrassTestFunctionLive, {
12 COMPONENT_NAME,
13 COMPONENT_VERSION,
14 GreengrassTestFunction,
15 } from "./handler";
16
17 const testOptions = { providers: AWS.providers() };
18 const { test, beforeAll, afterAll } = Test.make(testOptions);
19 const sharedStack = Core.scratchStack(testOptions, "GreengrassV2Bindings");
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 // The shared Lambda fixture occasionally answers a transient 5xx under load
34 // (cold re-init, IAM propagation on the freshly attached policy that the
35 // handler's `Effect.orDie` surfaces as a 500). Retry only 5xx; a genuine
36 // 4xx/assertion failure surfaces immediately.
37 const send = (request: HttpClientRequest.HttpClientRequest) =>
38 HttpClient.execute(request).pipe(
39 Effect.flatMap((response) =>
40 response.status >= 500
41 ? response.text.pipe(
42 Effect.flatMap((body) =>
43 Effect.fail(new TransientUpstream({ status: response.status, body })),
44 ),
45 )
46 : Effect.succeed(response),
47 ),
48 Effect.retry({
49 while: (e) => e._tag === "TransientUpstream",
50 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(6)]),
51 }),
52 );
53
54 const getJson = (path: string) =>
55 send(HttpClientRequest.get(`${baseUrl}${path}`)).pipe(Effect.flatMap((r) => r.json));
56
57 const postJson = (path: string) =>
58 send(HttpClientRequest.post(`${baseUrl}${path}`)).pipe(Effect.flatMap((r) => r.json));
59
60 // A type alias (not an interface) so it keeps the implicit index signature —
61 // interfaces are not comparable to the JSON `JsonObject` type that
62 // `response.json` returns, which breaks the `as Probe` casts below.
63 type Probe = { ok: boolean; tag?: string };
64
65 describe.sequential(
66 "GreengrassV2 Bindings",
67 {
68 tags: [
69 "provider:aws",
70 "provider:aws:batch",
71 "provider:aws:greengrassv2",
72 "provider:aws:iot",
73 "provider:aws:lambda",
74 "live",
75 ],
76 },
77 () => {
78 beforeAll(
79 Effect.gen(function* () {
80 yield* Effect.logInfo("GreengrassV2 test setup: destroying previous resources");
81 yield* sharedStack.destroy();
82
83 yield* Effect.logInfo("GreengrassV2 test setup: deploying fixture");
84 const attrs = yield* sharedStack.deploy(
85 Effect.gen(function* () {
86 return yield* GreengrassTestFunction;
87 }).pipe(Effect.provide(GreengrassTestFunctionLive)),
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(`GreengrassV2 test setup: probing readiness at ${readinessUrl}`);
96 yield* HttpClient.get(readinessUrl).pipe(
97 Effect.flatMap((response) =>
98 response.status === 200
99 ? Effect.succeed(response)
100 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
101 ),
102 Effect.tapError((error) =>
103 Effect.logWarning(`GreengrassV2 test setup: fixture not ready yet (${String(error)})`),
104 ),
105 Effect.retry({ schedule: readinessPolicy }),
106 );
107 }),
108 { timeout: 300_000 },
109 );
110
111 afterAll(sharedStack.destroy(), { timeout: 180_000 });
112
113 describe("binding registration", () => {
114 test.provider("all 19 capabilities initialize in the runtime", (_stack) =>
115 Effect.gen(function* () {
116 const response = (yield* getJson("/bindings")) as { bound: string[] };
117 expect(response.bound).toHaveLength(19);
118 }),
119 );
120 });
121
122 describe("DescribeComponent", () => {
123 test.provider("reads the bound component version's metadata (injected arn)", (_stack) =>
124 Effect.gen(function* () {
125 const response = (yield* getJson("/component")) as {
126 arn: string;
127 componentName: string;
128 componentVersion: string;
129 state: string;
130 };
131 expect(response.componentName).toBe(COMPONENT_NAME);
132 expect(response.componentVersion).toBe(COMPONENT_VERSION);
133 expect(response.arn).toContain(
134 `:components:${COMPONENT_NAME}:versions:${COMPONENT_VERSION}`,
135 );
136 expect(response.state).toBe("DEPLOYABLE");
137 }),
138 );
139 });
140
141 describe("GetComponent", () => {
142 test.provider("fetches the recipe (round-trips the name)", (_stack) =>
143 Effect.gen(function* () {
144 const response = (yield* getJson("/recipe")) as {
145 recipeOutputFormat: string;
146 hasName: boolean;
147 };
148 expect(response.recipeOutputFormat).toBe("JSON");
149 expect(response.hasName).toBe(true);
150 }),
151 );
152 });
153
154 describe("GetComponentVersionArtifact", () => {
155 test.provider("a missing artifact surfaces a typed error (never AccessDenied)", (_stack) =>
156 Effect.gen(function* () {
157 const response = (yield* getJson("/artifact")) as Probe;
158 expect(response.ok).toBe(false);
159 expect(response.tag).not.toBe("AccessDeniedException");
160 expect(["ResourceNotFoundException", "ValidationException"]).toContain(response.tag);
161 }),
162 );
163 });
164
165 describe("GetDeployment", () => {
166 test.provider("reads the bound deployment's detail (injected deployment id)", (_stack) =>
167 Effect.gen(function* () {
168 const response = (yield* getJson("/deployment")) as {
169 deploymentId: string;
170 deploymentStatus: string;
171 targetArn: string;
172 isLatestForTarget: boolean;
173 };
174 expect(response.deploymentId).toBeTruthy();
175 expect(response.targetArn).toContain(":thing/");
176 expect(response.isLatestForTarget).toBe(true);
177 }),
178 );
179 });
180
181 describe("ListDeployments", () => {
182 test.provider("enumerates the account's latest deployments", (_stack) =>
183 Effect.gen(function* () {
184 const deployment = (yield* getJson("/deployment")) as { deploymentId: string };
185 const response = (yield* getJson("/deployments")) as { ids: string[] };
186 expect(response.ids).toContain(deployment.deploymentId);
187 }),
188 );
189 });
190
191 describe("ListComponents", () => {
192 test.provider("enumerates private components incl. the fixture's", (_stack) =>
193 Effect.gen(function* () {
194 const response = (yield* getJson("/components")) as { names: string[] };
195 expect(response.names).toContain(COMPONENT_NAME);
196 }),
197 );
198 });
199
200 describe("ListComponentVersions", () => {
201 test.provider("lists the fixture component's versions", (_stack) =>
202 Effect.gen(function* () {
203 const response = (yield* getJson("/component-versions")) as { versions: string[] };
204 expect(response.versions).toContain(COMPONENT_VERSION);
205 }),
206 );
207 });
208
209 describe("ListCoreDevices", () => {
210 test.provider("enumerates core devices (count is a number)", (_stack) =>
211 Effect.gen(function* () {
212 const response = (yield* getJson("/core-devices")) as { count: number };
213 expect(response.count).toBeGreaterThanOrEqual(0);
214 }),
215 );
216 });
217
218 describe("core device bindings", () => {
219 test.provider(
220 "probes against a missing core device return typed errors (never AccessDenied)",
221 (_stack) =>
222 Effect.gen(function* () {
223 // Freshly attached IAM policy statements are eventually consistent —
224 // poll (bounded) until the grants have propagated before asserting
225 // the steady-state invariant below.
226 const response = (yield* getJson("/core-device-probes").pipe(
227 Effect.repeat({
228 schedule: Schedule.spaced("3 seconds"),
229 until: (r): boolean =>
230 Object.values(r as Record<string, Probe>).every(
231 (probe) => probe.tag !== "AccessDeniedException",
232 ),
233 times: 20,
234 }),
235 )) as Record<string, Probe>;
236 // Point reads/writes on a missing core device are typed not-found.
237 expect(response.getCoreDevice!.tag).toBe("ResourceNotFoundException");
238 expect(response.deleteCoreDevice!.tag).toBe("ResourceNotFoundException");
239 // Every probe proves IAM: none may be AccessDenied.
240 for (const probe of Object.values(response)) {
241 expect(probe.tag).not.toBe("AccessDeniedException");
242 }
243 }),
244 { timeout: 240_000 },
245 );
246 });
247
248 describe("connectivity info", () => {
249 test.provider(
250 "UpdateConnectivityInfo + GetConnectivityInfo round-trip on the fixture thing",
251 (_stack) =>
252 Effect.gen(function* () {
253 const response = (yield* postJson("/connectivity")) as { hostAddresses: string[] };
254 expect(response.hostAddresses).toContain("127.0.0.1");
255 }),
256 { timeout: 120_000 },
257 );
258 });
259
260 describe("ResolveComponentCandidates", () => {
261 // Per the AWS API reference, ResolveComponentCandidates must be called
262 // through the Greengrass data plane endpoint with an AWS IoT device
263 // certificate; IAM-signed calls are rejected with AccessDeniedException
264 // even with greengrass:ResolveComponentCandidates granted. This ungated
265 // probe proves the binding's request plumbing end-to-end: the call
266 // reaches the service and surfaces the documented typed rejection.
267 test.provider("IAM-signed resolve surfaces the documented typed rejection", (_stack) =>
268 Effect.gen(function* () {
269 const response = (yield* getJson("/resolve")) as {
270 ok: boolean;
271 names: string[];
272 tag?: string;
273 };
274 expect(response.ok).toBe(false);
275 expect(response.tag).toBe("AccessDeniedException");
276 }),
277 );
278 });
279
280 describe("consumeGreengrassEvents", { tags: ["provider:aws:eventbridge"] }, () => {
281 test.provider("the deploy created an EventBridge rule targeting the function", (_stack) =>
282 Effect.gen(function* () {
283 // Out-of-band via distilled: the fixture's consumeGreengrassEvents
284 // must have materialized as a rule on the default bus with the
285 // Lambda as target.
286 const { RuleNames } = yield* eventbridge.listRuleNamesByTarget({
287 TargetArn: functionArn,
288 });
289 expect((RuleNames ?? []).length).toBeGreaterThanOrEqual(1);
290 }),
291 );
292 });
293
294 describe("CancelDeployment", () => {
295 // Runs last: cancels the fixture rollout (the deployment stays ACTIVE
296 // until canceled because no live core device ever picks it up).
297 test.provider(
298 "cancels the bound deployment",
299 (_stack) =>
300 Effect.gen(function* () {
301 // The cancel path exercises freshly attached iot:CancelJob/UpdateJob
302 // grants — retry the attempt while IAM propagation still rejects it.
303 // A prior (retried) attempt may already have canceled the rollout,
304 // so the deployment status below is the authoritative assertion.
305 const response = (yield* postJson("/cancel-deployment").pipe(
306 Effect.repeat({
307 schedule: Schedule.spaced("3 seconds"),
308 until: (r): boolean => (r as Probe).tag !== "AccessDeniedException",
309 times: 20,
310 }),
311 )) as Probe;
312 expect(response.tag).not.toBe("AccessDeniedException");
313 const detail = (yield* getJson("/deployment").pipe(
314 Effect.repeat({
315 schedule: Schedule.spaced("3 seconds"),
316 until: (d): boolean =>
317 (d as { deploymentStatus: string }).deploymentStatus === "CANCELED",
318 times: 10,
319 }),
320 )) as { deploymentStatus: string };
321 expect(detail.deploymentStatus).toBe("CANCELED");
322 }),
323 { timeout: 150_000 },
324 );
325 });
326 },
327 );