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

main
ts 166 lines 6.28 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 Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as HttpClient from "effect/http/HttpClient";
8 import * as HttpClientRequest from "effect/http/HttpClientRequest";
9 import * as Schedule from "effect/Schedule";
10 import MailManagerTestFunctionLive, { MailManagerTestFunction } from "./handler";
11
12 const testOptions = { providers: AWS.providers() };
13 const { test, beforeAll, afterAll } = Test.make(testOptions);
14 const sharedStack = Core.scratchStack(testOptions, "MailManagerBindings");
15
16 // Lambda function URL cold-start (DNS, IAM propagation, init) can take well
17 // over 60s on a fresh deploy.
18 const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(75)]);
19
20 let baseUrl: string;
21
22 class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
23 readonly status: number;
24 readonly body: string;
25 }> {}
26
27 // The shared Lambda fixture occasionally answers a transient 5xx under load
28 // (cold re-init, IAM propagation on the freshly attached policy that the
29 // handler's `Effect.orDie` surfaces as a 500). Retry only 5xx; a genuine
30 // 4xx/assertion failure surfaces immediately.
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("500 millis"), Schedule.recurs(6)]),
45 }),
46 );
47
48 const getJson = (path: string) =>
49 send(HttpClientRequest.get(`${baseUrl}${path}`)).pipe(Effect.flatMap((r) => r.json));
50
51 const postJson = (path: string) =>
52 send(HttpClientRequest.post(`${baseUrl}${path}`)).pipe(Effect.flatMap((r) => r.json));
53
54 describe.sequential(
55 "MailManager Bindings",
56 { tags: ["provider:aws", "provider:aws:lambda", "provider:aws:mailmanager", "live"] },
57 () => {
58 beforeAll(
59 Effect.gen(function* () {
60 yield* Effect.logInfo("MailManager test setup: destroying previous resources");
61 yield* sharedStack.destroy();
62
63 yield* Effect.logInfo("MailManager test setup: deploying fixture");
64 const attrs = yield* sharedStack.deploy(
65 Effect.gen(function* () {
66 return yield* MailManagerTestFunction;
67 }).pipe(Effect.provide(MailManagerTestFunctionLive)),
68 );
69
70 expect(attrs.functionUrl).toBeTruthy();
71 baseUrl = attrs.functionUrl!.replace(/\/+$/, "");
72
73 const readinessUrl = `${baseUrl}/bindings`;
74 yield* Effect.logInfo(`MailManager test setup: probing readiness at ${readinessUrl}`);
75 yield* HttpClient.get(readinessUrl).pipe(
76 Effect.flatMap((response) =>
77 response.status === 200
78 ? Effect.succeed(response)
79 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
80 ),
81 Effect.tapError((error) =>
82 Effect.logWarning(`MailManager test setup: fixture not ready yet (${String(error)})`),
83 ),
84 Effect.retry({ schedule: readinessPolicy }),
85 );
86 }),
87 { timeout: 240_000 },
88 );
89
90 afterAll(sharedStack.destroy(), { timeout: 120_000 });
91
92 describe("binding registration", () => {
93 test.provider("all ten capabilities initialize in the runtime", (_stack) =>
94 Effect.gen(function* () {
95 const response = (yield* getJson("/bindings")) as { bound: string[] };
96 expect(response.bound).toHaveLength(10);
97 }),
98 );
99 });
100
101 describe("address list members", () => {
102 test.provider(
103 "register -> get -> list -> deregister roundtrip (injected list id)",
104 (_stack) =>
105 Effect.gen(function* () {
106 const response = (yield* postJson("/members/roundtrip")) as {
107 registered: boolean;
108 memberCount: number;
109 goneAfterDeregister: boolean;
110 };
111 expect(response.registered).toBe(true);
112 expect(response.memberCount).toBeGreaterThanOrEqual(1);
113 expect(response.goneAfterDeregister).toBe(true);
114 }),
115 { timeout: 60_000 },
116 );
117 });
118
119 describe("archive search", () => {
120 test.provider(
121 "start -> poll to completion -> zero rows on an empty archive",
122 (_stack) =>
123 Effect.gen(function* () {
124 const { searchId } = (yield* postJson("/search/start")) as { searchId: string };
125 expect(searchId).toBeTruthy();
126
127 const status = yield* getJson(
128 `/search/status?searchId=${encodeURIComponent(searchId)}`,
129 ).pipe(
130 Effect.map((s) => s as { state?: string; errorMessage?: string }),
131 Effect.repeat({
132 schedule: Schedule.spaced("5 seconds"),
133 until: (s: { state?: string }): boolean =>
134 s.state === "COMPLETED" || s.state === "FAILED" || s.state === "CANCELLED",
135 times: 24,
136 }),
137 );
138 expect(status.state).toBe("COMPLETED");
139
140 const results = (yield* getJson(
141 `/search/results?searchId=${encodeURIComponent(searchId)}`,
142 )) as { rowCount: number };
143 expect(results.rowCount).toBe(0);
144 }),
145 { timeout: 180_000 },
146 );
147 });
148
149 describe("archive + import job enumeration", () => {
150 test.provider("lists searches, exports, and import jobs (archive-scoped grants)", (_stack) =>
151 Effect.gen(function* () {
152 const response = (yield* getJson("/tasks")) as {
153 searchCount: number;
154 exportCount: number;
155 importJobCount: number;
156 };
157 // The search test above ran first (sequential) — at least one
158 // search is visible; no exports or import jobs were created.
159 expect(response.searchCount).toBeGreaterThanOrEqual(1);
160 expect(response.exportCount).toBe(0);
161 expect(response.importJobCount).toBe(0);
162 }),
163 );
164 });
165 },
166 );