diff --git a/infra/relay/src/persistence/drizzleMysql.ts b/infra/relay/src/persistence/drizzleMysql.ts index 2415a1d2fe..63f6774f53 100644 --- a/infra/relay/src/persistence/drizzleMysql.ts +++ b/infra/relay/src/persistence/drizzleMysql.ts @@ -1,53 +1,134 @@ -// @effect-diagnostics anyUnknownInErrorContext:off unsafeEffectTypeAssertion:off - mirrors alchemy/Drizzle's Postgres helper, which exposes framework-owned any requirements. +// @effect-diagnostics anyUnknownInErrorContext:off unsafeEffectTypeAssertion:off preferSchemaOverJson:off globalErrorInEffectFailure:off globalErrorInEffectCatch:off - vendored alchemy code, kept verbatim; alchemy owns these idioms. +// Vendored from alchemy-run/alchemy#1063 (src/SQL/MySQL.ts + src/Drizzle/MySQL.ts, +// merge commit 5ae3df20df): Drizzle.MySQL landed upstream after alchemy +// 2.0.0-beta.67 was cut, so no published release carries it yet. Delete this +// file and import `Drizzle.MySQL` from "alchemy/Drizzle" once the workspace +// moves to a release that contains it. import * as MysqlClient from "@effect/sql-mysql2/MysqlClient"; import { makeExecutionMemo } from "alchemy/Runtime/ExecutionMemo"; import { proxyChain } from "alchemy/Util/proxy-chain"; -import type * as Cloudflare from "alchemy/Cloudflare"; import type { AnyRelations, EmptyRelations } from "drizzle-orm"; import type { EffectMysql2Database } from "drizzle-orm/effect-mysql2"; -import * as MysqlDrizzle from "drizzle-orm/effect-mysql2"; +import * as MySqlDrizzle from "drizzle-orm/effect-mysql2"; import type { EffectDrizzleMySqlConfig } from "drizzle-orm/mysql-core/effect/utils"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Redacted from "effect/Redacted"; /** - * Open a Drizzle/MySQL database from a Cloudflare Hyperdrive binding using the + * Options for the MySQL client: `@effect/sql-mysql2`'s client configuration, + * with `url` widened to also accept an Effect (e.g. a Hyperdrive connection + * string, which resolves from the Worker environment at runtime). + */ +export type MySQLConfig = Omit & { + readonly url: Redacted.Redacted | Effect.Effect, E, R>; +}; + +const isWorkerd = () => + (globalThis as { navigator?: { userAgent?: string } }).navigator?.userAgent === + "Cloudflare-Workers" || "WebSocketPair" in globalThis; + +// Query-string params are JSON-parsed into poolConfig entries (mysql2's own +// URI convention), so `mysql://...?ssl={"rejectUnauthorized":true}` works. +const parseMySQLUrl = (url: Redacted.Redacted) => + Effect.try({ + try: () => { + const u = new URL(Redacted.value(url)); + const poolConfig: Record = {}; + for (const [key, value] of u.searchParams) { + try { + poolConfig[key] = JSON.parse(value); + } catch { + poolConfig[key] = value; + } + } + const database = decodeURIComponent(u.pathname.replace(/^\//, "")); + return { + host: u.hostname, + port: u.port === "" ? 3306 : Number(u.port), + database: database === "" ? undefined : database, + username: u.username === "" ? undefined : decodeURIComponent(u.username), + password: u.password === "" ? undefined : Redacted.make(decodeURIComponent(u.password)), + poolConfig: poolConfig as MysqlClient.MysqlClientConfig["poolConfig"], + }; + }, + catch: (cause) => new Error(`SQL.MySQL: failed to parse connection url: ${cause}`), + }).pipe(Effect.orDie); + +/** + * Resolve a {@link MySQLConfig} into the `MysqlClientConfig` handed to + * `@effect/sql-mysql2`. The `url` is parsed into discrete connection fields + * (mysql2's URI code path ignores `poolConfig`), and on workerd the defaults + * flip to `poolConfig.disableEval` (no runtime codegen in the isolate) and + * `disablePreparedStatements` (Hyperdrive's MySQL proxy has no + * `COM_STMT_PREPARE`). Explicit config fields always win over parsed / + * detected values. + */ +export const resolveMySQLConfig = ( + config: MySQLConfig, +): Effect.Effect => + Effect.gen(function* () { + const { url, ...overrides } = config; + const resolved = Effect.isEffect(url) ? yield* url : url; + const parsed = yield* parseMySQLUrl(resolved); + const workerd = yield* Effect.sync(isWorkerd); + return { + ...overrides, + host: overrides.host ?? parsed.host, + port: overrides.port ?? parsed.port, + database: overrides.database ?? parsed.database, + username: overrides.username ?? parsed.username, + password: overrides.password ?? parsed.password, + poolConfig: { + ...(workerd ? { disableEval: true } : {}), + ...parsed.poolConfig, + ...overrides.poolConfig, + }, + disablePreparedStatements: overrides.disablePreparedStatements ?? workerd, + } satisfies MysqlClient.MysqlClientConfig; + }); + +/** + * Open a Drizzle/MySQL database from a connection URL using the * `drizzle-orm/effect-mysql2` integration. * - * The MySQL counterpart of `alchemy/Drizzle`'s `Postgres` helper (which alchemy - * does not ship for MySQL yet): the same deferred `proxyChain` handle over the - * drizzle database, with the pool memoized per execution scope via - * `makeExecutionMemo`, so deploy/plan-time evaluation never opens a - * connection and each Worker invocation builds at most one pool. + * ```typescript + * const conn = yield* Cloudflare.Hyperdrive.Connect(Hyperdrive); + * const db = yield* DrizzleMysql.MySQL(conn.connectionString, { relations }); * - * Connection options are Workers/Hyperdrive specific: - * - discrete host/port/user/password fields instead of a URL, because - * `MysqlClient` ignores `poolConfig` on the URL path and mysql2 needs - * `disableEval: true` to run without eval() inside Workers; - * - `disablePreparedStatements`, because Hyperdrive's MySQL proxy does not - * support `COM_STMT_PREPARE`. + * fetch: Effect.gen(function* () { + * const rows = yield* db.select().from(users); + * }); + * ``` + * + * The pool opens on the first query of an execution, is reused for every + * query in it, and closes when the event settles (see + * {@link makeExecutionMemo}); plan/deploy never connect. Workers defaults + * ({@link resolveMySQLConfig}) are overridden via `config.client`. + * + * @binding */ -export const MySql = ( - hyperdrive: Cloudflare.Hyperdrive.ConnectClient, - config?: EffectDrizzleMySqlConfig, +export const MySQL = ( + connectionString: Effect.Effect, E, R>, + config?: EffectDrizzleMySqlConfig & { + /** + * Overrides for the underlying `@effect/sql-mysql2` client — pool + * options (e.g. `poolConfig.ssl` for a direct TLS connection), + * `disablePreparedStatements`, `maxConnections`, and friends. + */ + readonly client?: Omit; + }, ) => Effect.map( makeExecutionMemo( Effect.gen(function* () { + const { client, ...drizzleConfig } = config ?? {}; const mysqlCtx = yield* Layer.build( - MysqlClient.layer({ - host: yield* hyperdrive.host, - port: yield* hyperdrive.port, - database: yield* hyperdrive.database, - username: yield* hyperdrive.user, - password: yield* hyperdrive.password, - disablePreparedStatements: true, - poolConfig: { - disableEval: true, - }, - }), + MysqlClient.layer(yield* resolveMySQLConfig({ ...client, url: connectionString })), ); - return yield* MysqlDrizzle.makeWithDefaults(config).pipe(Effect.provideContext(mysqlCtx)); + return yield* MySqlDrizzle.makeWithDefaults( + drizzleConfig as EffectDrizzleMySqlConfig, + ).pipe(Effect.provideContext(mysqlCtx)); }), ), (db) => diff --git a/infra/relay/src/worker.ts b/infra/relay/src/worker.ts index df2288dec0..33ca75c5b7 100644 --- a/infra/relay/src/worker.ts +++ b/infra/relay/src/worker.ts @@ -143,7 +143,7 @@ export const ApiLive = Api.make( const cloudMintPrivateKey = yield* cloudMintKeyPair.privateKey; const cloudMintPublicKey = yield* cloudMintKeyPair.publicKey; const hyperdrive = yield* Cloudflare.Hyperdrive.Connect(yield* RelayDb.RelayHyperdrive); - const db = yield* DrizzleMysql.MySql(hyperdrive); + const db = yield* DrizzleMysql.MySQL(hyperdrive.connectionString); const managedEndpointTunnelBinding = yield* Cloudflare.Tunnel.ReadWriteTunnel(); // Keep Worker custom-domain reconciliation ordered after API zone provisioning.