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

main
ts 157 lines 5.86 KB
Raw
1 import * as MysqlClient from "@effect/sql-mysql2/MysqlClient";
2 import { makeExecutionMemo } from "alchemy/Runtime/ExecutionMemo";
3 import { proxyChain } from "alchemy/Util/proxy-chain";
4 import * as Context from "effect/Context";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as Layer from "effect/Layer";
8 import * as Redacted from "effect/Redacted";
9 import * as Sql from "effect/sql/SqlClient";
10 import type * as Mysql from "mysql2";
11
12 /**
13 * Options for {@link MySQL}: `@effect/sql-mysql2`'s client configuration,
14 * with `url` widened to also accept an Effect (e.g. a Hyperdrive connection
15 * string, which resolves from the Worker environment at runtime).
16 */
17 export type MySQLConfig<E = never, R = never> = Omit<MysqlClient.MysqlClientConfig, "url"> & {
18 readonly url: Redacted.Redacted<string> | Effect.Effect<Redacted.Redacted<string>, E, R>;
19 };
20
21 const isWorkerd = () =>
22 (globalThis as { navigator?: { userAgent?: string } }).navigator?.userAgent ===
23 "Cloudflare-Workers" || "WebSocketPair" in globalThis;
24
25 /** A MySQL connection url that could not be parsed. */
26 export class MySQLUrlError extends Data.TaggedError("MySQLUrlError")<{
27 readonly message: string;
28 readonly cause?: unknown;
29 }> {}
30
31 // Query-string params are JSON-parsed into poolConfig entries (mysql2's own
32 // URI convention), so `mysql://...?ssl={"rejectUnauthorized":true}` works.
33 const parseMySQLUrl = (url: Redacted.Redacted<string>) =>
34 Effect.try({
35 try: () => {
36 const u = new URL(Redacted.value(url));
37 const poolConfig: Record<string, unknown> = {};
38 for (const [key, value] of u.searchParams) {
39 try {
40 poolConfig[key] = JSON.parse(value);
41 } catch {
42 poolConfig[key] = value;
43 }
44 }
45 const database = decodeURIComponent(u.pathname.replace(/^\//, ""));
46 return {
47 host: u.hostname,
48 port: u.port === "" ? 3306 : Number(u.port),
49 database: database === "" ? undefined : database,
50 username: u.username === "" ? undefined : decodeURIComponent(u.username),
51 password: u.password === "" ? undefined : Redacted.make(decodeURIComponent(u.password)),
52 poolConfig: poolConfig as Mysql.PoolOptions,
53 };
54 },
55 catch: (cause) =>
56 new MySQLUrlError({
57 message: `SQL.MySQL: failed to parse connection url: ${cause instanceof Error ? cause.message : String(cause)}`,
58 cause,
59 }),
60 }).pipe(Effect.orDie);
61
62 /**
63 * Resolve a {@link MySQLConfig} into the `MysqlClientConfig` handed to
64 * `@effect/sql-mysql2`. The `url` is parsed into discrete connection fields
65 * (mysql2's URI code path ignores `poolConfig`), and on workerd the defaults
66 * flip to `poolConfig.disableEval` (no runtime codegen in the isolate) and
67 * `disablePreparedStatements` (Hyperdrive's MySQL proxy has no
68 * `COM_STMT_PREPARE`). Explicit config fields always win over parsed /
69 * detected values.
70 */
71 export const resolveMySQLConfig = <E = never, R = never>(
72 config: MySQLConfig<E, R>,
73 ): Effect.Effect<MysqlClient.MysqlClientConfig, E, R> =>
74 Effect.gen(function* () {
75 const { url, ...overrides } = config;
76 const resolved = Effect.isEffect(url) ? yield* url : url;
77 const parsed = yield* parseMySQLUrl(resolved);
78 const workerd = yield* Effect.sync(isWorkerd);
79 return {
80 ...overrides,
81 host: overrides.host ?? parsed.host,
82 port: overrides.port ?? parsed.port,
83 database: overrides.database ?? parsed.database,
84 username: overrides.username ?? parsed.username,
85 password: overrides.password ?? parsed.password,
86 poolConfig: {
87 ...(workerd ? { disableEval: true } : {}),
88 ...parsed.poolConfig,
89 ...overrides.poolConfig,
90 },
91 disablePreparedStatements: overrides.disablePreparedStatements ?? workerd,
92 } satisfies MysqlClient.MysqlClientConfig;
93 });
94
95 /**
96 * Open an `@effect/sql-mysql2` client (a connection pool) from a connection
97 * URL — a plain `Redacted` or an Effect of one, e.g. Hyperdrive's
98 * `connectionString`:
99 *
100 * ```typescript
101 * import * as SQL from "@alchemy.run/sql/MySQL";
102 *
103 * const hd = yield* Cloudflare.Hyperdrive.Connect(Hyperdrive);
104 * const sql = yield* SQL.MySQL({ url: hd.connectionString });
105 *
106 * fetch: Effect.gen(function* () {
107 * const users = yield* sql`SELECT * FROM users`;
108 * });
109 * ```
110 *
111 * The pool opens on the first query of an execution, is reused for every
112 * query in it, and closes when the event settles (see
113 * {@link makeExecutionMemo}); plan/deploy never connect. Workers defaults
114 * ({@link resolveMySQLConfig}) are overridden in the config:
115 *
116 * ```typescript
117 * const sql = yield* SQL.MySQL({
118 * url,
119 * disablePreparedStatements: true,
120 * poolConfig: { ssl: { rejectUnauthorized: true } },
121 * });
122 * ```
123 *
124 * @binding
125 */
126 export const MySQL = <E = never, R = never>(config: MySQLConfig<E, R>) =>
127 Effect.map(
128 makeExecutionMemo(
129 Effect.gen(function* () {
130 const resolved = yield* resolveMySQLConfig(config);
131 const mysqlCtx = yield* Layer.build(MysqlClient.layer(resolved));
132 return Context.get(mysqlCtx, MysqlClient.MysqlClient);
133 }),
134 ),
135 (client) => proxyChain<MysqlClient.MysqlClient>(client),
136 );
137
138 /**
139 * Provide an `@effect/sql-mysql2` client as the `MysqlClient` and generic
140 * `SqlClient` services:
141 *
142 * ```typescript
143 * const hd = yield* Cloudflare.Hyperdrive.Connect(Hyperdrive);
144 * const app = yield* makeApp.pipe(
145 * Effect.provide(SQL.MySQLLayer({ url: hd.connectionString })),
146 * );
147 * ```
148 *
149 * The layer itself builds synchronously at init; the underlying pool is
150 * created lazily per execution (see {@link MySQL}).
151 */
152 export const MySQLLayer = <E = never, R = never>(config: MySQLConfig<E, R>) =>
153 // Derive SqlClient from the single MysqlClient build so both tags share
154 // one per-execution pool.
155 Layer.effect(Sql.SqlClient, MysqlClient.MysqlClient).pipe(
156 Layer.provideMerge(Layer.effect(MysqlClient.MysqlClient, MySQL(config))),
157 );