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

main
ts 300 lines 11.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 mediatailor from "@distilled.cloud/aws/mediatailor";
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 * as Stream from "effect/Stream";
12 import MediaTailorTestFunctionLive, { MediaTailorTestFunction } from "./handler";
13
14 const testOptions = { providers: AWS.providers() };
15 const { test, beforeAll, afterAll } = Test.make(testOptions);
16 const sharedStack = Core.scratchStack(testOptions, "MediaTailorBindings");
17
18 const PREFETCH_NAME = "alchemy-test-prefetch-schedule";
19
20 let baseUrl: string;
21 let configName: string | undefined;
22 let configArn: string | undefined;
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 (cold
30 // re-init, IAM propagation on the freshly attached policy). Retry only 5xx.
31 const send = (request: HttpClientRequest.HttpClientRequest) =>
32 HttpClient.execute(request).pipe(
33 Effect.flatMap((response) =>
34 response.status >= 500
35 ? response.text.pipe(
36 Effect.flatMap((body) =>
37 Effect.fail(new TransientUpstream({ status: response.status, body })),
38 ),
39 )
40 : Effect.succeed(response),
41 ),
42 Effect.retry({
43 while: (e) => e._tag === "TransientUpstream",
44 schedule: Schedule.max([Schedule.exponential("1 second"), Schedule.recurs(8)]),
45 }),
46 );
47
48 // The fixture's IAM policies are attached moments before the first request;
49 // IAM propagation surfaces as a typed AccessDeniedException in the JSON body.
50 // Repeat (bounded) until the grant has propagated.
51 const untilAuthorized = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
52 effect.pipe(
53 Effect.repeat({
54 schedule: Schedule.spaced("3 seconds"),
55 until: (body): boolean => (body as { error?: string }).error !== "AccessDeniedException",
56 times: 20,
57 }),
58 );
59
60 const getJson = (path: string) =>
61 untilAuthorized(
62 send(HttpClientRequest.get(`${baseUrl}${path}`)).pipe(Effect.flatMap((r) => r.json)),
63 );
64
65 const postJson = (path: string, body: object) =>
66 untilAuthorized(
67 send(
68 HttpClientRequest.post(`${baseUrl}${path}`).pipe(HttpClientRequest.bodyJsonUnsafe(body)),
69 ).pipe(Effect.flatMap((r) => r.json)),
70 );
71
72 // Out-of-band: find the playback configuration the fixture deployed (its
73 // physical name is generated) by its alchemy ownership tags. Runs inside
74 // `test.provider` so distilled has credentials; memoized across tests.
75 const resolveConfig = Effect.gen(function* () {
76 if (configName !== undefined) return;
77 const configs = yield* mediatailor.listPlaybackConfigurations.items({}).pipe(Stream.runCollect);
78 const config = Array.from(configs).find(
79 (candidate) =>
80 candidate.Tags?.["alchemy::id"] === "BindingsConfig" &&
81 candidate.Tags?.["alchemy::stack"] === "MediaTailorBindings",
82 );
83 expect(config).toBeDefined();
84 configName = config!.Name!;
85 configArn = config!.PlaybackConfigurationArn!;
86 });
87
88 describe.sequential(
89 "MediaTailor Bindings",
90 { tags: ["provider:aws", "provider:aws:lambda", "provider:aws:mediatailor", "live"] },
91 () => {
92 beforeAll(
93 Effect.gen(function* () {
94 yield* Effect.logInfo("MediaTailor test setup: destroying previous resources");
95 yield* sharedStack.destroy();
96
97 yield* Effect.logInfo("MediaTailor test setup: deploying fixture");
98 const { functionUrl } = yield* sharedStack.deploy(
99 Effect.gen(function* () {
100 return yield* MediaTailorTestFunction;
101 }).pipe(Effect.provide(MediaTailorTestFunctionLive)),
102 );
103
104 expect(functionUrl).toBeTruthy();
105 baseUrl = functionUrl!.replace(/\/+$/, "");
106
107 // Readiness probe — fresh function URLs take seconds (sometimes over a
108 // minute) to serve 200s.
109 yield* HttpClient.get(`${baseUrl}/health`).pipe(
110 Effect.flatMap((response) =>
111 response.status === 200
112 ? Effect.succeed(response)
113 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
114 ),
115 Effect.retry({
116 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(75)]),
117 }),
118 );
119 }),
120 { timeout: 300_000 },
121 );
122 afterAll(sharedStack.destroy(), { timeout: 300_000 });
123
124 describe("CreatePrefetchSchedule + GetPrefetchSchedule + ListPrefetchSchedules + DeletePrefetchSchedule", () => {
125 test.provider(
126 "full prefetch-schedule lifecycle against the deployed configuration",
127 () =>
128 Effect.gen(function* () {
129 yield* resolveConfig;
130
131 // pre-clean: a previous partial run may have left the schedule
132 yield* postJson("/prefetch/delete", { name: PREFETCH_NAME });
133
134 // create
135 const created = (yield* postJson("/prefetch/create", { name: PREFETCH_NAME })) as {
136 arn?: string;
137 error?: string;
138 detail?: string;
139 };
140 expect(created.error, created.detail).toBeUndefined();
141 expect(created.arn).toContain(":prefetchSchedule/");
142
143 // out-of-band verification via distilled
144 const fetched = yield* mediatailor.getPrefetchSchedule({
145 Name: PREFETCH_NAME,
146 PlaybackConfigurationName: configName!,
147 });
148 expect(fetched.Name).toBe(PREFETCH_NAME);
149
150 // get through the binding
151 const got = (yield* getJson(`/prefetch/get?name=${PREFETCH_NAME}`)) as {
152 name?: string;
153 error?: string;
154 detail?: string;
155 };
156 expect(got.error, got.detail).toBeUndefined();
157 expect(got.name).toBe(PREFETCH_NAME);
158
159 // list through the binding
160 const listed = (yield* getJson("/prefetch/list")) as {
161 names: string[];
162 error?: string;
163 detail?: string;
164 };
165 expect(listed.error, listed.detail).toBeUndefined();
166 expect(listed.names).toContain(PREFETCH_NAME);
167
168 // delete through the binding
169 const deleted = (yield* postJson("/prefetch/delete", { name: PREFETCH_NAME })) as {
170 deleted: boolean;
171 error?: string;
172 detail?: string;
173 };
174 expect(deleted.error, deleted.detail).toBeUndefined();
175 expect(deleted.deleted).toBe(true);
176
177 // get after delete surfaces the typed synthetic tag
178 const gone = (yield* getJson(`/prefetch/get?name=${PREFETCH_NAME}`)) as {
179 name?: string;
180 error?: string;
181 };
182 expect(gone.error).toBe("PrefetchScheduleNotFound");
183 }),
184 { timeout: 120_000 },
185 );
186 });
187
188 describe("ListAlerts", () => {
189 test.provider(
190 "rejects a non-channel-assembly ARN with the typed BadRequestException",
191 () =>
192 Effect.gen(function* () {
193 yield* resolveConfig;
194
195 // ListAlerts only accepts channel-assembly resource ARNs; a
196 // playback-configuration ARN is rejected with the typed
197 // BadRequestException (never AccessDenied — proving the
198 // mediatailor:ListAlerts grant reached the API).
199 const body = (yield* getJson(`/alerts?arn=${encodeURIComponent(configArn!)}`)) as {
200 count: number;
201 error?: string;
202 detail?: string;
203 };
204 expect(body.error, body.detail).toBe("BadRequestException");
205 }),
206 { timeout: 120_000 },
207 );
208 });
209
210 describe("GetChannelSchedule", () => {
211 test.provider(
212 "returns the typed ChannelNotFound for a missing channel",
213 () =>
214 Effect.gen(function* () {
215 const body = (yield* getJson(
216 "/channel/schedule?name=alchemy-nonexistent-mediatailor-channel",
217 )) as { count: number; error?: string; detail?: string };
218 // A typed not-found (never AccessDenied) proves the
219 // mediatailor:GetChannelSchedule grant reached the API.
220 expect(body.error, body.detail).toBe("ChannelNotFound");
221 }),
222 { timeout: 120_000 },
223 );
224 });
225
226 describe("StartChannel + StopChannel", () => {
227 test.provider(
228 "start/stop of a missing channel fail with typed tags (never AccessDenied)",
229 () =>
230 Effect.gen(function* () {
231 const started = (yield* postJson("/channel/start", {
232 name: "alchemy-nonexistent-mediatailor-channel",
233 })) as { started: boolean; error?: string; detail?: string };
234 expect(started.started).toBe(false);
235 expect(["ChannelNotFound", "BadRequestException"], started.detail).toContain(
236 started.error,
237 );
238
239 const stopped = (yield* postJson("/channel/stop", {
240 name: "alchemy-nonexistent-mediatailor-channel",
241 })) as { stopped: boolean; error?: string; detail?: string };
242 expect(stopped.stopped).toBe(false);
243 expect(["ChannelNotFound", "BadRequestException"], stopped.detail).toContain(
244 stopped.error,
245 );
246 }),
247 { timeout: 120_000 },
248 );
249 });
250
251 describe("CreateProgram + DescribeProgram + UpdateProgram + DeleteProgram", () => {
252 test.provider(
253 "program operations on a missing channel fail with typed tags (never AccessDenied)",
254 () =>
255 Effect.gen(function* () {
256 const created = (yield* postJson("/program/create", {})) as {
257 created: boolean;
258 error?: string;
259 detail?: string;
260 };
261 expect(created.created).toBe(false);
262 expect(["ChannelNotFound", "BadRequestException"], created.detail).toContain(
263 created.error,
264 );
265
266 const described = (yield* getJson("/program")) as {
267 name?: string;
268 error?: string;
269 detail?: string;
270 };
271 expect(described.name).toBeUndefined();
272 expect(["ProgramNotFound", "BadRequestException"], described.detail).toContain(
273 described.error,
274 );
275
276 const updated = (yield* postJson("/program/update", {})) as {
277 updated: boolean;
278 error?: string;
279 detail?: string;
280 };
281 expect(updated.updated).toBe(false);
282 expect(["ProgramNotFound", "BadRequestException"], updated.detail).toContain(
283 updated.error,
284 );
285
286 const deleted = (yield* postJson("/program/delete", {})) as {
287 deleted: boolean;
288 error?: string;
289 detail?: string;
290 };
291 expect(deleted.deleted).toBe(false);
292 expect(["ProgramNotFound", "BadRequestException"], deleted.detail).toContain(
293 deleted.error,
294 );
295 }),
296 { timeout: 120_000 },
297 );
298 });
299 },
300 );