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

main
ts 232 lines 8.26 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 flagship from "@distilled.cloud/cloudflare/flagship";
6 import * as Alchemy from "alchemy";
7 import { Action } from "alchemy/Action";
8 import { poll } from "alchemy/Util/poll";
9 import * as Data from "effect/Data";
10 import * as Effect from "effect/Effect";
11 import * as HttpClient from "effect/http/HttpClient";
12 import { MinimumLogLevel } from "effect/References";
13 import * as Schedule from "effect/Schedule";
14 import * as pathe from "pathe";
15
16 // `dev: true` runs local providers behind the RPC sidecar proxy by default,
17 // matching the process topology of the real `alchemy dev` command.
18 const { test } = Test.make({
19 providers: Cloudflare.providers(),
20 dev: true,
21 });
22
23 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
24
25 const main = pathe.resolve(import.meta.dirname, "fixtures/local-worker.ts");
26
27 interface Details {
28 value: boolean;
29 variant?: string;
30 reason?: string;
31 errorCode?: string;
32 }
33
34 class WorkerNotReady extends Data.TaggedError("WorkerNotReady")<{
35 status: number;
36 }> {}
37
38 const getDetails = (url: string) =>
39 Effect.gen(function* () {
40 const client = yield* HttpClient.HttpClient;
41 const res = yield* client.get(url).pipe(
42 Effect.flatMap((res) =>
43 res.status === 200
44 ? Effect.succeed(res)
45 : Effect.fail(new WorkerNotReady({ status: res.status })),
46 ),
47 Effect.retry({
48 while: (e) => e._tag === "WorkerNotReady",
49 schedule: Schedule.max([
50 Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("2 seconds")]),
51 Schedule.recurs(10),
52 ]),
53 }),
54 );
55 return (yield* res.json) as unknown as Details;
56 }).pipe(Effect.orDie);
57
58 /**
59 * Under `alchemy dev` the App and Flag are emulated by the local providers
60 * (`dev:` app id, no cloud API calls): the Flag's reconcile seeds its
61 * definition into the local workerd Flagship simulator, and the worker's
62 * `flagship` binding is lowered onto the local evaluator, so targeting
63 * rules apply to the request's context. A flag update re-seeds the
64 * definition and the running worker sees it on the next evaluation.
65 */
66 test.provider(
67 "flagship flags evaluate against the local simulator",
68 (stack) =>
69 Effect.gen(function* () {
70 yield* stack.destroy();
71
72 const key = "local-dark-mode";
73 const deployAt = (enabled: boolean) =>
74 Effect.gen(function* () {
75 const app = yield* Cloudflare.Flagship.App("LocalFlags", {});
76 const flag = yield* Cloudflare.Flagship.Flag("LocalDarkMode", {
77 appId: app.appId,
78 key,
79 enabled,
80 defaultVariation: "off",
81 variations: { off: false, on: true },
82 rules: [
83 {
84 priority: 1,
85 conditions: [{ attribute: "country", operator: "equals", value: "US" }],
86 serveVariation: "on",
87 },
88 ],
89 });
90 const worker = yield* Cloudflare.Worker("flagship-local-worker", {
91 main,
92 env: { FLAGS: app },
93 });
94 // Deploy-time reads go through the same local evaluator.
95 const Read = Action(
96 "ReadLocalFlag",
97 Effect.gen(function* () {
98 const flags = yield* Cloudflare.Flagship.ReadFlags(app);
99 return Effect.fn(function* (input: { key: string }) {
100 return {
101 us: yield* flags.getBooleanDetails(input.key, false, { country: "US" }),
102 ca: yield* flags.getBooleanValue(input.key, true, { country: "CA" }),
103 };
104 });
105 }).pipe(Effect.provide(Cloudflare.Flagship.ReadFlagsLocal)),
106 );
107 // Taking the flag's key orders the read after the flag is written.
108 const read = yield* Read({ key: flag.key });
109 return { app, flag, worker, read };
110 });
111
112 const v1 = yield* stack.deploy(deployAt(true));
113
114 // The local providers fabricate a `dev:` app id — proof no cloud call
115 // ran — and the worker serves from the local dev proxy.
116 expect(v1.app.appId).toMatch(/^dev:/);
117 expect(v1.flag.appId).toBe(v1.app.appId);
118 expect(v1.flag.type).toBe("boolean");
119 expect(v1.worker.url).toMatch(/^http:\/\/localhost:\d+$/);
120
121 expect(v1.read.us).toMatchObject({ value: true, variant: "on", reason: "TARGETING_MATCH" });
122 expect(v1.read.ca).toBe(false);
123
124 expect(yield* getDetails(`${v1.worker.url}/details?flag=${key}&country=US`)).toMatchObject({
125 value: true,
126 variant: "on",
127 reason: "TARGETING_MATCH",
128 });
129 expect(yield* getDetails(`${v1.worker.url}/details?flag=${key}&country=CA`)).toMatchObject({
130 value: false,
131 reason: "DEFAULT",
132 });
133 expect(yield* getDetails(`${v1.worker.url}/details?flag=missing`)).toMatchObject({
134 value: false,
135 errorCode: "FLAG_NOT_FOUND",
136 });
137
138 // Disable the flag — same identity, re-seeded definition. The running
139 // worker reads definitions per evaluation, so it sees the change
140 // without a restart.
141 const v2 = yield* stack.deploy(deployAt(false));
142 expect(v2.app.appId).toBe(v1.app.appId);
143 expect(yield* getDetails(`${v2.worker.url}/details?flag=${key}&country=US`)).toMatchObject({
144 value: false,
145 reason: "DISABLED",
146 });
147
148 yield* stack.destroy();
149 }).pipe(logLevel),
150 {
151 tags: [
152 "provider:cloudflare",
153 "provider:cloudflare:flagship",
154 "provider:cloudflare:worker",
155 "local",
156 ],
157 timeout: 180_000,
158 },
159 );
160
161 /**
162 * `Alchemy.remote()` opts the App and Flag OUT of local emulation: even
163 * under `alchemy dev` they are created on real Cloudflare (live providers)
164 * and the worker's binding proxies to the live app remotely. Out-of-band
165 * reads prove the flag landed in the real app, and destroy (driven by the
166 * stamped `live` provider mode) removes both again.
167 */
168 test.provider(
169 "Alchemy.remote() flagship app runs live in dev",
170 (stack) =>
171 Effect.gen(function* () {
172 yield* stack.destroy();
173
174 const key = "remote-dark-mode";
175 const deployed = yield* stack.deploy(
176 Effect.gen(function* () {
177 const app = yield* Cloudflare.Flagship.App("RemoteFlags", {}).pipe(Alchemy.remote());
178 const flag = yield* Cloudflare.Flagship.Flag("RemoteDarkMode", {
179 appId: app.appId,
180 key,
181 defaultVariation: "on",
182 variations: { off: false, on: true },
183 }).pipe(Alchemy.remote());
184 const worker = yield* Cloudflare.Worker("flagship-remote-worker", {
185 main,
186 env: { FLAGS: app },
187 });
188 return { app, flag, worker };
189 }),
190 );
191
192 // Real (non-`dev:`) identity — the live providers ran.
193 expect(deployed.app.appId).not.toMatch(/^dev:/);
194 expect(deployed.flag.appId).toBe(deployed.app.appId);
195
196 // The locally-served worker evaluates the live flag through the
197 // remote-proxied binding; a fresh flag takes a moment to propagate.
198 const details = yield* poll({
199 description: "remote binding returns the live flag",
200 effect: getDetails(`${deployed.worker.url}/details?flag=${key}`),
201 predicate: (d) => d.value === true,
202 schedule: Schedule.max([Schedule.spaced("3 seconds"), Schedule.recurs(20)]),
203 });
204 expect(details.variant).toBe("on");
205
206 // Out-of-band: the flag exists in the real app.
207 const { accountId } = yield* yield* CloudflareEnvironment;
208 const live = yield* flagship.getAppFlag({
209 accountId,
210 appId: deployed.app.appId,
211 flagKey: key,
212 });
213 expect(live.defaultVariation).toBe("on");
214
215 yield* stack.destroy();
216
217 const gone = yield* flagship.getApp({ accountId, appId: deployed.app.appId }).pipe(
218 Effect.as(false),
219 Effect.catchTag("FlagshipAppNotFound", () => Effect.succeed(true)),
220 );
221 expect(gone).toBe(true);
222 }).pipe(logLevel),
223 {
224 tags: [
225 "provider:cloudflare",
226 "provider:cloudflare:flagship",
227 "provider:cloudflare:worker",
228 "live",
229 ],
230 timeout: 180_000,
231 },
232 );