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

main
ts 184 lines 6.51 KB
Raw
1 import { MigrationError, type SqlExecutor } from "@alchemy.run/sql/Migrations";
2 import { splitSqlStatements } from "@alchemy.run/sql/SqlFile";
3 import * as Data from "effect/Data";
4 import * as Effect from "effect/Effect";
5 import * as HttpClient from "effect/http/HttpClient";
6 import * as HttpClientRequest from "effect/http/HttpClientRequest";
7 import * as Redacted from "effect/Redacted";
8
9 /**
10 * A minimal Hrana-over-HTTP client (`POST /v2/pipeline`) — the SQL wire
11 * protocol every Turso database speaks. Deploy-time work (migrations, SQL
12 * imports) uses it instead of `@libsql/client`, so the provider needs no
13 * driver and runs anywhere `HttpClient` does.
14 *
15 * @see https://github.com/tursodatabase/libsql/blob/main/docs/HRANA_3_SPEC.md
16 */
17 export class HranaError extends Data.TaggedError("Turso::HranaError")<{
18 message: string;
19 code?: string;
20 cause?: unknown;
21 }> {}
22
23 type HranaValue =
24 | { type: "null" }
25 | { type: "integer"; value: string }
26 | { type: "float"; value: number }
27 | { type: "text"; value: string }
28 | { type: "blob"; base64: string };
29
30 interface HranaStmt {
31 sql: string;
32 args?: HranaValue[];
33 }
34
35 interface HranaExecuteResult {
36 cols: Array<{ name: string | null }>;
37 rows: HranaValue[][];
38 }
39
40 interface HranaError_ {
41 message: string;
42 code?: string;
43 }
44
45 interface PipelineResponse {
46 results: Array<
47 | { type: "ok"; response: { type: string; result?: unknown } }
48 | { type: "error"; error: HranaError_ }
49 >;
50 }
51
52 const toHranaValue = (value: unknown): HranaValue => {
53 if (value === null || value === undefined) return { type: "null" };
54 if (typeof value === "bigint") return { type: "integer", value: value.toString() };
55 if (typeof value === "number") {
56 return Number.isInteger(value)
57 ? { type: "integer", value: value.toString() }
58 : { type: "float", value };
59 }
60 if (typeof value === "boolean") return { type: "integer", value: value ? "1" : "0" };
61 if (value instanceof Uint8Array) {
62 return { type: "blob", base64: Buffer.from(value).toString("base64") };
63 }
64 if (typeof value === "string") return { type: "text", value };
65 if (value instanceof Date) return { type: "text", value: value.toISOString() };
66 return { type: "text", value: JSON.stringify(value) };
67 };
68
69 const fromHranaValue = (value: HranaValue): unknown => {
70 switch (value.type) {
71 case "null":
72 return null;
73 case "integer":
74 return Number(value.value);
75 case "float":
76 return value.value;
77 case "text":
78 return value.value;
79 case "blob":
80 return Buffer.from(value.base64, "base64");
81 }
82 };
83
84 const toRows = (result: HranaExecuteResult): Array<Record<string, unknown>> =>
85 result.rows.map((row) =>
86 Object.fromEntries(
87 result.cols.map((col, i) => [col.name ?? String(i), fromHranaValue(row[i]!)]),
88 ),
89 );
90
91 /** Connection details for one Turso database. */
92 export interface HranaConnection {
93 /** `https://<hostname>` of the database. */
94 url: string;
95 /** A database auth token (JWT). */
96 authToken: Redacted.Redacted<string>;
97 }
98
99 const pipeline = (connection: HranaConnection, requests: ReadonlyArray<unknown>) =>
100 Effect.gen(function* () {
101 const client = yield* HttpClient.HttpClient;
102 const response = yield* client
103 .execute(
104 HttpClientRequest.post(`${connection.url.replace(/\/$/, "")}/v2/pipeline`).pipe(
105 HttpClientRequest.bearerToken(Redacted.value(connection.authToken)),
106 HttpClientRequest.bodyJsonUnsafe({ requests: [...requests, { type: "close" }] }),
107 ),
108 )
109 .pipe(Effect.mapError((cause) => new HranaError({ message: String(cause), cause })));
110 if (response.status < 200 || response.status >= 300) {
111 const text = yield* response.text.pipe(Effect.orElseSucceed(() => ""));
112 return yield* new HranaError({
113 message: `Turso SQL request failed with HTTP ${response.status}: ${text}`,
114 });
115 }
116 const body = (yield* response.json.pipe(
117 Effect.mapError((cause) => new HranaError({ message: String(cause), cause })),
118 )) as unknown as PipelineResponse;
119 return body.results.slice(0, requests.length);
120 });
121
122 /** Execute one statement and return its rows as objects. */
123 export const query = (
124 connection: HranaConnection,
125 sql: string,
126 params?: ReadonlyArray<unknown>,
127 ): Effect.Effect<Array<Record<string, unknown>>, HranaError, HttpClient.HttpClient> =>
128 Effect.gen(function* () {
129 const stmt: HranaStmt = { sql, args: (params ?? []).map(toHranaValue) };
130 const [result] = yield* pipeline(connection, [{ type: "execute", stmt }]);
131 if (result === undefined) {
132 return yield* new HranaError({ message: "Turso returned no result" });
133 }
134 if (result.type === "error") {
135 return yield* new HranaError({ message: result.error.message, code: result.error.code });
136 }
137 return toRows(result.response.result as HranaExecuteResult);
138 });
139
140 /**
141 * Execute statements atomically. Each entry may hold several
142 * `;`-separated statements (a whole migration file or seed script), so they
143 * run as one Hrana `sequence` wrapped in `BEGIN`/`COMMIT`. A failing
144 * statement stops the sequence before `COMMIT`, and closing the stream
145 * rolls the open transaction back.
146 */
147 export const transaction = (
148 connection: HranaConnection,
149 statements: ReadonlyArray<string>,
150 ): Effect.Effect<void, HranaError, HttpClient.HttpClient> =>
151 Effect.gen(function* () {
152 const body = statements.flatMap(splitSqlStatements);
153 if (body.length === 0) return;
154 const sql = ["BEGIN", ...body.map((s) => s.replace(/;\s*$/, "")), "COMMIT"].join(";\n");
155 const [result] = yield* pipeline(connection, [{ type: "sequence", sql }]);
156 if (result === undefined) {
157 return yield* new HranaError({ message: "Turso returned no result" });
158 }
159 if (result.type === "error") {
160 return yield* new HranaError({ message: result.error.message, code: result.error.code });
161 }
162 });
163
164 /** Adapt a Turso database connection into the migration registry's executor. */
165 export const makeMigrationExecutor = (
166 connection: HranaConnection,
167 client: HttpClient.HttpClient,
168 ): SqlExecutor => {
169 const toMigrationError = (error: HranaError) =>
170 new MigrationError({ message: `turso: ${error.message}`, cause: error });
171 return {
172 dialect: "sqlite",
173 query: (sql, params) =>
174 query(connection, sql, params).pipe(
175 Effect.provideService(HttpClient.HttpClient, client),
176 Effect.mapError(toMigrationError),
177 ),
178 batch: (statements) =>
179 transaction(connection, statements).pipe(
180 Effect.provideService(HttpClient.HttpClient, client),
181 Effect.mapError(toMigrationError),
182 ),
183 };
184 };