@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, 04:45 UTC

main
ts 131 lines 4.64 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import * as Planetscale from "@alchemy.run/planetscale";
3 import * as SQL from "@alchemy.run/sql/MySQL";
4 import * as Data from "effect/Data";
5 import * as Effect from "effect/Effect";
6 import * as HttpServerRequest from "effect/http/HttpServerRequest";
7 import * as HttpServerResponse from "effect/http/HttpServerResponse";
8 import { makeLayerUsers, makeSqlRoutes, type UserRow } from "./routes.ts";
9
10 export const Hyperdrive = Effect.gen(function* () {
11 const database = yield* Planetscale.MySQLDatabase("SqlMySQLDb", {
12 name: "alchemy-sql-mysql",
13 region: { slug: "us-east" },
14 clusterSize: "PS_10",
15 });
16 // `admin` because the fixture creates its table over the wire (`/init`
17 // runs raw DDL); the default branch is `main`.
18 const password = yield* Planetscale.MySQLPassword("SqlMySQLPassword", {
19 database,
20 role: "admin",
21 });
22 return yield* Cloudflare.Hyperdrive.Connection("SqlMySQLEdge", {
23 origin: password.origin,
24 // The tests assert read-after-write; Hyperdrive's default SELECT caching
25 // (~60s TTL) can serve a pre-insert empty result — and keep serving it
26 // across retries — so caching is disabled for correctness assertions.
27 caching: { disabled: true },
28 });
29 });
30
31 const TABLE = "alchemy_sql_users";
32
33 const DDL = `CREATE TABLE IF NOT EXISTS ${TABLE} (
34 id INT PRIMARY KEY,
35 name VARCHAR(255) NOT NULL,
36 email VARCHAR(255) NOT NULL
37 )`;
38
39 class Rollback extends Data.TaggedError("Rollback")<{}> {}
40
41 /**
42 * Init effect for the whole route surface: binds the Hyperdrive connection,
43 * builds the `SQL.MySQL` client and the `SQL.MySQLLayer`-backed users
44 * service, and returns a handler that serves the MySQL transaction routes
45 * (`withTransaction` commit/rollback) before falling through to the shared
46 * dialect-agnostic table.
47 */
48 const MySQLRoutes = Effect.gen(function* () {
49 const hd = yield* Cloudflare.Hyperdrive.Connect(Hyperdrive);
50 const sql = yield* SQL.MySQL({ url: hd.connectionString });
51 const layerUsers = yield* makeLayerUsers(TABLE).pipe(
52 Effect.provide(SQL.MySQLLayer({ url: hd.connectionString })),
53 );
54 const shared = makeSqlRoutes({ sql, layerUsers, ddl: DDL, table: TABLE });
55
56 const handle = Effect.fn(function* (request: HttpServerRequest.HttpServerRequest) {
57 // POST /tx/commit — statements inside `withTransaction` share one
58 // transaction and commit together.
59 if (request.method === "POST" && request.url === "/tx/commit") {
60 const rows = (yield* request.json) as UserRow[];
61 yield* sql.withTransaction(
62 Effect.gen(function* () {
63 for (const row of rows) {
64 yield* sql`INSERT INTO ${sql(TABLE)} ${sql.insert(row)}`;
65 }
66 }),
67 );
68 const inserted = yield* sql`
69 SELECT id, name, email FROM ${sql(TABLE)}
70 WHERE ${sql.in(
71 "id",
72 rows.map((r) => r.id),
73 )}
74 ORDER BY id
75 `;
76 return yield* HttpServerResponse.json({ rows: inserted });
77 }
78
79 // POST /tx/rollback — a failure inside `withTransaction` rolls the
80 // insert back; the row must not be visible afterwards.
81 if (request.method === "POST" && request.url === "/tx/rollback") {
82 const row = (yield* request.json) as UserRow;
83 const error = yield* sql
84 .withTransaction(
85 Effect.gen(function* () {
86 yield* sql`INSERT INTO ${sql(TABLE)} ${sql.insert(row)}`;
87 return yield* Effect.fail(new Rollback());
88 }),
89 )
90 .pipe(Effect.flip);
91 const rows = yield* sql`SELECT id FROM ${sql(TABLE)} WHERE id = ${row.id}`;
92 return yield* HttpServerResponse.json({
93 error: (error as { _tag: string })._tag,
94 rows,
95 });
96 }
97
98 return yield* shared.handle(request);
99 });
100
101 return { handle };
102 });
103
104 /**
105 * Effect-native Worker driving `SQL.MySQL` (the raw `@effect/sql-mysql2`
106 * client) over a Hyperdrive connection to a PlanetScale MySQL origin.
107 */
108 export default class SqlMySQLWorker extends Cloudflare.Worker<SqlMySQLWorker>()(
109 "SqlMySQLWorker",
110 {
111 main: import.meta.url,
112 },
113 Effect.gen(function* () {
114 const routes = yield* MySQLRoutes;
115
116 return {
117 fetch: Effect.gen(function* () {
118 const request = yield* HttpServerRequest.HttpServerRequest;
119 const response = yield* routes.handle(request);
120 if (response !== undefined) {
121 return response;
122 }
123 return yield* HttpServerResponse.json({ error: "not found" }, { status: 404 });
124 }).pipe(
125 Effect.catchCause((cause) =>
126 HttpServerResponse.json({ error: String(cause) }, { status: 500 }),
127 ),
128 ),
129 };
130 }).pipe(Effect.provide(Cloudflare.Hyperdrive.ConnectBinding)),
131 ) {}