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

main
ts 255 lines 9.06 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import { expect } from "@alchemy.run/test";
4 import * as Test from "@alchemy.run/test/Alchemy";
5 import * as aisearch from "@distilled.cloud/cloudflare/aisearch";
6 import * as Provider from "alchemy/Provider";
7 import * as Effect from "effect/Effect";
8 import { MinimumLogLevel } from "effect/References";
9 import * as Schedule from "effect/Schedule";
10 import { stageSuffix } from "../../names.ts";
11
12 const { test } = Test.make({ providers: Cloudflare.providers() });
13
14 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
15
16 // The scoped API token the test harness mints propagates eventually-
17 // consistently across Cloudflare's edge — ride out 403 blips
18 // (`Forbidden`, declared in the distilled error union) on the test's
19 // own out-of-band verification calls. The backoff is CAPPED at 3s: an
20 // uncapped exponential balloons to 64s+ gaps within a handful of
21 // attempts, polling so sparsely that a settled token is detected tens
22 // of seconds late — under full-suite parallel load (when propagation
23 // windows stretch) that alone can blow the test timeout.
24 const propagationSchedule = Schedule.min([
25 Schedule.exponential("500 millis"),
26 Schedule.spaced("3 seconds"),
27 ]);
28
29 const getToken = (accountId: string, id: string) =>
30 aisearch.readToken({ accountId, id }).pipe(
31 Effect.retry({
32 while: (e) => e._tag === "Forbidden",
33 schedule: propagationSchedule,
34 times: 15,
35 }),
36 );
37
38 const expectGone = (accountId: string, id: string) =>
39 getToken(accountId, id).pipe(
40 Effect.flatMap(() => Effect.fail({ _tag: "TokenNotDeleted" } as const)),
41 // A missing token surfaces as `TokenNotFound` (Cloudflare error code
42 // 7075) — that's the success condition here.
43 Effect.catchTag("TokenNotFound", () => Effect.void),
44 Effect.retry({
45 while: (e) => e._tag === "TokenNotDeleted",
46 schedule: propagationSchedule,
47 times: 15,
48 }),
49 );
50
51 // AI Search validates the underlying credential on create/update — it
52 // must carry the "AI Search Index Engine" permission group, so the test
53 // mints a scoped account API token in the same stack and feeds its id +
54 // value into the service token.
55 const program = (accountId: string, props?: Partial<Cloudflare.AI.SearchTokenProps>) =>
56 Effect.gen(function* () {
57 const apiToken = yield* Cloudflare.ApiToken.AccountApiToken("TokenSource", {
58 policies: [
59 {
60 effect: "allow",
61 permissionGroups: ["AI Search Index Engine"],
62 resources: { [`com.cloudflare.api.account.${accountId}`]: "*" },
63 },
64 ],
65 });
66 const token = yield* Cloudflare.AI.SearchToken("Token", {
67 cfApiId: apiToken.tokenId,
68 cfApiKey: apiToken.value,
69 ...props,
70 });
71 return { apiToken, token };
72 });
73
74 test.provider(
75 "create, rename in place, and delete a service token",
76 (stack) =>
77 Effect.gen(function* () {
78 const { accountId } = yield* yield* CloudflareEnvironment;
79 const user = stageSuffix();
80 const renamed = `${user}-alchemy-aisearch-token-renamed`;
81
82 yield* stack.destroy();
83
84 // Create — engine-generated display name.
85 const initial = yield* stack.deploy(program(accountId));
86
87 expect(initial.token.id).toBeTruthy();
88 expect(initial.token.accountId).toEqual(accountId);
89 expect(initial.token.cfApiId).toEqual(initial.apiToken.tokenId);
90 expect(initial.token.name).toBeTruthy();
91
92 const live = yield* getToken(accountId, initial.token.id);
93 expect(live.id).toEqual(initial.token.id);
94 expect(live.cfApiId).toEqual(initial.apiToken.tokenId);
95 expect(live.name).toEqual(initial.token.name);
96
97 // Rename in place — the service token id is stable.
98 const updated = yield* stack.deploy(program(accountId, { name: renamed }));
99
100 expect(updated.token.id).toEqual(initial.token.id);
101 expect(updated.token.name).toEqual(renamed);
102
103 const liveUpdated = yield* getToken(accountId, updated.token.id);
104 expect(liveUpdated.name).toEqual(renamed);
105
106 // Redeploying identical props is a no-op (still the same token).
107 const noop = yield* stack.deploy(program(accountId, { name: renamed }));
108 expect(noop.token.id).toEqual(initial.token.id);
109
110 yield* stack.destroy();
111
112 yield* expectGone(accountId, initial.token.id);
113
114 // Destroy again — delete must be idempotent (already gone).
115 yield* stack.destroy();
116 }).pipe(logLevel),
117 {
118 tags: ["provider:cloudflare", "provider:cloudflare:ai", "provider:cloudflare:apitoken", "live"],
119 timeout: 240_000,
120 },
121 );
122
123 test.provider(
124 "recreates after out-of-band delete",
125 (stack) =>
126 Effect.gen(function* () {
127 const { accountId } = yield* yield* CloudflareEnvironment;
128 const user = stageSuffix();
129
130 yield* stack.destroy();
131
132 const initial = yield* stack.deploy(program(accountId));
133
134 // Delete the service token out-of-band. A redeploy with identical
135 // props is a planner no-op, so change a mutable prop to force
136 // reconcile — it must observe the token as missing and recreate it
137 // instead of failing on a 404.
138 yield* aisearch.deleteToken({ accountId, id: initial.token.id }).pipe(
139 Effect.retry({
140 while: (e) => e._tag === "Forbidden",
141 schedule: propagationSchedule,
142 times: 15,
143 }),
144 );
145 yield* expectGone(accountId, initial.token.id);
146
147 const healed = yield* stack.deploy(
148 program(accountId, { name: `${user}-alchemy-aisearch-token-healed` }),
149 );
150
151 // A new physical token exists (the id is assigned by Cloudflare).
152 expect(healed.token.id).not.toEqual(initial.token.id);
153 const live = yield* getToken(accountId, healed.token.id);
154 expect(live.id).toEqual(healed.token.id);
155
156 yield* stack.destroy();
157
158 yield* expectGone(accountId, healed.token.id);
159 }).pipe(logLevel),
160 {
161 tags: ["provider:cloudflare", "provider:cloudflare:ai", "provider:cloudflare:apitoken", "live"],
162 timeout: 240_000,
163 },
164 );
165
166 test.provider(
167 "list enumerates the deployed service token",
168 (stack) =>
169 Effect.gen(function* () {
170 const { accountId } = yield* yield* CloudflareEnvironment;
171
172 yield* stack.destroy();
173
174 const deployed = yield* stack.deploy(program(accountId));
175
176 const provider = yield* Provider.findProvider(Cloudflare.AI.SearchToken);
177 const all = yield* provider.list();
178
179 const found = all.find((t) => t.id === deployed.token.id);
180 expect(found).toBeDefined();
181 // list() emits the exact `read` Attributes shape.
182 expect(found?.accountId).toEqual(accountId);
183 expect(found?.cfApiId).toEqual(deployed.apiToken.tokenId);
184 expect(found?.name).toEqual(deployed.token.name);
185
186 yield* stack.destroy();
187
188 yield* expectGone(accountId, deployed.token.id);
189 }).pipe(logLevel),
190 {
191 tags: ["provider:cloudflare", "provider:cloudflare:ai", "provider:cloudflare:apitoken", "live"],
192 timeout: 240_000,
193 },
194 );
195
196 test.provider(
197 "an AI Search instance syncs with a stack-minted service token",
198 (stack) =>
199 Effect.gen(function* () {
200 const { accountId } = yield* yield* CloudflareEnvironment;
201
202 yield* stack.destroy();
203
204 // Full composition: AccountApiToken → AiSearchToken → Bucket →
205 // AiSearchInstance wired to the service token via `tokenId`.
206 const deployed = yield* stack.deploy(
207 Effect.gen(function* () {
208 const { apiToken, token } = yield* program(accountId);
209 const bucket = yield* Cloudflare.R2.Bucket("AiSearchTokenSource", {
210 forceDestroy: true,
211 });
212 const instance = yield* Cloudflare.AI.Search("Search", {
213 // Pass the Bucket resource (not `bucket.bucketName`) so the
214 // construct selects the R2 source path; a bare string is treated
215 // as a web-crawler seed URL.
216 source: bucket,
217 tokenId: token.id,
218 });
219 return { apiToken, token, bucket, instance };
220 }),
221 );
222
223 expect(deployed.instance.tokenId).toEqual(deployed.token.id);
224
225 const live = yield* aisearch
226 .readInstance({ accountId, id: deployed.instance.instanceId })
227 .pipe(
228 Effect.retry({
229 while: (e) => e._tag === "Forbidden",
230 schedule: propagationSchedule,
231 times: 15,
232 }),
233 );
234 expect(live.tokenId).toEqual(deployed.token.id);
235
236 yield* stack.destroy();
237
238 // The instance deletes before the token it references.
239 yield* expectGone(accountId, deployed.token.id);
240 }).pipe(logLevel),
241 // The instance create validates the freshly-minted service token and can
242 // legitimately ride the provider's `InvalidTokenCredentials` propagation
243 // window (~2 min under full-suite parallel load) before the deploy even
244 // returns — 240s leaves no room for the destroy + gone-poll that follow.
245 {
246 tags: [
247 "provider:cloudflare",
248 "provider:cloudflare:ai",
249 "provider:cloudflare:apitoken",
250 "provider:cloudflare:r2",
251 "live",
252 ],
253 timeout: 360_000,
254 },
255 );