diff --git a/.github/workflows/changelog.yml b/.github/workflows/changelog.yml index d1419e6..362b4cb 100644 --- a/.github/workflows/changelog.yml +++ b/.github/workflows/changelog.yml @@ -3,7 +3,7 @@ name: changelog on: pull_request: - branches: [main] + branches: [main, feat/d1-store] types: [opened, synchronize, reopened, labeled, unlabeled] permissions: diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fb471b1..2ea483c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,10 +2,10 @@ name: CI and documentation on: pull_request: - branches: [main] + branches: [main, feat/d1-store] types: [opened, synchronize, reopened, edited, ready_for_review] push: - branches: [main] + branches: [main, feat/d1-store] workflow_dispatch: permissions: diff --git a/package-lock.json b/package-lock.json index f405f12..cacc611 100644 --- a/package-lock.json +++ b/package-lock.json @@ -963,19 +963,6 @@ "effect": "^3.22.1" } }, - "node_modules/@effect/sql-mysql2": { - "version": "0.53.0", - "license": "MIT", - "dependencies": { - "mysql2": "^3.11.0" - }, - "peerDependencies": { - "@effect/experimental": "^0.61.0", - "@effect/platform": "^0.97.0", - "@effect/sql": "^0.52.0", - "effect": "^3.22.0" - } - }, "node_modules/@effect/vitest": { "version": "0.30.0", "dev": true, @@ -4634,6 +4621,7 @@ }, "node_modules/@types/node": { "version": "24.19.0", + "devOptional": true, "license": "MIT", "dependencies": { "undici-types": ">=7.24.0 <7.24.7" @@ -5247,6 +5235,7 @@ }, "node_modules/aws-ssl-profiles": { "version": "1.1.2", + "devOptional": true, "license": "MIT", "engines": { "node": ">= 6.0.0" @@ -6239,6 +6228,7 @@ }, "node_modules/generate-function": { "version": "2.3.1", + "devOptional": true, "license": "MIT", "dependencies": { "is-property": "^1.0.2" @@ -6532,6 +6522,7 @@ }, "node_modules/is-property": { "version": "1.0.2", + "devOptional": true, "license": "MIT" }, "node_modules/is-unsafe": { @@ -6931,6 +6922,7 @@ }, "node_modules/long": { "version": "5.3.2", + "devOptional": true, "license": "Apache-2.0" }, "node_modules/loupe": { @@ -6948,6 +6940,7 @@ }, "node_modules/lru.min": { "version": "1.1.5", + "devOptional": true, "license": "MIT", "engines": { "bun": ">=1.0.0", @@ -7125,6 +7118,7 @@ "version": "3.24.4", "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.24.4.tgz", "integrity": "sha512-A2olluVlj0mvgyIRRISMEzXc51m+21mRtcMVjJyIpt2GG98+XrC9m9HzsqcMsX2LcnfccJvY5NB22g8fENBnOA==", + "devOptional": true, "license": "MIT", "dependencies": { "aws-ssl-profiles": "^1.1.2", @@ -7144,6 +7138,7 @@ }, "node_modules/named-placeholders": { "version": "1.1.6", + "devOptional": true, "license": "MIT", "dependencies": { "lru.min": "^1.1.0" @@ -8033,6 +8028,7 @@ }, "node_modules/sql-escaper": { "version": "1.5.2", + "devOptional": true, "license": "MIT", "engines": { "bun": ">=1.0.0", @@ -8304,6 +8300,7 @@ }, "node_modules/undici-types": { "version": "7.24.6", + "devOptional": true, "license": "MIT" }, "node_modules/unenv": { @@ -9353,7 +9350,6 @@ "@effect/platform": "0.97.2", "@effect/platform-node": "0.108.2", "@effect/sql": "0.52.1", - "@effect/sql-mysql2": "0.53.0", "@modelcontextprotocol/sdk": "^1.31.0", "@sanctum/contracts": "*", "@sanctum/sdk": "*", @@ -9361,7 +9357,6 @@ "better-auth": "1.7.7", "effect": "3.22.2", "jose": "^6.2.12", - "mysql2": "3.24.4", "openid-client": "6.8.8" }, "devDependencies": { diff --git a/server/package.json b/server/package.json index 4c305e9..db98581 100644 --- a/server/package.json +++ b/server/package.json @@ -23,7 +23,6 @@ "@effect/platform": "0.97.2", "@effect/platform-node": "0.108.2", "@effect/sql": "0.52.1", - "@effect/sql-mysql2": "0.53.0", "@modelcontextprotocol/sdk": "^1.31.0", "@sanctum/contracts": "*", "@sanctum/sdk": "*", @@ -31,7 +30,6 @@ "better-auth": "1.7.7", "effect": "3.22.2", "jose": "^6.2.12", - "mysql2": "3.24.4", "openid-client": "6.8.8" }, "devDependencies": { diff --git a/server/src/config.ts b/server/src/config.ts index 848274a..cfa4ad0 100644 --- a/server/src/config.ts +++ b/server/src/config.ts @@ -2,7 +2,7 @@ * Process configuration and the plan section 02 engineering defaults. * Defaults are acceptance-test inputs and calibration starting points, not measured optima. */ -import { Config, Effect, Option, Redacted, Schema } from 'effect'; +import { Config, Effect, Option, Schema } from 'effect'; import { AccessScopeName, type JobKind, Unavailable } from '@sanctum/contracts'; /** Plan section 02 "Recommended engineering defaults"; change here, never as scattered literals. */ @@ -159,16 +159,9 @@ export const serverConfig = Config.all({ seatLimit: defaultSeatLimit, workspacePurgeGraceDays, apiPort: port('API_PORT', 7102), - mysql: Config.all({ - host: Config.string('MYSQL_HOST').pipe(Config.withDefault('127.0.0.1')), - port: port('MYSQL_PORT', 3306), - database: Config.string('MYSQL_DATABASE').pipe(Config.withDefault('sanctum')), - username: Config.string('MYSQL_USER').pipe(Config.withDefault('sanctum')), - password: Config.redacted('MYSQL_PASSWORD').pipe(Config.withDefault(Redacted.make(''))), - maxConnections: Config.integer('MYSQL_POOL_SIZE').pipe(Config.withDefault(10)), - queueLimit: Config.integer('MYSQL_POOL_QUEUE').pipe(Config.withDefault(100)), - /** PEM CA certificate; when set, connections require TLS verified against it, host name included. */ - caCert: Config.option(Config.string('MYSQL_CA_CERT')).pipe(Config.map(Option.getOrUndefined)), + /** `file:`, `:memory:`, or the D1 gateway `http://d1.internal`. */ + db: Config.all({ + url: Config.string('SANCTUM_DB_URL').pipe(Config.withDefault('file:./sanctum.db')), }), /** Decisions an operator has explicitly selected and configured, comma-separated. */ selectedDecisions: Config.array(Config.literal(...activationDecisions)(), 'SANCTUM_SELECTED_DECISIONS').pipe(Config.withDefault(noDecisions)), diff --git a/server/src/db-d1.ts b/server/src/db-d1.ts new file mode 100644 index 0000000..faa394d --- /dev/null +++ b/server/src/db-d1.ts @@ -0,0 +1,40 @@ +/** + * D1 backend: HTTP to the gateway Worker (`deploy/cloudflare/src/d1-gate.ts`) that the container reaches at + * `http://d1.internal`. Bytes travel as `{"$b":""}` in both directions. + */ +import { SqlError } from '@effect/sql'; +import { Effect } from 'effect'; +import type { DbBackend, DbResult, DbStatement } from './db-types.ts'; + +const encode = (value: unknown): unknown => { + if (value instanceof Uint8Array) return { $b: Buffer.from(value).toString('base64') }; + if (typeof value === 'boolean') return Number(value); + return value === undefined ? null : value; +}; + +const decode = (value: unknown): unknown => + typeof value === 'object' && value !== null && '$b' in value && typeof value.$b === 'string' ? new Uint8Array(Buffer.from(value.$b, 'base64')) : value; + +const decodeResult = (result: DbResult): DbResult => ({ + changes: result.changes, + rows: result.rows.map(row => Object.fromEntries(Object.entries(row).map(([column, value]) => [column, decode(value)]))), +}); + +const toBody = ({ sql, params }: DbStatement) => ({ sql, params: params.map(encode) }); + +export const d1Backend = (baseUrl: string): DbBackend => { + const post = (path: string, body: unknown) => + Effect.tryPromise({ + try: async signal => { + const response = await fetch(new URL(path, baseUrl), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), signal }); + const payload = (await response.json()) as A & { readonly error?: string }; + if (!response.ok) throw new Error(payload.error ?? `D1 gateway answered ${response.status}`); + return payload; + }, + catch: cause => new SqlError.SqlError({ cause, message: cause instanceof Error ? cause.message : String(cause) }), + }); + return { + run: statement => Effect.map(post('/run', toBody(statement)), decodeResult), + batch: statements => Effect.map(post<{ readonly results: ReadonlyArray }>('/batch', { statements: statements.map(toBody) }), payload => payload.results.map(decodeResult)), + }; +}; diff --git a/server/src/db-sqlite.ts b/server/src/db-sqlite.ts new file mode 100644 index 0000000..e7a623d --- /dev/null +++ b/server/src/db-sqlite.ts @@ -0,0 +1,51 @@ +/** `node:sqlite` backend for local runs, CI and compose: one synchronous connection, so each statement and batch is atomic. */ +import { DatabaseSync, type SQLInputValue } from 'node:sqlite'; +import { SqlError } from '@effect/sql'; +import { Effect, type Scope } from 'effect'; +import type { DbBackend, DbResult, DbStatement } from './db-types.ts'; + +const sqlError = (cause: unknown) => new SqlError.SqlError({ cause, message: cause instanceof Error ? cause.message : String(cause) }); + +const bind = (params: ReadonlyArray) => params.map(value => (typeof value === 'boolean' ? Number(value) : value === undefined ? null : value) as SQLInputValue); + +const execute = (database: DatabaseSync, { sql, params }: DbStatement): DbResult => { + const statement = database.prepare(sql); + if (statement.columns().length > 0) { + const rows = statement.all(...bind(params)) as Array>; + return { rows, changes: rows.length }; + } + return { rows: [], changes: Number(statement.run(...bind(params)).changes) }; +}; + +/** `path` is `:memory:`, `file:`, a bare path, or a `file:` URI with a query (`file:name?mode=memory&cache=shared` shares one memory database between connections). */ +export const sqliteBackend = (path: string): Effect.Effect => + Effect.acquireRelease( + Effect.try({ + try: () => { + const database = new DatabaseSync(path.includes('?') ? path : path.replace(/^file:/, '')); + database.exec('PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000; PRAGMA journal_mode = WAL'); + return database; + }, + catch: sqlError, + }), + database => Effect.sync(() => database.close()), + ).pipe( + Effect.map((database): DbBackend => ({ + run: statement => Effect.try({ try: () => execute(database, statement), catch: sqlError }), + batch: statements => + Effect.try({ + try: () => { + database.exec('BEGIN IMMEDIATE'); + try { + const results = statements.map(statement => execute(database, statement)); + database.exec('COMMIT'); + return results; + } catch (error) { + database.exec('ROLLBACK'); + throw error; + } + }, + catch: sqlError, + }), + })), + ); diff --git a/server/src/db-types.ts b/server/src/db-types.ts new file mode 100644 index 0000000..a130f16 --- /dev/null +++ b/server/src/db-types.ts @@ -0,0 +1,12 @@ +import type { Effect } from 'effect'; +import type { SqlError } from '@effect/sql'; + +/** `SANCTUM_DB_URL`: `file:`, `:memory:`, or the D1 gateway `http://d1.internal`. */ +export interface DbOptions { readonly url: string } +export interface DbStatement { readonly sql: string; readonly params: ReadonlyArray } +export interface DbResult { readonly rows: ReadonlyArray>; readonly changes: number } +export interface DbBackend { + readonly run: (statement: DbStatement) => Effect.Effect; + /** All statements commit together or none does. */ + readonly batch: (statements: ReadonlyArray) => Effect.Effect, SqlError.SqlError>; +} diff --git a/server/src/db.ts b/server/src/db.ts index f4739ed..48b1025 100644 --- a/server/src/db.ts +++ b/server/src/db.ts @@ -1,168 +1,127 @@ /** - * The one MySQL boundary (plan section 07): bounded pool, UTC sessions, and column schemas - * that turn mysql2 row values into wire-ready values. Domain code decodes rows with - * `SqlSchema` from `@effect/sql` using these column schemas; nothing else touches raw rows. + * The one database boundary (plan section 07): a SQLite-dialect `SqlClient` over a pluggable + * backend (`node:sqlite` file or memory, or the D1 gateway), buffered transactions with a commit + * guard, and column schemas that turn row values into wire-ready values. Domain code decodes + * rows with `SqlSchema` from `@effect/sql` using these column schemas; nothing else touches raw rows. + * + * D1 cannot hold a transaction open between requests, so a transaction reads at once, buffers its + * writes and commits them in one atomic batch behind a guard on `tx_clock`. A transaction that + * lost the race is rerun, so its body must not have external side effects. */ import * as Reactivity from '@effect/experimental/Reactivity'; -import { MysqlClient } from '@effect/sql-mysql2'; -import { SqlClient, type SqlConnection, SqlError } from '@effect/sql'; -import { Context, Effect, Exit, Fiber, Layer, ParseResult, type Redacted, Schema, Scope, Stream } from 'effect'; -import { Sha256Hex, UtcTimestamp, Unavailable, type WorkspaceId } from '@sanctum/contracts'; - -/** Connection settings; config.ts reads them from the environment. */ -export interface MysqlOptions { - readonly host: string; - readonly port: number; - readonly database: string; - readonly username: string; - readonly password: Redacted.Redacted; - readonly maxConnections: number; - readonly queueLimit: number; - /** PEM CA certificate; when set, TLS is required and verified, including the server host name. */ - readonly caCert?: string | undefined; -} +import { SqlClient, type SqlConnection, SqlError, Statement } from '@effect/sql'; +import { Context, Effect, Layer, Option, ParseResult, Schedule, Schema, Stream } from 'effect'; +import { Sha256Hex, UtcTimestamp, type WorkspaceId } from '@sanctum/contracts'; +import { d1Backend } from './db-d1.ts'; +import type { DbBackend, DbOptions, DbResult, DbStatement } from './db-types.ts'; +import { sqliteBackend } from './db-sqlite.ts'; -/** - * Pool options: DATETIME(6) and BIGINT/DECIMAL arrive as strings (no millisecond Date or - * rounded Number), connection waits are gated and bounded in `gatedClient`; without `caCert` - * the connection is unencrypted (local and test servers). - */ -const pooledClient = (mysql: MysqlOptions) => - MysqlClient.layer({ - host: mysql.host, - port: mysql.port, - database: mysql.database, - username: mysql.username, - password: mysql.password, - maxConnections: mysql.maxConnections, - poolConfig: { - charset: 'utf8mb4_0900_ai_ci', - timezone: 'Z', - dateStrings: true, - supportBigNumbers: true, - bigNumberStrings: true, - decimalNumbers: false, - waitForConnections: true, - queueLimit: mysql.queueLimit, - connectTimeout: 10_000, - enableKeepAlive: true, - ...(mysql.caCert === undefined ? {} : { ssl: { ca: mysql.caCert, verifyIdentity: true } }), - }, - }); +export type { DbBackend, DbOptions, DbResult, DbStatement } from './db-types.ts'; -/** - * mysql2 cannot run per-connection init SQL through the Effect client, so the server (or its - * host) must run in UTC; refuse to start otherwise. SQL uses UTC_TIMESTAMP(6), never NOW(). - */ -export const verifyUtcSession = Effect.gen(function*() { - const sql = yield* SqlClient.SqlClient; - const [row] = yield* sql<{ tz: string; system_tz: string }>`SELECT @@session.time_zone AS tz, @@system_time_zone AS system_tz`; - const utc = row?.tz === '+00:00' || row?.tz === 'UTC' || (row?.tz === 'SYSTEM' && row.system_tz === 'UTC'); - if (!utc) { - return yield* new Unavailable({ message: `MySQL session time zone must be UTC, got ${row?.tz}/${row?.system_tz}`, retryable: false }); - } -}); +const fail = (message: string) => new SqlError.SqlError({ cause: new Error(message), message }); +const messageOf = (error: SqlError.SqlError) => { + const cause: unknown = error.cause; + return cause instanceof Error ? cause.message : String(cause ?? error.message); +}; -/** - * TiDB speaks the MySQL protocol but has no `MATCH ... AGAINST`, FULLTEXT indexes or stored generated columns added by - * ALTER. Set once per process by `dbLayer`; search and migrations take their TiDB path when it is false. - */ -let fullTextAvailable = true; -export const hasFullText = () => fullTextAvailable; -const detectDialect = Effect.gen(function*() { - const sql = yield* SqlClient.SqlClient; - const [row] = yield* sql<{ version: string }>`SELECT VERSION() AS version`; - fullTextAvailable = !/tidb/i.test(row?.version ?? ''); -}); +/** The commit guard failed: another transaction committed after this one began. */ +const CONFLICT = /CHECK constraint failed: (tx_conflict_guard|v IS NULL)/; +const isConflict = (error: unknown) => error instanceof SqlError.SqlError && CONFLICT.test(messageOf(error)); -/** TiDB lacks the MySQL 8.0.19 row alias (`VALUES (...) AS new ON DUPLICATE KEY UPDATE x = new.x`); `VALUES(x)` means the same there. */ -const forDialect = (text: string) => - fullTextAvailable ? text : text.replace(/\)\s*AS\s+(\w+)\s+ON DUPLICATE KEY UPDATE([\s\S]*)$/i, (_all, alias: string, update: string) => - `) ON DUPLICATE KEY UPDATE${update.replace(new RegExp(`\\b${alias}\\.(\`?\\w+\`?)`, 'g'), 'VALUES($1)')}`); - -const translated = (c: SqlConnection.Connection): SqlConnection.Connection => ({ - execute: (sql, params, transform) => c.execute(forDialect(sql), params, transform), - executeRaw: (sql, params) => c.executeRaw(forDialect(sql), params), - executeValues: (sql, params) => c.executeValues(forDialect(sql), params), - executeUnprepared: (sql, params, transform) => c.executeUnprepared(forDialect(sql), params, transform), - executeStream: (sql, params, transform) => c.executeStream(forDialect(sql), params, transform), -}); +export const isDuplicate = (error: SqlError.SqlError) => /UNIQUE constraint failed/.test(messageOf(error)); +export const isMissingReference = (error: SqlError.SqlError) => /FOREIGN KEY constraint failed/.test(messageOf(error)); +export const isCheckViolation = (error: SqlError.SqlError) => /CHECK constraint failed/.test(messageOf(error)) && !CONFLICT.test(messageOf(error)); -/** - * The pool cannot drop a waiter: mysql2 keeps the queued callback of a cancelled request, and - * @effect/sql-mysql2 then still dispatches that request's statement once a connection frees. - * Waiting therefore happens here, in a FIFO semaphore whose waiters leave when interrupted; - * a statement or transaction asks the pool for a connection only while holding one of its - * `maxConnections` permits, so the pool's own queue never forms. A statement already dispatched - * is not cancelled: MySQL runs it to completion and keeps its permit and connection until then. - * As in mysql2, more than `queueLimit` waiters are refused (0 is unbounded). - */ -const gatedClient = (mysql: MysqlOptions) => - Layer.scopedContext( - Effect.gen(function* () { - const pooled = yield* MysqlClient.MysqlClient; - const permits = yield* Effect.makeSemaphore(mysql.maxConnections); - let busy = 0; - let waiting = 0; - const giveBack = Effect.suspend(() => { - busy--; - return permits.release(1); +/** Statements that return rows run at once; every other statement waits for the commit. */ +const isRead = (sql: string) => /^\s*(select|pragma|explain)\b/i.test(sql); + +interface TransactionState { + readonly backend: DbBackend; + readonly clock: number; + readonly buffer: DbStatement[]; + /** Counters this transaction already advanced, so a second `increment` reads no buffered write. */ + readonly counters: Map; +} +const states = new WeakMap(); + +const asRows = (result: DbResult, transform: Parameters[2]) => (transform ? transform(result.rows as Array) : result.rows); + +/** Reads go to the backend; writes join the buffer. */ +const transactionConnection = (backend: DbBackend, state: TransactionState): SqlConnection.Connection => { + const execute = (sql: string, params: ReadonlyArray): Effect.Effect => { + if (!isRead(sql)) { + state.buffer.push({ sql, params }); + return Effect.succeed({ rows: [], changes: 0 }); + } + if (state.buffer.length > 0) return Effect.fail(fail(`Read after a buffered write in a transaction: ${sql}`)); + return backend.run({ sql, params }); + }; + return connection(execute); +}; + +const connection = (execute: (sql: string, params: ReadonlyArray) => Effect.Effect): SqlConnection.Connection => { + const rows = (sql: string, params: ReadonlyArray, transform: Parameters[2]) => Effect.map(execute(sql, params), result => asRows(result, transform)); + return { + execute: rows, + executeUnprepared: rows, + executeRaw: execute, + executeValues: (sql, params) => Effect.map(execute(sql, params), result => result.rows.map(row => Object.values(row))), + executeStream: (sql, params, transform) => Stream.unwrap(Effect.map(rows(sql, params, transform), Stream.fromIterable)), + }; +}; + +const makeClient = (backend: DbBackend) => + Effect.gen(function* () { + const client = yield* SqlClient.make({ + acquirer: Effect.succeed(connection((sql, params) => backend.run({ sql, params }))), + compiler: Statement.makeCompilerSqlite(), + spanAttributes: [['db.system.name', 'sqlite']], + }); + const attempt = (effect: Effect.Effect) => + Effect.gen(function* () { + const [clock] = (yield* backend.run({ sql: 'SELECT v FROM tx_clock WHERE id = 1', params: [] })).rows; + const state: TransactionState = { backend, clock: Number(clock?.['v']), buffer: [], counters: new Map() }; + const scoped = transactionConnection(backend, state); + states.set(scoped, state); + const result = yield* Effect.provideService(effect, SqlClient.TransactionConnection, [scoped, 0] as const); + if (state.buffer.length > 0) { + yield* backend.batch([ + { sql: 'INSERT INTO tx_conflict (v) SELECT 1 WHERE (SELECT v FROM tx_clock WHERE id = 1) <> ?', params: [state.clock] }, + { sql: 'UPDATE tx_clock SET v = v + 1 WHERE id = 1', params: [] }, + ...state.buffer, + ]); + } + return result; }); - // Waiting is interruptible only where the caller is: a cleanup write of an interrupted fiber still waits its turn. - const reserveRaw = Effect.uninterruptibleMask(restore => - Effect.suspend(() => { - if (busy >= mysql.maxConnections && mysql.queueLimit > 0 && waiting >= mysql.queueLimit) return Effect.fail(new SqlError.SqlError({ cause: new Error('Queue limit reached.'), message: 'Failed to acquire connection' })); - waiting++; - return restore(permits.take(1)).pipe(Effect.onExit(exit => Effect.sync(() => { waiting--; if (Exit.isSuccess(exit)) busy++; }))); - }).pipe( - // A failed acquisition leaves no finalizer behind and its scope may never close, so the permit goes back here. - Effect.zipRight(Effect.onError(pooled.reserve, () => giveBack)), - Effect.tap(() => Effect.addFinalizer(() => giveBack)), - ), + const withTransaction = (effect: Effect.Effect): Effect.Effect => + Effect.flatMap(Effect.serviceOption(SqlClient.TransactionConnection), nested => + // shortcut: a nested transaction joins its parent and cannot roll back alone; upgrade when a caller needs savepoints. + Option.isSome(nested) + ? effect + : Effect.retry(attempt(effect), { schedule: Schedule.jittered(Schedule.exponential('10 millis')), times: 4, while: isConflict }), ); - const reserve = Effect.map(reserveRaw, translated); - // An interrupted statement is not aborted: MySQL still runs it on its connection, which must not be handed out before it - // answers. A daemon therefore owns the permit and connection until then, while the caller may leave at once. - const held = (use: (connection: SqlConnection.Connection) => Effect.Effect) => - Effect.uninterruptibleMask(restore => - Effect.flatMap(Scope.make(), scope => - restore(Scope.extend(reserve, scope)).pipe( - Effect.onError(cause => Scope.close(scope, Exit.failCause(cause))), - Effect.flatMap(connection => Effect.forkDaemon(Effect.onExit(use(connection), exit => Scope.close(scope, exit)))), - Effect.flatMap(statement => restore(Fiber.join(statement))), - ), - ), - ); - const statements: SqlConnection.Connection = { - execute: (sql, params, transform) => held(c => c.execute(sql, params, transform)), - executeRaw: (sql, params) => held(c => c.executeRaw(sql, params)), - executeValues: (sql, params) => held(c => c.executeValues(sql, params)), - executeUnprepared: (sql, params, transform) => held(c => c.executeUnprepared(sql, params, transform)), - executeStream: (sql, params, transform) => Stream.unwrapScoped(Effect.map(reserve, c => c.executeStream(sql, params, transform))), - }; - const client = yield* SqlClient.make({ - acquirer: Effect.succeed(statements), - transactionAcquirer: reserve, - compiler: MysqlClient.makeCompiler(), - spanAttributes: [['db.system.name', 'mysql']], - }); - return Context.make(SqlClient.SqlClient, client); - }), - ).pipe(Layer.provide(Reactivity.layer), Layer.provide(pooledClient(mysql))); + return Object.assign(client, { withTransaction }); + }).pipe(Effect.provide(Reactivity.layer)); -/** Pool plus the UTC precondition; API and worker each build their own process-scoped layer. */ -export const dbLayer = (mysql: MysqlOptions) => Layer.effectDiscard(Effect.zipRight(verifyUtcSession, detectDialect)).pipe(Layer.provideMerge(gatedClient(mysql))); +/** The backend named by `options.url`; API and worker each build their own process-scoped layer. */ +export const dbLayer = (options: DbOptions): Layer.Layer => + Layer.scopedContext( + Effect.gen(function* () { + const backend = /^https?:\/\//.test(options.url) ? d1Backend(options.url) : yield* sqliteBackend(options.url); + return Context.make(SqlClient.SqlClient, yield* makeClient(backend)); + }), + ); -const MYSQL_DATETIME = /^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?)$/; +const DB_DATETIME = /^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?)$/; -/** DATETIME(6) string `2026-09-26 17:08:16.123456` <-> UTC wire timestamp, preserving microseconds. */ -export const DbUtc = Schema.transform(Schema.String.pipe(Schema.pattern(MYSQL_DATETIME)), UtcTimestamp, { +/** DATETIME text `2026-09-26 17:08:16.123456` <-> UTC wire timestamp, preserving microseconds. */ +export const DbUtc = Schema.transform(Schema.String.pipe(Schema.pattern(DB_DATETIME)), UtcTimestamp, { strict: true, - decode: value => value.replace(MYSQL_DATETIME, '$1T$2Z'), + decode: value => value.replace(DB_DATETIME, '$1T$2Z'), encode: value => value.slice(0, -1).replace('T', ' '), }); -/** BIGINT/DECIMAL string (or small number) -> exact safe integer; unsafe values fail instead of rounding. */ +/** INTEGER (or its string form) -> exact safe integer; unsafe values fail instead of rounding. */ export const DbSafeInt = Schema.transformOrFail(Schema.Union(Schema.String, Schema.Number), Schema.Number, { strict: true, decode: (value, _, ast) => { @@ -172,43 +131,50 @@ export const DbSafeInt = Schema.transformOrFail(Schema.Union(Schema.String, Sche encode: value => ParseResult.succeed(value), }); -/** TINYINT(1)/BOOLEAN -> boolean. */ +/** 0/1 integer -> boolean. */ export const DbBool = Schema.transform(Schema.Literal(0, 1), Schema.Boolean, { strict: true, decode: value => value === 1, encode: value => (value ? 1 : 0), }); -/** Native JSON column: mysql2 returns parsed values; parameters are sent as JSON text. */ +/** JSON column stored as TEXT: rows return JSON text; parameters are sent as JSON text. */ export const DbJson = (schema: Schema.Schema) => Schema.Union(Schema.parseJson(schema), schema); -/** BINARY(32) SHA-256 <-> lowercase hex. */ +/** BLOB SHA-256 <-> lowercase hex. */ export const DbSha256 = Schema.transform(Schema.Uint8ArrayFromSelf, Sha256Hex, { strict: true, decode: bytes => Buffer.from(bytes).toString('hex'), encode: hex => Buffer.from(hex, 'hex'), }); -/** MySQL server error number of a failed statement, e.g. 1062 duplicate key, 1452 foreign key. */ -export const mysqlErrno = (error: SqlError.SqlError): number | undefined => { - const cause: unknown = error.cause; - return typeof cause === 'object' && cause !== null && 'errno' in cause && typeof cause.errno === 'number' ? cause.errno : undefined; -}; - -export const ER_DUP_ENTRY = 1062; -export const ER_NO_REFERENCED_ROW = 1452; -export const ER_CHECK_CONSTRAINT_VIOLATED = 3819; - /** - * `LAST_INSERT_ID(expr)` makes the increment and its read one statement; the row lock it takes - * lasts until the caller's transaction commits, which serializes allocation per workspace. + * Advances a workspace counter and returns the new value. Outside a transaction one + * `UPDATE ... RETURNING` does it; inside, the read happens now and the write joins the commit, + * whose guard makes the read-then-write safe. */ export const increment = (column: 'context_seq' | 'permission_revision') => (workspace_id: WorkspaceId) => Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; - const result = (yield* sql`UPDATE workspaces SET ${sql(column)} = LAST_INSERT_ID(${sql(column)} + 1) WHERE id = ${workspace_id}`.raw) as { readonly affectedRows: number; readonly insertId: number | string }; - if (result.affectedRows !== 1) return yield* Effect.dieMessage(`Unknown workspace ${workspace_id}`); - return Schema.decodeUnknownSync(DbSafeInt)(result.insertId); + const open = yield* Effect.serviceOption(SqlClient.TransactionConnection); + const state = Option.isSome(open) ? states.get(open.value[0]) : undefined; + if (state === undefined) { + const [row] = yield* sql<{ value: unknown }>`UPDATE workspaces SET ${sql(column)} = ${sql(column)} + 1 WHERE id = ${workspace_id} RETURNING ${sql(column)} AS value`; + if (row === undefined) return yield* Effect.dieMessage(`Unknown workspace ${workspace_id}`); + return Schema.decodeUnknownSync(DbSafeInt)(row.value); + } + const key = `${column}:${workspace_id}`; + let current = state.counters.get(key); + if (current === undefined) { + // Straight from the backend, past the read-after-write check: this transaction has not written the counter. + const [row] = (yield* state.backend.run({ sql: `SELECT ${column} AS value FROM workspaces WHERE id = ?`, params: [workspace_id] })).rows; + if (row === undefined) return yield* Effect.dieMessage(`Unknown workspace ${workspace_id}`); + current = Schema.decodeUnknownSync(DbSafeInt)(row.value); + } + const next = current + 1; + state.counters.set(key, next); + yield* sql`UPDATE workspaces SET ${sql(column)} = ${next} WHERE id = ${workspace_id}`; + return next; }); /** Next committed-order context sequence number; call inside the change's transaction. */ diff --git a/server/src/main.ts b/server/src/main.ts index b9865f4..b494719 100644 --- a/server/src/main.ts +++ b/server/src/main.ts @@ -13,7 +13,7 @@ import { type ConfigError, Effect, Layer, flow } from 'effect'; import { ApiLive, OpenApiLive } from './api.ts'; import { type Authenticator, KernelAuthenticatorLive } from './auth.ts'; import { requireActivation, serverConfig } from './config.ts'; -import { dbLayer, type MysqlOptions } from './db.ts'; +import { dbLayer, type DbOptions } from './db.ts'; import { embeddedIssuerLive } from './issuer.ts'; import { McpAuthorizationFromEnv, type McpAuthorizationServer, McpLive, withMcpDelegation } from './mcp.ts'; import { ListenerStreamLive } from './media/ingest.ts'; @@ -43,7 +43,7 @@ const requestLogger = HttpMiddleware.make(app => { * port), plus the website from `webRoot` when given. */ export const serverLayer = ( - config: { readonly apiPort: number; readonly mysql: MysqlOptions; readonly webRoot?: string | undefined }, + config: { readonly apiPort: number; readonly db: DbOptions; readonly webRoot?: string | undefined }, authenticator: Layer.Layer = KernelAuthenticatorLive, // Tests replace providers, models, the handler set, the MCP authorization server or the sign-in issuer; production uses the defaults. overrides: { @@ -58,7 +58,7 @@ export const serverLayer = ( HttpApiBuilder.serve(flow(requestLogger, secureResponses)).pipe( HttpServer.withLogAddress, Layer.provide(config.webRoot === undefined ? Layer.empty : webAssetsLive(config.webRoot)), - Layer.provide([ListenerStreamLive, McpLive, SignInLive, WidgetTokenLive, OpenApiLive, embeddedIssuerLive(config.mysql)]), + Layer.provide([ListenerStreamLive, McpLive, SignInLive, WidgetTokenLive, OpenApiLive, embeddedIssuerLive(config.db)]), Layer.provide([SpeechSynthesizerLive, Layer.merge(SpeechRepliesLive, SpeechWorkRequestsLive).pipe(Layer.provide(overrides.llm ?? LlmLive))]), Layer.provide((overrides.api ?? ApiLive(loadMigrations())).pipe(Layer.provide(overrides.llm ?? LlmLive))), Layer.provide(overrides.media ?? MediaProvidersLive), @@ -66,7 +66,7 @@ export const serverLayer = ( Layer.provide(overrides.mcp ?? McpAuthorizationFromEnv), Layer.provide(overrides.signIn ?? SignInFromEnv), Layer.provide(overrides.organizations ?? WorkosOrganizationsFromEnv), - Layer.provide(dbLayer(config.mysql)), + Layer.provide(dbLayer(config.db)), Layer.provideMerge(NodeHttpServer.layer(createServer, { port: config.apiPort, host: '0.0.0.0' })), HttpMiddleware.withTracerDisabledWhen(hasPairingCode), ); diff --git a/server/src/migrate.ts b/server/src/migrate.ts index 0f70ab3..4eff8db 100644 --- a/server/src/migrate.ts +++ b/server/src/migrate.ts @@ -1,209 +1,96 @@ /** - * Versioned schema migrations for MySQL 8.4 (plan sections 07 and 16). + * Applies `migrations-d1/NNNN_name.sql` to a `file:` or in-memory database for local runs, CI and tests. + * D1 itself is migrated by `wrangler d1 migrations apply sanctum`, which records applied files in the same + * `d1_migrations` table, so API and worker check readiness the same way on both. * - * MySQL DDL implicitly commits, so a migration file cannot be rolled back as a unit. Each - * file is split into single-object steps (CREATE TABLE / CREATE INDEX / ALTER TABLE ... ADD COLUMN, - * each atomic DDL in MySQL 8.4) recorded one by one in a ledger under a named execution lock. After a crash - * between a step and its ledger row, the rerun inspects information_schema: an object that - * exists for a migration this ledger already started is adopted, any other pre-existing - * object stops the run. Applied steps and completed files are checksum-verified. + * Each file runs in one SQLite transaction (DDL is transactional), so a failing file leaves nothing behind. * * Run explicitly (`npm run migrate --workspace server`); API and worker only check status. */ -import { createHash } from 'node:crypto'; import { readdirSync, readFileSync } from 'node:fs'; import { SqlClient } from '@effect/sql'; import { NodeRuntime } from '@effect/platform-node'; import { Data, Effect } from 'effect'; import { serverConfig } from './config.ts'; -import { dbLayer, hasFullText } from './db.ts'; +import { dbLayer } from './db.ts'; export class MigrationError extends Data.TaggedError('MigrationError')<{ readonly message: string }> { } -type SchemaObject = - | { readonly kind: 'table'; readonly table: string } - | { readonly kind: 'index'; readonly table: string; readonly index: string } - | { readonly kind: 'column'; readonly table: string; readonly column: string } - | { readonly kind: 'backfill'; readonly table: string }; - -export interface MigrationStep { - readonly index: number; - readonly sql: string; - readonly checksum: string; - readonly object: SchemaObject; -} - export interface Migration { - readonly version: number; readonly name: string; - readonly checksum: string; - readonly steps: ReadonlyArray; + readonly statements: ReadonlyArray; } -const sha256 = (text: string) => createHash('sha256').update(text).digest('hex'); - -const TABLE = /^CREATE TABLE `?(\w+)`?/i; -const INDEX = /^CREATE (?:UNIQUE |FULLTEXT )?INDEX `?(\w+)`? ON `?(\w+)`?/i; -/** One column per statement, so the step stays a single inspectable object. */ -const COLUMN = /^ALTER TABLE `?(\w+)`? ADD COLUMN `?(\w+)`?(?:[^,()]|\((?:[^()]|\([^()]*\))*\))*$/i; -/** Re-runnable data fix or column redefinition: it must be idempotent, so a crash needs no inspection. */ -const BACKFILL = /^(?:UPDATE `?(\w+)`? |ALTER TABLE `?(\w+)`? MODIFY COLUMN )/i; - -function schemaObject(statement: string, file: string): SchemaObject { - const table = TABLE.exec(statement); - if (table) return { kind: 'table', table: table[1]! }; - const index = INDEX.exec(statement); - if (index) return { kind: 'index', index: index[1]!, table: index[2]! }; - const column = COLUMN.exec(statement); - if (column) return { kind: 'column', table: column[1]!, column: column[2]! }; - const backfill = BACKFILL.exec(statement); - if (backfill) return { kind: 'backfill', table: (backfill[1] ?? backfill[2])! }; - throw new MigrationError({ message: `${file}: only CREATE TABLE, CREATE INDEX, single ADD COLUMN, MODIFY COLUMN and idempotent UPDATE steps are allowed: ${statement.slice(0, 60)}` }); -} +/** + * Splits a file into statements: `--` comment lines are dropped and a statement ends with `;` at end of line, + * except inside `CREATE TRIGGER ... BEGIN ... END;`, which ends at the line `END;`. + */ +const splitStatements = (text: string) => { + const statements: string[] = []; + let current = ''; + for (const line of text.split('\n')) { + if (line.trimStart().startsWith('--')) continue; + current += `${line}\n`; + const trigger = /^\s*CREATE\s+(?:TEMP(?:ORARY)?\s+)?TRIGGER\b/i.test(current); + if (trigger ? /^\s*END;\s*$/i.test(line) : /;\s*$/.test(line)) { + statements.push(current.trim().replace(/;$/, '')); + current = ''; + } + } + if (current.trim() !== '') throw new MigrationError({ message: `Unterminated statement: ${current.trim().slice(0, 60)}` }); + return statements; +}; -/** Parses `NNN_name.sql`: `--` comment lines are dropped and statements end with `;` at end of line. */ export function parseMigration(file: string, text: string): Migration { - const match = /^(\d{3})_(\w+)\.sql$/.exec(file); - if (!match) throw new MigrationError({ message: `Invalid migration file name: ${file}` }); - const body = text.split('\n').filter(line => !line.trimStart().startsWith('--')).join('\n'); - const statements = body.split(/;\s*$/m).map(statement => statement.trim()).filter(Boolean); - const steps = statements.map((sql, index) => ({ index, sql, checksum: sha256(sql), object: schemaObject(sql, file) })); - return { version: Number(match[1]), name: match[2]!, checksum: sha256(steps.map(step => step.checksum).join('\n')), steps }; + if (!/^\d{4}_\w+\.sql$/.test(file)) throw new MigrationError({ message: `Invalid migration file name: ${file}` }); + return { name: file, statements: splitStatements(text) }; } -const MIGRATIONS_DIR = new URL('../migrations/', import.meta.url); +const MIGRATIONS_DIR = new URL('../migrations-d1/', import.meta.url); export function loadMigrations(dir: URL = MIGRATIONS_DIR): Migration[] { - const migrations = readdirSync(dir) + return readdirSync(dir) .filter(file => file.endsWith('.sql')) .sort() .map(file => parseMigration(file, readFileSync(new URL(file, dir), 'utf8'))); - const versions = new Set(migrations.map(migration => migration.version)); - if (versions.size !== migrations.length) throw new MigrationError({ message: 'Duplicate migration version' }); - return migrations; } -const ensureLedger = Effect.gen(function*() { +const ensureLedger = Effect.flatMap(SqlClient.SqlClient, sql => + sql`CREATE TABLE IF NOT EXISTS d1_migrations (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, applied_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)`); + +const appliedNames = Effect.gen(function*() { const sql = yield* SqlClient.SqlClient; - yield* sql`CREATE TABLE IF NOT EXISTS schema_migrations ( - version INT UNSIGNED NOT NULL PRIMARY KEY, - name VARCHAR(128) NOT NULL, - checksum CHAR(64) CHARACTER SET ascii NOT NULL, - started_at DATETIME(6) NOT NULL, - completed_at DATETIME(6) NULL - ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`; - yield* sql`CREATE TABLE IF NOT EXISTS schema_migration_steps ( - version INT UNSIGNED NOT NULL, - step INT UNSIGNED NOT NULL, - checksum CHAR(64) CHARACTER SET ascii NOT NULL, - outcome ENUM('applied', 'adopted') NOT NULL, - recorded_at DATETIME(6) NOT NULL, - PRIMARY KEY (version, step) - ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`; + const [ledger] = yield* sql`SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = 'd1_migrations'`; + return new Set(ledger === undefined ? [] : (yield* sql<{ name: string }>`SELECT name FROM d1_migrations`).map(row => row.name)); }); -/** Named locks are server-wide; scope ours to the schema being migrated (names are limited to 64 chars). */ -const LOCK_NAME = "CONCAT('sanctum_migrate:', LEFT(SHA2(DATABASE(), 256), 40))"; - -/** Holds a MySQL named lock on one reserved connection for the duration of `effect`. */ -const withMigrationLock = (effect: Effect.Effect, timeoutSeconds: number) => - Effect.scoped( - Effect.gen(function*() { - const sql = yield* SqlClient.SqlClient; - const connection = yield* sql.reserve; - const acquired = yield* Effect.acquireRelease( - connection.executeRaw(`SELECT GET_LOCK(${LOCK_NAME}, ?) AS acquired`, [timeoutSeconds]), - () => Effect.ignore(connection.executeRaw(`SELECT RELEASE_LOCK(${LOCK_NAME})`, [])), - ); - const [row] = Array.isArray(acquired) ? acquired : []; - const granted = typeof row === 'object' && row !== null && 'acquired' in row && Number(row.acquired) === 1; - if (!granted) return yield* new MigrationError({ message: `Migration lock busy after ${timeoutSeconds}s` }); - return yield* effect; - }), - ); - -const objectExists = (object: SchemaObject) => +const applyFile = (migration: Migration) => Effect.gen(function*() { - if (object.kind === 'backfill') return false; - const sql = yield* SqlClient.SqlClient; - const [row] = - object.kind === 'table' - ? yield* sql<{ present: number }>`SELECT EXISTS(SELECT 1 FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ${object.table}) AS present` - : object.kind === 'index' - ? yield* sql<{ present: number }>`SELECT EXISTS(SELECT 1 FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ${object.table} AND INDEX_NAME = ${object.index}) AS present` - : yield* sql<{ present: number }>`SELECT EXISTS(SELECT 1 FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ${object.table} AND COLUMN_NAME = ${object.column}) AS present`; - return Number(row?.present) === 1; - }); - -export interface MigrationReport { - readonly applied: ReadonlyArray; - readonly adopted: ReadonlyArray; -} - -const stepLabel = (migration: Migration, step: MigrationStep) => - `${migration.version}.${step.index} ${step.object.kind === 'table' ? step.object.table : step.object.kind === 'backfill' ? `${step.object.table} backfill` : `${step.object.table}.${step.object.kind === 'index' ? step.object.index : step.object.column}`}`; - -const unsupportedOnTidb = (step: MigrationStep) => !hasFullText() && step.object.kind !== 'table' && /\bFULLTEXT\b|\bSTORED\b/i.test(step.sql); - -function runStep(migration: Migration, step: MigrationStep, resumed: boolean, recorded: Map, report: { applied: string[]; adopted: string[] }) { - return Effect.gen(function*() { - const sql = yield* SqlClient.SqlClient; - const label = stepLabel(migration, step); - const previous = recorded.get(step.index); - if (previous !== undefined) { - if (previous !== step.checksum) return yield* new MigrationError({ message: `Applied step ${label} was edited` }); - return; - } - // TiDB has no FULLTEXT and cannot add a stored generated column; its search path (context.ts) needs neither. - if (unsupportedOnTidb(step)) return; - const exists = yield* objectExists(step.object); - if (exists && !resumed) return yield* new MigrationError({ message: `Step ${label} targets an object that already exists outside the ledger` }); - if (!exists) yield* sql.unsafe(step.sql); - const outcome = exists ? 'adopted' : 'applied'; - yield* sql`INSERT INTO schema_migration_steps (version, step, checksum, outcome, recorded_at) VALUES (${migration.version}, ${step.index}, ${step.checksum}, ${outcome}, UTC_TIMESTAMP(6))`; - report[outcome].push(label); - }); -} - -function runMigration(migration: Migration, report: { applied: string[]; adopted: string[] }) { - return Effect.gen(function*() { const sql = yield* SqlClient.SqlClient; - const [ledger] = yield* sql<{ checksum: string; completed_at: string | null }>`SELECT checksum, completed_at FROM schema_migrations WHERE version = ${migration.version}`; - if (ledger?.completed_at) { - if (ledger.checksum !== migration.checksum) return yield* new MigrationError({ message: `Completed migration ${migration.version}_${migration.name} was edited` }); - return; - } - if (!ledger) { - yield* sql`INSERT INTO schema_migrations (version, name, checksum, started_at) VALUES (${migration.version}, ${migration.name}, ${migration.checksum}, UTC_TIMESTAMP(6))`; - } - const steps = yield* sql<{ step: number; checksum: string }>`SELECT step, checksum FROM schema_migration_steps WHERE version = ${migration.version}`; - const recorded = new Map(steps.map(row => [Number(row.step), row.checksum])); - for (const step of migration.steps) yield* runStep(migration, step, ledger !== undefined, recorded, report); - yield* sql`UPDATE schema_migrations SET checksum = ${migration.checksum}, completed_at = UTC_TIMESTAMP(6) WHERE version = ${migration.version}`; + yield* sql.unsafe('BEGIN'); + yield* Effect.gen(function*() { + for (const statement of migration.statements) yield* sql.unsafe(statement); + yield* sql`INSERT INTO d1_migrations (name) VALUES (${migration.name})`; + yield* sql.unsafe('COMMIT'); + }).pipe(Effect.tapErrorCause(() => Effect.ignore(sql.unsafe('ROLLBACK')))); }); -} -/** Applies pending migrations in version order; safe to rerun after any interruption. */ -export const migrate = (migrations: ReadonlyArray, lockTimeoutSeconds = 30) => +/** Applies pending migrations in name order; rerunning applies nothing. */ +export const migrate = (migrations: ReadonlyArray) => Effect.gen(function*() { yield* ensureLedger; - const report = { applied: [] as string[], adopted: [] as string[] }; - yield* withMigrationLock( - Effect.forEach(migrations, migration => runMigration(migration, report), { discard: true }), - lockTimeoutSeconds, - ); - return report satisfies MigrationReport; + const done = yield* appliedNames; + const applied: string[] = []; + for (const migration of migrations.filter(candidate => !done.has(candidate.name))) { + yield* applyFile(migration); + applied.push(migration.name); + } + return { applied } as const; }); -/** Pending migration versions; API readiness and worker startup refuse to run while any remain. */ +/** Pending migration names; API readiness and worker startup refuse to run while any remain. */ export const pendingMigrations = (migrations: ReadonlyArray) => - Effect.gen(function*() { - const sql = yield* SqlClient.SqlClient; - const [ledger] = yield* sql<{ present: number }>`SELECT EXISTS(SELECT 1 FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'schema_migrations') AS present`; - const done = Number(ledger?.present) === 1 ? yield* sql<{ version: number }>`SELECT version FROM schema_migrations WHERE completed_at IS NOT NULL` : []; - const completed = new Set(done.map(row => Number(row.version))); - return migrations.filter(migration => !completed.has(migration.version)).map(migration => migration.version); - }); + Effect.map(appliedNames, done => migrations.filter(migration => !done.has(migration.name)).map(migration => migration.name)); export const requireCurrentSchema = (migrations: ReadonlyArray) => Effect.flatMap(pendingMigrations(migrations), pending => @@ -213,7 +100,8 @@ export const requireCurrentSchema = (migrations: ReadonlyArray) => if (import.meta.main) { Effect.gen(function*() { const config = yield* serverConfig; - const report = yield* migrate(loadMigrations()).pipe(Effect.provide(dbLayer(config.mysql))); + if (/^https?:/.test(config.db.url)) return yield* new MigrationError({ message: 'D1 is migrated with `wrangler d1 migrations apply sanctum`, not this command' }); + const report = yield* migrate(loadMigrations()).pipe(Effect.provide(dbLayer(config.db))); yield* Effect.logInfo('Migrations complete', report); }).pipe(NodeRuntime.runMain); } diff --git a/server/src/sql-dialect.ts b/server/src/sql-dialect.ts new file mode 100644 index 0000000..2f3f58f --- /dev/null +++ b/server/src/sql-dialect.ts @@ -0,0 +1,41 @@ +/** + * SQLite spellings of the MySQL time functions the domain code used. Timestamps are TEXT + * `YYYY-MM-DD HH:MM:SS.ffffff` UTC; SQLite keeps milliseconds, so the last three digits are always 000. + */ +import { Statement } from '@effect/sql'; + +const FORMAT = "'%Y-%m-%d %H:%M:%f000'"; + +/** A SQL expression: a trusted column name or fragment, never user text. */ +type Expression = string | Statement.Fragment; + +/** Joins expressions and literal text into one fragment, keeping bound parameters in order. */ +const compose = (parts: ReadonlyArray): Statement.Fragment => { + const literals: Array = parts.flatMap((part): Array => + typeof part === 'string' ? [{ _tag: 'Literal', value: part }] : part.segments.filter(segment => segment._tag === 'Literal')); + return Statement.unsafeFragment(literals.map(literal => literal.value).join(''), literals.flatMap(literal => literal.params ?? [])); +}; + +/** `UTC_TIMESTAMP(6)` and `NOW()`. */ +export const now = Statement.unsafeFragment(`strftime(${FORMAT}, 'now')`); + +/** `DATE_ADD(expression, INTERVAL seconds SECOND)`; `seconds` may be negative or fractional. */ +export const addSeconds = (expression: Expression, seconds: number) => + compose([`strftime(${FORMAT}, `, expression, ', ', Statement.unsafeFragment("? || ' seconds')", [seconds])]); + +/** `TIMESTAMPDIFF(SECOND, from, to)`: whole seconds, truncated toward zero. */ +export const diffSeconds = (from: Expression, to: Expression) => + compose(["CAST((unixepoch(", to, ", 'subsec') - unixepoch(", from, ", 'subsec')) AS INTEGER)"]); + +/** `TIMESTAMPDIFF(MICROSECOND, from, to)`. */ +export const diffMicros = (from: Expression, to: Expression) => + compose(["CAST(ROUND((unixepoch(", to, ", 'subsec') - unixepoch(", from, ", 'subsec')) * 1000000) AS INTEGER)"]); + +/** Most bound parameters per statement D1 accepts. */ +export const MAX_PARAMS = 100; + +/** Splits `rows` so that a statement binding `paramsPerRow` values per row stays within D1's limit. */ +export const chunked = (rows: ReadonlyArray, paramsPerRow = 1): ReadonlyArray> => { + const size = Math.max(1, Math.floor(MAX_PARAMS / paramsPerRow)); + return Array.from({ length: Math.ceil(rows.length / size) }, (_, index) => rows.slice(index * size, (index + 1) * size)); +}; diff --git a/server/src/worker.ts b/server/src/worker.ts index de91384..551eb06 100644 --- a/server/src/worker.ts +++ b/server/src/worker.ts @@ -1,6 +1,6 @@ /** * Worker entrypoint: same image as the API, separate process and resource layers. Runs - * durable MySQL jobs (context, notes, recording assembly, batch ASR, memory, matching, + * durable database jobs (context, notes, recording assembly, batch ASR, memory, matching, * actions, WorkOS organization sync) that continue after browsers disconnect or the API restarts. */ import { NodeRuntime } from '@effect/platform-node'; @@ -26,6 +26,6 @@ if (import.meta.main) { // `workos.sync` registers beside its layer: one more import in job-handlers.ts would make it a Sentrux god file. const handlers = { ...jobHandlers, 'workos.sync': syncWorkosEvents }; const run = Effect.zipRight(requireCurrentSchema(loadMigrations()), Effect.zipRight(armWorkosSync, runWorker(handlers))); - return yield* Effect.provide(run, [dbLayer(config.mysql), PyannoteLive, MediaProvidersLive, LlmLive, PipedreamLive, WorkosOrganizationsFromEnv]); + return yield* Effect.provide(run, [dbLayer(config.db), PyannoteLive, MediaProvidersLive, LlmLive, PipedreamLive, WorkosOrganizationsFromEnv]); }).pipe(NodeRuntime.runMain); } diff --git a/server/tests/db.test.ts b/server/tests/db.test.ts index 38bd093..ce3ebac 100644 --- a/server/tests/db.test.ts +++ b/server/tests/db.test.ts @@ -1,156 +1,178 @@ -import { randomUUID } from 'node:crypto'; -import { rootCertificates } from 'node:tls'; import { SqlClient, type SqlError, SqlSchema } from '@effect/sql'; import { describe, expect, it } from '@effect/vitest'; -import { Effect, Exit, Layer, Schema } from 'effect'; -import { DbBool, DbJson, DbSafeInt, DbSha256, DbUtc, dbLayer, ER_CHECK_CONSTRAINT_VIOLATED, ER_DUP_ENTRY, ER_NO_REFERENCED_ROW, mysqlErrno, verifyUtcSession } from '../src/db.ts'; -import { createTestDatabase, withDatabase } from './support/database.ts'; -import { seedWorkspace } from './support/fixtures.ts'; +import { Deferred, Effect, Exit, Fiber, Schema } from 'effect'; +import type { WorkspaceId } from '@sanctum/contracts'; +import { DbBool, DbJson, DbSafeInt, DbSha256, DbUtc, dbLayer, increment, isCheckViolation, isDuplicate, isMissingReference } from '../src/db.ts'; +import { d1Backend } from '../src/db-d1.ts'; +import { addSeconds, chunked, diffMicros, diffSeconds, now } from '../src/sql-dialect.ts'; -const errnoOf = (effect: Effect.Effect) => - Effect.map(Effect.flip(effect), mysqlErrno); +const workspace = 'w1' as WorkspaceId; -const Row = Schema.Struct({ - created_at: DbUtc, - context_seq: DbSafeInt, - capture_policy: Schema.NullOr(DbJson(Schema.Struct({ note: Schema.String, nested: Schema.NullOr(Schema.Array(Schema.Number)) }))), - name: Schema.String, +/** The transaction guard tables plus two small tables; the baseline migration carries the real ones. */ +const schema = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + for (const statement of [ + "CREATE TABLE tx_clock (id INTEGER PRIMARY KEY CHECK (id = 1), v INTEGER NOT NULL)", + "INSERT INTO tx_clock VALUES (1, 0)", + "CREATE TABLE tx_conflict (v INTEGER CONSTRAINT tx_conflict_guard CHECK (v IS NULL))", + "CREATE TABLE workspaces (id TEXT PRIMARY KEY, context_seq INTEGER NOT NULL DEFAULT 0, permission_revision INTEGER NOT NULL DEFAULT 0, name TEXT NOT NULL CHECK (length(name) > 0))", + "CREATE TABLE notes (id INTEGER PRIMARY KEY, workspace_id TEXT NOT NULL REFERENCES workspaces(id), body BLOB, flag INTEGER)", + "INSERT INTO workspaces (id, name) VALUES ('w1', 'one')", + ]) yield* sql.unsafe(statement); }); -describe('database boundary', () => { - it.effect('round-trips UTC microseconds, BIGINT, JSON and Unicode through one decoding boundary', () => - withDatabase( - Effect.gen(function* () { - const sql = yield* SqlClient.SqlClient; - yield* verifyUtcSession; - const id = randomUUID(); - const name = 'Café 会議 🎙️ Ωmega'; - const policy = { note: 'straße ✓', nested: null }; - yield* sql`INSERT INTO workspaces (id, name, timezone, context_seq, capture_policy, created_at) - VALUES (${id}, ${name}, 'Europe/Berlin', ${String(Number.MAX_SAFE_INTEGER)}, ${JSON.stringify(policy)}, ${'2026-03-29 01:59:59.999999'})`; - const find = SqlSchema.single({ Request: Schema.String, Result: Row, execute: key => sql`SELECT created_at, context_seq, capture_policy, name FROM workspaces WHERE id = ${key}` }); - const row = yield* find(id); - expect(row).toEqual({ created_at: '2026-03-29T01:59:59.999999Z', context_seq: Number.MAX_SAFE_INTEGER, capture_policy: policy, name }); - yield* sql`UPDATE workspaces SET context_seq = context_seq + 1 WHERE id = ${id}`; - const unsafe = yield* Effect.exit(find(id)); - expect(Exit.isFailure(unsafe) && String(unsafe.cause)).toMatch(/not a safe integer/); - }), - { migrated: true }, - ), - ); +const withDb = (use: Effect.Effect) => Effect.provide(Effect.zipRight(schema, use), dbLayer({ url: ':memory:' })); +const count = (table: string) => SqlClient.SqlClient.pipe(Effect.flatMap(sql => sql.unsafe<{ n: number }>(`SELECT count(*) AS n FROM ${table}`)), Effect.map(rows => rows[0]!.n)); +const failureOf = (effect: Effect.Effect) => Effect.flip(effect); - it('column schemas encode back to MySQL representations', () => { +describe('column schemas', () => { + it('round-trip database representations', () => { expect(Schema.encodeSync(DbUtc)(Schema.decodeSync(DbUtc)('2026-09-26 17:08:16.000100'))).toBe('2026-09-26 17:08:16.000100'); expect(() => Schema.decodeUnknownSync(DbUtc)('2026-09-26T17:08:16Z')).toThrow(); expect(Schema.decodeSync(DbBool)(1)).toBe(true); - expect(Schema.encodeSync(DbBool)(false)).toBe(0); expect(Schema.decodeUnknownSync(DbSafeInt)('-42')).toBe(-42); expect(() => Schema.decodeUnknownSync(DbSafeInt)('1.5')).toThrow(); const hash = 'ab'.repeat(32); expect(Schema.decodeSync(DbSha256)(Schema.encodeSync(DbSha256)(hash))).toBe(hash); expect(Schema.decodeUnknownSync(DbJson(Schema.Array(Schema.Number)))('[1,2]')).toEqual([1, 2]); }); +}); + +describe('transactions', () => { + it.effect('commit applies buffered writes; reads before the first write see committed rows', () => + withDb(Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const seen = yield* sql.withTransaction(Effect.gen(function* () { + const before = yield* count('notes'); + yield* sql`INSERT INTO notes (workspace_id, body, flag) VALUES (${workspace}, ${new Uint8Array([1, 2, 255])}, ${true})`; + return before; + })); + expect(seen).toBe(0); + const [row] = yield* sql<{ body: Uint8Array; flag: number }>`SELECT body, flag FROM notes`; + expect([...row!.body]).toEqual([1, 2, 255]); + expect(row!.flag).toBe(1); + }))); + + it.effect('a failed body rolls back: nothing is written', () => + withDb(Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const exit = yield* Effect.exit(sql.withTransaction(Effect.zipRight(sql`INSERT INTO notes (workspace_id) VALUES (${workspace})`, Effect.fail('boom')))); + expect(Exit.isFailure(exit)).toBe(true); + expect(yield* count('notes')).toBe(0); + }))); + + it.effect('a failing batch rolls every buffered write back', () => + withDb(Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const error = yield* failureOf(sql.withTransaction(Effect.zipRight(sql`INSERT INTO notes (workspace_id) VALUES (${workspace})`, sql`UPDATE workspaces SET name = '' WHERE id = ${workspace}`))); + expect(isCheckViolation(error)).toBe(true); + expect(yield* count('notes')).toBe(0); + }))); - it.effect('refuses a non-UTC session', () => - withDatabase( - Effect.gen(function* () { - const sql = yield* SqlClient.SqlClient; - const exit = yield* Effect.exit(sql.withTransaction(Effect.zipRight(sql`SET time_zone = '+02:00'`, verifyUtcSession))); - expect(Exit.isFailure(exit) && String(exit.cause)).toMatch(/must be UTC/); - }), - ), - ); + it.effect('reading after a buffered write is an error', () => + withDb(Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const error = yield* failureOf(sql.withTransaction(Effect.zipRight(sql`INSERT INTO notes (workspace_id) VALUES (${workspace})`, sql`SELECT * FROM notes`))); + expect(error.message).toMatch(/Read after a buffered write/); + }))); - it.effect('with a CA configured, refuses a server it cannot verify instead of connecting in plain text', () => - Effect.acquireUseRelease( - Effect.promise(createTestDatabase), - database => Effect.gen(function* () { - // Any public root CA: it did not issue the test server's self-signed certificate. - const error = yield* Effect.flip(Layer.build(dbLayer({ ...database.mysql, caCert: rootCertificates[0]! })).pipe(Effect.scoped)); - expect(error._tag === 'SqlError' && String(error.cause)).toMatch(/certificate/i); - }), - database => Effect.promise(database.drop), - ), - ); + it.live('a transaction that lost the race reruns and commits once', () => + withDb(Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const started = yield* Deferred.make(); + const rival = yield* Deferred.make(); + let attempts = 0; + const slow = yield* Effect.fork(sql.withTransaction(Effect.gen(function* () { + attempts++; + if (attempts === 1) { + yield* Deferred.succeed(started, undefined); + yield* Deferred.await(rival); + } + yield* sql`INSERT INTO notes (workspace_id, flag) VALUES (${workspace}, 1)`; + }))); + yield* Deferred.await(started); + yield* sql.withTransaction(sql`INSERT INTO notes (workspace_id, flag) VALUES (${workspace}, 2)`); + yield* Deferred.succeed(rival, undefined); + yield* Fiber.join(slow); + expect(attempts).toBe(2); + expect(yield* count('notes')).toBe(2); + const [clock] = yield* sql<{ v: number }>`SELECT v FROM tx_clock`; + expect(clock!.v).toBe(2); + }))); + + it.effect('twenty parallel transactions on one row all commit with distinct numbers', () => + withDb(Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const numbers = yield* Effect.all(Array.from({ length: 20 }, () => sql.withTransaction(increment('context_seq')(workspace))), { concurrency: 'unbounded' }); + expect(new Set(numbers).size).toBe(20); + expect(Math.max(...numbers)).toBe(20); + }))); +}); + +describe('increment', () => { + it.effect('counts up outside a transaction and twice inside one', () => + withDb(Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + expect(yield* increment('permission_revision')(workspace)).toBe(1); + const pair = yield* sql.withTransaction(Effect.gen(function* () { + yield* sql`INSERT INTO notes (workspace_id) VALUES (${workspace})`; + return [yield* increment('permission_revision')(workspace), yield* increment('permission_revision')(workspace)]; + })); + expect(pair).toEqual([2, 3]); + const [row] = yield* sql<{ permission_revision: number }>`SELECT permission_revision FROM workspaces`; + expect(row!.permission_revision).toBe(3); + }))); }); -describe('schema constraints', () => { - it.effect('composite keys stop rows pointing into another workspace', () => - withDatabase( - Effect.gen(function* () { - const sql = yield* SqlClient.SqlClient; - const [alpha] = yield* seedWorkspace('Alpha'); - const [beta] = yield* seedWorkspace('Beta'); - const meeting = randomUUID(); - yield* sql`INSERT INTO meetings (id, workspace_id, state, timezone, started_at, processing, created_at, updated_at) - VALUES (${meeting}, ${alpha!.workspace_id}, 'active', 'UTC', UTC_TIMESTAMP(6), '{}', UTC_TIMESTAMP(6), UTC_TIMESTAMP(6))`; - const crossed = yield* errnoOf(sql`INSERT INTO meeting_access (workspace_id, meeting_id, principal_id, access, granted_by, created_at) - VALUES (${beta!.workspace_id}, ${meeting}, ${beta!.principal.id}, 'read', ${beta!.principal.id}, UTC_TIMESTAMP(6))`); - expect(crossed).toBe(ER_NO_REFERENCED_ROW); - const foreignMember = yield* errnoOf(sql`INSERT INTO meeting_access (workspace_id, meeting_id, principal_id, access, granted_by, created_at) - VALUES (${alpha!.workspace_id}, ${meeting}, ${beta!.principal.id}, 'read', ${alpha!.principal.id}, UTC_TIMESTAMP(6))`); - expect(foreignMember).toBe(ER_NO_REFERENCED_ROW); - }), - { migrated: true }, - ), - ); +describe('errors and dialect', () => { + it.effect('names duplicate, missing reference and check violations', () => + withDb(Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + expect(isDuplicate(yield* failureOf(sql`INSERT INTO workspaces (id, name) VALUES ('w1', 'x')`))).toBe(true); + expect(isMissingReference(yield* failureOf(sql`INSERT INTO notes (workspace_id) VALUES ('nope')`))).toBe(true); + expect(isCheckViolation(yield* failureOf(sql`UPDATE workspaces SET name = ''`))).toBe(true); + }))); - it.effect('recording chunks have one source identity and a valid WAV size', () => - withDatabase( - Effect.gen(function* () { - const sql = yield* SqlClient.SqlClient; - const [device] = yield* seedWorkspace('Room', ['device']); - const ws = device!.workspace_id; - const listener = randomUUID(); - const epoch = randomUUID(); - yield* sql`INSERT INTO listeners (id, workspace_id, principal_id, name, mode, capabilities, created_at) - VALUES (${listener}, ${ws}, ${device!.principal.id}, 'Room 1', 'room', '{}', UTC_TIMESTAMP(6))`; - yield* sql`INSERT INTO capture_epochs (id, workspace_id, listener_id, lease_generation, sample_rate, channels, encoding, sample_start, captured_at, timezone, start_reason, started_at, live_sample_end) - VALUES (${epoch}, ${ws}, ${listener}, 1, 48000, 1, 'pcm_s16le', 0, UTC_TIMESTAMP(6), 'UTC', 'start', UTC_TIMESTAMP(6), 0)`; - const chunk = (sequence: number, byteLength: number) => - sql`INSERT INTO recording_chunks (id, workspace_id, listener_id, epoch_id, track, sequence, sample_start, sample_count, sample_rate, captured_at, byte_length, sha256, object_key, upload_state, created_at) - VALUES (${randomUUID()}, ${ws}, ${listener}, ${epoch}, 0, ${sequence}, ${sequence * 1_440_000}, 1440000, 48000, UTC_TIMESTAMP(6), ${byteLength}, ${Buffer.alloc(32)}, ${`${epoch}/${sequence}-${byteLength}`}, 'pending', UTC_TIMESTAMP(6))`; - yield* chunk(0, 44 + 1_440_000 * 2); - expect(yield* errnoOf(chunk(0, 44 + 1_440_000 * 2))).toBe(ER_DUP_ENTRY); - expect(yield* errnoOf(chunk(1, 1_000))).toBe(ER_CHECK_CONSTRAINT_VIOLATED); - }), - { migrated: true }, - ), - ); + it.effect('time helpers and chunking', () => + withDb(Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const [row] = yield* sql<{ a: string; b: string; s: number; m: number }>`SELECT ${now} AS a, ${addSeconds("'2026-01-01 00:00:00.000000'", 90.5)} AS b, + ${diffSeconds("'2026-01-01 00:00:00'", "'2026-01-01 00:01:30.9'")} AS s, ${diffMicros("'2026-01-01 00:00:00'", "'2026-01-01 00:00:01.25'")} AS m`; + expect(Schema.decodeUnknownSync(DbUtc)(row!.a)).toMatch(/Z$/); + expect(row!.b).toBe('2026-01-01 00:01:30.500000'); + expect([row!.s, row!.m]).toEqual([90, 1_250_000]); + expect(chunked(Array.from({ length: 250 }, (_, i) => i), 3).map(chunk => chunk.length)).toEqual([33, 33, 33, 33, 33, 33, 33, 19]); + }))); - it.effect('allows one active job per work key while keeping finished history', () => - withDatabase( - Effect.gen(function* () { - const sql = yield* SqlClient.SqlClient; - const [owner] = yield* seedWorkspace('Jobs'); - const enqueue = (id: string) => - sql`INSERT INTO jobs (id, workspace_id, kind, work_key, status, payload, available_at, max_attempts, created_at, updated_at) - VALUES (${id}, ${owner!.workspace_id}, 'context.refresh', 'meeting:1', 'pending', '{}', UTC_TIMESTAMP(6), 3, UTC_TIMESTAMP(6), UTC_TIMESTAMP(6))`; - const first = randomUUID(); - yield* enqueue(first); - expect(yield* errnoOf(enqueue(randomUUID()))).toBe(ER_DUP_ENTRY); - yield* sql`UPDATE jobs SET status = 'succeeded' WHERE id = ${first}`; - yield* enqueue(randomUUID()); - const [count] = yield* sql<{ total: number }>`SELECT COUNT(*) AS total FROM jobs`; - expect(Number(count!.total)).toBe(2); - }), - { migrated: true }, - ), - ); + it.effect('FTS5 prefix and hyphenated-word search', () => + withDb(Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql.unsafe('CREATE VIRTUAL TABLE fts USING fts5(text)'); + yield* sql.unsafe("INSERT INTO fts (text) VALUES ('quarterly well-known budget'), ('other')"); + const find = (query: string) => SqlSchema.findAll({ Request: Schema.String, Result: Schema.Struct({ text: Schema.String }), execute: q => sql`SELECT text FROM fts WHERE fts MATCH ${q} ORDER BY bm25(fts)` })(query); + expect(yield* find('"budg"*')).toHaveLength(1); + expect(yield* find('"well-known"')).toHaveLength(1); + }))); +}); - it.effect('treats identifiers and idempotency keys case-sensitively', () => - withDatabase( - Effect.gen(function* () { - const sql = yield* SqlClient.SqlClient; - const [agent] = yield* seedWorkspace('Keys', ['agent']); - const add = (key: string) => - sql`INSERT INTO context_items (id, revision, workspace_id, kind, text, state, derivation, sources, author_type, author_principal_id, idempotency_key, payload_sha256, created_at) - VALUES (${randomUUID()}, 1, ${agent!.workspace_id}, 'decision', 'x', 'provisional', 'spoken', '[]', 'agent', ${agent!.principal.id}, ${key}, ${Buffer.alloc(32)}, UTC_TIMESTAMP(6))`; - yield* add('Run-1'); - yield* add('run-1'); - expect(yield* errnoOf(add('Run-1'))).toBe(ER_DUP_ENTRY); - }), - { migrated: true }, - ), - ); +describe('D1 backend', () => { + it.effect('posts statements as JSON with bytes in base64 and decodes the answer', () => + Effect.gen(function* () { + const seen: Array<{ url: string; body: unknown }> = []; + const original = globalThis.fetch; + globalThis.fetch = (async (url: URL, init: RequestInit) => { + seen.push({ url: String(url), body: JSON.parse(String(init.body)) }); + return Response.json(String(url).endsWith('/run') ? { rows: [{ b: { $b: 'AQL/' } }], changes: 0 } : { error: 'D1_ERROR: UNIQUE constraint failed: t.id' }, { status: String(url).endsWith('/run') ? 200 : 400 }); + }) as typeof fetch; + try { + const backend = d1Backend('http://d1.internal'); + const result = yield* backend.run({ sql: 'SELECT ?', params: [new Uint8Array([1, 2, 255]), true] }); + expect([...(result.rows[0]!['b'] as Uint8Array)]).toEqual([1, 2, 255]); + expect(seen[0]).toEqual({ url: 'http://d1.internal/run', body: { sql: 'SELECT ?', params: [{ $b: 'AQL/' }, 1] } }); + const error = yield* Effect.flip(backend.batch([{ sql: 'x', params: [] }])); + expect(isDuplicate(error)).toBe(true); + } finally { + globalThis.fetch = original; + } + })); }); diff --git a/server/tests/http-server.ts b/server/tests/http-server.ts index 2a6115c..f5f135e 100644 --- a/server/tests/http-server.ts +++ b/server/tests/http-server.ts @@ -36,10 +36,10 @@ export const serveApiWithDb = ( } = {}, ) => Effect.gen(function* () { - const database = yield* Effect.acquireRelease(Effect.promise(createTestDatabase), db => Effect.promise(db.drop)); - const db = dbLayer(database.mysql); + const database = yield* Effect.acquireRelease(Effect.promise(() => createTestDatabase()), db => Effect.promise(db.drop)); + const db = dbLayer(database.db); if (options.migrated !== false) yield* Effect.provide(migrate(loadMigrations()), db); - const context = yield* Layer.build(serverLayer({ apiPort: 0, mysql: database.mysql, webRoot: options.webRoot }, options.auth, options.overrides)); + const context = yield* Layer.build(serverLayer({ apiPort: 0, db: database.db, webRoot: options.webRoot }, options.auth, options.overrides)); const address = Context.get(context, HttpServer.HttpServer).address; if (address._tag !== 'TcpAddress') throw new Error('expected TCP'); return { base: `http://127.0.0.1:${address.port}`, db }; diff --git a/server/tests/migrations.test.ts b/server/tests/migrations.test.ts index 6e87abf..f1a2aca 100644 --- a/server/tests/migrations.test.ts +++ b/server/tests/migrations.test.ts @@ -1,167 +1,94 @@ +import { execFileSync } from 'node:child_process'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { DatabaseSync } from 'node:sqlite'; import { SqlClient } from '@effect/sql'; import { describe, expect, it } from '@effect/vitest'; import { Effect, Exit } from 'effect'; -import { loadMigrations, migrate, parseMigration, pendingMigrations, requireCurrentSchema, type Migration } from '../src/migrate.ts'; -import { withDatabase } from './support/database.ts'; +import { loadMigrations, migrate, parseMigration, pendingMigrations, requireCurrentSchema } from '../src/migrate.ts'; +import { createTestDatabase, withDatabase } from './support/database.ts'; const migrations = loadMigrations(); -const stepCount = migrations.reduce((total, migration) => total + migration.steps.length, 0); const tables = Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; - const rows = yield* sql<{ name: string }>`SELECT TABLE_NAME AS name FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() ORDER BY TABLE_NAME`; + const rows = yield* sql<{ name: string }>`SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name`; return rows.map(row => row.name); }); describe('migration files', () => { - it('are numbered, parsed into inspectable steps and create every plan section 07 table', () => { - expect(migrations.map(migration => migration.version)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]); - // 023 adds a generated column and its FULLTEXT index: MySQL fills it for existing rows, so no backfill. - expect(migrations.at(-2)!.steps.map(step => step.object)).toEqual([ - { kind: 'column', table: 'context_items', column: 'text_joined' }, - { kind: 'index', table: 'context_items', index: 'context_items_text_joined' }, - ]); - expect(migrations.at(-1)!.steps.map(step => step.object)).toEqual([ - { kind: 'table', table: 'devices' }, - { kind: 'table', table: 'device_pair_capacity' }, - { kind: 'table', table: 'device_pair_attempts' }, - { kind: 'column', table: 'listeners', column: 'device_id' }, - ]); - const created = migrations.flatMap(migration => migration.steps.map(step => step.object.table)); - expect(created).toEqual( - expect.arrayContaining([ - 'workspaces', 'principals', 'workspace_members', 'meetings', 'meeting_access', 'listeners', 'recording_chunks', - 'meeting_ranges', 'transcript_segments', 'speaker_tracks', 'voice_enrollments', 'profile_embeddings', - 'context_items', 'context_events', 'agent_credentials', 'integration_accounts', 'action_grants', 'actions', 'jobs', - 'workspace_orgs', 'sync_cursors', 'paid_model_calls', - ]), - ); + it('are numbered and create the transaction guard and every core table', () => { + expect(migrations.map(migration => migration.name)[0]).toBe('0001_baseline.sql'); + const created = migrations.flatMap(migration => migration.statements.flatMap(statement => /^CREATE (?:VIRTUAL )?TABLE (\w+)/i.exec(statement)?.[1] ?? [])); + expect(created).toEqual(expect.arrayContaining(['tx_clock', 'tx_conflict', 'workspaces', 'principals', 'meetings', 'jobs', 'context_items', 'context_items_fts'])); }); - it('rejects names and statements the runner cannot inspect after a crash', () => { - expect(() => parseMigration('1_bad.sql', 'CREATE TABLE a (id INT);')).toThrow(/Invalid migration file name/); - expect(() => parseMigration('010_drop.sql', 'DROP TABLE a;')).toThrow(/idempotent UPDATE steps/); - expect(() => parseMigration('010_alter.sql', 'ALTER TABLE a ADD COLUMN b INT, ADD COLUMN c INT;')).toThrow(/single ADD COLUMN/); - const parsed = parseMigration('010_ok.sql', '-- comment\nCREATE TABLE a (id INT);\nCREATE UNIQUE INDEX a_id ON a (id);\nALTER TABLE a ADD COLUMN b VARCHAR(10) NULL;\nALTER TABLE a MODIFY COLUMN b VARCHAR(20) NULL;\n'); - expect(parsed.steps.map(step => step.object)).toEqual([{ kind: 'table', table: 'a' }, { kind: 'index', table: 'a', index: 'a_id' }, { kind: 'column', table: 'a', column: 'b' }, { kind: 'backfill', table: 'a' }]); + it('splits statements, keeps trigger bodies whole and rejects bad names and unterminated text', () => { + const parsed = parseMigration('0002_x.sql', '-- comment\nCREATE TABLE a (id INTEGER);\nCREATE TRIGGER t AFTER INSERT ON a BEGIN\n INSERT INTO a VALUES (1);\n DELETE FROM a;\nEND;\nCREATE INDEX i ON a (id);\n'); + expect(parsed.statements.map(statement => statement.split(/\s+/).slice(0, 3).join(' '))).toEqual(['CREATE TABLE a', 'CREATE TRIGGER t', 'CREATE INDEX i']); + expect(parsed.statements[1]).toMatch(/DELETE FROM a;\nEND$/); + expect(() => parseMigration('2_bad.sql', 'CREATE TABLE a (id INTEGER);')).toThrow(/Invalid migration file name/); + expect(() => parseMigration('0003_x.sql', 'CREATE TABLE a (id INTEGER)')).toThrow(/Unterminated/); }); }); -describe('migrate against MySQL 8.4', () => { +describe('migrate', () => { it.effect('applies a fresh database once and is a no-op when repeated', () => withDatabase( Effect.gen(function* () { - expect(yield* pendingMigrations(migrations)).toEqual(migrations.map(migration => migration.version)); - const first = yield* migrate(migrations); - expect(first.applied).toHaveLength(stepCount); - const second = yield* migrate(migrations); - expect(second).toEqual({ applied: [], adopted: [] }); + expect(yield* pendingMigrations(migrations)).toEqual(migrations.map(migration => migration.name)); + expect((yield* migrate(migrations)).applied).toEqual(migrations.map(migration => migration.name)); + expect((yield* migrate(migrations)).applied).toEqual([]); expect(yield* pendingMigrations(migrations)).toEqual([]); yield* requireCurrentSchema(migrations); - expect(yield* tables).toContain('profile_embeddings'); + expect(yield* tables).toEqual(expect.arrayContaining(['d1_migrations', 'tx_clock', 'workspaces'])); }), ), ); - it.effect('serializes concurrent runners through the execution lock', () => + it.effect('requireCurrentSchema fails while a migration is pending', () => withDatabase( Effect.gen(function* () { - const reports = yield* Effect.all([migrate(migrations), migrate(migrations)], { concurrency: 2 }); - expect(reports.flatMap(report => report.applied)).toHaveLength(stepCount); - }), - ), - ); - - it.effect('resumes after DDL ran but its ledger step was not recorded', () => - withDatabase( - Effect.gen(function* () { - const sql = yield* SqlClient.SqlClient; - yield* migrate(migrations); - // Simulate a crash after the last migration ran DDL but before the ledger recorded it. - const last = migrations.at(-1)!; - yield* sql`DELETE FROM schema_migration_steps WHERE version = ${last.version}`; - yield* sql`UPDATE schema_migrations SET completed_at = NULL WHERE version = ${last.version}`; - const report = yield* migrate(migrations); - expect(report.applied).toHaveLength(last.steps.filter(step => step.object.kind === 'backfill').length); - expect(report.adopted).toHaveLength(last.steps.filter(step => step.object.kind !== 'backfill').length); - expect(yield* pendingMigrations(migrations)).toEqual([]); - }), - ), - ); - - it.effect('backfills the issuer of members already managed by organization sync', () => - withDatabase( - Effect.gen(function* () { - const sql = yield* SqlClient.SqlClient; - yield* migrate(migrations.filter(migration => migration.version < 16)); - yield* sql`INSERT INTO workspaces (id, name, timezone, created_at) VALUES ('w-linked', 'Linked', 'UTC', UTC_TIMESTAMP(6)), ('w-free', 'Free', 'UTC', UTC_TIMESTAMP(6))`; - yield* sql`INSERT INTO principals (id, kind, display_name, created_at) VALUES ('p-1', 'human', 'One', UTC_TIMESTAMP(6)), ('p-2', 'human', 'Two', UTC_TIMESTAMP(6))`; - yield* sql`INSERT INTO workspace_members (workspace_id, principal_id, role, created_at, revoked_at) VALUES - ('w-linked', 'p-1', 'owner', UTC_TIMESTAMP(6), NULL), ('w-linked', 'p-2', 'member', UTC_TIMESTAMP(6), UTC_TIMESTAMP(6)), ('w-free', 'p-1', 'owner', UTC_TIMESTAMP(6), NULL)`; - yield* sql`INSERT INTO workspace_orgs (issuer, org_id, workspace_id, created_at) VALUES ('https://issuer.test', 'org_1', 'w-linked', UTC_TIMESTAMP(6))`; - yield* migrate(migrations); - const rows = yield* sql<{ workspace_id: string; principal_id: string; org_issuer: string | null }>`SELECT workspace_id, principal_id, org_issuer FROM workspace_members ORDER BY workspace_id, principal_id`; - expect(rows).toEqual([ - { workspace_id: 'w-free', principal_id: 'p-1', org_issuer: null }, - { workspace_id: 'w-linked', principal_id: 'p-1', org_issuer: 'https://issuer.test' }, - { workspace_id: 'w-linked', principal_id: 'p-2', org_issuer: null }, - ]); - }), - ), - ); - - it.effect('continues a partially applied migration from its next step', () => - withDatabase( - Effect.gen(function* () { - const sql = yield* SqlClient.SqlClient; - const first = migrations[0]!; - const partial: Migration = { ...first, steps: first.steps.slice(0, 2) }; - yield* migrate([partial]); - yield* sql`UPDATE schema_migrations SET completed_at = NULL WHERE version = ${first.version}`; - const report = yield* migrate(migrations); - expect(report.applied).toHaveLength(stepCount - 2); + const exit = yield* Effect.exit(requireCurrentSchema(migrations)); + expect(Exit.isFailure(exit) && String(exit.cause)).toMatch(/pending migrations: 0001_baseline/); }), ), ); - it.effect('refuses objects created outside the ledger and edited applied migrations', () => + it.effect('a failing file leaves nothing behind and is not recorded', () => withDatabase( Effect.gen(function* () { - const sql = yield* SqlClient.SqlClient; - yield* sql`CREATE TABLE workspaces (id INT PRIMARY KEY)`; - const conflict = yield* Effect.exit(migrate(migrations)); - expect(Exit.isFailure(conflict) && String(conflict.cause)).toMatch(/already exists outside the ledger/); - yield* sql`DROP TABLE workspaces`; - yield* sql`DELETE FROM schema_migrations`; - yield* migrate(migrations); - const edited = migrations.map((migration, index) => (index === 0 ? { ...migration, checksum: 'edited' } : migration)); - const exit = yield* Effect.exit(migrate(edited)); - expect(Exit.isFailure(exit) && String(exit.cause)).toMatch(/was edited/); + const broken = parseMigration('0001_broken.sql', 'CREATE TABLE a (id INTEGER);\nCREATE TABLE a (id INTEGER);\n'); + const exit = yield* Effect.exit(migrate([broken])); + expect(Exit.isFailure(exit)).toBe(true); + expect(yield* tables).not.toContain('a'); + expect(yield* pendingMigrations([broken])).toEqual(['0001_broken.sql']); }), ), ); - it.effect('reports a behind schema to API readiness and worker startup', () => - withDatabase( - Effect.gen(function* () { - const exit = yield* Effect.exit(requireCurrentSchema(migrations)); - expect(Exit.isFailure(exit) && String(exit.cause)).toMatch(/pending migrations: 1, 2/); - }), - ), - ); + it('createTestDatabase returns a migrated database that every connection shares', async () => { + const database = await createTestDatabase(); + try { + const reader = new DatabaseSync(database.db.url); + expect(reader.prepare("SELECT count(*) AS n FROM sqlite_master WHERE name = 'workspaces'").get()).toEqual({ n: 1 }); + reader.close(); + } finally { + await database.drop(); + } + }); - it.effect('adds the End fence window to capture epochs as two nullable columns with no default, so existing epochs stay unfenced', () => - withDatabase( - Effect.gen(function* () { - const sql = yield* SqlClient.SqlClient; - yield* migrate(migrations); - const columns = yield* sql`SELECT TABLE_NAME AS tbl, COLUMN_NAME AS name, IS_NULLABLE AS nullable, COLUMN_DEFAULT AS dflt FROM information_schema.COLUMNS - WHERE TABLE_SCHEMA = DATABASE() AND COLUMN_NAME LIKE 'end_fence%' ORDER BY COLUMN_NAME`; - expect(columns).toEqual([ - { tbl: 'capture_epochs', name: 'end_fence_from_sample', nullable: 'YES', dflt: null }, - { tbl: 'capture_epochs', name: 'end_fence_sample', nullable: 'YES', dflt: null }, - ]); - }), - ), - ); + it('npm run migrate applies migrations-d1 to a file database', () => { + const directory = mkdtempSync(join(tmpdir(), 'sanctum-migrate-')); + try { + const path = join(directory, 'app.db'); + execFileSync(process.execPath, ['src/migrate.ts'], { cwd: join(import.meta.dirname, '..'), env: { ...process.env, SANCTUM_DB_URL: `file:${path}` }, stdio: 'pipe' }); + const database = new DatabaseSync(path); + expect(database.prepare('SELECT name FROM d1_migrations').all().map(row => row['name'])).toEqual(migrations.map(migration => migration.name)); + database.close(); + } finally { + rmSync(directory, { recursive: true, force: true }); + } + }); }); diff --git a/server/tests/pool.test.ts b/server/tests/pool.test.ts deleted file mode 100644 index 6bf864f..0000000 --- a/server/tests/pool.test.ts +++ /dev/null @@ -1,312 +0,0 @@ -/** Bounded MySQL pool at capacity: connection bound, queue-limit refusal, waiter cancellation, release and reuse. */ -import { tracingChannel } from 'node:diagnostics_channel'; -import { HttpServer } from '@effect/platform'; -import { SqlClient } from '@effect/sql'; -import { describe, expect, it } from '@effect/vitest'; -import type { AccessScope } from '@sanctum/contracts'; -import { Context, Deferred, Effect, Exit, Fiber, FiberId, Layer, Redacted, Ref, Tracer } from 'effect'; -import type { RowDataPacket } from 'mysql2'; -import { createConnection } from 'mysql2/promise'; -import { Authenticator } from '../src/auth.ts'; -import { dbLayer } from '../src/db.ts'; -import { serverLayer } from '../src/main.ts'; -import { loadMigrations, migrate } from '../src/migrate.ts'; -import { createTestDatabase, runSql, type TestDatabase } from './support/database.ts'; -import { seedWorkspace } from './support/fixtures.ts'; -import { testSsl } from './support/mysql-server.ts'; - -const POOL = 2; - -/** A pool of `POOL` connections and `queueLimit` queue places (0 is unbounded), over a database this test owns. */ -const withSmallPool = (use: (database: TestDatabase) => Effect.Effect, queueLimit = 1) => - Effect.acquireUseRelease( - Effect.promise(createTestDatabase), - database => Effect.provide(use(database), dbLayer({ ...database.mysql, maxConnections: POOL, queueLimit })), - database => Effect.promise(database.drop), - ); - -/** Holds one pooled connection inside a transaction until `release` is signalled; resolves once the connection is held. */ -const hold = Effect.gen(function* () { - const sql = yield* SqlClient.SqlClient; - const acquired = yield* Deferred.make(); - const release = yield* Deferred.make(); - const fiber = yield* Effect.fork(sql.withTransaction(Effect.gen(function* () { - const [row] = yield* sql<{ id: string }>`SELECT CONNECTION_ID() AS id`; - yield* Deferred.succeed(acquired, Number(row!.id)); - yield* Deferred.await(release); - }))); - return { id: yield* Deferred.await(acquired), release: Deferred.succeed(release, undefined), done: Fiber.join(fiber) }; -}); - -const holdAll = Effect.all(Array.from({ length: POOL }, () => hold)); - -/** Connections this account holds on the test database, counted from a connection that is not in the pool. */ -const connectionsOn = (database: TestDatabase) => - Effect.promise(async () => { - const { host, port, username, password } = database.mysql; - const observer = await createConnection({ host, port, user: username, password: Redacted.value(password), ...testSsl }); - try { - const [rows] = await observer.query('SELECT COUNT(*) AS total FROM information_schema.processlist WHERE db = ?', [database.name]); - return Number(rows[0]!.total); - } finally { - await observer.end(); - } - }); - -/** Starts a transaction waiter on the saturated pool and returns once the pool has queued it, proven by the queue limit refusing the next one. */ -const queueWaiter = (work: Effect.Effect) => - Effect.gen(function* () { - const sql = yield* SqlClient.SqlClient; - const waiter = yield* Effect.fork(sql.withTransaction(work)); - yield* Effect.repeat(Effect.yieldNow().pipe(Effect.zipRight(waiter.status)), { until: status => status._tag === 'Suspended' }); - const refused = yield* Effect.flip(sql.withTransaction(Effect.void)); - expect(String(refused.cause)).toMatch(/Queue limit reached/); - return waiter; - }); - -/** If a connection leaked, fewer than `POOL` holders could ever acquire one and this would not complete. */ -const poolIsWhole = Effect.gen(function* () { - const holders = yield* holdAll; - expect(new Set(holders.map(holder => holder.id)).size).toBe(POOL); - yield* Effect.all(holders.map(holder => holder.release)); - yield* Effect.all(holders.map(holder => holder.done)); -}); - -describe('bounded connection pool', () => { - it.effect('opens at most the configured connections, refuses past the queue limit and serves the waiter once a connection is released', () => - withSmallPool(database => - Effect.gen(function* () { - const holders = yield* holdAll; - expect(new Set(holders.map(holder => holder.id)).size).toBe(POOL); - const waiter = yield* queueWaiter(Effect.sync(() => 'served')); - expect(yield* connectionsOn(database)).toBe(POOL); - - yield* holders[0]!.release; - expect(yield* Fiber.join(waiter)).toBe('served'); - yield* Effect.all(holders.map(holder => holder.release)); - yield* Effect.all(holders.map(holder => holder.done)); - - yield* poolIsWhole; - expect(yield* connectionsOn(database)).toBeLessThanOrEqual(POOL); - const [row] = yield* (yield* SqlClient.SqlClient)<{ ok: number }>`SELECT 1 AS ok`; - expect(Number(row?.ok)).toBe(1); - }), - ), - ); - - it.effect('cancelling a queued waiter runs none of its work and leaks no connection', () => - withSmallPool(database => - Effect.gen(function* () { - const holders = yield* holdAll; - const ran = yield* Ref.make(false); - const waiter = yield* queueWaiter(Ref.set(ran, true)); - - // @effect/sql acquires a transaction's connection uninterruptibly, so cancelling the waiter finishes once a slot frees. - const cancel = yield* Effect.fork(Fiber.interrupt(waiter)); - yield* holders[0]!.release; - const exit = yield* Fiber.join(cancel); - expect(Exit.isInterrupted(exit)).toBe(true); - expect(yield* Ref.get(ran)).toBe(false); - - yield* Effect.all(holders.map(holder => holder.release)); - yield* Effect.all(holders.map(holder => holder.done)); - yield* poolIsWhole; - expect(yield* connectionsOn(database)).toBeLessThanOrEqual(POOL); - }), - ), - ); - - it.effect('interrupting a statement while the pool hands it a connection leaks no permit or connection', () => - withSmallPool(database => - Effect.gen(function* () { - const sql = yield* SqlClient.SqlClient; - // With one connection held, the statement's checkout opens a new one, so the interrupt arrives while that is in flight. - const holder = yield* hold; - const asked = yield* Deferred.make(); - const onAsk = (message: { database?: string }) => { - if (message.database === database.name) Deferred.unsafeDone(asked, Exit.void); - }; - const poolConnect = tracingChannel('mysql2:pool:connect'); - poolConnect.start.subscribe(onAsk as never); - const statement = yield* Effect.fork(sql`SELECT 1`); - yield* Effect.ensuring(Deferred.await(asked), Effect.sync(() => poolConnect.start.unsubscribe(onAsk as never))); - expect(Exit.isInterrupted(yield* Fiber.interrupt(statement))).toBe(true); - - yield* holder.release; - yield* holder.done; - yield* poolIsWhole; - }), - ), - ); - - it.effect('queues every waiter without refusal when the queue limit is 0', () => - withSmallPool(database => - Effect.gen(function* () { - const sql = yield* SqlClient.SqlClient; - const holders = yield* holdAll; - const waiters = yield* Effect.all(Array.from({ length: 3 }, (_, n) => Effect.fork(Effect.map(sql<{ n: number }>`SELECT ${n} AS n`, ([row]) => Number(row!.n))))); - // A refused waiter is done at once; holders are released before any assertion so a failure cannot block teardown. - const queued = yield* Effect.repeat(Effect.yieldNow().pipe(Effect.zipRight(Effect.all(waiters.map(waiter => waiter.status)))), { - until: statuses => statuses.every(status => status._tag !== 'Running'), - }); - const open = yield* connectionsOn(database); - yield* Effect.all(holders.map(holder => holder.release)); - yield* Effect.all(holders.map(holder => holder.done)); - - expect(queued.map(status => status._tag)).toEqual(['Suspended', 'Suspended', 'Suspended']); - expect(open).toBe(POOL); - expect(yield* Effect.all(waiters.map(Fiber.join))).toEqual([0, 1, 2]); - yield* poolIsWhole; - }), - 0), - ); -}); - -/** - * The real API on a two-connection pool over a disposable database. A test-owned transaction holds the workspace row lock, so - * a request that is dispatched blocks inside MySQL and keeps its pooled connection, which lets two requests saturate the pool. - * `mysql2` diagnostics channels (public API) report when a request asks the pool for a connection and when its SQL is dispatched. - */ -const serveRenames = Effect.gen(function* () { - const database = yield* Effect.acquireRelease(Effect.promise(createTestDatabase), db => Effect.promise(db.drop)); - yield* Effect.provide(migrate(loadMigrations()), dbLayer(database.mysql)); - const [owner] = yield* Effect.promise(() => runSql(database, seedWorkspace('Pool', ['owner']))); - - // `x-label` names a request; the entry settles with the exit of that request's server fiber. - const ended = new Map>>(); - const endOf = (label: string) => { - const entry = ended.get(label) ?? Deferred.unsafeMake>(FiberId.none); - ended.set(label, entry); - return entry; - }; - const fibers = new Map>(); - const authenticator = Layer.succeed(Authenticator, { - authenticate: request => - Effect.withFiberRuntime(fiber => { - const label = request.headers['x-label'] ?? ''; - fibers.set(label, fiber); - return Effect.as(Effect.forkDaemon(Effect.flatMap(Fiber.await(fiber), exit => Deferred.succeed(endOf(label), exit))), owner!); - }), - }); - const waiting: Array<() => void> = []; - const changed = () => waiting.slice().forEach(check => check()); - // Each SQL statement opens one `sql.execute` span before it asks for a connection. - let statements = 0; - const defaultTracer = yield* Effect.tracer; - const counting = Layer.setTracer( - Tracer.make({ - span: (name, ...rest) => { - if (name === 'sql.execute') { - statements++; - changed(); - } - return defaultTracer.span(name, ...rest); - }, - context: defaultTracer.context, - }), - ); - const context = yield* Layer.build( - serverLayer({ apiPort: 0, mysql: { ...database.mysql, maxConnections: POOL, queueLimit: 10 } }, authenticator).pipe(Layer.provide(counting)), - ); - statements = 0; // the server's own start-up statements are not requests - const address = Context.get(context, HttpServer.HttpServer).address; - if (address._tag !== 'TcpAddress') throw new Error('expected TCP'); - - const dispatched: Array = []; - const finished: Array = []; - const rename = (list: Array) => (message: { query?: string; values?: ReadonlyArray; database?: string }) => { - if (message.database === database.name && message.query?.startsWith('UPDATE workspaces SET name')) list.push(String(message.values?.[0])); - changed(); - }; - const channels = [ - ['mysql2:execute', 'start', rename(dispatched)], - ['mysql2:execute', 'asyncEnd', rename(finished)], - ] as const; - yield* Effect.acquireRelease( - Effect.sync(() => channels.forEach(([name, event, handler]) => tracingChannel(name)[event].subscribe(handler as never))), - () => Effect.sync(() => channels.forEach(([name, event, handler]) => tracingChannel(name)[event].unsubscribe(handler as never))), - ); - /** Resolves when `condition` holds, re-checked after every pool or SQL event. */ - const until = (condition: () => boolean) => - Effect.async(resume => { - const check = () => { - if (!condition()) return; - waiting.splice(waiting.indexOf(check), 1); - resume(Effect.void); - }; - waiting.push(check); - check(); - }); - - const { host, port, username, password } = database.mysql; - const lock = yield* Effect.acquireRelease( - Effect.promise(async () => { - const connection = await createConnection({ host, port, user: username, password: Redacted.value(password), database: database.name, ...testSsl }); - await connection.query('SET autocommit = 0'); - await connection.query('SELECT id FROM workspaces WHERE id = ? FOR UPDATE', [owner!.workspace_id]); - return connection; - }), - connection => Effect.promise(() => connection.end()), - ); - const workspaceName = Effect.promise(async () => { - const [rows] = await lock.query('SELECT name FROM workspaces WHERE id = ?', [owner!.workspace_id]); - return String(rows[0]!.name); - }); - const post = (label: string, name: string, signal?: AbortSignal) => - fetch(`http://127.0.0.1:${address.port}/api/v1/workspace/name`, { - method: 'POST', - headers: { 'content-type': 'application/json', 'x-label': label }, - body: JSON.stringify({ name }), - signal: signal ?? null, - }); - /** The request's fiber has begun its statement and is suspended again: the next thing it waits for is a connection. */ - const waitingForConnection = (label: string, statementNumber: number) => - Effect.zipRight( - until(() => statements >= statementNumber), - Effect.repeat(Effect.yieldNow().pipe(Effect.zipRight(Effect.suspend(() => fibers.get(label)!.status))), { until: status => status._tag === 'Suspended' }), - ); - return { dispatched, finished, until, waitingForConnection, endOf, post, workspaceName, unlock: Effect.promise(() => lock.commit()) }; -}); - -describe('cancelled requests on a saturated pool', () => { - it.scoped('a request cancelled while waiting for a connection never dispatches its write', () => - Effect.gen(function* () { - const server = yield* serveRenames; - const first = server.post('first', 'first'); - const second = server.post('second', 'second'); - // Both statements are inside MySQL, blocked on the row lock, holding both pooled connections. - yield* server.until(() => server.dispatched.length === 2); - - const abort = new AbortController(); - const queued = server.post('queued', 'queued', abort.signal).catch(error => error); - yield* server.waitingForConnection('queued', 3); - abort.abort(); - expect(yield* Effect.promise(() => queued)).toMatchObject({ name: 'AbortError' }); - expect(Exit.isInterrupted(yield* Deferred.await(server.endOf('queued')))).toBe(true); - - yield* server.unlock; - expect((yield* Effect.promise(() => first)).status).toBe(200); - expect((yield* Effect.promise(() => second)).status).toBe(200); - // The pool queue is first-in first-out: once this later write is dispatched, anything cancelled before it has had its chance to run. - expect((yield* Effect.promise(() => server.post('after', 'after'))).status).toBe(200); - expect([...server.dispatched].sort()).toEqual(['after', 'first', 'second']); - expect(yield* server.workspaceName).toBe('after'); - }), - ); - - it.scoped('a request cancelled after its write was dispatched does not roll the write back', () => - Effect.gen(function* () { - const server = yield* serveRenames; - const abort = new AbortController(); - const sent = server.post('sent', 'kept', abort.signal).catch(error => error); - yield* server.until(() => server.dispatched.length === 1); - abort.abort(); - expect(yield* Effect.promise(() => sent)).toMatchObject({ name: 'AbortError' }); - expect(Exit.isInterrupted(yield* Deferred.await(server.endOf('sent')))).toBe(true); - - yield* server.unlock; - yield* server.until(() => server.finished.length === 1); - expect(yield* server.workspaceName).toBe('kept'); - }), - ); -}); diff --git a/server/tests/support/actions.ts b/server/tests/support/actions.ts index ca60b8a..65270d8 100644 --- a/server/tests/support/actions.ts +++ b/server/tests/support/actions.ts @@ -1,5 +1,5 @@ /** Fixture accounts, grants, ledger rows and a fake provider behind `executeIntegrationAction`; nothing leaves the process. */ -import { randomUUID } from 'node:crypto'; +import { createHash, randomUUID } from 'node:crypto'; import { SqlClient } from '@effect/sql'; import { type AccessScope, type ActionId, IntegrationAccountId, JobId, type JobKind, type MeetingId, type PrincipalId, type WorkspaceId } from '@sanctum/contracts'; import { Effect, Layer } from 'effect'; @@ -8,6 +8,7 @@ import type { executeIntegrationAction, IntegrationFailure } from '../../src/int import { LlmClient, makeLlm } from '../../src/llm.ts'; import { claimed } from './capture.ts'; import { fixturePipedream } from './pipedream.ts'; +import { now } from '../../src/sql-dialect.ts'; type ExecuteInput = Parameters[0]; @@ -52,7 +53,7 @@ export const seedAccount = (owner: AccessScope, status: 'active' | 'disconnected const id = IntegrationAccountId.make(randomUUID()); yield* sql` INSERT INTO integration_accounts (id, workspace_id, owner_principal_id, external_user_id, provider_account_id, app_slug, status, created_at, updated_at) - VALUES (${id}, ${owner.workspace_id}, ${owner.principal.id}, ${`user-${id}`}, ${`apn_${id}`}, ${app}, ${status}, UTC_TIMESTAMP(6), UTC_TIMESTAMP(6))`; + VALUES (${id}, ${owner.workspace_id}, ${owner.principal.id}, ${`user-${id}`}, ${`apn_${id}`}, ${app}, ${status}, ${now}, ${now})`; return id; }); @@ -60,7 +61,7 @@ export const seedAccount = (owner: AccessScope, status: 'active' | 'disconnected export const seedCredential = (owner: AccessScope, agent: AccessScope) => Effect.flatMap(SqlClient.SqlClient, sql => sql` INSERT INTO agent_credentials (id, workspace_id, principal_id, owner_principal_id, token_hash, scopes, created_at) - VALUES (${randomUUID()}, ${agent.workspace_id}, ${agent.principal.id}, ${owner.principal.id}, UNHEX(SHA2(${randomUUID()}, 256)), ${JSON.stringify(agent.scopes)}, UTC_TIMESTAMP(6))`); + VALUES (${randomUUID()}, ${agent.workspace_id}, ${agent.principal.id}, ${owner.principal.id}, ${createHash('sha256').update(randomUUID()).digest()}, ${JSON.stringify(agent.scopes)}, ${now})`); /** Restricted meeting; each of `writers` gets write access. */ export const seedMeeting = (workspace_id: WorkspaceId, writers: ReadonlyArray = []) => @@ -69,11 +70,11 @@ export const seedMeeting = (workspace_id: WorkspaceId, writers: ReadonlyArray Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; const id = randomUUID(); - yield* sql`INSERT INTO capture_groups (id, workspace_id, name, created_at) VALUES (${id}, ${workspace_id}, 'Room A', UTC_TIMESTAMP(6))`; + yield* sql`INSERT INTO capture_groups (id, workspace_id, name, created_at) VALUES (${id}, ${workspace_id}, 'Room A', ${now})`; return id; }); @@ -68,8 +69,8 @@ export const commitChunk = (listener: Listener, epoch: CaptureEpochId, sequence: const key = `chunks/${epoch}/${sequence}.wav`; store.objects.set(key, { body: wav, sha256, contentType: 'audio/wav' }); yield* sql`INSERT INTO recording_chunks (id, workspace_id, listener_id, epoch_id, track, sequence, sample_start, sample_count, sample_rate, captured_at, byte_length, sha256, object_key, upload_state, created_at, committed_at) - VALUES (${randomUUID()}, ${listener.workspace_id}, ${listener.listener_id}, ${epoch}, 0, ${sequence}, ${sequence * count}, ${count}, ${RATE}, UTC_TIMESTAMP(6), ${wav.byteLength}, - ${Buffer.from(sha256, 'hex')}, ${key}, 'committed', UTC_TIMESTAMP(6), UTC_TIMESTAMP(6))`; + VALUES (${randomUUID()}, ${listener.workspace_id}, ${listener.listener_id}, ${epoch}, 0, ${sequence}, ${sequence * count}, ${count}, ${RATE}, ${now}, ${wav.byteLength}, + ${Buffer.from(sha256, 'hex')}, ${key}, 'committed', ${now}, ${now})`; }); export const seedConnection = (listener: Listener, epoch_id: CaptureEpochId, purpose = 'asr', provider = 'workers-ai') => @@ -77,7 +78,7 @@ export const seedConnection = (listener: Listener, epoch_id: CaptureEpochId, pur const sql = yield* SqlClient.SqlClient; const id = ProviderConnectionId.make(randomUUID()); yield* sql`INSERT INTO provider_connections (id, workspace_id, epoch_id, track, purpose, provider, model, anchor_sample, sample_rate, opened_at) - VALUES (${id}, ${listener.workspace_id}, ${epoch_id}, 0, ${purpose}, ${provider}, 'fixture', 0, ${RATE}, UTC_TIMESTAMP(6))`; + VALUES (${id}, ${listener.workspace_id}, ${epoch_id}, 0, ${purpose}, ${provider}, 'fixture', 0, ${RATE}, ${now})`; return id; }); @@ -109,9 +110,9 @@ export const speak = ( }; yield* sql`INSERT INTO transcript_segments (id, workspace_id, epoch_id, track, sample_start, sample_end, text, status, revision, origin, provider, model, provider_connection_id, speaker_label, confidence, created_at) VALUES (${segment.id}, ${listener.workspace_id}, ${epoch_id}, 0, ${segment.source.sample_start}, ${segment.source.sample_end}, ${text}, 'final', 1, 'live', 'workers-ai', 'fixture', - ${segment.provider_connection_id}, ${segment.speaker_label}, 0.9, UTC_TIMESTAMP(6))`; + ${segment.provider_connection_id}, ${segment.speaker_label}, 0.9, ${now})`; yield* sql`INSERT INTO transcript_coverage (workspace_id, epoch_id, track, sample_start, sample_end, origin, created_at) - VALUES (${listener.workspace_id}, ${epoch_id}, 0, ${segment.source.sample_start}, ${segment.source.sample_end}, 'live', UTC_TIMESTAMP(6))`; + VALUES (${listener.workspace_id}, ${epoch_id}, 0, ${segment.source.sample_start}, ${segment.source.sample_end}, 'live', ${now})`; return segment; }); @@ -131,10 +132,11 @@ export const hear = (...args: Parameters) => const assignOwners = (workspace_id: WorkspaceId) => Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; - yield* sql`INSERT IGNORE INTO meeting_access (workspace_id, meeting_id, principal_id, access, granted_by, created_at) - SELECT m.workspace_id, m.id, w.principal_id, 'owner', w.principal_id, UTC_TIMESTAMP(6) + yield* sql`INSERT INTO meeting_access (workspace_id, meeting_id, principal_id, access, granted_by, created_at) + SELECT m.workspace_id, m.id, w.principal_id, 'owner', w.principal_id, ${now} FROM meetings m JOIN workspace_members w ON w.workspace_id = m.workspace_id AND w.role IN ('owner', 'admin') AND w.revoked_at IS NULL - WHERE m.workspace_id = ${workspace_id}`; + WHERE m.workspace_id = ${workspace_id} + ON CONFLICT DO NOTHING`; }); export const meetingsOf = (workspace_id: WorkspaceId) => diff --git a/server/tests/support/context.ts b/server/tests/support/context.ts index 999464a..21eb354 100644 --- a/server/tests/support/context.ts +++ b/server/tests/support/context.ts @@ -4,13 +4,13 @@ import { SqlClient } from '@effect/sql'; import { type AccessScope, MeetingId, TranscriptSegmentId, type WorkspaceId } from '@sanctum/contracts'; import { Effect, Layer } from 'effect'; import { dbLayer } from '../../src/db.ts'; -import { loadMigrations, migrate } from '../../src/migrate.ts'; import { createTestDatabase } from './database.ts'; +import { now } from '../../src/sql-dialect.ts'; /** One migrated database shared by a suite; each test seeds its own workspace. */ export const migratedDatabase = Layer.unwrapScoped( - Effect.map(Effect.acquireRelease(Effect.promise(createTestDatabase), database => Effect.promise(database.drop)), database => - Layer.effectDiscard(migrate(loadMigrations())).pipe(Layer.provideMerge(dbLayer(database.mysql)))), + Effect.map(Effect.acquireRelease(Effect.promise(() => createTestDatabase()), database => Effect.promise(database.drop)), database => + dbLayer(database.db)), ); const SAMPLE_RATE = 16_000; @@ -32,16 +32,16 @@ export const seedMeeting = (device: AccessScope, options: { readonly started_at: const [listener, epoch_id, meeting_id] = [randomUUID(), randomUUID(), MeetingId.make(randomUUID())]; const timezone = options.timezone ?? 'America/Los_Angeles'; yield* sql`INSERT INTO listeners (id, workspace_id, principal_id, name, mode, capabilities, created_at) - VALUES (${listener}, ${workspace_id}, ${device.principal.id}, 'Room', 'room', '{}', UTC_TIMESTAMP(6))`; + VALUES (${listener}, ${workspace_id}, ${device.principal.id}, 'Room', 'room', '{}', ${now})`; yield* sql`INSERT INTO capture_epochs (id, workspace_id, listener_id, lease_generation, sample_rate, channels, encoding, sample_start, captured_at, timezone, start_reason, started_at, live_sample_end) VALUES (${epoch_id}, ${workspace_id}, ${listener}, 1, ${SAMPLE_RATE}, 1, 'pcm_s16le', 0, ${options.started_at}, ${timezone}, 'start', ${options.started_at}, 0)`; yield* sql`INSERT INTO meetings (id, workspace_id, listener_id, state, timezone, started_at, processing, visibility, created_at, updated_at) VALUES (${meeting_id}, ${workspace_id}, ${listener}, 'active', ${timezone}, ${options.started_at}, - '{"transcript":"partial","notes":"pending","memory":"pending","recording":"pending"}', ${options.visibility ?? 'workspace'}, UTC_TIMESTAMP(6), UTC_TIMESTAMP(6))`; + '{"transcript":"partial","notes":"pending","memory":"pending","recording":"pending"}', ${options.visibility ?? 'workspace'}, ${now}, ${now})`; if (options.visibility !== 'restricted') { // Workspace visibility grants reads only; the workspace's principals get explicit write so tests that write context to an open meeting stay meaningful. yield* sql`INSERT INTO meeting_access (workspace_id, meeting_id, principal_id, access, granted_by, created_at) - SELECT workspace_id, ${meeting_id}, principal_id, 'write', principal_id, UTC_TIMESTAMP(6) FROM workspace_members WHERE workspace_id = ${workspace_id}`; + SELECT workspace_id, ${meeting_id}, principal_id, 'write', principal_id, ${now} FROM workspace_members WHERE workspace_id = ${workspace_id}`; } yield* sql`INSERT INTO meeting_ranges (workspace_id, meeting_id, boundary_revision, epoch_id, track, sample_start, sample_end) VALUES (${workspace_id}, ${meeting_id}, 1, ${epoch_id}, 0, 0, ${SAMPLE_RATE * 36_000})`; @@ -54,7 +54,7 @@ export const seedSegment = (meeting: FixtureMeeting, from: number, to: number, t const sql = yield* SqlClient.SqlClient; const id = TranscriptSegmentId.make(randomUUID()); yield* sql`INSERT INTO transcript_segments (id, workspace_id, epoch_id, track, sample_start, sample_end, text, status, revision, origin, provider, model, created_at) - VALUES (${id}, ${meeting.workspace_id}, ${meeting.epoch_id}, ${track}, ${from * SAMPLE_RATE}, ${to * SAMPLE_RATE}, ${text}, ${status}, 1, 'live', 'fixture', 'fixture-asr', UTC_TIMESTAMP(6))`; + VALUES (${id}, ${meeting.workspace_id}, ${meeting.epoch_id}, ${track}, ${from * SAMPLE_RATE}, ${to * SAMPLE_RATE}, ${text}, ${status}, 1, 'live', 'fixture', 'fixture-asr', ${now})`; return id; }); @@ -63,5 +63,5 @@ export const grantMeeting = (access: AccessScope, meeting: FixtureMeeting, level Effect.gen(function*() { const sql = yield* SqlClient.SqlClient; yield* sql`INSERT INTO meeting_access (workspace_id, meeting_id, principal_id, access, granted_by, created_at) - VALUES (${meeting.workspace_id}, ${meeting.meeting_id}, ${access.principal.id}, ${level}, ${access.principal.id}, UTC_TIMESTAMP(6))`; + VALUES (${meeting.workspace_id}, ${meeting.meeting_id}, ${access.principal.id}, ${level}, ${access.principal.id}, ${now})`; }); diff --git a/server/tests/support/database.ts b/server/tests/support/database.ts index 75821e8..f22e5c5 100644 --- a/server/tests/support/database.ts +++ b/server/tests/support/database.ts @@ -1,60 +1,48 @@ -/** Per-suite disposable database on the shared test server plus the application layer for it. */ +/** Per-suite disposable in-memory SQLite database plus the application layer for it. */ import { randomBytes } from 'node:crypto'; +import { DatabaseSync } from 'node:sqlite'; import type { SqlClient } from '@effect/sql'; -import { Effect, Redacted } from 'effect'; -import { dbLayer, type MysqlOptions } from '../../src/db.ts'; +import { Effect } from 'effect'; +import { type DbOptions, dbLayer } from '../../src/db.ts'; import { loadMigrations, migrate } from '../../src/migrate.ts'; -import { connectAdmin, testCaCert } from './mysql-server.ts'; export interface TestDatabase { readonly name: string; - readonly mysql: MysqlOptions; + readonly db: DbOptions; } -/** Creates `sanctum_t_` on the server at `adminUrl`; the returned `drop` removes it. Usable outside Vitest. */ -export async function createDatabaseOn(adminUrl: string): Promise Promise }> { - const admin = () => connectAdmin(adminUrl); +/** + * A uniquely named shared-cache memory database: every `dbLayer(database.db)` connects to the same data. + * `drop` closes it and frees the data. + */ +export async function createEmptyDatabase(): Promise Promise }> { const name = `sanctum_t_${randomBytes(6).toString('hex')}`; - const connection = await admin(); - await connection.query(`CREATE DATABASE \`${name}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci`); - await connection.end(); - const url = new URL(adminUrl); - const mysql = { - host: url.hostname, - port: Number(url.port), - database: name, - username: decodeURIComponent(url.username), - password: Redacted.make(decodeURIComponent(url.password)), - maxConnections: 4, - queueLimit: 50, - caCert: testCaCert, - }; - const drop = async () => { - const cleanup = await admin(); - await cleanup.query(`DROP DATABASE IF EXISTS \`${name}\``); - await cleanup.end(); - }; - return { name, mysql, drop }; + const db = { url: `file:${name}?mode=memory&cache=shared` }; + // The data lives while one connection is open, so this one stays until `drop`. + const keeper = new DatabaseSync(db.url); + return { name, db, drop: async () => keeper.close() }; } -/** A database on the Vitest run's shared server (Vitest is imported lazily so other processes can load this module). */ -export const createTestDatabase = async () => createDatabaseOn((await import('vitest')).inject('mysqlAdminUrl')); +/** An empty database with every `migrations-d1` file applied. */ +export async function createTestDatabase() { + const database = await createEmptyDatabase(); + await Effect.runPromise(migrateDatabase(database)); + return database; +} -/** A fresh database dropped with the scope; migrate it with `migrateDatabase`. */ -export const freshDatabase = Effect.acquireRelease(Effect.promise(createTestDatabase), database => Effect.promise(database.drop)); +/** A fresh empty database dropped with the scope; migrate it with `migrateDatabase`. */ +export const freshDatabase = Effect.acquireRelease(Effect.promise(createEmptyDatabase), database => Effect.promise(database.drop)); -export const migrateDatabase = (database: TestDatabase) => Effect.provide(migrate(loadMigrations()), dbLayer(database.mysql)); +/** Applies every `migrations-d1` file to `database`. */ +export const migrateDatabase = (database: TestDatabase) => Effect.provide(migrate(loadMigrations()), dbLayer(database.db)); /** Runs `effect` against `database` and resolves with its result. */ -export const runSql = (database: TestDatabase, effect: Effect.Effect) => Effect.runPromise(Effect.provide(effect, dbLayer(database.mysql))); +export const runSql = (database: TestDatabase, effect: Effect.Effect) => Effect.runPromise(Effect.provide(effect, dbLayer(database.db))); -/** Runs `use` against a fresh database (optionally fully migrated) and drops it afterwards. */ +/** Runs `use` against a fresh database (empty unless `migrated`) and drops it afterwards. */ export const withDatabase = (use: Effect.Effect, options: { readonly migrated?: boolean } = {}) => Effect.acquireUseRelease( - Effect.promise(createTestDatabase), - database => { - const prepared = options.migrated ? Effect.zipRight(migrate(loadMigrations()), use) : use; - return Effect.provide(prepared, dbLayer(database.mysql)); - }, + Effect.promise(options.migrated === true ? createTestDatabase : createEmptyDatabase), + database => Effect.provide(use, dbLayer(database.db)), database => Effect.promise(database.drop), ); diff --git a/server/tests/support/fixtures.ts b/server/tests/support/fixtures.ts index a5069bf..5398da8 100644 --- a/server/tests/support/fixtures.ts +++ b/server/tests/support/fixtures.ts @@ -3,6 +3,7 @@ import { randomUUID } from 'node:crypto'; import { SqlClient } from '@effect/sql'; import { type AccessScope, type AccessScopeName, PrincipalId, WorkspaceId, type WorkspaceRole } from '@sanctum/contracts'; import { Effect } from 'effect'; +import { now } from '../../src/sql-dialect.ts'; const ALL_SCOPES: ReadonlyArray = ['context:read', 'context:write', 'recordings:read', 'actions:request', 'actions:execute', 'workspace:admin']; @@ -24,13 +25,13 @@ export const seedWorkspace = (name: string, roles: ReadonlyArray Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; const workspace_id = WorkspaceId.make(randomUUID()); - yield* sql`INSERT INTO workspaces (id, name, timezone, created_at) VALUES (${workspace_id}, ${name}, 'America/Los_Angeles', UTC_TIMESTAMP(6))`; + yield* sql`INSERT INTO workspaces (id, name, timezone, created_at) VALUES (${workspace_id}, ${name}, 'America/Los_Angeles', ${now})`; return yield* Effect.forEach(roles, role => Effect.gen(function* () { const access = fixtureAccess({ workspace_id, role }); const kind = role === 'agent' || role === 'device' ? role : 'human'; - yield* sql`INSERT INTO principals (id, kind, display_name, created_at) VALUES (${access.principal.id}, ${kind}, ${`${name} ${role}`}, UTC_TIMESTAMP(6))`; - yield* sql`INSERT INTO workspace_members (workspace_id, principal_id, role, created_at) VALUES (${workspace_id}, ${access.principal.id}, ${role}, UTC_TIMESTAMP(6))`; + yield* sql`INSERT INTO principals (id, kind, display_name, created_at) VALUES (${access.principal.id}, ${kind}, ${`${name} ${role}`}, ${now})`; + yield* sql`INSERT INTO workspace_members (workspace_id, principal_id, role, created_at) VALUES (${workspace_id}, ${access.principal.id}, ${role}, ${now})`; return { ...access, principal: { ...access.principal, kind } } satisfies AccessScope; }), ); diff --git a/server/tests/support/media.ts b/server/tests/support/media.ts index 2525722..8a7ffa2 100644 --- a/server/tests/support/media.ts +++ b/server/tests/support/media.ts @@ -24,15 +24,15 @@ import { type AsrBatch, type AsrResult, SpeechToText, whisperSpeechToText } from import { createTestDatabase, type TestDatabase } from './database.ts'; import { seedWorkspace } from './fixtures.ts'; -class TestMysql extends Context.Tag('test/TestMysql')() {} +class TestDb extends Context.Tag('test/TestDb')() {} /** One migrated database for a whole suite; tests isolate themselves with fresh workspaces. */ export const MigratedDatabase = Layer.unwrapScoped( Effect.gen(function* () { - const database = yield* Effect.acquireRelease(Effect.promise(createTestDatabase), db => Effect.promise(db.drop)); - const db = dbLayer(database.mysql); + const database = yield* Effect.acquireRelease(Effect.promise(() => createTestDatabase()), db => Effect.promise(db.drop)); + const db = dbLayer(database.db); yield* Effect.provide(migrate(loadMigrations()), db); - return Layer.merge(db, Layer.succeed(TestMysql, database.mysql)); + return Layer.merge(db, Layer.succeed(TestDb, database.db)); }), ); @@ -189,8 +189,8 @@ const liveClock = Clock.make(); /** Starts the real API server (`serverLayer` from main.ts, port 0) on the suite database; resolves to `host:port`. */ export const serveApi = (server: typeof serverLayer, tokens: Map, media: Layer.Layer) => Effect.gen(function* () { - const mysql = yield* TestMysql; - const context = yield* Effect.withClock(Layer.build(server({ apiPort: 0, mysql }, tokenAuthenticator(tokens), { media })), liveClock); + const db = yield* TestDb; + const context = yield* Effect.withClock(Layer.build(server({ apiPort: 0, db }, tokenAuthenticator(tokens), { media })), liveClock); const address = Context.get(context, HttpServer.HttpServer).address; if (address._tag !== 'TcpAddress') throw new Error('expected TCP'); return `127.0.0.1:${address.port}`; diff --git a/server/tests/support/mysql-server.ts b/server/tests/support/mysql-server.ts deleted file mode 100644 index fe1afcd..0000000 --- a/server/tests/support/mysql-server.ts +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Vitest global setup: one MySQL 8.4 server per test run, shared by every suite in it. - * `SANCTUM_TEST_MYSQL_URL` (an account allowed to CREATE/DROP DATABASE) reuses an external - * server; otherwise a uniquely named throwaway `mysql:8.4` container with small memory - * settings is started and removed on exit. Suites isolate themselves with `testDatabase`. - */ -import { execFileSync } from 'node:child_process'; -import { randomBytes } from 'node:crypto'; -import { createConnection } from 'mysql2/promise'; -import type { TestProject } from 'vitest/node'; - -declare module 'vitest' { - export interface ProvidedContext { - mysqlAdminUrl: string; - } -} - -const IMAGE = 'mirror.gcr.io/library/mysql:8.4'; -const LOW_MEMORY = [ - '--innodb-buffer-pool-size=32M', - '--innodb-log-buffer-size=4M', - '--performance-schema=OFF', - '--skip-log-bin', - '--max-connections=200', - '--table-open-cache=400', -]; - -/** A server that requires TLS (TiDB Cloud) is trusted through `SANCTUM_TEST_MYSQL_CA_CERT`, PEM text. */ -export const testCaCert = process.env.SANCTUM_TEST_MYSQL_CA_CERT; -export const testSsl = testCaCert === undefined ? {} : { ssl: { ca: testCaCert } }; -export const connectAdmin = (url: string) => createConnection({ uri: url, ...testSsl }); - -const docker = (...args: string[]) => execFileSync('docker', args, { encoding: 'utf8' }).trim(); - -async function waitForServer(url: string, deadline: number): Promise { - for (;;) { - try { - const connection = await connectAdmin(url); - await connection.end(); - return; - } catch (error) { - if (Date.now() > deadline) throw error; - await new Promise(resolve => setTimeout(resolve, 500)); - } - } -} - -function startContainer(): { url: string; name: string } { - const name = `sanctum-test-${process.pid}-${randomBytes(3).toString('hex')}`; - const password = randomBytes(12).toString('hex'); - docker('run', '--detach', '--rm', '--name', name, '--memory', '512m', '--publish', '127.0.0.1::3306', - '--env', `MYSQL_ROOT_PASSWORD=${password}`, '--env', 'TZ=UTC', IMAGE, ...LOW_MEMORY); - const port = docker('port', name, '3306/tcp').split('\n')[0]!.split(':').at(-1)!; - return { name, url: `mysql://root:${password}@127.0.0.1:${port}` }; -} - -export default async function setup(project: TestProject) { - const external = process.env.SANCTUM_TEST_MYSQL_URL; - const container = external ? null : startContainer(); - const url = external ?? container!.url; - const stop = () => { - if (container) execFileSync('docker', ['rm', '--force', '--volumes', container.name], { stdio: 'ignore' }); - }; - process.once('exit', stop); - try { - await waitForServer(url, Date.now() + 90_000); - } catch (error) { - stop(); - throw error; - } - project.provide('mysqlAdminUrl', url); - return stop; -} diff --git a/server/tests/support/review-server.ts b/server/tests/support/review-server.ts index c146f53..089a2d1 100644 --- a/server/tests/support/review-server.ts +++ b/server/tests/support/review-server.ts @@ -1,6 +1,6 @@ /** * Real API server for the website's Review end-to-end test: `serverLayer` from main.ts on a free - * port over a disposable migrated database on `SANCTUM_TEST_MYSQL_URL`, seeded with one closed + * port over a disposable migrated in-memory database, seeded with one closed * meeting whose recording was assembled with a gap, context items, a committed memory revision * and an action receipt. A second port serves the in-memory object store behind the URLs the API * signs, refusing expired or unsigned ones. The owner signs in with a real browser session, so @@ -22,9 +22,10 @@ import { loadMigrations, migrate } from '../../src/migrate.ts'; import { assembleRecording } from '../../src/playback.ts'; import { SpeechToTextLive } from '../../src/media/providers.ts'; import { claimed, commitChunk, hear, meetingsOf, seedEpoch, seedListener } from './capture.ts'; -import { createDatabaseOn } from './database.ts'; +import { createTestDatabase } from './database.ts'; import { seedWorkspace } from './fixtures.ts'; import { type MemoryObjectStore, memoryObjectStore } from './object-store.ts'; +import { now } from '../../src/sql-dialect.ts'; /** Seconds `[0, 30)` and `[40, 60)` of audio reached storage; the meeting's speech ends at 55 s. */ const seed = (store: MemoryObjectStore) => @@ -55,9 +56,9 @@ const seed = (store: MemoryObjectStore) => const sql = yield* SqlClient.SqlClient; yield* sql`INSERT INTO actions (id, workspace_id, meeting_id, requested_by, action_key, idempotency_key, args, args_sha256, version, state, attempts, created_at, updated_at) VALUES (${randomUUID()}, ${owner!.workspace_id}, ${meeting_id}, ${owner!.principal.id}, 'gmail-send-email', 'notes-email', '{}', ${randomBytes(32)}, '0.1.4', 'succeeded', 1, - UTC_TIMESTAMP(6), UTC_TIMESTAMP(6))`; + ${now}, ${now})`; // A returning person: the first-run welcome was done before, so it does not cover Review. - yield* sql`UPDATE principals SET onboarded_at = UTC_TIMESTAMP(6) WHERE id = ${owner!.principal.id}`; + yield* sql`UPDATE principals SET onboarded_at = ${now} WHERE id = ${owner!.principal.id}`; return owner!; }); @@ -74,9 +75,7 @@ const objectServer = (store: MemoryObjectStore) => response.writeHead(from === undefined ? 200 : 206, { 'content-type': object.contentType, 'accept-ranges': 'bytes', ...range }).end(body.subarray(start, end + 1)); }); -const adminUrl = process.env['SANCTUM_TEST_MYSQL_URL']; -if (adminUrl === undefined) throw new Error('SANCTUM_TEST_MYSQL_URL must name a MySQL server that allows CREATE/DROP DATABASE'); -const { mysql, drop } = await createDatabaseOn(adminUrl); +const { db: dbOptions, drop } = await createTestDatabase(); const store = memoryObjectStore(); const scope = Effect.runSync(Scope.make()); const objects = objectServer(store); @@ -88,10 +87,10 @@ const stop = async () => { }; process.once('SIGTERM', () => void stop()); try { - const db = Layer.merge(dbLayer(mysql), store.layer); + const db = Layer.merge(dbLayer(dbOptions), store.layer); const owner = seed(store).pipe(Effect.flatMap(({ workspace_id, principal }) => openSession({ workspace_id, principal_id: principal.id }))); const { token: session, csrf_token: csrf } = await Effect.runPromise(Effect.provide(owner, db)); - const layer = serverLayer({ apiPort: 0, mysql }, KernelAuthenticatorLive, { media: Layer.merge(SpeechToTextLive, store.layer) }); + const layer = serverLayer({ apiPort: 0, db: dbOptions }, KernelAuthenticatorLive, { media: Layer.merge(SpeechToTextLive, store.layer) }); const address = Context.get(await Effect.runPromise(Scope.extend(Layer.build(layer), scope)), HttpServer.HttpServer).address; if (address._tag !== 'TcpAddress') throw new Error('expected TCP'); await new Promise(resolve => objects.listen(0, '127.0.0.1', resolve)); diff --git a/server/tests/support/serve.ts b/server/tests/support/serve.ts index fb32081..8bbe87f 100644 --- a/server/tests/support/serve.ts +++ b/server/tests/support/serve.ts @@ -11,11 +11,11 @@ import { fakeApi, fakeDomain } from './fake-domain.ts'; /** `env` overrides process settings read while the layer builds, such as the embedded issuer's. */ export const serveFake = (mcp: Option.Option = Option.none(), env: Record = {}) => Effect.gen(function* () { - const database = yield* Effect.acquireRelease(Effect.promise(createTestDatabase), db => Effect.promise(db.drop)); - const db = dbLayer(database.mysql); + const database = yield* Effect.acquireRelease(Effect.promise(() => createTestDatabase()), db => Effect.promise(db.drop)); + const db = dbLayer(database.db); yield* Effect.provide(migrate(loadMigrations()), db); const domain = fakeDomain(); - const layer = serverLayer({ apiPort: 0, mysql: database.mysql }, domain.authenticator, { + const layer = serverLayer({ apiPort: 0, db: database.db }, domain.authenticator, { api: fakeApi(domain), mcp: Layer.succeed(McpAuthorizationServer, mcp), }); diff --git a/server/tests/support/team-server.ts b/server/tests/support/team-server.ts index 4701e61..95f87f0 100644 --- a/server/tests/support/team-server.ts +++ b/server/tests/support/team-server.ts @@ -1,7 +1,7 @@ /** * Real API server for the website's Team CSP end-to-end test: `serverLayer` from main.ts serving * the built website (`argv[2]`) with its real security headers, over a disposable migrated - * database on `SANCTUM_TEST_MYSQL_URL`. The owner has a WorkOS identity and the workspace a linked + * in-memory database. The owner has a WorkOS identity and the workspace a linked * organization, so `POST /api/v1/workspace/widget-token` runs for real; WorkOS is faked at the * fetch boundary and answers an unsigned token granting the user-management widget. Prints * `{ url, session, csrf }` as one JSON line, serves until SIGTERM, then drops its database. @@ -11,17 +11,15 @@ import { Context, Effect, Exit, Layer, Option, Redacted, Scope } from 'effect'; import { KernelAuthenticatorLive, linkIdentity, openSession } from '../../src/auth.ts'; import { dbLayer } from '../../src/db.ts'; import { serverLayer } from '../../src/main.ts'; -import { loadMigrations, migrate } from '../../src/migrate.ts'; import { WorkosOrganizations, workosSettings } from '../../src/org-sync.ts'; import { SignInSettings } from '../../src/signin.ts'; import { linkWorkspaceOrg } from '../../src/store.ts'; -import { createDatabaseOn } from './database.ts'; +import { createTestDatabase } from './database.ts'; import { seedWorkspace } from './fixtures.ts'; const ISSUER = 'https://team.authkit.test'; const webRoot = process.argv[2]; -const adminUrl = process.env['SANCTUM_TEST_MYSQL_URL']; -if (webRoot === undefined || adminUrl === undefined) throw new Error('usage: SANCTUM_TEST_MYSQL_URL=... team-server.ts '); +if (webRoot === undefined) throw new Error('usage: team-server.ts '); const claims = { sub: 'user_ada', org_id: 'org_acme', permissions: ['widgets:users-table:manage'], exp: Math.floor(Date.now() / 1000) + 3600 }; const token = [{ alg: 'none' }, claims].map(part => Buffer.from(JSON.stringify(part)).toString('base64url')).join('.') + '.fixture'; @@ -29,22 +27,21 @@ const workosFetch = (async (input: string | URL | Request) => String(input) === 'https://api.workos.com/widgets/token' ? Response.json({ token }) : Response.json({ message: 'unexpected request' }, { status: 400 })) as typeof fetch; const seed = Effect.gen(function* () { - yield* migrate(loadMigrations()); const [owner] = yield* seedWorkspace('Acme', ['owner']); yield* linkIdentity({ issuer: ISSUER, subject: 'user_ada', principal_id: owner!.principal.id }); yield* linkWorkspaceOrg({ workspace_id: owner!.workspace_id, issuer: ISSUER, org_id: 'org_acme' }); return yield* openSession({ workspace_id: owner!.workspace_id, principal_id: owner!.principal.id }); }); -const { mysql, drop } = await createDatabaseOn(adminUrl); +const { db: dbOptions, drop } = await createTestDatabase(); const scope = Effect.runSync(Scope.make()); /** Closes the server, drops the database and exits; SIGTERM and a failed start both end here. */ const shutdown = () => Effect.runPromise(Scope.close(scope, Exit.void)).then(drop).then(() => process.exit(0)); process.once('SIGTERM', () => void shutdown()); try { - const session = await Effect.runPromise(Effect.provide(seed, dbLayer(mysql))); + const session = await Effect.runPromise(Effect.provide(seed, dbLayer(dbOptions))); const client = { issuer: new URL(ISSUER), clientId: 'team', clientSecret: Option.none(), redirectUri: new URL('https://team.test/auth/callback'), scopes: 'openid' }; - const layer = serverLayer({ apiPort: 0, mysql, webRoot }, KernelAuthenticatorLive, { + const layer = serverLayer({ apiPort: 0, db: dbOptions, webRoot }, KernelAuthenticatorLive, { signIn: Layer.succeed(SignInSettings, { client: Option.some(client), embeddedIssuer: null }), organizations: Layer.succeed(WorkosOrganizations, Option.some(workosSettings({ apiKey: Redacted.make('sk_test_team'), timeoutMs: 5_000, fetch: workosFetch, issuer: ISSUER, selfServe: false }))), }); diff --git a/server/vitest.config.ts b/server/vitest.config.ts index b2a7096..14ba9bd 100644 --- a/server/vitest.config.ts +++ b/server/vitest.config.ts @@ -4,8 +4,6 @@ export default defineProject({ test: { name: 'server', include: ['tests/**/*.test.ts'], - globalSetup: ['tests/support/mysql-server.ts'], testTimeout: 30_000, - hookTimeout: 120_000, }, });