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

main
ts 259 lines 9.63 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import * as Drizzle from "@alchemy.run/drizzle";
4 import { expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as d1 from "@distilled.cloud/cloudflare/d1";
7 import { Interaction, type InteractionError, type SelectOptions } from "alchemy/Interaction";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as FileSystem from "effect/FileSystem";
11 import * as HttpClient from "effect/http/HttpClient";
12 import * as HttpClientRequest from "effect/http/HttpClientRequest";
13 import type * as HttpClientResponse from "effect/http/HttpClientResponse";
14 import * as Layer from "effect/Layer";
15 import * as Path from "effect/Path";
16 import * as Predicate from "effect/Predicate";
17 import * as Schedule from "effect/Schedule";
18 import Stack from "./fixtures/drizzle-stack.ts";
19
20 const { test, beforeAll, afterAll, deploy, destroy } = Test.make({
21 providers: Layer.mergeAll(Cloudflare.providers(), Drizzle.providers()),
22 state: Cloudflare.state(),
23 });
24
25 const HOOK_TIMEOUT = 300_000;
26 const TEST_TIMEOUT = 120_000;
27
28 class WorkerNotReady extends Data.TaggedError("WorkerNotReady")<{
29 status: number;
30 body: string;
31 }> {}
32
33 // Bounded spaced schedule — rides out fresh-workers.dev cold-start
34 // propagation without blowing past the test timeout.
35 const ready = Schedule.max([Schedule.spaced("2 seconds"), Schedule.recurs(45)]);
36
37 /** Retry an HTTP call until it returns 200. */
38 const untilOk = <E, R>(eff: Effect.Effect<HttpClientResponse.HttpClientResponse, E, R>) =>
39 eff.pipe(
40 Effect.flatMap((res) =>
41 res.status === 200
42 ? Effect.succeed(res)
43 : res.text.pipe(
44 Effect.flatMap((body) => Effect.fail(new WorkerNotReady({ status: res.status, body }))),
45 ),
46 ),
47 Effect.retry({
48 while: (e): e is WorkerNotReady => e instanceof WorkerNotReady,
49 schedule: ready,
50 }),
51 );
52
53 /**
54 * End-to-end test of the Drizzle-on-D1 surface against a real Cloudflare
55 * Worker + D1 database:
56 *
57 * - deploy applies the checked-in migration (generated by drizzle-kit from
58 * `fixtures/drizzle-schema.ts`) via `migrationsDir` into the
59 * `drizzle_migrations` table;
60 * - `Drizzle.D1(d1, { relations })` drives insert/select/relational queries
61 * through the drizzle-orm `effect-d1` driver;
62 * - `SQL.D1(d1)` drives raw tagged-template SQL through `@effect/sql-d1`.
63 */
64 const stack = beforeAll(deploy(Stack), { timeout: HOOK_TIMEOUT });
65 afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(Stack), {
66 timeout: HOOK_TIMEOUT,
67 });
68
69 test(
70 "Drizzle.D1 + SQL.D1 exercise the deployed database",
71 Effect.gen(function* () {
72 const { url } = yield* stack;
73
74 // drizzle insert ... returning
75 const userRes = yield* untilOk(
76 HttpClient.execute(
77 HttpClientRequest.post(`${url}/users`).pipe(
78 HttpClientRequest.bodyJsonUnsafe({
79 name: "alice",
80 email: "alice@example.com",
81 }),
82 ),
83 ),
84 );
85 const { user } = (yield* userRes.json) as {
86 user: { id: number; name: string; email: string };
87 };
88 expect(user.name).toBe("alice");
89 expect(user.email).toBe("alice@example.com");
90 expect(typeof user.id).toBe("number");
91
92 const postRes = yield* untilOk(
93 HttpClient.execute(
94 HttpClientRequest.post(`${url}/posts`).pipe(
95 HttpClientRequest.bodyJsonUnsafe({
96 userId: user.id,
97 title: "hello world",
98 }),
99 ),
100 ),
101 );
102 const { post } = (yield* postRes.json) as {
103 post: { id: number; userId: number; title: string };
104 };
105 expect(post.userId).toBe(user.id);
106 expect(post.title).toBe("hello world");
107
108 // drizzle select
109 const listRes = yield* untilOk(HttpClient.get(`${url}/users`));
110 const { users } = (yield* listRes.json) as {
111 users: Array<{ id: number; name: string }>;
112 };
113 expect(users.map((u) => u.name)).toContain("alice");
114
115 // drizzle relational query (RQB v2): user with posts
116 const relRes = yield* untilOk(HttpClient.get(`${url}/users/${user.id}`));
117 const rel = (yield* relRes.json) as {
118 user: { id: number; posts: Array<{ title: string }> };
119 };
120 expect(rel.user.id).toBe(user.id);
121 expect(rel.user.posts.map((p) => p.title)).toContain("hello world");
122
123 // raw @effect/sql-d1 tagged-template client
124 const sqlRes = yield* untilOk(HttpClient.get(`${url}/sql/users`));
125 const { rows } = (yield* sqlRes.json) as {
126 rows: Array<{ id: number; name: string; email: string }>;
127 };
128 expect(rows.map((r) => r.email)).toContain("alice@example.com");
129 }),
130 {
131 tags: ["provider:cloudflare", "provider:cloudflare:d1", "provider:cloudflare:worker", "live"],
132 timeout: TEST_TIMEOUT,
133 },
134 );
135
136 const USERS_SCHEMA = `
137 import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
138
139 export const users = sqliteTable("users", {
140 id: integer("id").primaryKey(),
141 name: text("name").notNull(),
142 });
143 `;
144
145 // `name` renamed to `full_name`, plus a new `posts` table.
146 const RENAMED_USERS_SCHEMA = `
147 import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
148
149 export const users = sqliteTable("users", {
150 id: integer("id").primaryKey(),
151 fullName: text("full_name").notNull(),
152 });
153
154 export const posts = sqliteTable("posts", {
155 id: integer("id").primaryKey(),
156 title: text("title").notNull(),
157 });
158 `;
159
160 const queryAll = Effect.fn(function* <T>(accountId: string, databaseId: string, sql: string) {
161 const queryDb = yield* d1.queryDatabase;
162 const result = yield* queryDb({ accountId, databaseId, sql });
163 return (result.result[0]?.results ?? []) as T[];
164 });
165
166 class DatabaseStillExists extends Data.TaggedError("DatabaseStillExists") {}
167
168 const waitForDatabaseToBeDeleted = (accountId: string, databaseId: string) =>
169 d1.getDatabase({ accountId, databaseId }).pipe(
170 Effect.flatMap(() => Effect.fail(new DatabaseStillExists())),
171 Effect.retry({
172 while: (e) => e._tag === "DatabaseStillExists",
173 schedule: Schedule.max([Schedule.exponential("200 millis"), Schedule.recurs(10)]),
174 }),
175 Effect.catchTag("DatabaseNotFound", () => Effect.void),
176 );
177
178 test.provider(
179 "Drizzle.Schema snapshot updates migrate the live database, renames included",
180 (stack) =>
181 Effect.gen(function* () {
182 const { accountId } = yield* yield* CloudflareEnvironment;
183 const fs = yield* FileSystem.FileSystem;
184 const path = yield* Path.Path;
185
186 // Inside the workspace so the schema module resolves `drizzle-orm`.
187 const tmp = path.join(yield* Effect.sync(() => process.cwd()), ".alchemy", "tmp");
188 yield* fs.makeDirectory(tmp, { recursive: true });
189 const root = yield* fs.makeTempDirectoryScoped({ directory: tmp, prefix: "d1-drizzle-" });
190 const schemaPath = path.join(root, "schema.ts");
191 const out = path.join(root, "migrations");
192 yield* fs.writeFileString(schemaPath, USERS_SCHEMA);
193
194 const deploy = (source: string) =>
195 stack.deploy(
196 Effect.gen(function* () {
197 const schema = yield* Drizzle.Schema("live-schema", {
198 dialect: "sqlite",
199 schema: source,
200 out,
201 });
202 return yield* Cloudflare.D1.Database("LiveSchemaDatabase", {
203 migrations: { dir: schema.out, table: "drizzle_migrations" },
204 });
205 }),
206 );
207
208 yield* stack.destroy();
209 const database = yield* deploy(schemaPath);
210 const query = <T>(sql: string) => queryAll<T>(accountId, database.databaseId, sql);
211 yield* query("INSERT INTO users (id, name) VALUES (1, 'alice');");
212
213 // Rename the column; answer the rename-or-create question with rename.
214 // A new file: the process has already imported (and cached) the first.
215 const renamedPath = path.join(root, "schema-renamed.ts");
216 yield* fs.writeFileString(renamedPath, RENAMED_USERS_SCHEMA);
217 const asked: Array<string> = [];
218 const base = yield* Interaction;
219 const scripted = Interaction.of({
220 ...base,
221 prompt: {
222 ...base.prompt,
223 select: <Value>(options: SelectOptions<Value>) =>
224 Effect.sync(() => {
225 asked.push(options.message);
226 const rename = options.options.find(
227 ({ value }) => Predicate.hasProperty(value, "type") && value.type === "rename",
228 );
229 return (rename ?? options.options[0]!).value;
230 }) as Effect.Effect<Value, InteractionError>,
231 },
232 });
233 const updated = yield* deploy(renamedPath).pipe(Effect.provideService(Interaction, scripted));
234 expect(updated.databaseId).toEqual(database.databaseId);
235 expect(asked).toEqual(["Is column users.full_name created or renamed from another column?"]);
236
237 // The row survived: the column was renamed, not dropped and recreated.
238 expect(yield* query("SELECT id, full_name FROM users;")).toEqual([
239 { id: 1, full_name: "alice" },
240 ]);
241 const tables = yield* query<{ name: string }>(
242 "SELECT name FROM sqlite_master WHERE type='table';",
243 );
244 expect(tables.map((t) => t.name)).toContain("posts");
245 const applied = yield* query<{ n: number }>("SELECT count(*) AS n FROM drizzle_migrations;");
246 expect(applied).toEqual([{ n: 2 }]);
247
248 // A redeploy with no schema change applies nothing new.
249 yield* deploy(renamedPath);
250 expect(yield* query("SELECT count(*) AS n FROM drizzle_migrations;")).toEqual([{ n: 2 }]);
251
252 yield* stack.destroy();
253 yield* waitForDatabaseToBeDeleted(accountId, database.databaseId);
254 }).pipe(Effect.scoped),
255 {
256 tags: ["provider:cloudflare", "provider:cloudflare:d1", "live"],
257 timeout: TEST_TIMEOUT,
258 },
259 );