@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 159 lines 5.93 KB
Raw
1 import { D1 } from "@alchemy.run/cloudflare-runtime/core/bindings";
2 import { SERVICE_D1 } from "@alchemy.run/cloudflare-runtime/core/bindings/d1/D1Options";
3 /**
4 * Node-side query path into the local workerd D1 simulator, built on the
5 * runtime's platform proxy (`PlatformProxy.open` — our `getPlatformProxy`).
6 *
7 * The simulator (a `d1` service routing to a per-database
8 * `D1DatabaseObject` Durable Object over DO SQLite) is only reachable from
9 * inside workerd — but alchemy's migration runner and the
10 * `QueryDatabaseLocal` capability run in Node. The platform proxy bridges
11 * the two: it hosts the binding in a scoped workerd instance and exposes it
12 * to Node. We bind the raw `d1` service (the same designator the
13 * `cloudflare-internal:d1-api` wrapped binding targets) so Node speaks the
14 * full D1 HTTP protocol (`POST /query`, multi-statement SQL) rather than
15 * the line-based `exec()` surface of the wrapped binding:
16 *
17 * Node ── proxy.env.D1_RAW.fetch({sql}) ──▶ `d1` service ──▶ D1DatabaseObject
18 *
19 * Data lands in the same `{storage}/d1` directory every local worker
20 * binding reads.
21 *
22 * NOT exported from `index.ts` — provider-internal scaffolding.
23 */
24 import { open } from "@alchemy.run/cloudflare-runtime/core/platform-proxy";
25 import type { BindingHook } from "@alchemy.run/cloudflare-runtime/core/PluginContext";
26 import { splitSqliteStatements } from "@alchemy.run/sql/SqlFile";
27 import * as Data from "effect/Data";
28 import * as Effect from "effect/Effect";
29 import { gatewayName, localGatewayRuntime } from "../LocalGateway.ts";
30 import type { D1QueryResult, D1SqlExecutor } from "./ApplyMigrations.ts";
31
32 export { localGatewayRuntime as localD1GatewayRuntime };
33
34 export class LocalD1QueryError extends Data.TaggedError("LocalD1QueryError")<{
35 message: string;
36 cause?: unknown;
37 }> {}
38
39 /**
40 * A single query or batch in the shape the cloud `d1.queryDatabase` op
41 * accepts — the local gateway speaks the same surface so client code can
42 * swap transports without translation.
43 */
44 export type D1QueryBody =
45 | { sql: string; params?: unknown[] }
46 | { batch: Array<{ sql: string; params?: unknown[] }> };
47
48 interface D1StatementResponse {
49 success: boolean;
50 results?: unknown;
51 meta?: unknown;
52 error?: string;
53 }
54
55 /**
56 * A plain service binding onto the raw `d1` service for `databaseId` —
57 * bypassing the `cloudflare-internal:d1-api` wrapper so the proxy's fetch
58 * passthrough can POST the full D1 HTTP protocol.
59 */
60 const rawD1Binding = (databaseId: string): BindingHook =>
61 Effect.succeed({
62 name: "D1_RAW",
63 service: {
64 name: SERVICE_D1,
65 props: { json: JSON.stringify({ databaseId }) },
66 },
67 });
68
69 /**
70 * Boot a scoped platform proxy for `databaseId`, hand `use` a query
71 * function that tunnels {@link D1QueryBody} requests into the local
72 * simulator, and tear the instance down when `use` completes.
73 */
74 export const withLocalD1Query = <A, E, R>(
75 databaseId: string,
76 use: (
77 query: (body: D1QueryBody) => Effect.Effect<D1QueryResult, LocalD1QueryError>,
78 ) => Effect.Effect<A, E, R>,
79 ) =>
80 Effect.scoped(
81 Effect.gen(function* () {
82 const proxy = yield* open({
83 name: gatewayName("alchemy-d1-gateway", databaseId),
84 bindings: [
85 // The wrapped binding is unused by the gateway itself, but its
86 // hook registers the database with the D1 plugin so the `d1`
87 // service is emitted into this workerd config.
88 D1.local({ binding: "DB", id: databaseId }),
89 rawD1Binding(databaseId),
90 ],
91 });
92 const raw = (proxy.env as Record<string, unknown>).D1_RAW as {
93 fetch: (input: string, init?: RequestInit) => Promise<Response>;
94 };
95
96 const query = (body: D1QueryBody) =>
97 Effect.tryPromise({
98 try: async () => {
99 const response = await raw.fetch("http://d1/query", {
100 method: "POST",
101 headers: { "content-type": "application/json" },
102 // The DO accepts a single D1Query or an array (one
103 // transaction) — a batch maps to the array form.
104 body: JSON.stringify("batch" in body ? body.batch : body),
105 });
106 return (await response.json()) as unknown;
107 },
108 catch: (cause) =>
109 new LocalD1QueryError({
110 message: "Failed to reach the local D1 gateway",
111 cause,
112 }),
113 }).pipe(
114 Effect.flatMap((responseBody) => {
115 // Protocol errors come back `{ success: false, error }` (a
116 // single object); successes are one envelope per statement.
117 const responses = (
118 Array.isArray(responseBody) ? responseBody : [responseBody]
119 ) as D1StatementResponse[];
120 const failed = responses.find((r) => !r.success);
121 if (failed) {
122 return Effect.fail(
123 new LocalD1QueryError({
124 message: failed.error ?? "Local D1 query failed",
125 }),
126 );
127 }
128 return Effect.succeed({
129 result: responses.map((r) => ({
130 results: r.results,
131 success: true,
132 meta: r.meta,
133 })),
134 } as D1QueryResult);
135 }),
136 );
137
138 return yield* use(query);
139 }),
140 );
141
142 /**
143 * SQL-only view of {@link withLocalD1Query} matching the migration flow's
144 * {@link D1SqlExecutor} contract. Multi-statement SQL runs as a batch of its
145 * statements, as the cloud query endpoint splits it: the simulator's SQLite
146 * rejects one statement over its length limit.
147 */
148 export const withLocalD1Executor = <A, E, R>(
149 databaseId: string,
150 use: (executor: D1SqlExecutor<LocalD1QueryError>) => Effect.Effect<A, E, R>,
151 ) =>
152 withLocalD1Query(databaseId, (query) =>
153 use((sql) => {
154 const statements = splitSqliteStatements(sql);
155 return statements.length > 1
156 ? query({ batch: statements.map((statement) => ({ sql: statement })) })
157 : query({ sql });
158 }),
159 );