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

main
ts 209 lines 7.68 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 IvsTestFunctionLive, { IvsTestFunction } from "./fixtures/handler";
12
13 const testOptions = { providers: AWS.providers() };
14 const { test, beforeAll, afterAll } = Test.make(testOptions);
15 const sharedStack = Core.scratchStack(testOptions, "IVSBindings");
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 "IVS Bindings",
58 {
59 tags: ["provider:aws", "provider:aws:batch", "provider:aws:ivs", "provider:aws:lambda", "live"],
60 },
61 () => {
62 beforeAll(
63 Effect.gen(function* () {
64 yield* Effect.logInfo("IVS test setup: destroying previous resources");
65 yield* sharedStack.destroy();
66
67 yield* Effect.logInfo("IVS test setup: deploying fixture");
68 const attrs = yield* sharedStack.deploy(
69 Effect.gen(function* () {
70 return yield* IvsTestFunction;
71 }).pipe(Effect.provide(IvsTestFunctionLive)),
72 );
73
74 expect(attrs.functionUrl).toBeTruthy();
75 baseUrl = attrs.functionUrl!.replace(/\/+$/, "");
76 functionArn = attrs.functionArn;
77
78 const readinessUrl = `${baseUrl}/bindings`;
79 yield* Effect.logInfo(`IVS test setup: probing readiness at ${readinessUrl}`);
80 yield* HttpClient.get(readinessUrl).pipe(
81 Effect.flatMap((response) =>
82 response.status === 200
83 ? Effect.succeed(response)
84 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
85 ),
86 Effect.tapError((error) =>
87 Effect.logWarning(`IVS test setup: fixture not ready yet (${String(error)})`),
88 ),
89 Effect.retry({ schedule: readinessPolicy }),
90 );
91 }),
92 { timeout: 240_000 },
93 );
94
95 afterAll(sharedStack.destroy(), { timeout: 120_000 });
96
97 describe("binding registration", () => {
98 test.provider("all nine capabilities initialize in the runtime", () =>
99 Effect.gen(function* () {
100 const response = (yield* getJson("/bindings")) as { bound: string[] };
101 expect(response.bound).toHaveLength(9);
102 }),
103 );
104 });
105
106 describe("GetStream", () => {
107 test.provider("an idle channel answers with the typed ChannelNotBroadcasting", () =>
108 Effect.gen(function* () {
109 const response = (yield* getJson("/stream")) as { live: boolean; viewers: number };
110 expect(response.live).toBe(false);
111 expect(response.viewers).toBe(0);
112 }),
113 );
114 });
115
116 describe("GetStreamSession", () => {
117 test.provider("a never-broadcast channel has no latest session", () =>
118 Effect.gen(function* () {
119 const response = (yield* getJson("/session")) as { found: boolean };
120 expect(response.found).toBe(false);
121 }),
122 );
123 });
124
125 describe("ListStreamSessions", () => {
126 test.provider("the idle channel's session history is empty", () =>
127 Effect.gen(function* () {
128 const response = (yield* getJson("/sessions")) as { count: number };
129 expect(response.count).toBe(0);
130 }),
131 );
132 });
133
134 describe("ListStreams", () => {
135 test.provider("account-level live-stream enumeration succeeds", () =>
136 Effect.gen(function* () {
137 const response = (yield* getJson("/streams")) as { count: number };
138 expect(response.count).toBeGreaterThanOrEqual(0);
139 }),
140 );
141 });
142
143 describe("PutMetadata", () => {
144 test.provider(
145 "inserting metadata into an idle stream is the typed ChannelNotBroadcasting",
146 () =>
147 Effect.gen(function* () {
148 const response = (yield* postJson("/metadata")) as { inserted: boolean; tag?: string };
149 expect(response.inserted).toBe(false);
150 expect(response.tag).toBe("ChannelNotBroadcasting");
151 }),
152 );
153 });
154
155 describe("StopStream", () => {
156 test.provider("stopping an idle channel is the typed ChannelNotBroadcasting", () =>
157 Effect.gen(function* () {
158 const response = (yield* postJson("/stop")) as { stopped: boolean; tag?: string };
159 expect(response.stopped).toBe(false);
160 expect(response.tag).toBe("ChannelNotBroadcasting");
161 }),
162 );
163 });
164
165 describe("StartViewerSessionRevocation", () => {
166 test.provider("revoking a viewer session succeeds", () =>
167 Effect.gen(function* () {
168 const response = (yield* postJson("/revoke")) as { ok: boolean; tag?: string };
169 expect(response.ok).toBe(true);
170 }),
171 );
172 });
173
174 describe("InsertAdBreak", () => {
175 test.provider("inserting an ad break into an idle stream is a typed failure", () =>
176 Effect.gen(function* () {
177 const response = (yield* postJson("/adbreak")) as { inserted: boolean; tag?: string };
178 expect(response.inserted).toBe(false);
179 expect(["ChannelNotBroadcasting", "ValidationException", "ConflictException"]).toContain(
180 response.tag,
181 );
182 }),
183 );
184 });
185
186 describe("BatchStartViewerSessionRevocation", () => {
187 test.provider("batch-revoking a viewer session reports no per-pair errors", () =>
188 Effect.gen(function* () {
189 const response = (yield* postJson("/revoke-batch")) as { errorCount: number };
190 expect(response.errorCount).toBe(0);
191 }),
192 );
193 });
194
195 describe("consumeStreamEvents", { tags: ["provider:aws:eventbridge"] }, () => {
196 test.provider("the deploy created an EventBridge rule targeting the function", () =>
197 Effect.gen(function* () {
198 // Out-of-band via distilled: the fixture's consumeStreamEvents
199 // must have materialized as a rule on the default bus with the
200 // Lambda as target.
201 const { RuleNames } = yield* eventbridge.listRuleNamesByTarget({
202 TargetArn: functionArn,
203 });
204 expect((RuleNames ?? []).length).toBeGreaterThanOrEqual(1);
205 }),
206 );
207 });
208 },
209 );