@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 321 lines 12.6 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import {
4 bootstrap,
5 loginWithCloudflare,
6 teardownStateStore,
7 } from "@alchemy.run/cloudflare/StateStore/State";
8 import {
9 AuthTokenSecretName,
10 EncryptionKeySecretName,
11 stateStoreSecretName,
12 } from "@alchemy.run/cloudflare/StateStore/Token";
13 import { expect } from "@alchemy.run/test";
14 import * as Test from "@alchemy.run/test/Alchemy";
15 import * as secretsStore from "@distilled.cloud/cloudflare/secrets-store";
16 import * as workers from "@distilled.cloud/cloudflare/workers";
17 import * as Alchemist from "alchemy/Alchemist";
18 import { currentProfileName } from "alchemy/Auth/Profile";
19 import { checkHttpStateStoreAuth } from "alchemy/State/HttpStateStore";
20 import { State } from "alchemy/State/State";
21 import * as Cause from "effect/Cause";
22 import * as Effect from "effect/Effect";
23 import * as Exit from "effect/Exit";
24 import * as Redacted from "effect/Redacted";
25 import * as Schedule from "effect/Schedule";
26 import * as Stream from "effect/Stream";
27
28 const { test } = Test.make({ providers: Cloudflare.providers() });
29
30 /** Run with `CI` and the given env set, as a CI deploy would. */
31 const inCI = <A, E, R>(env: Readonly<Record<string, string>>, effect: Effect.Effect<A, E, R>) =>
32 Effect.acquireUseRelease(
33 Effect.sync(() => {
34 const vars = { CI: "true", ...env };
35 const previous = Object.fromEntries(Object.keys(vars).map((key) => [key, process.env[key]]));
36 Object.assign(process.env, vars);
37 return previous;
38 }),
39 () => effect,
40 (previous) =>
41 Effect.sync(() => {
42 for (const [key, value] of Object.entries(previous)) {
43 if (value === undefined) delete process.env[key];
44 else process.env[key] = value;
45 }
46 }),
47 );
48
49 const scriptExists = (accountId: string, scriptName: string) =>
50 workers.getScriptSetting({ accountId, scriptName }).pipe(
51 Effect.as(true),
52 Effect.catchTag(["WorkerNotFound", "InvalidRoute", "WorkerHasNoVersions"], () =>
53 Effect.succeed(false),
54 ),
55 );
56
57 test.provider(
58 "a named Cloudflare state store bootstraps, serves state and tears down beside the default",
59 (stack) =>
60 Effect.gen(function* () {
61 const environment = yield* yield* CloudflareEnvironment;
62 const { accountId } = environment;
63 // Never the default store, which every other run on the account uses.
64 const worker = "alchemy-state-store-lifecycle";
65 // `--name` is the store's full Worker name.
66 const target = { type: "provider", backend: "cloudflare", name: worker } as const;
67 const alchemist = Alchemist.layer();
68 const defaultStacks = () =>
69 Effect.flatMap(
70 Alchemist.State.store({ type: "provider", backend: "cloudflare" }).pipe(
71 Effect.provide(alchemist),
72 ),
73 (store) => store.listStacks(),
74 );
75
76 const before = yield* defaultStacks();
77 yield* stack.destroy();
78 yield* Alchemist.State.teardown(target).pipe(Effect.provide(alchemist));
79
80 const created = yield* Alchemist.State.bootstrap(target).pipe(Effect.provide(alchemist));
81 expect(created.status).toBe("created");
82 expect(yield* scriptExists(accountId, worker)).toBe(true);
83
84 const adopted = yield* Alchemist.State.bootstrap(target).pipe(Effect.provide(alchemist));
85 expect(adopted.status).toBe("adopted");
86
87 // Opening the store from a profile with no cached credentials, with a
88 // token that can't read Workers scripts, can't tell whether the store
89 // exists. It fails instead of bootstrapping over the live store.
90 const limited = yield* stack.deploy(
91 Cloudflare.ApiToken.AccountApiToken("NoWorkersScriptsRead", {
92 policies: [
93 {
94 effect: "allow",
95 permissionGroups: ["Account Settings Read"],
96 resources: { [`com.cloudflare.api.account.${accountId}`]: "*" },
97 },
98 ],
99 }),
100 );
101 const unknown = `Could not determine whether Cloudflare State Store '${worker}' exists, so it was left untouched`;
102 const blind = yield* inCI(
103 {
104 CLOUDFLARE_API_TOKEN: Redacted.value(limited.value),
105 CLOUDFLARE_ACCOUNT_ID: accountId,
106 ALCHEMY_PROFILE: `${stack.stage}-no-scripts-read`,
107 },
108 Effect.exit(
109 Alchemist.State.store(target).pipe(
110 Effect.flatMap((store) => store.listStacks()),
111 Effect.provide(alchemist),
112 ),
113 ),
114 ).pipe(
115 // A fresh token can take a few seconds to authenticate.
116 Effect.repeat({
117 until: (exit) => Exit.isFailure(exit) && Cause.pretty(exit.cause).includes(unknown),
118 schedule: Schedule.spaced("5 seconds"),
119 times: 6,
120 }),
121 );
122 expect(Exit.isFailure(blind)).toBe(true);
123 if (Exit.isFailure(blind)) {
124 expect(Cause.pretty(blind.cause)).toContain(unknown);
125 expect(Cause.pretty(blind.cause)).toContain("Workers Scripts Read");
126 }
127
128 // The store is deployed without a stack, so a new one holds no state,
129 // and it still serves with the credentials it had.
130 const store = yield* Alchemist.State.store(target).pipe(Effect.provide(alchemist));
131 expect(yield* store.listStacks()).toEqual([]);
132
133 const torn = yield* Alchemist.State.teardown(target).pipe(Effect.provide(alchemist));
134 expect(torn.deleted).toEqual([worker]);
135 expect(yield* scriptExists(accountId, worker)).toBe(false);
136
137 // In CI, a missing store fails instead of being deployed on first use.
138 // CI reads Cloudflare credentials from the environment only. The
139 // deleted Worker's workers.dev URL can keep serving for a few seconds,
140 // so retry until the edge reports it gone.
141 expect(environment.type).toBe("apiToken");
142 const expected = `Run 'alchemy state bootstrap --backend cloudflare --name ${worker}`;
143 const inCi = yield* inCI(
144 environment.type === "apiToken"
145 ? {
146 CLOUDFLARE_API_TOKEN: Redacted.value(environment.apiToken),
147 CLOUDFLARE_ACCOUNT_ID: accountId,
148 }
149 : {},
150 Effect.exit(
151 Alchemist.State.store(target).pipe(
152 Effect.flatMap((store) => store.listStacks()),
153 Effect.provide(alchemist),
154 ),
155 ),
156 ).pipe(
157 Effect.repeat({
158 until: (exit) => Exit.isFailure(exit) && Cause.pretty(exit.cause).includes(expected),
159 schedule: Schedule.spaced("5 seconds"),
160 times: 12,
161 }),
162 );
163 expect(Exit.isFailure(inCi)).toBe(true);
164 if (Exit.isFailure(inCi)) expect(Cause.pretty(inCi.cause)).toContain(expected);
165 expect(yield* scriptExists(accountId, worker)).toBe(false);
166
167 // The default store kept serving through all of it.
168 expect(yield* scriptExists(accountId, "alchemy-state-store")).toBe(true);
169 expect(yield* defaultStacks()).toEqual(before);
170 yield* stack.destroy();
171 }),
172 // Exclusive: sets `CI` on the process.
173 {
174 tags: ["provider:cloudflare", "provider:cloudflare:statestore", "live"],
175 timeout: 300_000,
176 exclusive: true,
177 },
178 );
179
180 /** The ids of a store's two secrets, observed out-of-band. */
181 const secretIds = (accountId: string, workerName: string) =>
182 Effect.gen(function* () {
183 const names = [
184 stateStoreSecretName(AuthTokenSecretName, workerName),
185 stateStoreSecretName(EncryptionKeySecretName, workerName),
186 ];
187 const store = yield* secretsStore.listStores.items({ accountId }).pipe(Stream.runHead);
188 if (store._tag === "None") return [];
189 const secrets = yield* secretsStore.listStoreSecrets
190 .items({ accountId, storeId: store.value.id })
191 .pipe(Stream.runCollect);
192 return names.map((name) => Array.from(secrets).find((secret) => secret.name === name)?.id);
193 });
194
195 test.provider(
196 "a state store pinned to an account and named by workerName deploys there and keeps its secrets",
197 () =>
198 Effect.gen(function* () {
199 const { accountId } = yield* yield* CloudflareEnvironment;
200 const workerName = `alchemy-state-store-pin-${Test.defaultStage().replaceAll("_", "-")}`;
201 const record = {
202 kind: "resource" as const,
203 resourceType: "Test.Resource",
204 namespace: undefined,
205 fqn: "pinned/a",
206 logicalId: "a",
207 instanceId: "kept",
208 providerVersion: 1,
209 status: "created" as const,
210 downstream: [],
211 bindings: [],
212 props: { hello: "world" },
213 attr: { id: "kept" },
214 };
215 yield* teardownStateStore({ workerName, accountId });
216
217 // An account the credentials can't reach fails instead of falling back
218 // to the profile's account.
219 const unreachable = yield* Effect.exit(
220 State.pipe(
221 Effect.flatten,
222 Effect.provide(Cloudflare.state({ workerName, accountId: "0".repeat(32) })),
223 ),
224 );
225 expect(Exit.isFailure(unreachable)).toBe(true);
226 if (Exit.isFailure(unreachable)) {
227 expect(Cause.pretty(unreachable.cause)).toContain(`pinned to account ${"0".repeat(32)}`);
228 }
229 expect(yield* scriptExists(accountId, workerName)).toBe(false);
230
231 // The pinned account deploys the Worker under exactly `workerName`.
232 const state = yield* State.pipe(
233 Effect.flatten,
234 Effect.provide(Cloudflare.state({ workerName, accountId })),
235 );
236 yield* state.set({ stack: "pinned", stage: "test", fqn: "pinned/a", value: record });
237 expect(yield* scriptExists(accountId, workerName)).toBe(true);
238 const secrets = yield* secretIds(accountId, workerName);
239 expect(secrets.every((id) => id !== undefined)).toBe(true);
240
241 // A forced redeploy reuses both secrets, so state written before it
242 // still decrypts.
243 const redeployed = yield* bootstrap({ workerName, accountId, force: true });
244 expect(yield* secretIds(accountId, workerName)).toEqual(secrets);
245 expect(yield* redeployed.get({ stack: "pinned", stage: "test", fqn: "pinned/a" })).toEqual(
246 record,
247 );
248
249 yield* teardownStateStore({ workerName, accountId });
250 expect(yield* scriptExists(accountId, workerName)).toBe(false);
251 }),
252 {
253 tags: ["provider:cloudflare", "provider:cloudflare:statestore", "live"],
254 timeout: 300_000,
255 },
256 );
257
258 const ZONE = process.env.CLOUDFLARE_TEST_DNS_ZONE_NAME ?? "alchemy-test-2.us";
259
260 /** The Workers custom domains attached to `hostname`. */
261 const attachedDomains = (accountId: string, hostname: string) =>
262 workers
263 .listDomains({ accountId, hostname })
264 .pipe(
265 Effect.map(({ result }) =>
266 (result ?? []).filter((d) => d.hostname === hostname).map((d) => d.service),
267 ),
268 );
269
270 test.provider(
271 "a state store with a domain serves and logs in on it",
272 () =>
273 Effect.gen(function* () {
274 const { accountId } = yield* yield* CloudflareEnvironment;
275 const stage = Test.defaultStage().replaceAll("_", "-");
276 const workerName = `alchemy-state-store-domain-${stage}`;
277 const domain = `state-${stage}.${ZONE}`;
278 const record = {
279 kind: "resource" as const,
280 resourceType: "Test.Resource",
281 namespace: undefined,
282 fqn: "domain/a",
283 logicalId: "a",
284 instanceId: "kept",
285 providerVersion: 1,
286 status: "created" as const,
287 downstream: [],
288 bindings: [],
289 props: { hello: "world" },
290 attr: { id: "kept" },
291 };
292 yield* teardownStateStore({ workerName });
293
294 // First use deploys the store and attaches the domain to its Worker.
295 const state = yield* State.pipe(
296 Effect.flatten,
297 Effect.provide(Cloudflare.state({ workerName, domain })),
298 );
299 yield* state.set({ stack: "domain", stage: "test", fqn: "domain/a", value: record });
300 expect(yield* attachedDomains(accountId, domain)).toEqual([workerName]);
301
302 // A fresh login reads the token through a preview served on the domain
303 // and points the store at it.
304 const profile = yield* currentProfileName;
305 const credentials = yield* loginWithCloudflare(profile, true, workerName, accountId, domain);
306 expect(credentials.url).toBe(`https://${domain}`);
307 expect(yield* checkHttpStateStoreAuth(credentials)).toBe(true);
308 const adopted = yield* bootstrap({ workerName, domain });
309 expect(yield* adopted.get({ stack: "domain", stage: "test", fqn: "domain/a" })).toEqual(
310 record,
311 );
312
313 yield* teardownStateStore({ workerName });
314 expect(yield* scriptExists(accountId, workerName)).toBe(false);
315 expect(yield* attachedDomains(accountId, domain)).toEqual([]);
316 }),
317 {
318 tags: ["provider:cloudflare", "provider:cloudflare:statestore", "live"],
319 timeout: 300_000,
320 },
321 );