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

main
ts 109 lines 3.54 KB
Raw
1 import * as d1 from "@distilled.cloud/cloudflare/d1";
2 import { md5 } from "alchemy/Util/md5";
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
8 export interface ImportDatabaseOptions {
9 accountId: string;
10 databaseId: string;
11 sqlData: string | Uint8Array;
12 filename?: string;
13 }
14
15 export interface ImportDatabaseResult {
16 filename: string;
17 numQueries: number;
18 }
19
20 /**
21 * A D1 import that Cloudflare accepted but could not finish: the SQL upload
22 * was rejected, ingestion reported `status: "error"`, or an in-progress
23 * response carried no bookmark to poll.
24 */
25 export class D1ImportError extends Data.TaggedError("D1ImportError")<{
26 databaseId: string;
27 message: string;
28 }> {}
29
30 /**
31 * Import SQL into a D1 database via the multi-step Cloudflare flow:
32 * 1. POST `action: "init"` -> returns a presigned `upload_url`, unless D1
33 * already holds a file with this etag, in which case the init response
34 * is itself the first polling response (the import has started).
35 * 2. PUT raw SQL to `upload_url` (only when one was returned)
36 * 3. POST `action: "ingest"` -> returns the first polling response
37 * 4. POST `action: "poll"` with `at_bookmark` until `status === "complete"`
38 */
39 export const importD1Database = Effect.fn(function* (options: ImportDatabaseOptions) {
40 const { accountId, databaseId } = options;
41 const importDb = yield* d1.importDatabase;
42 const client = yield* HttpClient.HttpClient;
43 const etag = yield* md5(options.sqlData);
44
45 const init = yield* importDb({ accountId, databaseId, action: "init", etag });
46
47 const sqlData = options.sqlData;
48 const uploadUrl = init.uploadUrl;
49 let firstPoll = init;
50 if (uploadUrl) {
51 const bytes =
52 typeof sqlData === "string"
53 ? yield* Effect.sync(() => new TextEncoder().encode(sqlData))
54 : sqlData;
55 const putRes = yield* client.execute(
56 HttpClientRequest.put(uploadUrl).pipe(
57 HttpClientRequest.bodyUint8Array(bytes, "application/sql"),
58 ),
59 );
60 if (putRes.status < 200 || putRes.status >= 300) {
61 const text = yield* putRes.text.pipe(Effect.orElseSucceed(() => ""));
62 return yield* new D1ImportError({
63 databaseId,
64 message: `Failed to upload SQL file to D1 (${putRes.status}): ${text}`,
65 });
66 }
67 firstPoll = yield* importDb({
68 accountId,
69 databaseId,
70 action: "ingest",
71 etag,
72 filename: init.filename ?? undefined,
73 });
74 }
75
76 const poll = (
77 response: d1.ImportDatabaseResponse,
78 ): Effect.Effect<ImportDatabaseResult, d1.ImportDatabaseError | D1ImportError> =>
79 Effect.gen(function* () {
80 if (response.status === "complete") {
81 return {
82 filename: response.filename ?? options.filename ?? init.filename ?? "import.sql",
83 numQueries: response.result?.numQueries ?? 0,
84 };
85 }
86 if (response.status === "error") {
87 return yield* new D1ImportError({
88 databaseId,
89 message: response.error ?? "Error during D1 import",
90 });
91 }
92 if (!response.atBookmark) {
93 return yield* new D1ImportError({
94 databaseId,
95 message: response.error ?? "D1 import response is incomplete and has no bookmark to poll",
96 });
97 }
98 return yield* poll(
99 yield* importDb({
100 accountId,
101 databaseId,
102 action: "poll",
103 currentBookmark: response.atBookmark,
104 }),
105 );
106 });
107
108 return yield* poll(firstPoll);
109 });