⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
fix: run migrations as a separate step before the apps start (#444)
Croff942551408ab6
diff --git a/.env.example b/.env.exampleindex 2a8f39af..5f60623a 100644--- a/.env.example+++ b/.env.example@@ -41,12 +41,12 @@ BETTER_AUTH_SECRET=change-me-please-generate-a-real-secret # openssl rand -baseAPI_PORT=3000# ── Database backup taken before migrations ──-# The api dumps the database on startup whenever a release has migrations to apply,-# and refuses to start when the dump fails. Dumps older than the retention window are-# removed on the next startup.+# The migrate step dumps the database whenever a release has migrations to apply,+# and stops when the dump fails. Dumps older than the retention window are removed on+# the next run.# BACKUP_RETENTION_DAYS=30# Where the dumps are written. Under the compose files the db-backups volume pins it-# to /backups, so it only applies to an api started outside a container.+# to /backups, so it only applies to a migration run outside a container.# BACKUP_DIR=/backups# Upgrade without a dump — for an operator who backs up by other means.# SKIP_PRE_MIGRATION_BACKUP=1diff --git a/AGENTS.md b/AGENTS.mdindex dac31d35..4c5e3b64 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -171,9 +171,15 @@ are the part to preserve when changing the script:| `docker-compose.test.yml` | test gate against a throwaway Postgres. |A change to the deploy stack usually has to land in **all three** of `docker-compose.yml`,-`docker-compose.coolify.yml`, and `docker-compose.coolify-images.yml`. The **api applies migrations on startup** (`migrate.ts` in-its Dockerfile CMD), and dumps the database into the `db-backups` volume first — a failed-dump stops the startup, so nothing is migrated without a way back. `bot` runs Telegram long polling and must stay at one replica.+`docker-compose.coolify.yml`, and `docker-compose.coolify-images.yml`. Migrations run as a+separate step before the apps start: the one-shot `migrate` service in the compose files,+which api, worker and bot wait for, and the `migrate` init container of the api pods in+the Helm chart, where worker and bot pods wait in a `wait-for-migrations` init container. Both run `migrate.ts` from the api image and override the api command to+start only the server. The api image's own CMD still migrates first, for deploy targets+with no separate step (Railway, a plain `docker run`). `migrate.ts` dumps the database+into the `db-backups` volume first — a failed dump stops the run, so nothing is migrated+without a way back. Every run takes a Postgres advisory lock: runs that start together+apply the migrations once, and the rest wait and then find nothing pending. `bot` runs Telegram long polling and must stay at one replica.## Test gate (Docker)diff --git a/apps/api/AGENTS.md b/apps/api/AGENTS.mdindex 107d3a31..f96501de 100644--- a/apps/api/AGENTS.md+++ b/apps/api/AGENTS.md@@ -287,4 +287,4 @@ directly). Helpers in `src/__tests__/helpers/`: `api` (anonymous client), `authe`APP_URL` here.- swagger `/docs` (planner) is separate from better-auth's `/api/auth/reference`; bothstay reachable without a session.-- Dev: `bun run dev`. Prod: the Dockerfile migrates, then starts the server.+- Dev: `bun run dev`. Prod: the Dockerfile migrates, then starts the server; the compose files and the Helm chart run the migrations as a separate step and start only the server.diff --git a/charts/itsaplan/README.md b/charts/itsaplan/README.mdindex 26973e4c..467c4e45 100644--- a/charts/itsaplan/README.md+++ b/charts/itsaplan/README.md@@ -197,6 +197,10 @@ bot:| `api.healthcheck.periodSeconds` | Probe period | `15` || `api.healthcheck.timeoutSeconds` | Probe timeout | `5` || `api.healthcheck.failureThreshold` | Probe failure threshold | `5` |+| `api.backups.persistence.enabled` | Keep the pre-migration dump on a volume | `false` |+| `api.backups.persistence.size` | Backup volume size | `10Gi` |+| `api.backups.persistence.storageClass` | Backup volume storage class | `""` |+| `api.backups.persistence.accessMode` | Backup volume access mode | `ReadWriteOnce` |### Webdiff --git a/charts/itsaplan/templates/_helpers.tpl b/charts/itsaplan/templates/_helpers.tplindex de3692a1..ed3a7b8d 100644--- a/charts/itsaplan/templates/_helpers.tpl+++ b/charts/itsaplan/templates/_helpers.tpl@@ -78,4 +78,25 @@ Compute the internal API URL for inter-service communication.{{- else }}{{- printf "http://%s-api:%d" (include "itsaplan.fullname" .) (int .Values.api.port) }}{{- end }}-{{- end }}\ No newline at end of file+{{- end }}++{{/*+Init container of the worker and bot pods: holds them until the api pods' migrate init+container has applied this release's migrations.+*/}}+{{- define "itsaplan.waitForMigrations" -}}+initContainers:+ - name: wait-for-migrations+ image: "{{ .Values.api.image.repository }}:{{ .Values.api.image.tag | default .Chart.AppVersion }}"+ imagePullPolicy: {{ .Values.api.image.pullPolicy }}+ command: ["bun", "run", "packages/db/src/wait-for-migrations.ts"]+ {{- with .Values.securityContext }}+ securityContext:+ {{- toYaml . | nindent 6 }}+ {{- end }}+ envFrom:+ - configMapRef:+ name: {{ include "itsaplan.fullname" . }}+ - secretRef:+ name: {{ include "itsaplan.fullname" . }}+{{- end }}diff --git a/charts/itsaplan/templates/deployment-api.yaml b/charts/itsaplan/templates/deployment-api.yamlindex f0bb5e3e..f049254a 100644--- a/charts/itsaplan/templates/deployment-api.yaml+++ b/charts/itsaplan/templates/deployment-api.yaml@@ -43,10 +43,33 @@ spec:affinity:{{- toYaml . | nindent 8 }}{{- end }}+ # Replicas run it together; the advisory lock in migrate.ts lets one dump and+ # migrate while the others wait and then find nothing pending.+ initContainers:+ - name: migrate+ image: "{{ .Values.api.image.repository }}:{{ .Values.api.image.tag | default .Chart.AppVersion }}"+ imagePullPolicy: {{ .Values.api.image.pullPolicy }}+ command: ["bun", "run", "packages/db/src/migrate.ts"]+ {{- with .Values.securityContext }}+ securityContext:+ {{- toYaml . | nindent 12 }}+ {{- end }}+ envFrom:+ - configMapRef:+ name: {{ include "itsaplan.fullname" . }}+ - secretRef:+ name: {{ include "itsaplan.fullname" . }}+ volumeMounts:+ - name: backups+ mountPath: /backupscontainers:- name: apiimage: "{{ .Values.api.image.repository }}:{{ .Values.api.image.tag | default .Chart.AppVersion }}"imagePullPolicy: {{ .Values.api.image.pullPolicy }}+ command: ["bun", "run", "apps/api/src/index.ts"]+ volumeMounts:+ - name: backups+ mountPath: /backups{{- with .Values.securityContext }}securityContext:{{- toYaml . | nindent 12 }}@@ -80,3 +103,13 @@ spec:resources:{{- toYaml . | nindent 12 }}{{- end }}+ # Without a volume the dump is kept in an emptyDir the api container also mounts,+ # so it lives as long as the pod.+ volumes:+ - name: backups+ {{- if .Values.api.backups.persistence.enabled }}+ persistentVolumeClaim:+ claimName: {{ include "itsaplan.fullname" . }}-api-backups+ {{- else }}+ emptyDir: {}+ {{- end }}diff --git a/charts/itsaplan/templates/deployment-bot.yaml b/charts/itsaplan/templates/deployment-bot.yamlindex 7e702791..ffc7b787 100644--- a/charts/itsaplan/templates/deployment-bot.yaml+++ b/charts/itsaplan/templates/deployment-bot.yaml@@ -47,6 +47,7 @@ spec:affinity:{{- toYaml . | nindent 8 }}{{- end }}+ {{- include "itsaplan.waitForMigrations" . | nindent 6 }}containers:- name: botimage: "{{ .Values.bot.image.repository }}:{{ .Values.bot.image.tag | default .Chart.AppVersion }}"diff --git a/charts/itsaplan/templates/deployment-worker.yaml b/charts/itsaplan/templates/deployment-worker.yamlindex 7636bdd0..7eddc861 100644--- a/charts/itsaplan/templates/deployment-worker.yaml+++ b/charts/itsaplan/templates/deployment-worker.yaml@@ -43,6 +43,7 @@ spec:affinity:{{- toYaml . | nindent 8 }}{{- end }}+ {{- include "itsaplan.waitForMigrations" . | nindent 6 }}containers:- name: workerimage: "{{ .Values.worker.image.repository }}:{{ .Values.worker.image.tag | default .Chart.AppVersion }}"diff --git a/charts/itsaplan/templates/pvc-api-backups.yaml b/charts/itsaplan/templates/pvc-api-backups.yamlnew file mode 100644index 00000000..61c9a67c--- /dev/null+++ b/charts/itsaplan/templates/pvc-api-backups.yaml@@ -0,0 +1,18 @@+{{- if .Values.api.backups.persistence.enabled }}+apiVersion: v1+kind: PersistentVolumeClaim+metadata:+ name: {{ include "itsaplan.fullname" . }}-api-backups+ labels:+ {{- include "itsaplan.labels" . | nindent 4 }}+ app.kubernetes.io/component: api+spec:+ accessModes:+ - {{ .Values.api.backups.persistence.accessMode }}+ {{- if .Values.api.backups.persistence.storageClass }}+ storageClassName: {{ .Values.api.backups.persistence.storageClass | quote }}+ {{- end }}+ resources:+ requests:+ storage: {{ .Values.api.backups.persistence.size }}+{{- end }}diff --git a/charts/itsaplan/values.yaml b/charts/itsaplan/values.yamlindex b627376a..5898ac6d 100644--- a/charts/itsaplan/values.yaml+++ b/charts/itsaplan/values.yaml@@ -60,6 +60,16 @@ api:periodSeconds: 15timeoutSeconds: 5failureThreshold: 5+ # The dump the migrate init container takes before it applies a migration. Without+ # a volume it is kept in an emptyDir and lost with the pod. ReadWriteOnce only works while+ # every api replica runs on one node; spread across nodes, use ReadWriteMany, or set+ # SKIP_PRE_MIGRATION_BACKUP=1 in api.env when the database is backed up another way.+ backups:+ persistence:+ enabled: false+ size: 10Gi+ storageClass: ""+ accessMode: ReadWriteOnce# -- Web (Next.js frontend)web:diff --git a/docker-compose.coolify-images.yml b/docker-compose.coolify-images.ymlindex c8965bf3..a297510e 100644--- a/docker-compose.coolify-images.yml+++ b/docker-compose.coolify-images.yml@@ -84,15 +84,40 @@ services:echo 'bucket ready: '\"$$S3_BUCKET\""+ # One-shot: dumps the database and applies the migrations, then exits. api, worker+ # and bot start only after it succeeds, so none of them runs against an old schema.+ # restart 'no' keeps a finished run from being started again.+ migrate:+ image: ghcr.io/croffasia/itsaplan-api:${VERSION:-latest}+ restart: 'no'+ exclude_from_hc: true+ command: ['bun', 'run', 'packages/db/src/migrate.ts']+ depends_on:+ postgres:+ condition: service_healthy+ environment:+ - DATABASE_URL=postgres://${POSTGRES_USER:-itsaplan}:${SERVICE_PASSWORD_POSTGRES}@postgres:5432/${POSTGRES_DB:-itsaplan}+ # How long the dumps are kept, and the switch that upgrades without one.+ # BACKUP_DIR is not among them: the volume below pins it.+ - BACKUP_RETENTION_DAYS=${BACKUP_RETENTION_DAYS:-}+ - SKIP_PRE_MIGRATION_BACKUP=${SKIP_PRE_MIGRATION_BACKUP:-}+ # Holds the dump taken before a release's migrations, kept for+ # BACKUP_RETENTION_DAYS (30) so a downgrade has something to restore.+ volumes:+ - db-backups:/backups+api:image: ghcr.io/croffasia/itsaplan-api:${VERSION:-latest}restart: unless-stopped+ # The image's own CMD migrates first; here the migrate service has done that.+ command: ['bun', 'run', 'apps/api/src/index.ts']depends_on:postgres:condition: service_healthy+ migrate:+ condition: service_completed_successfullyminio:condition: service_started- # Applies migrations on startup, then starts the server (see api Dockerfile CMD).environment:# Listed without a value, this asks Coolify for the public domain of this# service on port 3000. The port belongs to the declaration only — the value read@@ -119,22 +144,12 @@ services:# Hosts trusted even though they resolve privately. Also governs webhook URL# validation and attachment import.- SSRF_ALLOWED_HOSTS=${SSRF_ALLOWED_HOSTS:-}- # How long the pre-migration dumps are kept, and the switch that upgrades- # without one. BACKUP_DIR is not among them: the volume below pins it.- - BACKUP_RETENTION_DAYS=${BACKUP_RETENTION_DAYS:-}- - SKIP_PRE_MIGRATION_BACKUP=${SKIP_PRE_MIGRATION_BACKUP:-}- # Holds the dump migrate.ts takes before it applies a release's migrations, and- # keeps it for BACKUP_RETENTION_DAYS (30) so a downgrade has something to restore.- volumes:- - db-backups:/backups- # start_period covers the backup and the migrations the container applies before- # it listens.healthcheck:test: ['CMD', 'wget', '-q', '-O', '/dev/null', 'http://127.0.0.1:3000/']interval: 15stimeout: 5sretries: 5- start_period: 180s+ start_period: 30s# Background worker for webhook delivery, agent schedules, and autonomous agent# runs. Shares the database with the api. No public ports, so nothing to probe.@@ -145,8 +160,8 @@ services:depends_on:postgres:condition: service_healthy- api:- condition: service_started+ migrate:+ condition: service_completed_successfullyenvironment:NODE_ENV: productionDATABASE_URL: postgres://${POSTGRES_USER:-itsaplan}:${SERVICE_PASSWORD_POSTGRES}@postgres:5432/${POSTGRES_DB:-itsaplan}@@ -189,6 +204,8 @@ services:depends_on:postgres:condition: service_healthy+ migrate:+ condition: service_completed_successfullyenvironment:NODE_ENV: productionDATABASE_URL: postgres://${POSTGRES_USER:-itsaplan}:${SERVICE_PASSWORD_POSTGRES}@postgres:5432/${POSTGRES_DB:-itsaplan}diff --git a/docker-compose.coolify.yml b/docker-compose.coolify.ymlindex 1395e6ec..d1abb242 100644--- a/docker-compose.coolify.yml+++ b/docker-compose.coolify.yml@@ -81,17 +81,44 @@ services:echo 'bucket ready: '\"$$S3_BUCKET\""+ # One-shot: dumps the database and applies the migrations, then exits. api, worker+ # and bot start only after it succeeds, so none of them runs against an old schema.+ # restart 'no' keeps a finished run from being started again.+ migrate:+ build:+ context: .+ dockerfile: apps/api/Dockerfile+ restart: 'no'+ exclude_from_hc: true+ command: ['bun', 'run', 'packages/db/src/migrate.ts']+ depends_on:+ postgres:+ condition: service_healthy+ environment:+ DATABASE_URL: postgres://${POSTGRES_USER:-itsaplan}:${SERVICE_PASSWORD_POSTGRES}@postgres:5432/${POSTGRES_DB:-itsaplan}+ # How long the dumps are kept, and the switch that upgrades without one.+ # BACKUP_DIR is not among them: the volume below pins it.+ BACKUP_RETENTION_DAYS: ${BACKUP_RETENTION_DAYS:-}+ SKIP_PRE_MIGRATION_BACKUP: ${SKIP_PRE_MIGRATION_BACKUP:-}+ # Holds the dump taken before a release's migrations, kept for+ # BACKUP_RETENTION_DAYS (30) so a downgrade has something to restore.+ volumes:+ - db-backups:/backups+api:build:context: .dockerfile: apps/api/Dockerfilerestart: unless-stopped+ # The image's own CMD migrates first; here the migrate service has done that.+ command: ['bun', 'run', 'apps/api/src/index.ts']depends_on:postgres:condition: service_healthy+ migrate:+ condition: service_completed_successfullyminio:condition: service_started- # Applies migrations on startup, then starts the server (see api Dockerfile CMD).environment:NODE_ENV: productionAPI_PORT: 3000@@ -114,22 +141,12 @@ services:# Hosts trusted even though they resolve privately. Also governs webhook URL# validation and attachment import.SSRF_ALLOWED_HOSTS: ${SSRF_ALLOWED_HOSTS:-}- # How long the pre-migration dumps are kept, and the switch that upgrades- # without one. BACKUP_DIR is not among them: the volume below pins it.- BACKUP_RETENTION_DAYS: ${BACKUP_RETENTION_DAYS:-}- SKIP_PRE_MIGRATION_BACKUP: ${SKIP_PRE_MIGRATION_BACKUP:-}- # Holds the dump migrate.ts takes before it applies a release's migrations, and- # keeps it for BACKUP_RETENTION_DAYS (30) so a downgrade has something to restore.- volumes:- - db-backups:/backups- # start_period covers the backup and the migrations the container applies before- # it listens.healthcheck:test: ['CMD', 'wget', '-q', '-O', '/dev/null', 'http://127.0.0.1:3000/']interval: 15stimeout: 5sretries: 5- start_period: 180s+ start_period: 30s# Set API_PORT in Coolify if 3000 is taken on the host.ports:- '${API_PORT:-3000}:3000'@@ -145,8 +162,8 @@ services:depends_on:postgres:condition: service_healthy- api:- condition: service_started+ migrate:+ condition: service_completed_successfullyenvironment:NODE_ENV: productionDATABASE_URL: postgres://${POSTGRES_USER:-itsaplan}:${SERVICE_PASSWORD_POSTGRES}@postgres:5432/${POSTGRES_DB:-itsaplan}@@ -191,6 +208,8 @@ services:depends_on:postgres:condition: service_healthy+ migrate:+ condition: service_completed_successfullyenvironment:NODE_ENV: productionDATABASE_URL: postgres://${POSTGRES_USER:-itsaplan}:${SERVICE_PASSWORD_POSTGRES}@postgres:5432/${POSTGRES_DB:-itsaplan}diff --git a/docker-compose.yml b/docker-compose.ymlindex b47b2542..d43f45ca 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -78,16 +78,43 @@ services:echo 'bucket ready: '\"$$S3_BUCKET\""- # Applies database migrations on startup, then serves the API.+ # One-shot: dumps the database and applies the migrations, then exits. api, worker+ # and bot start only after it succeeds, so none of them runs against an old schema.+ # restart 'no' keeps a finished run from being started again.+ migrate:+ image: ghcr.io/croffasia/itsaplan-api:${VERSION:-latest}+ build:+ context: .+ dockerfile: apps/api/Dockerfile+ restart: 'no'+ command: ['bun', 'run', 'packages/db/src/migrate.ts']+ depends_on:+ postgres:+ condition: service_healthy+ environment:+ DATABASE_URL: postgres://${POSTGRES_USER:-itsaplan}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB:-itsaplan}+ # How long the dumps are kept, and the switch that upgrades without one.+ # BACKUP_DIR is not among them: the volume below pins it.+ BACKUP_RETENTION_DAYS: ${BACKUP_RETENTION_DAYS:-}+ SKIP_PRE_MIGRATION_BACKUP: ${SKIP_PRE_MIGRATION_BACKUP:-}+ # Holds the dump taken before a release's migrations, kept for+ # BACKUP_RETENTION_DAYS (30) so a downgrade has something to restore.+ volumes:+ - db-backups:/backups+api:image: ghcr.io/croffasia/itsaplan-api:${VERSION:-latest}build:context: .dockerfile: apps/api/Dockerfilerestart: unless-stopped+ # The image's own CMD migrates first; here the migrate service has done that.+ command: ['bun', 'run', 'apps/api/src/index.ts']depends_on:postgres:condition: service_healthy+ migrate:+ condition: service_completed_successfullyminio-init:condition: service_completed_successfullyenvironment:@@ -114,22 +141,12 @@ services:# Hosts trusted even though they resolve privately. Also governs webhook URL# validation and attachment import.SSRF_ALLOWED_HOSTS: ${SSRF_ALLOWED_HOSTS:-}- # How long the pre-migration dumps are kept, and the switch that upgrades- # without one. BACKUP_DIR is not among them: the volume below pins it.- BACKUP_RETENTION_DAYS: ${BACKUP_RETENTION_DAYS:-}- SKIP_PRE_MIGRATION_BACKUP: ${SKIP_PRE_MIGRATION_BACKUP:-}- # Holds the dump migrate.ts takes before it applies a release's migrations, and- # keeps it for BACKUP_RETENTION_DAYS (30) so a downgrade has something to restore.- volumes:- - db-backups:/backups- # start_period covers the backup and the migrations the container applies before- # it listens.healthcheck:test: ['CMD', 'wget', '-q', '-O', '/dev/null', 'http://127.0.0.1:3000/']interval: 15stimeout: 5sretries: 5- start_period: 180s+ start_period: 30sports:- '${API_PORT:-3000}:3000'@@ -144,8 +161,8 @@ services:depends_on:postgres:condition: service_healthy- api:- condition: service_started+ migrate:+ condition: service_completed_successfullyenvironment:NODE_ENV: productionDATABASE_URL: postgres://${POSTGRES_USER:-itsaplan}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB:-itsaplan}@@ -185,6 +202,8 @@ services:depends_on:postgres:condition: service_healthy+ migrate:+ condition: service_completed_successfullyenvironment:NODE_ENV: productionDATABASE_URL: postgres://${POSTGRES_USER:-itsaplan}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB:-itsaplan}diff --git a/docs/coolify.md b/docs/coolify.mdindex f292c079..5d93ea07 100644--- a/docs/coolify.md+++ b/docs/coolify.md@@ -50,8 +50,9 @@ change.## 4. Deploy-Press **Deploy**. Postgres, RustFS, api, worker, bot, and web come up together; the api-applies the migrations on startup. The first account registered becomes the instance admin.+Press **Deploy**. Postgres, RustFS, api, worker, bot, and web come up together; the+one-shot `migrate` service applies the migrations first, and api, worker and bot start once+it exits. The first account registered becomes the instance admin.Secrets (database password, auth secret, encryption key, worker token, object store credentials)are generated on the first deploy and stay stable across later ones — nothing to fill in bydiff --git a/docs/helm.md b/docs/helm.mdindex 0961677a..c7e29046 100644--- a/docs/helm.md+++ b/docs/helm.md@@ -33,7 +33,7 @@ Install the chart:helm install itsaplan charts/itsaplan -f values.yaml```-The API applies database migrations on startup. The first account registered becomes the instance admin.+Each API pod applies the database migrations in its `migrate` init container before the server starts. With several replicas, one applies them and the others wait on a Postgres advisory lock. Worker and bot pods wait in their own init container until the migrations are applied. The first account registered becomes the instance admin.## What gets deployeddiff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex a4b61bf1..bac7c794 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -28,7 +28,7 @@ write the files: it prints `.env` and `apps/web/.env` for you to copy onto the sThat starts the whole stack: Postgres, RustFS, api, worker, bot, and web. The four servicesrun from the images published on each release. `VERSION` in `.env` pins one release instead-of the newest. The api applies migrations when it starts, and the first account you register+of the newest. The `migrate` service applies migrations before the api starts, and the first account you registerbecomes the instance admin.`.env.example` documents every variable, including the optional ones: legal document URLs,@@ -108,9 +108,10 @@ docker compose up -d`git pull` updates the compose file. The services come from the registry. Changing `API_URL`or `APP_URL` afterwards only needs `docker compose up -d`.-The api applies its migrations on startup, so an upgrade needs no database step. Before-it applies anything it dumps the database into the `db-backups` volume (`/backups` in the-api container) and refuses to start if that dump fails — a release whose migrations+The one-shot `migrate` service applies the migrations on every `docker compose up -d`, and+api, worker and bot start only after it succeeds, so an upgrade needs no database step.+Before it applies anything it dumps the database into the `db-backups` volume (`/backups`+in the `migrate` container) and fails if that dump fails — a release whose migrationsrewrite data is not applied without something to go back to. Dumps are deleted after 30days, on the first startup past that; `BACKUP_RETENTION_DAYS` changes the window and`SKIP_PRE_MIGRATION_BACKUP=1` upgrades without one, for an operator who backs up bydiff --git a/packages/db/AGENTS.md b/packages/db/AGENTS.mdindex 0a7eefc7..42cea1ff 100644--- a/packages/db/AGENTS.md+++ b/packages/db/AGENTS.md@@ -24,7 +24,8 @@ See root `AGENTS.md` for monorepo-wide rules.(`@repo/auth`, api, worker), a team's notification providers (api, worker), and theinstance's upload limits and project-storage-quota accounting (api, worker — animported attachment is checked against the same limits an interactive upload is).-- `src/migrate.ts` — programmatic migrator run on api container startup (no drizzle-kit in prod).+- `src/migrate.ts` — programmatic migrator (no drizzle-kit in prod), run by the `migrate` compose service, the api pods' init container, and the api image's CMD.+- `src/wait-for-migrations.ts` — exits once the database holds this release's migrations; the Helm init container of the worker and bot pods.- `drizzle/` — generated SQL migrations (committed).## Workflowdiff --git a/packages/db/src/migrate.ts b/packages/db/src/migrate.tsindex 0e65110e..4af74e9a 100644--- a/packages/db/src/migrate.ts+++ b/packages/db/src/migrate.ts@@ -18,7 +18,9 @@ if (!connectionString) {throw new Error('DATABASE_URL is not set — cannot run migrations.');}-const migrationClient = postgres(connectionString, { max: 1 });+// max_lifetime off: postgres.js otherwise closes the connection after 30–60 minutes,+// which would release the migration lock below while a long pg_dump is still running.+const migrationClient = postgres(connectionString, { max: 1, max_lifetime: null });const db = drizzle(migrationClient);const migrationsFolder = fileURLToPath(new URL('../drizzle', import.meta.url));@@ -41,6 +43,18 @@ for (let attempt = 1; ; attempt++) {}}+// Several api replicas start together on every rollout. The lock lets one of them dump+// and migrate while the rest wait, and the rest then find nothing pending. It belongs+// to this session, so Postgres releases it when the connection closes, a crash included.+const MIGRATION_LOCK_KEY = 804_216_551;+const [{ locked }] = await migrationClient<{ locked: boolean }[]>`+ select pg_try_advisory_lock(${MIGRATION_LOCK_KEY}) as locked+`;+if (!locked) {+ console.log('⏳ Another instance is migrating the database, waiting for it to finish...');+ await migrationClient`select pg_advisory_lock(${MIGRATION_LOCK_KEY})`;+}+// A dump of the database as this release found it, so an operator who has to go back// to the previous release has something to restore. Taken before anything is applied,// and a failure stops the startup: a migration that runs without one cannot be undone.diff --git a/packages/db/src/wait-for-migrations.ts b/packages/db/src/wait-for-migrations.tsnew file mode 100644index 00000000..4c5aa895--- /dev/null+++ b/packages/db/src/wait-for-migrations.ts@@ -0,0 +1,32 @@+// Init container of the worker and bot pods in the Helm chart: exits once the database+// holds every migration of this release. The api pods' migrate init container applies+// them; this one only waits, so the dump stays with the api pods.+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import postgres from 'postgres';++const connectionString = process.env.DATABASE_URL;+if (!connectionString) {+ throw new Error('DATABASE_URL is not set — cannot check migrations.');+}++const journal: { entries: { when: number }[] } = JSON.parse(+ readFileSync(fileURLToPath(new URL('../drizzle/meta/_journal.json', import.meta.url)), 'utf8'),+);+const latest = Math.max(...journal.entries.map((e) => e.when));++const sql = postgres(connectionString, { max: 1 });+const RETRY_DELAY_MS = 3000;++// A refused connection and a missing drizzle table both read as "not yet".+for (;;) {+ const [applied] = await sql<{ last: string | null }[]>`+ select max(created_at)::text as last from drizzle.__drizzle_migrations+ `.catch(() => [{ last: null }]);+ if (applied?.last && Number(applied.last) >= latest) break;+ console.log('⏳ Waiting for the database migrations to be applied...');+ await Bun.sleep(RETRY_DELAY_MS);+}++await sql.end();+console.log('✅ Database is migrated');diff --git a/scripts/setup.ts b/scripts/setup.tsindex 50fa3341..97aee268 100644--- a/scripts/setup.ts+++ b/scripts/setup.ts@@ -331,9 +331,9 @@ if (mode === 'try') {const spinner = p.spinner();spinner.start('Starting the rest of the stack');await run(...compose, 'up', '-d');- // --wait names api and web only: minio-init is a one-shot and its exit counts as a- // failure. api is worth waiting for on its own — it migrates before it listens, and- // web renders /login without it.+ // --wait names api and web only: minio-init and migrate are one-shots and their exit+ // counts as a failure. api is worth waiting for on its own — it starts only after the+ // migrations, and web renders /login without it.await run(...compose, 'up', '-d', '--wait', '--no-recreate', 'api', 'web');spinner.stop('Stack is up');@@ -422,7 +422,7 @@ if (mode === 'dev') {migrations.start('Applying migrations');// The programmatic runner, not `bun run db:migrate`: drizzle-kit exits 1 without printing// what the database refused, and a failure here is exactly what needs reading.- // Its pre-migration dump goes to BACKUP_DIR, a path only the api container has, and a+ // Its pre-migration dump goes to BACKUP_DIR, a path only the migrate container has, and a// local database the operator recreates at will has nothing to go back to anyway.process.env.SKIP_PRE_MIGRATION_BACKUP = '1';await run('bun', '--env-file=.env', 'packages/db/src/migrate.ts');