@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 226 lines 8.21 KB
Raw
1 import type * as Duration from "effect/Duration";
2 import * as Effect from "effect/Effect";
3 import * as Schedule from "effect/Schedule";
4 import type { Connection, ConnectionOptions } from "mysql2/promise";
5 import type { Client, ClientConfig } from "pg";
6 import { importMySql } from "../MySQLDriver.ts";
7 import { importPg } from "../PostgresDriver.ts";
8 import { MigrationError, type MigrationDialect, type SqlExecutor } from "./Format.ts";
9 import { makeMySQLMigrationExecutor } from "./MySQLExecutor.ts";
10 import { makePgMigrationExecutor } from "./PgExecutor.ts";
11 import { inlineSqlParams } from "./Utils.ts";
12
13 const describeCause = (cause: unknown): string => {
14 if (typeof cause === "object" && cause !== null) {
15 const { message, _tag } = cause as { message?: unknown; _tag?: unknown };
16 if (typeof message === "string" && message.length > 0) return message;
17 if (typeof _tag === "string") return _tag;
18 }
19 return String(cause);
20 };
21
22 /**
23 * Wrap any failure from a migration transport as a {@link MigrationError}
24 * that names what failed: `Effect.mapError(migrationError("executeSql on app"))`.
25 */
26 export const migrationError =
27 (context: string) =>
28 (cause: unknown): MigrationError =>
29 new MigrationError({ message: `${context} failed: ${describeCause(cause)}`, cause });
30
31 /**
32 * Open a `pg` client for the scope of `use`; it always closes afterwards,
33 * including when `connect` itself fails. `config` goes to
34 * `new Client(config)` unchanged — a connection string, TLS options, or a
35 * `stream` the provider already connected (the Cloud SQL connector).
36 * Prefer {@link withPgExecutor}; use this when the provider runs its own
37 * executor over the client (DSQL) or plain SQL (`importFiles`).
38 */
39 export interface ConnectOptions {
40 /**
41 * Retry the connect — never `use` — while this holds for the driver's
42 * error, e.g. DNS that hasn't propagated for a just-created host.
43 */
44 readonly retryConnect?: {
45 readonly while: (cause: unknown) => boolean;
46 readonly times: number;
47 readonly interval: Duration.Input;
48 };
49 /** Rewrite a connect failure that survived the retry, e.g. to add a hint. */
50 readonly onConnectFailure?: (error: MigrationError) => MigrationError;
51 }
52
53 const retryingConnect = <A>(
54 connect: Effect.Effect<A, MigrationError>,
55 options: ConnectOptions | undefined,
56 ): Effect.Effect<A, MigrationError> => {
57 const retry = options?.retryConnect;
58 const retried = retry
59 ? connect.pipe(
60 Effect.retry({
61 while: (error) => retry.while(error.cause),
62 schedule: Schedule.spaced(retry.interval),
63 times: retry.times,
64 }),
65 )
66 : connect;
67 const rewrite = options?.onConnectFailure;
68 return rewrite ? retried.pipe(Effect.mapError(rewrite)) : retried;
69 };
70
71 export const withPgClient = <A, E, R>(
72 config: ClientConfig,
73 use: (client: Client) => Effect.Effect<A, E, R>,
74 options?: ConnectOptions,
75 ): Effect.Effect<A, MigrationError | E, R> =>
76 Effect.acquireUseRelease(
77 retryingConnect(
78 Effect.tryPromise({
79 try: async () => {
80 const { Client } = await importPg();
81 const client = new Client(config);
82 // pg reports idle socket failures as events; the next query fails
83 // through the error channel instead of crashing the process.
84 client.on("error", () => {});
85 try {
86 await client.connect();
87 } catch (error) {
88 await client.end().catch(() => {});
89 throw error;
90 }
91 return client;
92 },
93 catch: migrationError(`Connecting to postgres${config.host ? ` at ${config.host}` : ""}`),
94 }),
95 options,
96 ),
97 use,
98 (client) => Effect.promise(() => client.end().catch(() => {})),
99 );
100
101 /** {@link withPgClient} handing over the client as a {@link SqlExecutor}. */
102 export const withPgExecutor = <A, E, R>(
103 config: ClientConfig,
104 use: (executor: SqlExecutor) => Effect.Effect<A, E, R>,
105 options?: ConnectOptions,
106 ): Effect.Effect<A, MigrationError | E, R> =>
107 withPgClient(config, (client) => use(makePgMigrationExecutor(client)), options);
108
109 /**
110 * Open a `mysql2` connection for the scope of `use`; it always closes
111 * afterwards. `config` goes to `createConnection(config)` unchanged.
112 * Prefer {@link withMySqlExecutor}.
113 */
114 export const withMySqlConnection = <A, E, R>(
115 config: ConnectionOptions,
116 use: (connection: Connection) => Effect.Effect<A, E, R>,
117 options?: ConnectOptions,
118 ): Effect.Effect<A, MigrationError | E, R> =>
119 Effect.acquireUseRelease(
120 retryingConnect(
121 Effect.tryPromise({
122 try: async () => {
123 const { createConnection } = await importMySql();
124 return createConnection(config);
125 },
126 catch: migrationError(`Connecting to mysql${config.host ? ` at ${config.host}` : ""}`),
127 }),
128 options,
129 ),
130 use,
131 (connection) => Effect.promise(() => connection.end().catch(() => {})),
132 );
133
134 /** {@link withMySqlConnection} handing over the connection as a {@link SqlExecutor}. */
135 export const withMySqlExecutor = <A, E, R>(
136 config: ConnectionOptions,
137 use: (executor: SqlExecutor) => Effect.Effect<A, E, R>,
138 options?: ConnectOptions,
139 ): Effect.Effect<A, MigrationError | E, R> =>
140 withMySqlConnection(config, (connection) => use(makeMySQLMigrationExecutor(connection)), options);
141
142 export type Rows = Array<Record<string, unknown>>;
143
144 /** Each statement ends with exactly one `;`, so several share one request. */
145 const terminated = (statement: string) => {
146 const trimmed = statement.trim();
147 return trimmed.endsWith(";") ? trimmed : `${trimmed};`;
148 };
149
150 /**
151 * A {@link SqlExecutor} over an API that runs a SQL string and returns rows —
152 * the Cloud SQL and AlloyDB Data APIs, or any HTTP SQL endpoint. The provider
153 * supplies only `execute`, which must fail when the database reports an
154 * error (Data APIs return SQL errors inside a 200). Params are inlined, since
155 * these APIs bind none.
156 *
157 * `batch` sets how a migration and its bookkeeping row commit together:
158 * - `"transaction"` — one request wrapped in `BEGIN`/`COMMIT`
159 * (`START TRANSACTION` on MySQL).
160 * - `"atomic"` — one request the API already commits as a unit.
161 */
162 export const makeStatementExecutor = (options: {
163 dialect: MigrationDialect;
164 execute: (sql: string) => Effect.Effect<Rows, MigrationError>;
165 batch: "transaction" | "atomic";
166 }): SqlExecutor => ({
167 dialect: options.dialect,
168 query: (sql, params) => options.execute(inlineSqlParams(sql, params ?? [], options.dialect)),
169 batch: (statements) => {
170 const body = statements.map(terminated);
171 return options
172 .execute(
173 (options.batch === "transaction"
174 ? [options.dialect === "mysql" ? "START TRANSACTION;" : "BEGIN;", ...body, "COMMIT;"]
175 : body
176 ).join("\n"),
177 )
178 .pipe(Effect.asVoid);
179 },
180 });
181
182 /**
183 * Rows keyed by column name from the `columns` + `rows[].values[]` shape the
184 * GCP Data APIs return; `nullValue` cells become `null`.
185 */
186 export const rowsFromCells = (
187 columns: ReadonlyArray<{ readonly name?: string }> | undefined,
188 rows:
189 | ReadonlyArray<{
190 readonly values?: ReadonlyArray<{ readonly value?: string; readonly nullValue?: boolean }>;
191 }>
192 | undefined,
193 ): Rows => {
194 const names = (columns ?? []).map((column) => column.name ?? "");
195 return (rows ?? []).map((row) =>
196 Object.fromEntries(
197 names.map((name, index) => {
198 const cell = row.values?.[index];
199 return [name, cell?.nullValue ? null : (cell?.value ?? null)];
200 }),
201 ),
202 );
203 };
204
205 /**
206 * Retry `effect` while a just-created user or database starts accepting
207 * logins, which can take seconds. Wrap only idempotent work — a probe
208 * query or a connection that runs one — never a migration batch.
209 */
210 export const retryLogin = <A, E, R>(
211 effect: Effect.Effect<A, E, R>,
212 options?: { attempts?: number; interval?: Duration.Input },
213 ): Effect.Effect<A, E, R> =>
214 effect.pipe(
215 Effect.retry({
216 schedule: Schedule.spaced(options?.interval ?? "5 seconds"),
217 times: options?.attempts ?? 6,
218 }),
219 );
220
221 /**
222 * Run `SELECT 1` under {@link retryLogin}, then return the executor, so a
223 * login delay is retried before any migration batch runs.
224 */
225 export const probeExecutor = (executor: SqlExecutor): Effect.Effect<SqlExecutor, MigrationError> =>
226 retryLogin(executor.query("SELECT 1")).pipe(Effect.as(executor));