Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

feat(self-hosting): the api applies code migrations after it starts (#572)

Carl-Gerhard Lindesvärd6d65364254dc
diff --git a/.env.example b/.env.example
index 64a4ffb11..a7cb1bb49 100644
--- a/.env.example
+++ b/.env.example
@@ -9,6 +9,13 @@ CLICKHOUSE_URL="http://localhost:23123/openpanel"
# Generate with: openssl rand -hex 32
ENCRYPTION_KEY=""
+# CODE MIGRATIONS
+# Lets the api/worker apply pending ClickHouse code migrations once it is
+# listening (blocking ones first, then online data moves); a Redis lock makes
+# one process do it. Self-hosted installs set it; without it, run them with
+# `bun run --filter @openpanel/db migrate:deploy` (blocking only) or by name.
+# AUTOMATIC_MIGRATIONS="true"
+
# OBJECT-STORE EXPORT (S3/GCS) tuning — optional, sensible defaults shown.
# The flushExports cron job windows ClickHouse by inserted_at and uploads
# batched files. LAG keeps a safety gap behind now() for in-flight inserts;
diff --git a/.github/smoke/docker-compose.yml b/.github/smoke/docker-compose.yml
index a64a96646..318a86490 100644
--- a/.github/smoke/docker-compose.yml
+++ b/.github/smoke/docker-compose.yml
@@ -82,8 +82,7 @@ services:
command: >
sh -c "
echo 'Running migrations...'
- cd /app/packages/db && bunx [email protected] migrate deploy
- cd /app/packages/core && bun scripts/migrate-code.ts
+ cd /app/packages/db && prisma migrate deploy
cd /app/apps/api && bun run start
"
@@ -92,6 +91,7 @@ services:
environment: &app_env
NODE_ENV: production
SELF_HOSTED: "true"
+ AUTOMATIC_MIGRATIONS: "true"
BATCH_SIZE: "5000"
BATCH_INTERVAL: "10000"
ALLOW_REGISTRATION: "true"
diff --git a/.github/smoke/smoke.sh b/.github/smoke/smoke.sh
index 579347191..187015928 100755
--- a/.github/smoke/smoke.sh
+++ b/.github/smoke/smoke.sh
@@ -101,6 +101,28 @@ assert_migrations_ran() {
echo " op-api migrations applied"
}
+# The api applies ClickHouse code migrations after it starts listening, so a
+# green readiness probe says nothing about them: wait until every migration
+# file in the image is recorded as finished.
+assert_code_migrations_ran() {
+ local expected recorded missing
+ expected=$(docker compose exec -T op-api sh -c \
+ 'ls /app/packages/db/src/code-migrations | grep -E "^[0-9]+-.*\.ts$" | grep -v "\.test\.ts$"' | sort)
+ for _ in $(seq 1 60); do
+ recorded=$(docker compose exec -T op-db psql -U postgres -tAc \
+ 'SELECT name FROM __code_migrations' 2>/dev/null | sort || true)
+ missing=$(comm -23 <(echo "$expected") <(echo "$recorded"))
+ if [ -z "$missing" ]; then
+ echo " code migrations applied ($(echo "$expected" | wc -l | tr -d ' '))"
+ return
+ fi
+ sleep 2
+ done
+ echo "--- not applied ---"
+ echo "$missing"
+ fail "the api did not apply every code migration"
+}
+
# An SSR failure that gets swallowed into a 200 would still show up here.
assert_no_server_errors() {
local svc="$1" logs
@@ -125,6 +147,7 @@ wait_for "dashboard" "$DASHBOARD/api/healthcheck"
echo "==> database migrations"
assert_migrations_ran
+assert_code_migrations_ran
echo "==> SSR rendering (the check that would have caught main-8e60)"
assert_ssr_route "/login"
diff --git a/AGENTS.md b/AGENTS.md
index f0eb05f97..cd4c39a0e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -157,6 +157,38 @@ results — use `GLOBAL IN` or a join. Never commit ClickHouse SQL you have not
against your worktree's database; when replacing a query, diff old and new results
on the same data.
+## Migrations
+
+The api starts serving the moment its container starts. Only Prisma runs before it;
+with `AUTOMATIC_MIGRATIONS=true` (self-hosted installs set it, cloud decides per
+deploy) the api applies pending ClickHouse code migrations itself once it is listening,
+one process at a time (`startCodeMigrations` in
+`packages/core/src/modules/code-migration/`), every blocking one first, then the online
+ones. So write every change in two parts:
+
+- **Blocking** (the default): the fast breaking change the new code needs — a new
+ table or column, a metadata-only `ALTER`. Seconds, whatever the data size: until it
+ lands, the new code runs against the old schema, so keep that window short. The
+ runner warns when one takes over 30 s. A failed migration is retried, so make
+ each statement safe to repeat (`IF NOT EXISTS`, `IF EXISTS`) for when an earlier
+ statement of the same migration already ran.
+- **Online** (`export const online = true`): anything that grows with the data —
+ rebuilding or copying a table, a backfill. It runs after the blocking ones, in the
+ background, and it must:
+ - stay correct while ingestion and the dashboard read and write the table. If the
+ write path reads the table back (the profile buffer does), copy before you swap;
+ otherwise swap first and copy after;
+ - be safe to rerun from any point, since a process can die mid-way and another one
+ resumes it;
+ - never be something a blocking migration depends on.
+
+A change that needs both ships as two migrations: a blocking one that lets the new code
+work with the old data, then an online one that moves the data. Time a blocking
+migration against a large seed (`bun run seed --size xl`) before calling it fast.
+`migrate:deploy` runs only the blocking ones, so a fresh database has its schema before
+anything seeds it; set `AUTOMATIC_MIGRATIONS=true` for your api to apply the online ones,
+or run one by name (`bun ./scripts/migrate-code.ts <file>` in `packages/db`).
+
## Code style
Formatting and linting is ultracite (Biome 2). Do not hand-format against it and do not
diff --git a/apps/api/Dockerfile b/apps/api/Dockerfile
index 9357206da..91e39c680 100644
--- a/apps/api/Dockerfile
+++ b/apps/api/Dockerfile
@@ -89,6 +89,23 @@ RUN find /app/node_modules/.bun -maxdepth 1 -name '*musl*' -prune -exec rm -rf {
find /app/packages -type f -name '*.test.ts' -delete && \
rm -rf /app/packages/sdks
+# PRISMA-CLI — the Prisma CLI the start command runs (`prisma migrate deploy`), with its engines, installed on its own
+# so it does not pull devDependencies into the app's node_modules. Shipping it means a container start needs no
+# registry and downloads nothing. The version must match packages/db's `prisma` devDependency, which generated the
+# client; the build fails if they drift. `prisma --version` proves the CLI runs and its engines are present.
+FROM base AS prisma-cli
+
+ARG PRISMA_VERSION=6.14.0
+
+WORKDIR /opt/prisma
+
+COPY packages/db/package.json /tmp/db-package.json
+
+RUN grep -q "\"prisma\": \"${PRISMA_VERSION}\"" /tmp/db-package.json && \
+ echo '{"name":"prisma-cli","private":true}' > package.json && \
+ bun add --exact "prisma@${PRISMA_VERSION}" && \
+ ./node_modules/.bin/prisma --version
+
# RUNTIME — oven/bun:${BUN_VERSION}-slim, nothing but the app: the isolated node_modules and the source (with
# `build`'s generated output), both from `prod-deps` so the store and the per-package symlinks come from one install.
FROM base AS runtime
@@ -96,10 +113,11 @@ FROM base AS runtime
ENV NODE_ENV=production
# The image runs as `bun` (uid 1000, created by the base image), so HOME must
-# point somewhere that user owns. Docker does not move HOME with USER, and the
-# start command in all three compose files runs `bunx [email protected] migrate
-# deploy`, which writes to bun's install cache under HOME.
+# point somewhere that user owns. Docker does not move HOME with USER, and
+# compose files from before the CLI shipped in the image run `bunx
+# [email protected] migrate deploy`, which writes to bun's install cache under HOME.
ENV HOME=/home/bun
+ENV PATH="/opt/prisma/node_modules/.bin:${PATH}"
WORKDIR /app
@@ -112,11 +130,15 @@ COPY --from=prod-deps --chown=bun:bun /app/apps/api ./apps/api
COPY --from=prod-deps --chown=bun:bun /app/packages ./packages
COPY --from=prod-deps --chown=bun:bun /app/tooling/typescript ./tooling/typescript
-# The shipped start command is `cd /app/packages/db && bunx [email protected] migrate deploy`, so the schema and the
+COPY --from=prisma-cli --chown=bun:bun /opt/prisma /opt/prisma
+
+# The shipped start command is `cd /app/packages/db && prisma migrate deploy`, so the CLI, the schema and the
# migrations directory are load-bearing image content. Assert them at build time rather than let a self-hoster find
-# out at container start. The code migrations' entrypoint is asserted too: `packages/core/scripts/migrate-code.ts`,
-# which the shipped compose files name, forwards to `packages/db/scripts/migrate-code.ts`, so both are load-bearing.
-RUN test -f /app/packages/db/prisma/schema.prisma && \
+# out at container start. The code migrations' entrypoints are asserted too: the api runs
+# `packages/db/src/code-migrations` itself, and `packages/core/scripts/migrate-code.ts`, which older compose files
+# still name, forwards to `packages/db/scripts/migrate-code.ts`.
+RUN prisma --version >/dev/null && \
+ test -f /app/packages/db/prisma/schema.prisma && \
test -d /app/packages/db/prisma/migrations && \
test -f /app/packages/db/scripts/migrate-code.ts && \
test -d /app/packages/db/src/code-migrations && \
diff --git a/apps/api/src/config/env.ts b/apps/api/src/config/env.ts
index 13695d358..2d9f23505 100644
--- a/apps/api/src/config/env.ts
+++ b/apps/api/src/config/env.ts
@@ -373,6 +373,12 @@ const rawSchema = z.object({
* cloud-only cron jobs.
*/
SELF_HOSTED: trueOrOneSchema,
+ /**
+ * Lets this process apply pending code migrations once it is listening; a
+ * Redis lock makes one process do it. Self-hosted installs set it, cloud
+ * decides per deploy.
+ */
+ AUTOMATIC_MIGRATIONS: trueOrOneSchema,
SHUTDOWN_FORCE_EXIT_MS: z.preprocess(
blankToUndefined,
z.coerce.number().int().positive().default(DEFAULT_SHUTDOWN_FORCE_EXIT_MS)
@@ -967,6 +973,7 @@ export interface Config {
QUEUE_NAMESPACE: string | undefined;
ENABLED_QUEUES: EnabledQueue[];
DISABLE_WORKERS: boolean;
+ AUTOMATIC_MIGRATIONS: boolean;
DISABLE_BULLBOARD: boolean;
COOKIE_SECRET: string;
SHUTDOWN_FORCE_EXIT_MS: number;
@@ -1015,6 +1022,7 @@ const envSchema = rawSchema
QUEUE_NAMESPACE: raw.QUEUE_NAMESPACE,
ENABLED_QUEUES: raw.ENABLED_QUEUES,
DISABLE_WORKERS: raw.DISABLE_WORKERS,
+ AUTOMATIC_MIGRATIONS: raw.AUTOMATIC_MIGRATIONS,
DISABLE_BULLBOARD: raw.DISABLE_BULLBOARD,
COOKIE_SECRET: raw.COOKIE_SECRET,
SHUTDOWN_FORCE_EXIT_MS: raw.SHUTDOWN_FORCE_EXIT_MS,
diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts
index 1b2b79a66..af897847a 100644
--- a/apps/api/src/main.ts
+++ b/apps/api/src/main.ts
@@ -54,6 +54,7 @@ import {
type SessionMetricsRedis,
setBooting,
setShuttingDown,
+ startCodeMigrations,
startKafkaEventsConsumer,
startSchedulers,
startWorkers,
@@ -61,6 +62,15 @@ import {
type WorkerHandle,
} from '@openpanel/core';
import { ch } from '@openpanel/db/src/clickhouse/client';
+import {
+ abortMigrationCommands,
+ allowMigrationCommands,
+ MigrationQueryStillRunningError,
+} from '@openpanel/db/src/clickhouse/migration';
+import {
+ getPendingMigrations,
+ runMigration,
+} from '@openpanel/db/src/code-migrations/migrate';
import { db, Prisma } from '@openpanel/db/src/prisma-client';
import {
configureRedisCache,
@@ -407,6 +417,22 @@ async function buildHttpApp(deps: AppDeps) {
return app;
}
+/** Without AUTOMATIC_MIGRATIONS someone applies them by hand; say what is waiting. */
+function warnAboutPendingMigrations(): void {
+ getPendingMigrations()
+ .then((pending) => {
+ if (pending.length > 0) {
+ logger.warn(
+ { pending },
+ 'code migrations pending; set AUTOMATIC_MIGRATIONS=true or run them with migrate-code.ts'
+ );
+ }
+ })
+ .catch((error) => {
+ logger.warn({ err: error }, 'could not list pending code migrations');
+ });
+}
+
/**
* uncaughtException / unhandledRejection: the process state is corrupt, so log and exit fast.
* Fatals are mirrored to the REAL stderr, bypassing the output interceptor: the OTLP flush window is often lost
@@ -465,6 +491,32 @@ async function main() {
);
});
+ // Right after listening, so the api serves from the start and the fast
+ // blocking migrations land within seconds; see AGENTS.md → Migrations.
+ const codeMigrations = config.AUTOMATIC_MIGRATIONS
+ ? startCodeMigrations({
+ redis: deps.redis,
+ logger,
+ migrations: {
+ getPending: getPendingMigrations,
+ run: (file) =>
+ runMigration(file, {
+ clickhouseCluster: Boolean(config.core.clickhouseClustered),
+ selfHosted: Boolean(config.core.selfHosted),
+ databaseUrl: undefined,
+ clickhouseUrl: undefined,
+ }),
+ abort: abortMigrationCommands,
+ allow: allowMigrationCommands,
+ isQueryStillRunning: (error) =>
+ error instanceof MigrationQueryStillRunningError,
+ },
+ })
+ : undefined;
+ if (!codeMigrations) {
+ warnAboutPendingMigrations();
+ }
+
let workers: WorkerHandle | undefined;
let consumer: KafkaConsumerHandle | undefined;
@@ -520,12 +572,16 @@ async function main() {
setShuttingDown(true);
logger.info({ signal }, 'Starting graceful shutdown');
+ // Armed first, so stopping a migration that hangs is bounded too.
const forceExit = setTimeout(() => {
logger.error({ signal }, 'Graceful shutdown timed out — forcing exit');
process.exit(1);
}, config.SHUTDOWN_FORCE_EXIT_MS);
forceExit.unref();
+ // Interrupting is safe: the next process resumes where this one stopped.
+ await codeMigrations?.stop();
+
const exitCode = await runShutdownSequence(
{
stopHttpServer: async () => {
diff --git a/docs/DOCKER_IMAGES.md b/docs/DOCKER_IMAGES.md
index 7cbec6aa7..6090c8a46 100644
--- a/docs/DOCKER_IMAGES.md
+++ b/docs/DOCKER_IMAGES.md
@@ -104,36 +104,44 @@ Cuts deliberately **not** taken, each because M14-203 says so:
Both final stages run as uid 1000 — `bun` in the api image, `node` in the
dashboard image, both created by their base images. The api stage also sets
-`HOME=/home/bun`, because Docker does not move `HOME` with `USER` and the
-shipped start command's `bunx [email protected]` writes to bun's install cache
-under `HOME`. Verified 2026-09-11: `id` inside both running containers reports
+`HOME=/home/bun`, because Docker does not move `HOME` with `USER` and compose
+files from before the image shipped the Prisma CLI run `bunx [email protected]`,
+which writes to bun's install cache under `HOME`. Verified 2026-09-11: `id` inside both running containers reports
uid 1000, the api answers `/healthz/ready` 200, and the dashboard
server-renders `/login`.
## Migrations
-Migrations run in the **api container's start command** (Carl, 2026-09-08 —
-*"I don't want to move the migration out of it"*). All three shipped compose
-files now read:
+Migrations run in the **api container** (Carl, 2026-09-08 — *"I don't want to
+move the migration out of it"*). The start command runs only Prisma before the
+api:
```sh
-cd /app/packages/db && bunx [email protected] migrate deploy
-cd /app/packages/core && bun scripts/migrate-code.ts
+cd /app/packages/db && prisma migrate deploy
```
-- The Prisma CLI is a devDependency, so the image's production-only install
- correctly omits it; `bunx` fetches it at start rather than the image carrying
- the CLI plus `@prisma/engines` (~86 MB) for a once-per-deploy command.
-- **The version is pinned.** A bare `bunx prisma` fetches latest, which can
- drift from the generated client and the schema the image ships. The repo is
- on `prisma 6.14.0`.
+and, with `AUTOMATIC_MIGRATIONS=true` (set by the shipped compose `.env` and
+the Coolify template), the api applies pending ClickHouse code migrations
+itself once it is listening (Carl, 2026-10-20: the api starts at once, fast
+breaking changes first, long data moves after; see AGENTS.md → Migrations). Installs whose
+compose file still runs `cd /app/packages/core && bun scripts/migrate-code.ts`
+first keep working; that step simply finds less to do.
+
+- **The image ships the Prisma CLI** (Carl, 2026-10-20), installed on its own in
+ `/opt/prisma` and on `PATH`, engines included, so a container start reaches
+ no registry and downloads nothing. It adds about 127 MB. The image used to
+ leave the CLI out and fetch it with `bunx` at every start; compose files
+ that still say `bunx [email protected] migrate deploy` keep working, and
+ `openpanel doctor` rewrites them.
+- **The version is pinned** (`PRISMA_VERSION` in `apps/api/Dockerfile`) and the
+ build fails unless it matches `packages/db`'s `prisma` devDependency, the
+ version that generated the client.
- **The code migrations moved to `@openpanel/db` in M15-204** (ADR-022, Carl's
rulings: they run as a script with direct database access and no services).
- The real entrypoint is now `packages/db/scripts/migrate-code.ts`, and
- `packages/core/scripts/migrate-code.ts` is a one-line forwarder to it, kept
- so the command above — which the three shipped compose files still spell
- against `packages/core` — keeps working. The forwarder goes away in the task
- that is allowed to edit `self-hosting/*` and `.github/smoke/*`.
+ The command-line entrypoint is `packages/db/scripts/migrate-code.ts`
+ (`migrate:deploy`, for development, CI and operators), and the api calls the
+ same runner in-process. `packages/core/scripts/migrate-code.ts` is a
+ one-line forwarder kept for compose files that still run it.
- `packages/db/prisma/schema.prisma`, `packages/db/prisma/migrations`,
`packages/db/scripts/migrate-code.ts`, `packages/db/src/code-migrations` and
`packages/core/scripts/migrate-code.ts` are asserted at build time by a `RUN
@@ -141,8 +149,6 @@ cd /app/packages/core && bun scripts/migrate-code.ts
alternative is a self-hoster finding out at container start.
- No new apt packages: the runtime stage is `FROM base`, which already carries
`ca-certificates`, `openssl` and `libssl3` — what Prisma's engines need.
-- Accepted consequence, recorded not re-argued: the api container needs
- npm-registry reach at start and downloads the CLI on a cold start.
Verified 2026-09-11 against a scratch local Postgres, running as uid 1000
inside the built image: `bunx [email protected] migrate deploy` → *"All migrations
diff --git a/packages/core/scripts/migrate-code.ts b/packages/core/scripts/migrate-code.ts
index e415685c9..b19ea2a5d 100644
--- a/packages/core/scripts/migrate-code.ts
+++ b/packages/core/scripts/migrate-code.ts
@@ -1,7 +1,6 @@
-// Forwards to `@openpanel/db`'s code migrations: the shipped compose files and
-// the Coolify template still run `cd /app/packages/core && bun
-// scripts/migrate-code.ts`. Delete once self-hosting/docker-compose.template.yml,
-// self-hosting/coolify.yml and .github/smoke/docker-compose.yml name
-// `packages/db` instead.
+// Forwards to `@openpanel/db`'s code migrations for installs whose compose
+// file still runs `cd /app/packages/core && bun scripts/migrate-code.ts`
+// before starting the api. The shipped compose files no longer do: the api
+// applies pending code migrations itself once it is listening.
import '@openpanel/db/scripts/migrate-code';
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 45330e99b..0c5ca2c42 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -144,6 +144,10 @@ export {
// apps/api's session e2e clears one client's cache between runs.
getClientByIdCached,
} from './modules/client/client.service';
+export {
+ type CodeMigrationsHandle,
+ startCodeMigrations,
+} from './modules/code-migration/code-migration.service';
export { createConversationService } from './modules/conversation/conversation.service';
export type { IServiceCustomEvent } from './modules/custom-event/custom-event.service';
export type {
diff --git a/packages/core/src/modules/code-migration/code-migration.service.test.ts b/packages/core/src/modules/code-migration/code-migration.service.test.ts
new file mode 100644
index 000000000..5dcf17415
--- /dev/null
+++ b/packages/core/src/modules/code-migration/code-migration.service.test.ts
@@ -0,0 +1,240 @@
+import { beforeEach, expect, mock, test } from 'bun:test';
+import { getRedisCache } from '@openpanel/redis';
+import type { Logger } from '../../logger';
+import {
+ type CodeMigrationRunner,
+ startCodeMigrations,
+} from './code-migration.service';
+
+const LOCK_KEY = 'lock:code-migrations';
+const FAST = { lockTtlMs: 300, lockRenewIntervalMs: 50, retryIntervalMs: 50 };
+
+const redis = getRedisCache();
+const STILL_RUNNING = 'query still running';
+
+/** The real client, except that every Lua script call goes through `script`. */
+function withScripts(script: () => Promise<unknown>): typeof redis {
+ return new Proxy(redis, {
+ get(target, property) {
+ if (property === 'evalsha' || property === 'eval') {
+ return script;
+ }
+ const value = Reflect.get(target, property, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+}
+
+function silentLogger(): Logger {
+ const log = () => undefined;
+ const logger: Logger = {
+ fatal: log,
+ error: log,
+ warn: log,
+ info: log,
+ debug: log,
+ trace: log,
+ child: () => logger,
+ };
+ return logger;
+}
+
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+/** A runner over an in-memory list; `run` removes a migration once it ran. */
+function fakeRunner(
+ pending: string[],
+ run: (file: string) => Promise<void> = async () => undefined
+) {
+ const ran: string[] = [];
+ const runner = {
+ getPending: mock(async () => [...pending]),
+ run: mock(async (file: string) => {
+ await run(file);
+ ran.push(file);
+ pending.splice(pending.indexOf(file), 1);
+ }),
+ abort: mock((): void => undefined),
+ allow: mock((): void => undefined),
+ isQueryStillRunning: (error: unknown) =>
+ error instanceof Error && error.message === STILL_RUNNING,
+ } satisfies CodeMigrationRunner;
+ return { runner, ran };
+}
+
+beforeEach(async () => {
+ await redis.del(LOCK_KEY);
+});
+
+test('does nothing and never locks when nothing is pending', async () => {
+ const { runner } = fakeRunner([]);
+ const set = mock(redis.set.bind(redis));
+ const handle = startCodeMigrations(
+ {
+ redis: { ...redis, set } as unknown as typeof redis,
+ logger: silentLogger(),
+ migrations: runner,
+ },
+ FAST
+ );
+ await handle.done;
+ expect(runner.getPending).toHaveBeenCalled();
+ expect(set).not.toHaveBeenCalled();
+ expect(runner.run).not.toHaveBeenCalled();
+});
+
+test('runs pending migrations in order and releases the lock', async () => {
+ const { runner, ran } = fakeRunner(['27-a.ts', '28-b.ts']);
+ const handle = startCodeMigrations(
+ { redis, logger: silentLogger(), migrations: runner },
+ FAST
+ );
+ await handle.done;
+ expect(ran).toEqual(['27-a.ts', '28-b.ts']);
+ expect(runner.allow).toHaveBeenCalled();
+ expect(await redis.get(LOCK_KEY)).toBeNull();
+});
+
+test('waits while another process holds the lock, then takes over', async () => {
+ await redis.set(LOCK_KEY, 'someone-else', 'PX', 10_000);
+ const { runner, ran } = fakeRunner(['27-a.ts']);
+ const handle = startCodeMigrations(
+ { redis, logger: silentLogger(), migrations: runner },
+ FAST
+ );
+ await sleep(200);
+ expect(runner.run).not.toHaveBeenCalled();
+
+ await redis.del(LOCK_KEY);
+ await handle.done;
+ expect(ran).toEqual(['27-a.ts']);
+});
+
+test('retries a failed migration and releases the lock in between', async () => {
+ let attempts = 0;
+ let lockDuringRetryWait: string | null = 'unset';
+ const { runner, ran } = fakeRunner(['27-a.ts'], async () => {
+ attempts += 1;
+ if (attempts === 1) {
+ setTimeout(async () => {
+ lockDuringRetryWait = await redis.get(LOCK_KEY);
+ }, 20);
+ throw new Error('clickhouse went away');
+ }
+ });
+ const handle = startCodeMigrations(
+ { redis, logger: silentLogger(), migrations: runner },
+ FAST
+ );
+ await handle.done;
+ expect(attempts).toBe(2);
+ expect(ran).toEqual(['27-a.ts']);
+ expect(lockDuringRetryWait).toBeNull();
+});
+
+test('aborts when the lock is taken over mid-run', async () => {
+ let release: () => void = () => undefined;
+ const { runner } = fakeRunner(['27-a.ts'], async () => {
+ // Another process steals the lock, then the abort ends this run.
+ await redis.set(LOCK_KEY, 'thief', 'PX', 10_000);
+ await new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ throw new Error('Migration commands aborted');
+ });
+ runner.abort.mockImplementation(() => release());
+ const handle = startCodeMigrations(
+ { redis, logger: silentLogger(), migrations: runner },
+ FAST
+ );
+ await sleep(200);
+ expect(runner.abort).toHaveBeenCalled();
+ // The thief's lock is not ours to release.
+ expect(await redis.get(LOCK_KEY)).toBe('thief');
+ await handle.stop();
+ await handle.done;
+});
+
+test('stop() aborts the running migration and stops retrying', async () => {
+ let release: () => void = () => undefined;
+ const { runner } = fakeRunner(['27-a.ts'], async () => {
+ await new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ throw new Error('Migration commands aborted');
+ });
+ runner.abort.mockImplementation(() => release());
+ const handle = startCodeMigrations(
+ { redis, logger: silentLogger(), migrations: runner },
+ FAST
+ );
+ await sleep(50);
+ await handle.stop();
+ expect(runner.abort).toHaveBeenCalled();
+ // Released by the time stop() settles, not only after the TTL.
+ expect(await redis.get(LOCK_KEY)).toBeNull();
+ await sleep(150);
+ expect(runner.run).toHaveBeenCalledTimes(1);
+});
+
+test('aborts before the lock can expire when renewals keep failing', async () => {
+ let release: () => void = () => undefined;
+ const { runner } = fakeRunner(['28-a.ts'], async () => {
+ await new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ throw new Error('Migration commands aborted');
+ });
+ let abortedAfterMs = 0;
+ const startedAt = performance.now();
+ runner.abort.mockImplementation(() => {
+ abortedAfterMs = performance.now() - startedAt;
+ release();
+ });
+ const handle = startCodeMigrations(
+ {
+ redis: withScripts(() => Promise.reject(new Error('redis unreachable'))),
+ logger: silentLogger(),
+ migrations: runner,
+ },
+ FAST
+ );
+ await sleep(FAST.lockTtlMs + 100);
+ expect(runner.abort).toHaveBeenCalled();
+ expect(abortedAfterMs).toBeLessThan(FAST.lockTtlMs);
+ await handle.stop();
+});
+
+test('keeps the lock when an aborted query may still be running', async () => {
+ const { runner } = fakeRunner(['28-a.ts'], async () => {
+ throw new Error(STILL_RUNNING);
+ });
+ const handle = startCodeMigrations(
+ { redis, logger: silentLogger(), migrations: runner },
+ { ...FAST, retryIntervalMs: 10_000 }
+ );
+ await sleep(50);
+ expect(runner.run).toHaveBeenCalledTimes(1);
+ expect(await redis.get(LOCK_KEY)).not.toBeNull();
+ await handle.stop();
+});
+
+test('ignores a renewal answer that arrives after the run finished', async () => {
+ const { runner } = fakeRunner(['28-a.ts'], async () => {
+ await sleep(FAST.lockRenewIntervalMs + 10);
+ });
+ // The renewal sent during the run answers "not yours" only after it ended.
+ const slowNotOwned = () => sleep(100).then(() => 0);
+ const handle = startCodeMigrations(
+ {
+ redis: withScripts(slowNotOwned),
+ logger: silentLogger(),
+ migrations: runner,
+ },
+ FAST
+ );
+ await handle.done;
+ await sleep(150);
+ expect(runner.run).toHaveBeenCalledTimes(1);
+ expect(runner.abort).not.toHaveBeenCalled();
+});
diff --git a/packages/core/src/modules/code-migration/code-migration.service.ts b/packages/core/src/modules/code-migration/code-migration.service.ts
new file mode 100644
index 000000000..86861271f
--- /dev/null
+++ b/packages/core/src/modules/code-migration/code-migration.service.ts
@@ -0,0 +1,240 @@
+// Applies pending code migrations from the running api, so it serves from the
+// moment it starts instead of waiting on them. The migration functions are
+// injected so the orchestration is testable without `mock.module`.
+
+import type { Redis } from '@openpanel/redis';
+import { generateSecureId } from '@openpanel/shared';
+import { defineRedisScript } from '../../buffers/redis-script';
+import type { Logger } from '../../logger';
+
+const LOCK_KEY = 'lock:code-migrations';
+// Short, and renewed while a migration runs, so a crashed holder frees the
+// lock within a minute instead of blocking the others for hours.
+const LOCK_TTL_MS = 60_000;
+const LOCK_RENEW_INTERVAL_MS = 20_000;
+const RETRY_INTERVAL_MS = 5 * 60_000;
+
+const renewLockScript = defineRedisScript(`
+if redis.call("GET", KEYS[1]) == ARGV[1] then
+ return redis.call("PEXPIRE", KEYS[1], ARGV[2])
+end
+return 0
+`);
+
+const releaseLockScript = defineRedisScript(`
+if redis.call("GET", KEYS[1]) == ARGV[1] then
+ return redis.call("DEL", KEYS[1])
+end
+return 0
+`);
+
+export interface CodeMigrationRunner {
+ /** Unfinished migrations in run order: blocking first, then online. */
+ getPending: () => Promise<string[]>;
+ /** Runs one migration and records it as finished; throws on failure. */
+ run: (file: string) => Promise<void>;
+ /**
+ * Whether `run` failed because it aborted a statement ClickHouse did not
+ * confirm stopping. The lock is then kept until it expires, so no other
+ * process starts the same copy while the old one may still be running.
+ */
+ isQueryStillRunning: (error: unknown) => boolean;
+ /** Kills the statement in flight; nothing more runs until `allow()`. */
+ abort: () => void;
+ allow: () => void;
+}
+
+export interface CodeMigrationDeps {
+ redis: Redis;
+ logger: Logger;
+ migrations: CodeMigrationRunner;
+}
+
+export interface CodeMigrationTiming {
+ lockTtlMs: number;
+ lockRenewIntervalMs: number;
+ retryIntervalMs: number;
+}
+
+export interface CodeMigrationsHandle {
+ /**
+ * Stops retrying and aborts a migration this process is running; settles
+ * once that run has unwound and released the lock, so the next process can
+ * take over at once instead of waiting out the lock's TTL.
+ */
+ stop: () => Promise<void>;
+ /** Settles once nothing is pending or `stop()` was called. */
+ done: Promise<void>;
+}
+
+type AttemptResult = 'finished' | 'retry';
+
+/**
+ * Every process calls this once it listens; the lock picks one to do the
+ * work, so replicas never run a migration twice at once. The others check
+ * back every `retryIntervalMs`, so a holder that dies mid-way is replaced and
+ * the migration resumes, which online migrations must support.
+ */
+export function startCodeMigrations(
+ deps: CodeMigrationDeps,
+ timing: CodeMigrationTiming = {
+ lockTtlMs: LOCK_TTL_MS,
+ lockRenewIntervalMs: LOCK_RENEW_INTERVAL_MS,
+ retryIntervalMs: RETRY_INTERVAL_MS,
+ }
+): CodeMigrationsHandle {
+ const { redis, migrations } = deps;
+ const logger = deps.logger.child({ name: 'code-migrations' });
+ let isStopped = false;
+ let retryTimer: ReturnType<typeof setTimeout> | undefined;
+ let running: Promise<void> | undefined;
+ let finish: () => void = () => undefined;
+ const done = new Promise<void>((resolve) => {
+ finish = resolve;
+ });
+
+ async function runPending(lockId: string): Promise<void> {
+ let isLockLost = false;
+ let isFinished = false;
+ let isQueryStillRunning = false;
+ let lastRenewedAt = performance.now();
+ // Past this, the lock may expire before the next renewal succeeds.
+ const maxRenewalGapMs = timing.lockTtlMs - timing.lockRenewIntervalMs;
+
+ const loseLock = (message: string, error?: unknown) => {
+ if (isFinished || isLockLost) {
+ return;
+ }
+ // Another process may take over now; two copies running at once is the
+ // one thing an online migration cannot survive.
+ isLockLost = true;
+ logger.error({ err: error }, message);
+ migrations.abort();
+ };
+
+ const renewTimer = setInterval(async () => {
+ try {
+ const renewed = await renewLockScript(
+ redis,
+ [LOCK_KEY],
+ [lockId, String(timing.lockTtlMs)]
+ );
+ if (renewed === 1) {
+ lastRenewedAt = performance.now();
+ return;
+ }
+ loseLock('code migration lock lost, aborting');
+ } catch (error) {
+ if (performance.now() - lastRenewedAt >= maxRenewalGapMs) {
+ loseLock('code migration lock cannot be renewed, aborting', error);
+ return;
+ }
+ logger.warn({ err: error }, 'code migration lock renewal failed');
+ }
+ }, timing.lockRenewIntervalMs);
+
+ try {
+ for (const file of await migrations.getPending()) {
+ if (isStopped || isLockLost) {
+ return;
+ }
+ const startedAt = performance.now();
+ logger.info({ migration: file }, 'code migration started');
+ await migrations.run(file);
+ logger.info(
+ {
+ migration: file,
+ durationMs: Math.round(performance.now() - startedAt),
+ },
+ 'code migration finished'
+ );
+ }
+ } catch (error) {
+ isQueryStillRunning = migrations.isQueryStillRunning(error);
+ throw error;
+ } finally {
+ isFinished = true;
+ clearInterval(renewTimer);
+ if (isQueryStillRunning) {
+ logger.error(
+ 'an aborted code migration query may still run; keeping the lock until it expires'
+ );
+ } else {
+ await releaseLockScript(redis, [LOCK_KEY], [lockId]).catch(
+ () => undefined
+ );
+ }
+ }
+ }
+
+ async function attempt(): Promise<AttemptResult> {
+ const pending = await migrations.getPending();
+ if (pending.length === 0) {
+ return 'finished';
+ }
+
+ const lockId = generateSecureId('lock');
+ const acquired = await redis.set(
+ LOCK_KEY,
+ lockId,
+ 'PX',
+ timing.lockTtlMs,
+ 'NX'
+ );
+ if (acquired !== 'OK') {
+ logger.info(
+ { pending },
+ 'code migrations pending; another process is running them'
+ );
+ return 'retry';
+ }
+
+ migrations.allow();
+ await runPending(lockId);
+ return (await migrations.getPending()).length === 0 ? 'finished' : 'retry';
+ }
+
+ async function tick(): Promise<void> {
+ if (isStopped) {
+ return;
+ }
+ let result: AttemptResult = 'retry';
+ try {
+ result = await attempt();
+ } catch (error) {
+ if (!isStopped) {
+ logger.error({ err: error }, 'code migration failed, retrying later');
+ }
+ }
+ if (result === 'finished') {
+ logger.info('code migrations up to date');
+ }
+ if (result === 'finished' || isStopped) {
+ finish();
+ return;
+ }
+ scheduleTick(timing.retryIntervalMs);
+ }
+
+ function scheduleTick(delayMs: number) {
+ retryTimer = setTimeout(() => {
+ running = tick();
+ }, delayMs);
+ retryTimer.unref?.();
+ }
+
+ scheduleTick(0);
+
+ return {
+ stop: async () => {
+ isStopped = true;
+ if (retryTimer) {
+ clearTimeout(retryTimer);
+ }
+ migrations.abort();
+ await running;
+ finish();
+ },
+ done,
+ };
+}
diff --git a/packages/db/src/clickhouse/migration.ts b/packages/db/src/clickhouse/migration.ts
index 3de160acb..7fdf8929f 100644
--- a/packages/db/src/clickhouse/migration.ts
+++ b/packages/db/src/clickhouse/migration.ts
@@ -409,6 +409,41 @@ export function countRows(tableName: string) {
return `SELECT count() FROM ${tableName}`;
}
+// KILL QUERY ... SYNC returns once the query stopped; past this, assume it
+// did not.
+const KILL_QUERY_TIMEOUT_MS = 60_000;
+
+/**
+ * An aborted statement that ClickHouse did not confirm stopping. It may still
+ * be writing, so nothing may start the same work until it is known to be gone.
+ */
+export class MigrationQueryStillRunningError extends Error {
+ constructor(queryId: string, cause: unknown) {
+ super(`Could not confirm migration query ${queryId} stopped`, { cause });
+ this.name = 'MigrationQueryStillRunningError';
+ }
+}
+
+let isAbortRequested = false;
+const inFlight = new Set<AbortController>();
+
+/**
+ * Stops runClickhouseMigrationCommands: the statement in flight is killed and
+ * no further one starts, in this call or a later one, until
+ * allowMigrationCommands(). Sticky because a migration may issue several
+ * calls, and an abort between two of them must not let the second start.
+ */
+export function abortMigrationCommands() {
+ isAbortRequested = true;
+ for (const controller of inFlight) {
+ controller.abort();
+ }
+}
+
+export function allowMigrationCommands() {
+ isAbortRequested = false;
+}
+
export async function runClickhouseMigrationCommands(sqls: string[]) {
let abort: AbortController | undefined;
let activeQueryId: string | undefined;
@@ -431,7 +466,14 @@ export async function runClickhouseMigrationCommands(sqls: string[]) {
try {
for (const sql of sqls) {
+ if (isAbortRequested) {
+ throw new Error('Migration commands aborted');
+ }
+ if (abort) {
+ inFlight.delete(abort);
+ }
abort = new AbortController();
+ inFlight.add(abort);
let timer: NodeJS.Timeout | undefined;
let resolve: ((value: unknown) => void) | undefined;
activeQueryId = crypto.createHash('sha256').update(sql).digest('hex');
@@ -524,18 +566,25 @@ export async function runClickhouseMigrationCommands(sqls: string[]) {
}
if (activeQueryId) {
+ // An INSERT ... SELECT keeps running on the server after the client
+ // goes away, so the abort is only done once ClickHouse says it stopped.
try {
await chMigrationClient.command({
- query: `KILL QUERY WHERE query_id = '${activeQueryId}'`,
+ query: `KILL QUERY WHERE query_id = '${activeQueryId}' SYNC`,
+ abort_signal: AbortSignal.timeout(KILL_QUERY_TIMEOUT_MS),
});
console.log(`Successfully killed query ${activeQueryId}`);
} catch (err) {
console.error(`Failed to kill query ${activeQueryId}:`, err);
+ throw new MigrationQueryStillRunningError(activeQueryId, err);
}
}
throw e;
} finally {
+ if (abort) {
+ inFlight.delete(abort);
+ }
// Clean up event listeners. bun-types' `Process.off` override declares
// only its own "memoryPressure" overload and wins over the @types/node
// Signals overload, so the cast is what keeps this compiling (dropping it
diff --git a/packages/db/src/code-migrations/migrate.ts b/packages/db/src/code-migrations/migrate.ts
index e793f49b9..1d3d41864 100644
--- a/packages/db/src/code-migrations/migrate.ts
+++ b/packages/db/src/code-migrations/migrate.ts
@@ -1,6 +1,7 @@
import fs from 'node:fs';
import path, { dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { chMigrationClient } from '../clickhouse/migration';
import { db } from '../prisma-client';
import {
type CodeMigrationEnv,
@@ -13,45 +14,173 @@ import {
} from './helpers';
const MIGRATIONS_DIR = dirname(fileURLToPath(import.meta.url));
+// The api is already serving while blocking migrations run, against the old
+// schema until they finish, so they must stay fast.
+const SLOW_BLOCKING_MIGRATION_MS = 30_000;
-export async function runCodeMigrations(env: CodeMigrationEnv) {
- const args = process.argv.slice(2);
- const migration = args.filter((arg) => !arg.startsWith('--'))[0];
+/**
+ * A code migration module. The api applies pending ones after it starts
+ * listening (`startCodeMigrations` in @openpanel/core): every blocking one
+ * first, then the `online` ones. `online` marks work that grows with the data:
+ * it must stay correct under live traffic and resume after an interruption,
+ * and no blocking migration may depend on it.
+ */
+interface CodeMigration {
+ up: (env: CodeMigrationEnv) => Promise<void>;
+ online?: boolean;
+}
+
+function migrationVersion(file: string) {
+ return Number.parseInt(file.split('-')[0] ?? '', 10);
+}
- const migrations = fs
- .readdirSync(MIGRATIONS_DIR)
- .filter((file) => {
- const version = file.split('-')[0];
+function listMigrationFiles() {
+ return (
+ fs
+ .readdirSync(MIGRATIONS_DIR)
// A migration's test sits beside it and must not run as a migration.
- return (
- !Number.isNaN(Number.parseInt(version ?? '', 10)) &&
- file.endsWith('.ts') &&
- !file.endsWith('.test.ts')
- );
- })
- .sort((a, b) => {
- const aVersion = Number.parseInt(a.split('-')[0]!, 10);
- const bVersion = Number.parseInt(b.split('-')[0]!, 10);
- return aVersion - bVersion;
+ .filter(
+ (file) =>
+ !Number.isNaN(migrationVersion(file)) &&
+ file.endsWith('.ts') &&
+ !file.endsWith('.test.ts')
+ )
+ .sort((a, b) => migrationVersion(a) - migrationVersion(b))
+ );
+}
+
+async function loadMigration(file: string): Promise<CodeMigration> {
+ return await import(path.join(MIGRATIONS_DIR, file));
+}
+
+async function getFinishedMigrationNames() {
+ const finished = await db.codeMigration.findMany({ select: { name: true } });
+ return new Set(finished.map((migration) => migration.name));
+}
+
+// Present on every install once the first migrations ran; Distributed when
+// the database is a cluster.
+const LAYOUT_TABLES = ['events', 'sessions', 'profiles'];
+
+/**
+ * A migration written for one ClickHouse layout and run against the other
+ * swaps or rewrites the wrong tables, so the configured mode must match what
+ * the database actually has. A database without these tables yet is being
+ * created and has nothing to check.
+ */
+async function assertClusterModeMatchesDatabase(env: CodeMigrationEnv) {
+ const response = await chMigrationClient.query({
+ query:
+ 'SELECT name, engine FROM system.tables WHERE database = currentDatabase() AND name IN {names:Array(String)}',
+ query_params: { names: LAYOUT_TABLES },
+ format: 'JSONEachRow',
+ });
+ const tables = await response.json<{ name: string; engine: string }>();
+ if (tables.length === 0) {
+ return;
+ }
+ const isDistributed = tables.some((table) => table.engine === 'Distributed');
+ const isCluster = getIsCluster(env);
+ if (isDistributed !== isCluster) {
+ const found = tables
+ .map((table) => `${table.name}=${table.engine}`)
+ .join(', ');
+ throw new Error(
+ `CLICKHOUSE_CLUSTER is ${isCluster ? 'set' : 'not set'}, but the database has ${found}. Refusing to migrate: fix CLICKHOUSE_CLUSTER for this process.`
+ );
+ }
+}
+
+/**
+ * Runs one migration and records it as finished. Throws on failure. Warns
+ * when a blocking migration is slow enough to be a long window of the api
+ * running against the old schema.
+ */
+export async function runMigration(file: string, env: CodeMigrationEnv) {
+ await assertClusterModeMatchesDatabase(env);
+ const migration = await loadMigration(file);
+ const startedAt = performance.now();
+ await migration.up(env);
+ const durationMs = performance.now() - startedAt;
+ if (!migration.online && durationMs > SLOW_BLOCKING_MIGRATION_MS) {
+ printBoxMessage('🐢 Slow blocking migration', [
+ `${file} took ${Math.round(durationMs / 1000)}s; the api ran against the old schema meanwhile.`,
+ 'Work that grows with the data belongs in an online migration (AGENTS.md → Migrations).',
+ ]);
+ }
+ if (!(getIsDry() || getShouldIgnoreRecord())) {
+ await db.codeMigration.upsert({
+ where: { name: file },
+ update: { name: file },
+ create: { name: file },
});
+ }
+}
+
+/**
+ * Unfinished migrations in the order the api runs them: blocking ones first,
+ * so a fast breaking change never waits behind a long online data move.
+ */
+export async function getPendingMigrations() {
+ const finished = await getFinishedMigrationNames();
+ const blocking: string[] = [];
+ const online: string[] = [];
+ for (const file of listMigrationFiles()) {
+ if (finished.has(file)) {
+ continue;
+ }
+ if ((await loadMigration(file)).online) {
+ online.push(file);
+ } else {
+ blocking.push(file);
+ }
+ }
+ return [...blocking, ...online];
+}
+
+async function runMigrationOrExit(file: string, env: CodeMigrationEnv) {
+ printBoxMessage('⚡️ Running Migration ⚡️ ', [`${file}`]);
+ try {
+ await runMigration(file, env);
+ } catch (error) {
+ printBoxMessage('❌ Migration Failed ❌', [
+ `Error running migration ${file}:`,
+ error,
+ ]);
+ process.exit(1);
+ }
+}
- const finishedMigrations = await db.codeMigration.findMany();
+/**
+ * The command-line runner (`migrate:deploy`, for development, CI and
+ * operators): every unfinished blocking migration, in order, so a fresh
+ * database has its schema before anything seeds it. Online ones are left to
+ * the api. A migration named on the command line runs either way.
+ */
+export async function runCodeMigrations(env: CodeMigrationEnv) {
+ const args = process.argv.slice(2);
+ const named = args.filter((arg) => !arg.startsWith('--'))[0];
+
+ const finished = await getFinishedMigrationNames();
+ const unfinished = listMigrationFiles().filter((file) => !finished.has(file));
+ const online = new Set<string>();
+ for (const file of unfinished) {
+ if ((await loadMigration(file)).online) {
+ online.add(file);
+ }
+ }
printBoxMessage('📋 Plan', [
'\t✅ Finished:',
- ...finishedMigrations.map(
- (migration) => `\t- ${migration.name} (${migration.createdAt})`
- ),
+ ...[...finished].map((name) => `\t- ${name}`),
'',
'\t🔄 Will run now:',
- ...migrations
- .filter(
- (migration) =>
- !finishedMigrations.some(
- (finishedMigration) => finishedMigration.name === migration
- )
- )
- .map((migration) => `\t- ${migration}`),
+ ...unfinished
+ .filter((file) => !online.has(file))
+ .map((file) => `\t- ${file}`),
+ '',
+ '\t🌙 Online, applied by the api once it is up:',
+ ...[...online].map((file) => `\t- ${file}`),
]);
printBoxMessage('🤝 Config', [
@@ -73,46 +202,16 @@ export async function runCodeMigrations(env: CodeMigrationEnv) {
}
}
- if (migration) {
- await runMigration(migration, env);
+ if (named) {
+ await runMigrationOrExit(named, env);
} else {
- for (const file of migrations) {
- if (finishedMigrations.some((migration) => migration.name === file)) {
- printBoxMessage('✅ Already Migrated ✅', [`${file}`]);
- continue;
+ for (const file of unfinished) {
+ if (!online.has(file)) {
+ await runMigrationOrExit(file, env);
}
-
- await runMigration(file, env);
}
}
console.log('Migrations finished');
process.exit(0);
}
-
-async function runMigration(file: string, env: CodeMigrationEnv) {
- printBoxMessage('⚡️ Running Migration ⚡️ ', [`${file}`]);
- try {
- const migration = await import(path.join(MIGRATIONS_DIR, file));
- await migration.up(env);
- if (!(getIsDry() || getShouldIgnoreRecord())) {
- await db.codeMigration.upsert({
- where: {
- name: file,
- },
- update: {
- name: file,
- },
- create: {
- name: file,
- },
- });
- }
- } catch (error) {
- printBoxMessage('❌ Migration Failed ❌', [
- `Error running migration ${file}:`,
- error,
- ]);
- process.exit(1);
- }
-}
diff --git a/self-hosting/.env.template b/self-hosting/.env.template
index 6aa7b5cce..d72cffc44 100644
--- a/self-hosting/.env.template
+++ b/self-hosting/.env.template
@@ -1,5 +1,6 @@
NODE_ENV="production"
SELF_HOSTED="true"
+AUTOMATIC_MIGRATIONS="true"
BATCH_SIZE="5000"
BATCH_INTERVAL="10000"
ALLOW_REGISTRATION="false"
diff --git a/self-hosting/cli/src/doctor/checks.ts b/self-hosting/cli/src/doctor/checks.ts
index bb860a283..9be5efa7c 100644
--- a/self-hosting/cli/src/doctor/checks.ts
+++ b/self-hosting/cli/src/doctor/checks.ts
@@ -375,25 +375,47 @@ export const workerHealthcheck: Check = (install) => {
};
};
+const replaceApiCommand = (target: Install) => {
+ const next = templateCompose.getIn(['services', 'op-api', 'command']);
+ target.compose.setIn(['services', 'op-api', 'command'], next);
+};
+
export const apiMigrations: Check = (install) => {
const command = install.compose.getIn(['services', 'op-api', 'command']);
- if (
- typeof command !== 'string' ||
- command.includes('scripts/migrate-code.ts')
- ) {
+ if (typeof command !== 'string') {
return null;
}
- return {
- id: 'compose/api-migrations',
- severity: 'error',
- title: 'op-api start command runs the old migration steps',
- detail:
- 'v3 migrates with prisma + scripts/migrate-code.ts under bun; pnpm is gone from the image.',
- fix: (target) => {
- const next = templateCompose.getIn(['services', 'op-api', 'command']);
- target.compose.setIn(['services', 'op-api', 'command'], next);
- },
- };
+ if (command.includes('pnpm')) {
+ return {
+ id: 'compose/api-migrations',
+ severity: 'error',
+ title: 'op-api start command runs the old migration steps',
+ detail:
+ 'v3 runs the Prisma CLI the image ships and the api applies code migrations; pnpm is gone from the image.',
+ fix: replaceApiCommand,
+ };
+ }
+ if (command.includes('bunx prisma')) {
+ return {
+ id: 'compose/api-migrations',
+ severity: 'warn',
+ title: 'op-api downloads the Prisma CLI at every start',
+ detail:
+ 'The image ships the Prisma CLI, so the api can start without reaching the npm registry.',
+ fix: replaceApiCommand,
+ };
+ }
+ if (command.includes('scripts/migrate-code.ts')) {
+ return {
+ id: 'compose/api-migrations',
+ severity: 'warn',
+ title: 'op-api runs the code migrations before it starts',
+ detail:
+ 'The api now starts at once and applies code migrations itself, so a long migration no longer keeps it down.',
+ fix: replaceApiCommand,
+ };
+ }
+ return null;
};
export const kafkaBrokers: Check = (install) => {
@@ -553,6 +575,23 @@ export const selfHosted: Check = (install) => {
};
};
+export const automaticMigrations: Check = (install) => {
+ const value = install.env.get('AUTOMATIC_MIGRATIONS');
+ if (value === 'true' || value === '1') {
+ return null;
+ }
+ return {
+ id: 'env/automatic-migrations',
+ // The api still boots without it, so it must not block `reload`;
+ // `upgrade` applies the fix either way.
+ severity: 'warn',
+ title: `AUTOMATIC_MIGRATIONS is ${value === undefined ? 'not set' : `"${value}"`}`,
+ detail:
+ 'The api and worker apply ClickHouse code migrations only when it is `true` or `1`.',
+ fix: (target) => target.env.set('AUTOMATIC_MIGRATIONS', 'true'),
+ };
+};
+
export const enabledQueues: Check = (install) => {
const value = install.env.get('ENABLED_QUEUES');
if (!value) {
@@ -700,6 +739,7 @@ export const checks: Check[] = [
apiUrl,
adminCredentials,
selfHosted,
+ automaticMigrations,
enabledQueues,
removedEnvVars,
caddyBullboardRedirect,
diff --git a/self-hosting/cli/test/doctor.test.ts b/self-hosting/cli/test/doctor.test.ts
index 681b3f072..c54252eed 100644
--- a/self-hosting/cli/test/doctor.test.ts
+++ b/self-hosting/cli/test/doctor.test.ts
@@ -36,6 +36,7 @@ describe('doctor on a v1 install', () => {
'compose/api-migrations',
'env/kafka-brokers',
'env/kafka-partitions',
+ 'env/automatic-migrations',
'env/enabled-queues',
'env/removed-vars',
'caddy/bullboard-redirect',
@@ -62,8 +63,10 @@ describe('doctor on a v1 install', () => {
);
expect(compose.services['op-worker'].environment).toContain('ROLE=worker');
expect(compose.services['op-api'].command).toContain(
- 'scripts/migrate-code.ts'
+ 'prisma migrate deploy'
);
+ expect(compose.services['op-api'].command).not.toContain('pnpm');
+ expect(compose.services['op-api'].command).not.toContain('bunx');
expect(compose.services['op-api'].depends_on).toHaveProperty('op-rp');
expect(compose.services['op-worker'].depends_on).toHaveProperty('op-rp');
expect(JSON.stringify(compose.services['op-worker'].healthcheck)).toContain(
@@ -71,6 +74,35 @@ describe('doctor on a v1 install', () => {
);
});
+ test('a v3 start command that downloads Prisma or runs the code migrations is rewritten', () => {
+ const install = loadInstall(V1_FIXTURE);
+ applyFixes(install);
+ install.compose.setIn(
+ ['services', 'op-api', 'command'],
+ [
+ 'sh -c "',
+ ' cd /app/packages/db && bunx [email protected] migrate deploy',
+ ' cd /app/packages/core && bun scripts/migrate-code.ts',
+ ' cd /app/apps/api && bun run start',
+ '"',
+ ].join('\n')
+ );
+
+ const finding = runDoctor(install).find(
+ (candidate) => candidate.id === 'compose/api-migrations'
+ );
+ expect(finding?.severity).toBe('warn');
+
+ applyFixes(install);
+ const command = String(
+ install.compose.getIn(['services', 'op-api', 'command'])
+ );
+ expect(command).not.toContain('migrate-code.ts');
+ expect(command).not.toContain('bunx');
+ expect(command).toContain('prisma migrate deploy');
+ expect(install.env.get('AUTOMATIC_MIGRATIONS')).toBe('true');
+ });
+
test('env keeps user values and only touches what is stale', () => {
const install = loadInstall(V1_FIXTURE);
applyFixes(install);
diff --git a/self-hosting/coolify.yml b/self-hosting/coolify.yml
index d2f64496e..625bc7acc 100644
--- a/self-hosting/coolify.yml
+++ b/self-hosting/coolify.yml
@@ -112,8 +112,8 @@ services:
restart: always
# Same contract as docker-compose.template.yml's op-api: no second package
# manager exists in this image (P13 / ADR-014), migrations run in this
- # container's start command, and the Prisma CLI is fetched by `bunx` at a
- # PINNED version rather than shipped. See the long note there.
+ # container's start command, with the Prisma CLI the image ships. See the
+ # long note there.
command: >
sh -c "
echo 'Waiting for PostgreSQL to be ready...'
@@ -129,8 +129,7 @@ services:
echo 'ClickHouse is ready'
echo 'Running migrations...'
- cd /app/packages/db && bunx [email protected] migrate deploy
- cd /app/packages/core && bun scripts/migrate-code.ts
+ cd /app/packages/db && prisma migrate deploy
cd /app/apps/api && bun run start
"
@@ -145,6 +144,7 @@ services:
# Common
- NODE_ENV=production
- SELF_HOSTED=true
+ - AUTOMATIC_MIGRATIONS=true
# URLs
- DATABASE_URL=postgres://${SERVICE_USER_POSTGRES}:${SERVICE_PASSWORD_POSTGRES}@opdb:5432/${OPENPANEL_POSTGRES_DB:-openpanel-db}?schema=public
- DATABASE_URL_DIRECT=postgres://${SERVICE_USER_POSTGRES}:${SERVICE_PASSWORD_POSTGRES}@opdb:5432/${OPENPANEL_POSTGRES_DB:-openpanel-db}?schema=public
@@ -217,6 +217,7 @@ services:
# Common
- NODE_ENV=production
- SELF_HOSTED=true
+ - AUTOMATIC_MIGRATIONS=true
# URLs
- DATABASE_URL=postgres://${SERVICE_USER_POSTGRES}:${SERVICE_PASSWORD_POSTGRES}@opdb:5432/${OPENPANEL_POSTGRES_DB:-openpanel-db}?schema=public
- DATABASE_URL_DIRECT=postgres://${SERVICE_USER_POSTGRES}:${SERVICE_PASSWORD_POSTGRES}@opdb:5432/${OPENPANEL_POSTGRES_DB:-openpanel-db}?schema=public
diff --git a/self-hosting/docker-compose.template.yml b/self-hosting/docker-compose.template.yml
index 6e4f2cf56..6a1249c04 100644
--- a/self-hosting/docker-compose.template.yml
+++ b/self-hosting/docker-compose.template.yml
@@ -124,14 +124,13 @@ services:
op-api:
image: lindesvard/openpanel-api:3
restart: always
- # Database migrations run here, before the api starts. The Prisma CLI is
- # fetched at start (pinned to the version the image was built with), so
- # this container needs to reach the npm registry when it boots.
+ # Prisma migrations run here, before the api starts, with the Prisma CLI
+ # the image ships. The ClickHouse code migrations run inside the api once
+ # it is listening.
command: >
sh -c "
echo 'Running migrations...'
- cd /app/packages/db && bunx [email protected] migrate deploy
- cd /app/packages/core && bun scripts/migrate-code.ts
+ cd /app/packages/db && prisma migrate deploy
cd /app/apps/api && bun run start
"