diff --git a/CHANGELOG.md b/CHANGELOG.md index 03e0b2073b..2ba6efe38a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -97,6 +97,7 @@ - A damaged Gadgetbridge or Health Connect database is refused as a broken file, also when the damage sits behind a sound header and only shows once a table is read. The import used to fail with SQLite's own message as an internal error. - A FHIR Bundle, or a health record inside an Apple Health export, that nests deeper than 64 levels is refused as an unreadable file. A few hundred kilobytes nested deep enough made the import fail with an internal error instead. - An Apple Health export no longer stops as a whole at one cycle sample with a date that does not read. That sample is skipped and counted, and the rest of the export is imported. +- Restoring an off-host database copy that was renamed or altered says so on any Node and OpenSSL version. The restore recognised a failed integrity check by the wording of OpenSSL's error, which Node 22 gives as "unable to authenticate data" and Node 26 on OpenSSL 4 as "bad decrypt", so a restore run on a newer Node showed the raw OpenSSL error instead of the explanation. The check now goes by where the failure arose, not by its text. - A measurement CSV or a dose-history CSV with more than 100 000 rows, or a row wider than 1000 columns, is refused straight away. Blank lines are no longer held as rows while the file is read. Sixteen megabytes of line breaks used to hold several gigabytes of server memory for most of a minute, and a file of short junk lines answered with a status line for each of millions of rows. - The sleep page's night timeline is drawn only for a night whose stages were recorded in order. A Garmin night arrives as one total per stage, all stamped on the wake time, and the page drew those totals as a timeline of bars stacked against the morning. Whether a night holds an order is now decided once on the server, from the shape of its stages rather than from a list of services, so Garmin, Oura's stage totals and any later service that sends totals get the same note WHOOP and Polar already had, and the iPhone app reads the same answer. Such a night no longer counts awakenings it cannot know. When two services describe the same night, the copy with a recorded order wins: a Garmin night that also reaches HealthLog through Apple Health shows the Apple Health timeline, and so now does a WHOOP or Polar night, which used to win on the source order and hide the recorded one. Thanks to @kruemelro for the report and the side-by-side screenshots. (Refs [#1419](https://github.com/MBombeck/HealthLog/issues/1419)) - A PDF read by an AI provider that takes page images is now rendered sharp enough for small print. Pages were rendered at 72 dpi, so an A4 lab report reached the model 842 px tall and decimal commas or units like `mmol/l` could get lost. Pages now render at 200 dpi, held to 2000 px on the long edge so every provider reads them without downscaling them first; an A4 page arrives at about 171 dpi. Document reads, lab scans, supplement labels and previews all render through this one path. @@ -144,6 +145,7 @@ - A snooze stays with the dose it was set on. It was dated by the medication's last change, so a later write to the medication, such as the low-stock notice or an edit, carried a morning snooze over to the afternoon dose: the today list showed it snoozed and its reminder stayed silent. The snooze now keeps its own time. - Readiness counts a reading on the day it was taken in the time zone of the person's profile. The dashboard, the score pages, the API, the iPhone app, the Coach and the nightly scores grouped the day in Berlin time, so for someone in another zone a late-evening resting pulse or HRV landed in the next day's readiness. - A high stress or strain score reads as high. A stress of 80 was described as "on the low side" in the score's assessment and labelled "low" under its ring, and the ring on the score page announced it as good. Stress and strain now read low, moderate or high, the way their bands already run. +- A database server on a newer PostgreSQL major than the client tools in the image is now named as the problem, with both version numbers and the way out. Before, the dump the app takes before migrating failed with a one-line version mismatch, the boot stopped there and the container restarted into the same error every few seconds, while the nightly dumps failed with the same line and `db-restore` would have too. Every path that dumps or restores now compares the two majors first. At boot the app still refuses to migrate without its dump, but says why once and waits ten minutes before it exits; with nothing to migrate it starts and logs a warning. A nightly dump that fails this way shows as failing on the backups page from the first night and reaches admins as a backup alert, and `db-restore` refuses before it writes anything. The upgrade guide now states the ceiling: the highest server major HealthLog supports is the client major in the image, 19 today. Thanks to @aw23edfr4 for tracing it. (Refs [#1431](https://github.com/MBombeck/HealthLog/issues/1431)) ### Security @@ -187,6 +189,11 @@ - @Gen-X-Jim for the report with the database counts that showed what the card was missing, and for asking for a day-total form. ([#1459](https://github.com/MBombeck/HealthLog/issues/1459)) - @camiracode for counting the pairs that stayed after the 1.48.3 cleanup. ([#1414](https://github.com/MBombeck/HealthLog/issues/1414)) +### Updating + +- A new password longer than 1024 characters is refused when you register, claim a profile or change your password. A password you already have keeps working whatever its length: signing in and confirming your current password are not capped. +- If you run HealthLog against your own PostgreSQL server, keep its major at or below the client major in the image (`docker run --rm --entrypoint pg_dump ghcr.io/mbombeck/healthlog:latest --version`). See `docs/ops/postgres-major-upgrade.md`. + ## [1.49.0] — 2026-11-23 ### Added diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh index 271cd5e0bc..bb3016324e 100644 --- a/docker-entrypoint.sh +++ b/docker-entrypoint.sh @@ -106,7 +106,25 @@ node scripts/pending-migrations.mjs || true # without the backups volume): a warning, and the boot goes on. A kept # directory and a failed dump: the boot stops here, before anything is # migrated. -if ! node scripts/db-dump.mjs pre-migration; then +# +# Exit 3 is the dump that cannot be taken at all: the database server's major +# is newer than this image's pg_dump (#1431). A restart does not change that, +# and with `restart: unless-stopped` an immediate exit came straight back into +# the same error every few seconds. So the reason is said once, and the +# entrypoint waits ten minutes (inside the healthcheck's start period) before +# it exits; `docker stop` ends the wait at once. +dump_status=0 +node scripts/db-dump.mjs pre-migration || dump_status=$? +if [ "$dump_status" -eq 3 ]; then + echo "HealthLog: ERROR — not migrating: this image's PostgreSQL client cannot dump this database server (see above). Nothing was changed." >&2 + echo "HealthLog: to migrate without a dump this once, set DB_BACKUP_BEFORE_MIGRATE=false; the nightly dumps fail until the client and the server match." >&2 + echo "HealthLog: waiting 10 minutes before exiting, so a restart policy does not restart into the same error. docker stop ends the wait." >&2 + trap 'kill "$wait_pid" 2>/dev/null; exit 1' TERM INT + sleep 600 & + wait_pid=$! + wait "$wait_pid" || true + exit 1 +elif [ "$dump_status" -ne 0 ]; then echo "HealthLog: ERROR — not migrating without the dump. Free disk space or fix the error above and start again." >&2 echo "HealthLog: to migrate without a dump this once, set DB_BACKUP_BEFORE_MIGRATE=false." >&2 exit 1 diff --git a/docs/ops/postgres-major-upgrade.md b/docs/ops/postgres-major-upgrade.md index 49cbc32558..fa92335799 100644 --- a/docs/ops/postgres-major-upgrade.md +++ b/docs/ops/postgres-major-upgrade.md @@ -7,21 +7,48 @@ on the first start after the update. Nothing needs doing by hand on a stack that runs the project's `docker-compose.yml`. Installs that bring their own Postgres (Unraid, an existing database server) -are not touched: HealthLog runs on 16, 18 and 19 alike, and the move there is -yours to schedule with the steps under [By hand](#by-hand). +are not touched, and the move there is yours to schedule with the steps under +[By hand](#by-hand), within one ceiling. -One limit holds in the other direction, though. The image carries `pg_dump` -and `pg_restore` of major 19, and a PostgreSQL client reads servers of its own -major and older but refuses a newer one. A server above the client's major -fails the dump the app takes before every migration, and the app then stops -rather than migrate without one — by which time its nightly dumps have been -failing for as long as the server has been newer. So keep your own server at -or below the major the image carries; this names it for the release you run: +## The highest server major this image supports + +The image carries `pg_dump` and `pg_restore` of one major, and a PostgreSQL +client works with servers of its own major and older, never a newer one. So +**the highest server major HealthLog supports is the client major in the +image you run**: 19 for the current releases, with 16, 18 and 19 all +supported. Check it for the release you run: ```bash docker run --rm --entrypoint pg_dump ghcr.io/mbombeck/healthlog:latest --version ``` +and the server's major with `SHOW server_version;` in `psql`. Keep the server +at or below the client's major; move it past only once a HealthLog release +ships the newer client. + +Every path that runs one of the tools checks the pair first: the dump before +migrating, the nightly dump, and `db-restore`. A server newer than the client +is refused before anything is written, with one line that names both majors: + +``` +HealthLog: ERROR — This image's PostgreSQL client (pg_dump) is 19; your server is 20. ... +``` + +- **At boot, with migrations pending**, the app does not migrate without the + dump. It says why once, waits ten minutes and then exits, so a restart + policy does not restart it into the same error every few seconds; + `docker stop` ends the wait. Bring the server back to the client's major + (restore a dump into a server of that major), or migrate this once without + a dump with `DB_BACKUP_BEFORE_MIGRATE=false`, knowing the nightly dumps + keep failing until the two match. +- **At boot, with nothing to migrate**, the app starts and logs the same line + as a warning. +- **The nightly dump** fails the run with that line. The recovery readiness + check under Admin, Backups calls it failing from the first run, and every + admin gets it as a backup alert on the channels they enabled. +- **`db-restore`** refuses before `pg_restore` runs. Restore into a server of + the client's major or older. + ## What happens on the first start `db-upgrade` is a short-lived container next to `db`. It starts after the new diff --git a/docs/self-hosting/getting-started.md b/docs/self-hosting/getting-started.md index e69461f2ae..c52d6bdeed 100644 --- a/docs/self-hosting/getting-started.md +++ b/docs/self-hosting/getting-started.md @@ -124,6 +124,10 @@ Compose starts two services and one short-lived step: - `db-upgrade` — moves a Postgres 16 database from v1.45 or earlier into the new one, once, and exits; on a new install it has nothing to do. See [Moving to a newer Postgres major](../ops/postgres-major-upgrade.md). + Pointing `DATABASE_URL` at your own server instead works for any major up + to the PostgreSQL client major in the image (19 today); the app refuses a + newer one, see + [the highest supported major](../ops/postgres-major-upgrade.md#the-highest-server-major-this-image-supports). - `app` — HealthLog itself, listening on `localhost:3000`. The image runs `prisma migrate deploy` on boot so the schema lands automatically; subsequent restarts no-op when the database is diff --git a/docs/self-hosting/truenas.md b/docs/self-hosting/truenas.md index 61b1e64473..8eb90239eb 100644 --- a/docs/self-hosting/truenas.md +++ b/docs/self-hosting/truenas.md @@ -221,15 +221,15 @@ before you touch it. Until the catalog app is listed, install HealthLog with Apps, Discover Apps, the menu next to Custom App, Install via YAML, using these values: -| Setting | Value | -| ------------ | -------------------------------------------------------------------------------------- | -| Image | `ghcr.io/mbombeck/healthlog`, tag `X.Y.Z` (amd64 and arm64) | -| Port | `3000` (HTTP) | -| User | runs as uid `1001` by default; no extra capabilities, `no-new-privileges` is fine | -| Health check | `GET /api/health`, `200` when ready | -| Start period | 10 min, like the image: migrations run at every boot and wait out a held lock | -| Database | PostgreSQL 18 (16 works too), no extensions, in its own container with its own dataset | -| Volumes | `/var/lib/healthlog/backups` for the database dumps (uid `1001`); the database its own | +| Setting | Value | +| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Image | `ghcr.io/mbombeck/healthlog`, tag `X.Y.Z` (amd64 and arm64) | +| Port | `3000` (HTTP) | +| User | runs as uid `1001` by default; no extra capabilities, `no-new-privileges` is fine | +| Health check | `GET /api/health`, `200` when ready | +| Start period | 10 min, like the image: migrations run at every boot and wait out a held lock | +| Database | PostgreSQL 18 (16 and 19 work too, nothing newer than the image's client major, see `docs/ops/postgres-major-upgrade.md`), no extensions, in its own container with its own dataset | +| Volumes | `/var/lib/healthlog/backups` for the database dumps (uid `1001`); the database its own | | Variable | Required | Notes | | ----------------------- | -------- | ---------------------------------------------------------------------------------------- | diff --git a/docs/self-hosting/unraid.md b/docs/self-hosting/unraid.md index fe10923e12..f02dcc72a5 100644 --- a/docs/self-hosting/unraid.md +++ b/docs/self-hosting/unraid.md @@ -76,8 +76,10 @@ then add HealthLog pointed at it. 1. In **Apps** (Community Applications), search for a **PostgreSQL** container (for example jj9987's `postgresql`). Install version 18; an existing 16 - works too. Moving a 16 to 18 later is a dump and restore, see - [Moving to a newer Postgres major](../ops/postgres-major-upgrade.md#by-hand). + works too, and so does 19. Do not go past the PostgreSQL client major in + the HealthLog image (19 today): the app cannot dump a newer server, and + then refuses to migrate. Moving a 16 to 18 later is a dump and restore, see + [Moving to a newer Postgres major](../ops/postgres-major-upgrade.md#the-highest-server-major-this-image-supports). 2. Set: - `POSTGRES_USER` = `healthlog` - `POSTGRES_PASSWORD` = your generated password diff --git a/messages/de.json b/messages/de.json index 3790729dbb..9793c34033 100644 --- a/messages/de.json +++ b/messages/de.json @@ -9617,6 +9617,7 @@ "first_pending": "Der erste Datenbank-Dump ist noch nicht gelaufen.", "stale": "Der neueste Datenbank-Dump ist {hours, plural, one {# Stunde} other {# Stunden}} alt.", "last_failed": "Der letzte Datenbank-Dump ist fehlgeschlagen. Der davor ist noch aktuell.", + "client_too_old": "Der PostgreSQL-Client dieses Images hat Version {client}, der Datenbankserver läuft aber auf {server}, daher kann kein Datenbank-Dump erstellt werden. Nutze ein HealthLog-Image mit Client {server} oder neuer, oder lass den Server auf {client} oder älter.", "fresh": "Der neueste Datenbank-Dump ist aktuell.", "nowhere_to_write": "Das Dump-Verzeichnis {directory} ist nicht beschreibbar und es ist kein externer Bucket eingerichtet, daher kann kein Dump aufbewahrt werden.", "not_persistent": "Das Dump-Verzeichnis {directory} liegt nicht auf dauerhaftem Speicher, und es ist kein externer Bucket eingerichtet. Jeder Dump wäre beim nächsten Update verloren. Binde das Backup-Volume ein.", diff --git a/messages/en.json b/messages/en.json index fdfd87cd9f..933dc103c6 100644 --- a/messages/en.json +++ b/messages/en.json @@ -9617,6 +9617,7 @@ "first_pending": "The first database dump has not run yet.", "stale": "The newest database dump is {hours, plural, one {# hour} other {# hours}} old.", "last_failed": "The last database dump failed. The one before it is still recent.", + "client_too_old": "This image's PostgreSQL client is {client}, but the database server runs {server}, so no database dump can be taken. Use a HealthLog image whose client is {server} or newer, or keep the server on {client} or older.", "fresh": "The newest database dump is recent.", "nowhere_to_write": "The dump directory {directory} cannot be written to and no off-host bucket is set up, so no dump can be kept.", "not_persistent": "The dump directory {directory} is not on persistent storage and no off-host bucket is set up, so every dump would be lost at the next update. Mount the backups volume.", diff --git a/messages/es.json b/messages/es.json index 943634d51a..5e4d3d0328 100644 --- a/messages/es.json +++ b/messages/es.json @@ -9617,6 +9617,7 @@ "first_pending": "El primer volcado de la base de datos aún no se ha ejecutado.", "stale": "El volcado de la base de datos más reciente tiene {hours, plural, one {# hora} other {# horas}}.", "last_failed": "El último volcado de la base de datos falló. El anterior sigue siendo reciente.", + "client_too_old": "El cliente de PostgreSQL de esta imagen es la versión {client}, pero el servidor de base de datos usa la {server}, así que no se puede hacer ningún volcado. Usa una imagen de HealthLog cuyo cliente sea {server} o posterior, o mantén el servidor en {client} o anterior.", "fresh": "El último volcado de la base de datos es reciente.", "nowhere_to_write": "No se puede escribir en el directorio de volcados {directory} y no hay ningún bucket externo configurado, así que no se puede guardar ningún volcado.", "not_persistent": "El directorio de volcados {directory} no está en almacenamiento persistente y no hay un bucket externo configurado, así que cada volcado se perdería en la próxima actualización. Monta el volumen de copias.", diff --git a/messages/fr.json b/messages/fr.json index 881f78cb3b..73758d6fbe 100644 --- a/messages/fr.json +++ b/messages/fr.json @@ -9617,6 +9617,7 @@ "first_pending": "Le premier dump de la base de données n'a pas encore été lancé.", "stale": "Le dump de la base de données le plus récent date de {hours, plural, one {# heure} other {# heures}}.", "last_failed": "Le dernier dump de la base de données a échoué. Le précédent est encore récent.", + "client_too_old": "Le client PostgreSQL de cette image est en version {client}, mais le serveur de base de données est en {server} : aucun dump ne peut être réalisé. Utilisez une image HealthLog dont le client est en {server} ou plus récent, ou gardez le serveur en {client} ou plus ancien.", "fresh": "Le dernier dump de la base de données est récent.", "nowhere_to_write": "Le dossier des dumps {directory} n'est pas accessible en écriture et aucun bucket externe n'est configuré, donc aucun dump ne peut être conservé.", "not_persistent": "Le répertoire des dumps {directory} n'est pas sur un stockage persistant et aucun bucket hors site n'est configuré : chaque dump serait perdu à la prochaine mise à jour. Montez le volume de sauvegarde.", diff --git a/messages/it.json b/messages/it.json index 51dbd14620..30b4129c04 100644 --- a/messages/it.json +++ b/messages/it.json @@ -9617,6 +9617,7 @@ "first_pending": "Il primo dump del database non è ancora stato eseguito.", "stale": "Il dump del database più recente ha {hours, plural, one {# ora} other {# ore}}.", "last_failed": "L'ultimo dump del database non è riuscito. Quello precedente è ancora recente.", + "client_too_old": "Il client PostgreSQL di questa immagine è la versione {client}, ma il server del database usa la {server}, quindi non si può fare nessun dump. Usa un'immagine HealthLog con client {server} o più recente, oppure tieni il server su {client} o precedente.", "fresh": "L'ultimo dump del database è recente.", "nowhere_to_write": "La cartella dei dump {directory} non è scrivibile e non è configurato nessun bucket esterno, quindi non si può conservare alcun dump.", "not_persistent": "La cartella dei dump {directory} non è su uno spazio persistente e non è configurato alcun bucket esterno, quindi ogni dump andrebbe perso al prossimo aggiornamento. Monta il volume dei backup.", diff --git a/messages/ko.json b/messages/ko.json index e03a3b7d5a..090622336f 100644 --- a/messages/ko.json +++ b/messages/ko.json @@ -9617,6 +9617,7 @@ "first_pending": "첫 데이터베이스 덤프가 아직 실행되지 않았습니다.", "stale": "최신 데이터베이스 덤프가 {hours, plural, other {#시간}} 전 것입니다.", "last_failed": "마지막 데이터베이스 덤프가 실패했습니다. 그 전 덤프는 아직 최근 것입니다.", + "client_too_old": "이 이미지의 PostgreSQL 클라이언트는 {client} 버전인데 데이터베이스 서버는 {server} 버전이라 데이터베이스 덤프를 만들 수 없습니다. 클라이언트가 {server} 이상인 HealthLog 이미지를 쓰거나, 서버를 {client} 이하로 유지하세요.", "fresh": "최신 데이터베이스 덤프가 최근 것입니다.", "nowhere_to_write": "덤프 디렉터리 {directory}에 쓸 수 없고 외부 버킷도 설정되어 있지 않아 덤프를 보관할 수 없습니다.", "not_persistent": "덤프 디렉터리 {directory}이(가) 영구 저장소에 있지 않고 외부 버킷도 설정되지 않아, 모든 덤프가 다음 업데이트 때 사라집니다. 백업 볼륨을 마운트하세요.", diff --git a/messages/nl.json b/messages/nl.json index 2b8c16273c..d7dc35e15f 100644 --- a/messages/nl.json +++ b/messages/nl.json @@ -9617,6 +9617,7 @@ "first_pending": "De eerste databasedump is nog niet uitgevoerd.", "stale": "De nieuwste databasedump is {hours, plural, one {# uur} other {# uur}} oud.", "last_failed": "De laatste databasedump is mislukt. De dump daarvoor is nog recent.", + "client_too_old": "De PostgreSQL-client van dit image is versie {client}, maar de databaseserver draait {server}, dus er kan geen databasedump worden gemaakt. Gebruik een HealthLog-image met client {server} of nieuwer, of houd de server op {client} of ouder.", "fresh": "De nieuwste databasedump is recent.", "nowhere_to_write": "De dumpmap {directory} is niet beschrijfbaar en er is geen externe bucket ingesteld, dus er kan geen dump worden bewaard.", "not_persistent": "De dumpmap {directory} staat niet op blijvende opslag en er is geen externe bucket ingesteld, dus elke dump gaat bij de volgende update verloren. Koppel het back-upvolume.", diff --git a/messages/pl.json b/messages/pl.json index 404a10a39d..8601f719af 100644 --- a/messages/pl.json +++ b/messages/pl.json @@ -9617,6 +9617,7 @@ "first_pending": "Pierwszy zrzut bazy danych jeszcze się nie odbył.", "stale": "Najnowszy zrzut bazy danych ma {hours, plural, one {# godzinę} few {# godziny} many {# godzin} other {# godziny}}.", "last_failed": "Ostatni zrzut bazy danych nie powiódł się. Poprzedni jest jeszcze aktualny.", + "client_too_old": "Klient PostgreSQL w tym obrazie ma wersję {client}, a serwer bazy danych działa na {server}, więc nie da się wykonać zrzutu bazy. Użyj obrazu HealthLog z klientem {server} lub nowszym albo zostaw serwer na {client} lub starszym.", "fresh": "Najnowszy zrzut bazy danych jest aktualny.", "nowhere_to_write": "Katalog zrzutów {directory} nie jest zapisywalny i nie skonfigurowano zewnętrznego bucketu, więc żaden zrzut nie może zostać zachowany.", "not_persistent": "Katalog zrzutów {directory} nie leży na trwałym nośniku, a zewnętrzny bucket nie jest ustawiony, więc każdy zrzut przepadnie przy następnej aktualizacji. Podłącz wolumin kopii.", diff --git a/messages/pt-BR.json b/messages/pt-BR.json index 77262050ec..8a4cfa00c2 100644 --- a/messages/pt-BR.json +++ b/messages/pt-BR.json @@ -9617,6 +9617,7 @@ "first_pending": "O primeiro dump do banco de dados ainda não foi executado.", "stale": "O dump do banco de dados mais recente tem {hours, plural, one {# hora} other {# horas}}.", "last_failed": "O último dump do banco de dados falhou. O anterior ainda é recente.", + "client_too_old": "O cliente PostgreSQL desta imagem é a versão {client}, mas o servidor do banco de dados roda a {server}, então nenhum dump pode ser feito. Use uma imagem do HealthLog com cliente {server} ou mais novo, ou mantenha o servidor na {client} ou anterior.", "fresh": "O dump do banco de dados mais recente está em dia.", "nowhere_to_write": "Não é possível gravar no diretório de dumps {directory} e nenhum bucket externo está configurado, então nenhum dump pode ser guardado.", "not_persistent": "A pasta de dumps {directory} não está em armazenamento persistente e nenhum bucket externo está configurado, então cada dump se perde na próxima atualização. Monte o volume de backups.", diff --git a/messages/ru.json b/messages/ru.json index 27e3e12762..1d1114ea2a 100644 --- a/messages/ru.json +++ b/messages/ru.json @@ -9617,6 +9617,7 @@ "first_pending": "Первый дамп базы данных ещё не выполнялся.", "stale": "Самому новому дампу базы данных {hours, plural, one {# час} few {# часа} many {# часов} other {# часа}}.", "last_failed": "Последний дамп базы данных не удался. Предыдущий всё ещё свежий.", + "client_too_old": "Клиент PostgreSQL в этом образе версии {client}, а сервер базы данных работает на {server}, поэтому дамп базы сделать нельзя. Используйте образ HealthLog с клиентом {server} или новее либо оставьте сервер на {client} или старше.", "fresh": "Новейший дамп базы данных свежий.", "nowhere_to_write": "В каталог дампов {directory} нельзя писать, и внешний бакет не настроен, поэтому ни один дамп нельзя сохранить.", "not_persistent": "Каталог дампов {directory} не на постоянном хранилище, и внешний бакет не настроен, поэтому каждый дамп был бы потерян при следующем обновлении. Смонтируйте том резервных копий.", diff --git a/scripts/__tests__/db-dump.test.ts b/scripts/__tests__/db-dump.test.ts index bad66da72d..f876b86a8e 100644 --- a/scripts/__tests__/db-dump.test.ts +++ b/scripts/__tests__/db-dump.test.ts @@ -11,10 +11,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; const pendingMigrations = vi.fn<() => Promise>(); -const createDatabaseDump = vi.fn(async () => ({ +const createDatabaseDump = vi.fn<() => Promise>(async () => ({ dumpPath: "/b/healthlog-20261025T013000Z-pre-migration.dump", manifest: { dump: { bytes: 1024 }, rowCounts: { "public.users": 1 } }, })); +const assertClientServesServer = vi.fn<() => Promise>(async () => ({ + clientMajor: 19, + serverMajor: 18, +})); vi.mock("../pending-migrations.mjs", () => ({ pendingMigrations: () => pendingMigrations(), @@ -28,9 +32,14 @@ vi.mock("../../src/lib/database-backup/dump-core.mjs", async (original) => ({ latestMigration: async () => "0488_account_deletion_grace", listUserTables: async () => ["public.users"], createDatabaseDump: () => createDatabaseDump(), + assertClientServesServer: () => assertClientServesServer(), applyRetention: async () => [], })); +import { + ClientTooOldError, + clientServerMismatch, +} from "../../src/lib/database-backup/dump-core.mjs"; import { preMigrationDump } from "../db-dump.mjs"; const env = { @@ -44,7 +53,21 @@ beforeEach(() => { vi.spyOn(console, "log").mockImplementation(() => {}); vi.spyOn(console, "error").mockImplementation(() => {}); createDatabaseDump.mockClear(); + assertClientServesServer.mockClear(); }); + +/** What `pg_dump` 19 against a server on 20 is refused with. */ +function tooOld() { + const pair = { tool: "pg_dump", clientMajor: 19, serverMajor: 20 }; + return new ClientTooOldError(clientServerMismatch(pair) ?? "", pair); +} + +function errorLines(): string { + return vi + .mocked(console.error) + .mock.calls.map((c) => String(c[0])) + .join("\n"); +} afterEach(() => vi.restoreAllMocks()); describe("the dump before migrating", () => { @@ -67,4 +90,43 @@ describe("the dump before migrating", () => { expect(await preMigrationDump(env, { directoryStatus: kept })).toBe(0); expect(createDatabaseDump).toHaveBeenCalledTimes(1); }); + + // #1431: a server newer than the image's client stopped the boot with + // pg_dump's own mismatch line. It stops the boot still, with its own exit + // code, so the entrypoint does not restart it in a hot loop, and with one + // message that names both majors. + it("stops with its own exit code and one clear message when the server is newer than the client", async () => { + pendingMigrations.mockResolvedValue(["0489_database_backup_run_key"]); + createDatabaseDump.mockRejectedValueOnce(tooOld()); + expect(await preMigrationDump(env, { directoryStatus: kept })).toBe(3); + const errors = errorLines(); + expect(errors).toMatch( + /This image's PostgreSQL client \(pg_dump\) is 19; your server is 20\./, + ); + expect(errors.match(/your server is 20/g)).toHaveLength(1); + expect(errors).not.toContain("the database dump before migrating failed"); + }); + + it("keeps exit 1 for any other failed dump", async () => { + pendingMigrations.mockResolvedValue(["0489_database_backup_run_key"]); + createDatabaseDump.mockRejectedValueOnce(new Error("No space left")); + expect(await preMigrationDump(env, { directoryStatus: kept })).toBe(1); + }); + + it("warns at a boot with nothing to migrate that the nightly dump cannot work", async () => { + pendingMigrations.mockResolvedValue([]); + assertClientServesServer.mockRejectedValueOnce(tooOld()); + expect(await preMigrationDump(env, { directoryStatus: kept })).toBe(0); + expect(createDatabaseDump).not.toHaveBeenCalled(); + expect(errorLines()).toMatch( + /WARNING .*client \(pg_dump\) is 19; your server is 20\..*nightly database dump/, + ); + }); + + it("says nothing at such a boot when the client serves the server", async () => { + pendingMigrations.mockResolvedValue([]); + expect(await preMigrationDump(env, { directoryStatus: kept })).toBe(0); + expect(assertClientServesServer).toHaveBeenCalledTimes(1); + expect(errorLines()).toBe(""); + }); }); diff --git a/scripts/__tests__/db-restore.test.ts b/scripts/__tests__/db-restore.test.ts index 3479d2566f..fe5eece966 100644 --- a/scripts/__tests__/db-restore.test.ts +++ b/scripts/__tests__/db-restore.test.ts @@ -16,7 +16,9 @@ import { join } from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; const tablesInTarget = vi.fn(async (): Promise => []); -const runTool = vi.fn(async () => ""); +const runTool = vi.fn(async (..._args: unknown[]) => ""); +/** What the target answers for `server_version_num`; null answers nothing. */ +let serverVersionNum: number | null = null; const end = vi.fn(async () => {}); /** What the stand-in bucket lists under `database/`; downloads are refused. */ const bucketKeys = vi.fn(async (): Promise => []); @@ -26,7 +28,15 @@ const downloads = vi.fn(async (key: string) => { vi.mock("../../src/lib/database-backup/dump-core.mjs", async (original) => ({ ...(await original>()), - connect: async () => ({ query: async () => ({ rows: [] }), end }), + connect: async () => ({ + query: async (sql: string) => + serverVersionNum !== null && /server_version_num/.test(sql) + ? { + rows: [{ v: `${serverVersionNum / 10000}.0`, n: serverVersionNum }], + } + : { rows: [] }, + end, + }), listUserTables: () => tablesInTarget(), runTool: (...args: unknown[]) => runTool(...(args as [])), openBucket: async () => ({ @@ -93,7 +103,9 @@ beforeEach(() => { lines.push(String(line)); }); tablesInTarget.mockResolvedValue([]); - runTool.mockClear(); + runTool.mockReset(); + runTool.mockResolvedValue(""); + serverVersionNum = null; }); afterEach(() => { rmSync(dir, { recursive: true, force: true }); @@ -150,6 +162,44 @@ describe("db-restore refuses before it writes", () => { expect(runTool).not.toHaveBeenCalled(); }); + // #1431: the same ceiling as the dump's. `pg_restore` is not run against a + // server newer than its own major; the refusal names both and the way out. + it("refuses a server newer than this image's pg_restore, before it restores", async () => { + writeDump(); + serverVersionNum = 200000; + runTool.mockImplementation(async (...args: unknown[]) => + (args[1] as string[]).includes("--version") + ? "pg_restore (PostgreSQL) 19.1\n" + : "", + ); + expect(await main(["latest"], env())).toBe(1); + expect(errors.join("\n")).toMatch( + /This image's PostgreSQL client \(pg_restore\) is 19; your server is 20\./, + ); + const restored = runTool.mock.calls.filter( + (c) => !(c[1] as string[]).includes("--version"), + ); + expect(restored).toEqual([]); + }); + + it("restores into a server of the client's own major", async () => { + writeDump(); + serverVersionNum = 190001; + runTool.mockImplementation(async (...args: unknown[]) => + (args[1] as string[]).includes("--version") + ? "pg_restore (PostgreSQL) 19.1\n" + : "", + ); + await main(["latest"], env()); + expect( + runTool.mock.calls.some( + (c) => + c[0] === "pg_restore" && + (c[1] as string[]).includes("--single-transaction"), + ), + ).toBe(true); + }); + it("says when there is nothing to restore, and how it is used", async () => { expect(await main(["latest"], env())).toBe(1); expect(errors.join("\n")).toMatch(/no restorable dump/); diff --git a/scripts/__tests__/docker-entrypoint.test.ts b/scripts/__tests__/docker-entrypoint.test.ts new file mode 100644 index 0000000000..0053e1a074 --- /dev/null +++ b/scripts/__tests__/docker-entrypoint.test.ts @@ -0,0 +1,136 @@ +/** + * How `docker-entrypoint.sh` ends when the dump before migrating fails. + * + * `node` is a stand-in on PATH: every check the entrypoint runs with it + * passes, `scripts/db-dump.mjs` exits with the code a case asks for, and + * `scripts/migrate-deploy.mjs` leaves a mark, so a case can tell whether the + * boot went on to migrate. The real dump step and its exit codes are in + * `db-dump.test.ts` and `tests/integration/database-backup.test.ts`. + * + * A server newer than the image's `pg_dump` (#1431) is the failure a restart + * cannot fix. With `restart: unless-stopped` an immediate exit restarted into + * the same error every few seconds; the entrypoint now says why once and + * waits before it exits, and `docker stop` still ends it at once. + */ +import { spawn } from "node:child_process"; +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { afterAll, describe, expect, it } from "vitest"; + +const ENTRYPOINT = join(process.cwd(), "docker-entrypoint.sh"); +const work = mkdtempSync(join(tmpdir(), "hl-entrypoint-")); +const bin = join(work, "bin"); + +mkdirSync(bin, { recursive: true }); +writeFileSync( + join(bin, "node"), + `#!/bin/sh +case "$*" in + *scripts/db-dump.mjs*) + [ "$DUMP_EXIT" = 3 ] && echo "HealthLog: ERROR — This image's PostgreSQL client (pg_dump) is 19; your server is 20." >&2 + exit "$DUMP_EXIT" ;; + *scripts/migrate-deploy.mjs*) : > "$MIGRATED_MARK"; exit 0 ;; + *) exit 0 ;; +esac +`, +); +chmodSync(join(bin, "node"), 0o755); + +afterAll(() => rmSync(work, { recursive: true, force: true })); + +interface Run { + code: number | null; + signal: NodeJS.Signals | null; + stderr: string; + stdout: string; + migrated: boolean; + ms: number; +} + +/** + * Run the entrypoint with the dump step exiting `dumpExit`. With `stopAfter`, + * SIGTERM is sent that many ms after the wait message appears, as + * `docker stop` would. + */ +function boot(dumpExit: number, stopAfter?: number): Promise { + const mark = join(work, `migrated-${dumpExit}-${Date.now()}`); + return new Promise((resolve, reject) => { + const started = Date.now(); + const child = spawn("sh", [ENTRYPOINT, "true"], { + env: { + PATH: `${bin}:${process.env.PATH}`, + DATABASE_URL: "postgresql://u:p@127.0.0.1:5432/healthlog", + API_TOKEN_HMAC_KEY: "hmac", + ENCRYPTION_KEY: "a".repeat(64), + DUMP_EXIT: String(dumpExit), + MIGRATED_MARK: mark, + }, + stdio: ["ignore", "pipe", "pipe"], + }); + let stderr = ""; + let stdout = ""; + let stopping = false; + child.stdout.on("data", (c) => (stdout += String(c))); + child.stderr.on("data", (c) => { + stderr += String(c); + if (stopAfter !== undefined && !stopping && /waiting/i.test(stderr)) { + stopping = true; + setTimeout(() => child.kill("SIGTERM"), stopAfter); + } + }); + const guard = setTimeout(() => { + child.kill("SIGKILL"); + reject(new Error(`the entrypoint did not end: ${stderr}`)); + }, 15_000); + child.on("close", (code, signal) => { + clearTimeout(guard); + resolve({ + code, + signal, + stderr, + stdout, + migrated: existsSync(mark), + ms: Date.now() - started, + }); + }); + }); +} + +describe("the entrypoint when the dump before migrating fails", () => { + it("migrates and starts after a dump that worked", async () => { + const run = await boot(0); + expect(run.code, run.stderr).toBe(0); + expect(run.migrated).toBe(true); + }); + + it("stops at once, without migrating, after a dump that failed", async () => { + const run = await boot(1); + expect(run.code).toBe(1); + expect(run.migrated).toBe(false); + expect(run.stderr).toContain("not migrating without the dump"); + expect(run.stderr).not.toMatch(/waiting/i); + }); + + it("does not migrate, says why once, and waits instead of restarting into the same error, when the server is newer than the client", async () => { + const run = await boot(3, 1500); + // It was still waiting when it was stopped, and the stop ended it with + // the entrypoint's own failure code rather than a kill. + expect(run.ms).toBeGreaterThanOrEqual(1500); + expect(run.signal).toBeNull(); + expect(run.code).toBe(1); + expect(run.migrated).toBe(false); + expect(run.stderr.match(/your server is 20/g)).toHaveLength(1); + expect(run.stderr).toContain("cannot dump this database server"); + expect(run.stderr).toContain("DB_BACKUP_BEFORE_MIGRATE=false"); + expect(run.stderr).not.toContain("Free disk space"); + }); +}); diff --git a/scripts/db-dump.mjs b/scripts/db-dump.mjs index 6337658f65..83312522e4 100644 --- a/scripts/db-dump.mjs +++ b/scripts/db-dump.mjs @@ -21,7 +21,11 @@ * not a reason to keep the app down. Exit 1: the directory is kept and the * dump failed. The entrypoint then stops the boot and names the switch that skips * the dump, because migrating without the way back the operator was promised - * is the one thing this step exists to prevent. + * is the one thing this step exists to prevent. Exit 3: the dump cannot be + * taken at all, because the server's major is newer than this image's + * `pg_dump` (#1431). That does not pass with a restart, so the entrypoint + * says so once and does not restart in a hot loop. At a boot with nothing to + * migrate the same pair is a warning, since the nightly dump fails on it. * * Fast on purpose: one snapshot, `pg_dump`, a count per table for the * manifest, `pg_restore --list` to prove the file reads. Nothing else. @@ -32,7 +36,9 @@ import { pathToFileURL } from "node:url"; import { applyRetention, + assertClientServesServer, backupDirectoryStatus, + ClientTooOldError, connect, createDatabaseDump, latestMigration, @@ -59,6 +65,32 @@ function imageVersion(env) { } } +/** The exit code for a server newer than this image's `pg_dump`. */ +export const CLIENT_TOO_OLD_EXIT = 3; + +/** + * Warn, and only warn, when this image's `pg_dump` cannot dump the server: + * nothing is migrated at this boot, but the nightly dump fails until the + * pair is fixed. Any other error here is not this step's to report. + * + * @param {string} databaseUrl + */ +async function warnIfClientTooOld(databaseUrl) { + let client; + try { + client = await connect(databaseUrl); + await assertClientServesServer(client, "pg_dump"); + } catch (error) { + if (error instanceof ClientTooOldError) { + warn( + `${error.message} The nightly database dump fails until the two match; the app starts.`, + ); + } + } finally { + await client?.end().catch(() => {}); + } +} + /** Megabytes as an operator reads them. */ function mb(bytes) { return `${(bytes / 1024 / 1024).toFixed(1)} MB`; @@ -93,7 +125,10 @@ export async function preMigrationDump(env = process.env, options = {}) { ); pending = null; } - if (pending !== null && pending.length === 0) return 0; + if (pending !== null && pending.length === 0) { + await warnIfClientTooOld(databaseUrl); + return 0; + } const migrations = pending === null ? "any pending migrations" @@ -129,6 +164,7 @@ export async function preMigrationDump(env = process.env, options = {}) { `${dir} ${why}, so no dump is taken before ${pending === null ? migrations : `the ${migrations}`}. ` + "Mount the backups volume (docker-compose.yml) to keep a way back; continuing.", ); + await warnIfClientTooOld(databaseUrl); return 0; } @@ -148,6 +184,10 @@ export async function preMigrationDump(env = process.env, options = {}) { `${Object.keys(manifest.rowCounts).length} tables, ${Math.round((Date.now() - started) / 1000)} s).`, ); } catch (error) { + if (error instanceof ClientTooOldError) { + console.error(`HealthLog: ERROR — ${error.message}`); + return CLIENT_TOO_OLD_EXIT; + } console.error( `HealthLog: ERROR — the database dump before migrating failed: ${error instanceof Error ? error.message : String(error)}`, ); diff --git a/scripts/db-restore.mjs b/scripts/db-restore.mjs index 39aa4810dd..4a965b7e91 100644 --- a/scripts/db-restore.mjs +++ b/scripts/db-restore.mjs @@ -34,7 +34,9 @@ * fingerprints; each one missing or different is named, and a mismatch * of the active encryption key refuses (`--ignore-key-mismatch` restores * anyway, for an operator who knows the key is lost); - * 4. the target database must hold no table at all. This never overwrites. + * 4. the target database must hold no table at all. This never overwrites; + * 5. the target server's major must not be newer than this image's + * `pg_restore` (#1431): the refusal names both majors and the way out. * Then `pg_restore` in one transaction, `ANALYZE`, and a count of every table * against the manifest. A count that differs empties the database again and * fails, so the app is never started on a restore that does not match. @@ -48,6 +50,8 @@ import { basename, dirname, isAbsolute, join } from "node:path"; import { pathToFileURL } from "node:url"; import { + assertClientServesServer, + ClientTooOldError, compareKeyFingerprints, compareRowCounts, connect, @@ -437,6 +441,22 @@ async function restoreCommand(arg, flags, env) { ); } + // 5. The image's client can work with this server. + try { + await assertClientServesServer(client, "pg_restore", { + versionLine: () => + runTool("pg_restore", ["--version"], { capture: true }).then( + (line) => line.trim(), + () => null, + ), + }); + } catch (error) { + if (error instanceof ClientTooOldError) { + throw new Refusal(error.message); + } + throw error; + } + say("restoring (one transaction)..."); const started = Date.now(); await runTool( diff --git a/src/app/api/export/health-record/__tests__/route.test.ts b/src/app/api/export/health-record/__tests__/route.test.ts index ff56c3f23a..79285c0144 100644 --- a/src/app/api/export/health-record/__tests__/route.test.ts +++ b/src/app/api/export/health-record/__tests__/route.test.ts @@ -12,7 +12,7 @@ * reads what comes out, with a positive control beside each exclusion so * nothing can pass on an empty fixture. */ -import { describe, it, expect, vi, beforeEach } from "vitest"; +import { describe, it, expect, vi, beforeAll, beforeEach } from "vitest"; import { NextRequest } from "next/server"; import { unzipSync } from "fflate"; @@ -176,6 +176,13 @@ function pdfBytesText(bytes: Uint8Array): Promise { return readPdfText(bytes); } +// The route pulls in the PDF, FHIR and zip writers. Loading that graph cold +// takes seconds on a loaded machine, so it happens once here, on a hook's +// budget, instead of inside whichever test happens to run first. +beforeAll(async () => { + await import("../route"); +}, 60_000); + beforeEach(() => { vi.clearAllMocks(); vi.mocked(resolveModuleMap).mockResolvedValue({} as never); diff --git a/src/components/charts/__tests__/health-chart-comparison.test.tsx b/src/components/charts/__tests__/health-chart-comparison.test.tsx index 6b2d61ccad..936abb5303 100644 --- a/src/components/charts/__tests__/health-chart-comparison.test.tsx +++ b/src/components/charts/__tests__/health-chart-comparison.test.tsx @@ -1,4 +1,4 @@ -import { describe, it, expect, vi } from "vitest"; +import { describe, it, beforeAll, expect, vi } from "vitest"; import { renderToStaticMarkup } from "react-dom/server"; /** @@ -62,6 +62,13 @@ vi.mock("@/hooks/use-auth", () => ({ }), })); +// The chart pulls in Recharts and the chart kit. Transforming that graph cold +// takes seconds on a loaded machine, so it happens once here, on a hook's +// budget, instead of inside whichever test happens to run first. +beforeAll(async () => { + await import("../health-chart"); +}, 60_000); + describe("", () => { it("renders no comparison caption when baseline is 'none' (regression guard)", async () => { const { I18nProvider } = await import("@/lib/i18n/context"); diff --git a/src/components/charts/__tests__/health-chart-data-table.test.tsx b/src/components/charts/__tests__/health-chart-data-table.test.tsx index 1b98d2849b..3b25cf91a5 100644 --- a/src/components/charts/__tests__/health-chart-data-table.test.tsx +++ b/src/components/charts/__tests__/health-chart-data-table.test.tsx @@ -1,4 +1,4 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; +import { describe, it, expect, vi, beforeAll, beforeEach } from "vitest"; import { renderToStaticMarkup } from "react-dom/server"; import enMessages from "../../../../messages/en.json"; @@ -65,6 +65,13 @@ function rowCount(html: string): number { return (html.match(/data-slot="chart-data-table-row"/g) ?? []).length; } +// The chart pulls in Recharts and the chart kit. Transforming that graph cold +// takes seconds on a loaded machine, so it happens once here, on a hook's +// budget, instead of inside whichever test happens to run first. +beforeAll(async () => { + await import("../health-chart"); +}, 60_000); + describe(" — data table", () => { beforeEach(() => { vi.resetModules(); diff --git a/src/components/charts/__tests__/health-chart-heading-level.test.tsx b/src/components/charts/__tests__/health-chart-heading-level.test.tsx index 5343a6b0a3..3b68f4cc36 100644 --- a/src/components/charts/__tests__/health-chart-heading-level.test.tsx +++ b/src/components/charts/__tests__/health-chart-heading-level.test.tsx @@ -1,4 +1,4 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; +import { describe, it, expect, vi, beforeAll, beforeEach } from "vitest"; import { renderToStaticMarkup } from "react-dom/server"; import deMessages from "../../../../messages/de.json"; @@ -41,6 +41,13 @@ vi.mock("@/hooks/use-auth", () => ({ }), })); +// The chart pulls in Recharts and the chart kit. Transforming that graph cold +// takes seconds on a loaded machine, so it happens once here, on a hook's +// budget, instead of inside whichever test happens to run first. +beforeAll(async () => { + await import("../health-chart"); +}, 60_000); + describe(" — card heading level", () => { beforeEach(() => { vi.resetModules(); diff --git a/src/components/charts/__tests__/health-chart-type-label.test.tsx b/src/components/charts/__tests__/health-chart-type-label.test.tsx index aaefdf00dd..75b472457e 100644 --- a/src/components/charts/__tests__/health-chart-type-label.test.tsx +++ b/src/components/charts/__tests__/health-chart-type-label.test.tsx @@ -1,4 +1,4 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; +import { describe, it, expect, vi, beforeAll, beforeEach } from "vitest"; import { renderToStaticMarkup } from "react-dom/server"; import de from "../../../../messages/de.json"; @@ -55,6 +55,13 @@ vi.mock("@/hooks/use-chart-overlay-prefs", () => ({ }), })); +// The chart pulls in Recharts and the chart kit. Transforming that graph cold +// takes seconds on a loaded machine, so it happens once here, on a hook's +// budget, instead of inside whichever test happens to run first. +beforeAll(async () => { + await import("../health-chart"); +}, 60_000); + describe(" — series names", () => { beforeEach(() => { vi.resetModules(); diff --git a/src/components/charts/__tests__/medication-compliance-chart-empty-state-gate.test.tsx b/src/components/charts/__tests__/medication-compliance-chart-empty-state-gate.test.tsx index d2ab37256b..b12c7f2da6 100644 --- a/src/components/charts/__tests__/medication-compliance-chart-empty-state-gate.test.tsx +++ b/src/components/charts/__tests__/medication-compliance-chart-empty-state-gate.test.tsx @@ -1,4 +1,4 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; +import { describe, it, expect, vi, beforeAll, beforeEach } from "vitest"; import { renderToStaticMarkup } from "react-dom/server"; // vi.doMock below invalidates the module registry, so the re-imported // provider gets a fresh (unprimed) locale cache — pass the DE bundle @@ -24,6 +24,13 @@ vi.mock("@/hooks/use-auth", () => ({ }), })); +// The chart pulls in Recharts and the chart kit. Transforming that graph cold +// takes seconds on a loaded machine, so it happens once here, on a hook's +// budget, instead of inside whichever test happens to run first. +beforeAll(async () => { + await import("../medication-compliance-chart"); +}, 60_000); + describe(" — empty-state gate by raw count", () => { beforeEach(() => { vi.resetModules(); diff --git a/src/components/charts/__tests__/mood-chart-empty-state-gate.test.tsx b/src/components/charts/__tests__/mood-chart-empty-state-gate.test.tsx index 48a3c552a5..b8519cc21c 100644 --- a/src/components/charts/__tests__/mood-chart-empty-state-gate.test.tsx +++ b/src/components/charts/__tests__/mood-chart-empty-state-gate.test.tsx @@ -1,4 +1,4 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; +import { describe, it, expect, vi, beforeAll, beforeEach } from "vitest"; import { renderToStaticMarkup } from "react-dom/server"; // vi.doMock below invalidates the module registry, so the re-imported // provider gets a fresh (unprimed) locale cache — pass the DE bundle @@ -32,6 +32,13 @@ function dayKeyAgo(agoDays: number): string { return new Date(Date.now() - agoDays * 86_400_000).toISOString().slice(0, 10); } +// The chart pulls in Recharts and the chart kit. Transforming that graph cold +// takes seconds on a loaded machine, so it happens once here, on a hook's +// budget, instead of inside whichever test happens to run first. +beforeAll(async () => { + await import("../mood-chart"); +}, 60_000); + describe(" — empty-state gate by raw count", () => { beforeEach(() => { vi.resetModules(); diff --git a/src/lib/auth/__tests__/password-estimate-cost.test.ts b/src/lib/auth/__tests__/password-estimate-cost.test.ts index e462ea6d89..97adb6c4f9 100644 --- a/src/lib/auth/__tests__/password-estimate-cost.test.ts +++ b/src/lib/auth/__tests__/password-estimate-cost.test.ts @@ -22,6 +22,11 @@ import { estimatePasswordStrength, passwordEstimateInput, } from "@/lib/auth/password"; +import { + changePasswordSchema, + loginPasswordSchema, + newAccountPasswordSchema, +} from "@/lib/validations/auth"; import { PASSWORD_STRENGTH_MAX_LENGTH } from "@/lib/zxcvbn-i18n"; import { readSourceFolder } from "@/__tests__/helpers/source-files"; import { @@ -207,3 +212,36 @@ describe("zxcvbn has one caller", () => { expect(callers).toEqual(["lib/auth/password.ts"]); }); }); + +describe("new password length cap", () => { + const ok = "Xq7#vLp2!mRt".padEnd(1024, "z"); + const tooLong = ok + "z"; + + it("accepts 1024 characters and refuses 1025 on every new-password schema", () => { + expect(newAccountPasswordSchema.safeParse(ok).success).toBe(true); + expect(newAccountPasswordSchema.safeParse(tooLong).success).toBe(false); + const change = (pw: string) => + changePasswordSchema.safeParse({ + currentPassword: "current", + newPassword: pw, + confirmPassword: pw, + }).success; + expect(change(ok)).toBe(true); + expect(change(tooLong)).toBe(false); + }); + + it("leaves sign-in and the current password uncapped", () => { + const existing = "y".repeat(4096); + expect( + loginPasswordSchema.safeParse({ email: "someone", password: existing }) + .success, + ).toBe(true); + expect( + changePasswordSchema.safeParse({ + currentPassword: existing, + newPassword: ok, + confirmPassword: ok, + }).success, + ).toBe(true); + }); +}); diff --git a/src/lib/database-backup/__tests__/client-server-major.test.ts b/src/lib/database-backup/__tests__/client-server-major.test.ts new file mode 100644 index 0000000000..cf733bf1cd --- /dev/null +++ b/src/lib/database-backup/__tests__/client-server-major.test.ts @@ -0,0 +1,180 @@ +/** + * The client tools' major caps the server major (#1431). `pg_dump` refuses a + * server newer than its own major, and it says so in a line that, inside a + * boot abort, did not point at the cause. These are the rules of the check + * that runs before any client tool touches the server: how a `--version` + * line and `server_version_num` are read, when the pair is refused, and the + * one message an operator gets for it. + */ +import { describe, expect, it } from "vitest"; + +import { + ClientTooOldError, + assertClientServesServer, + clientMajorFromVersionLine, + clientServerMismatch, + serverMajorFromVersionNum, +} from "../dump-core.mjs"; +import { clientTooOldIn } from "../dump-problems"; + +describe("reading the client's major", () => { + it.each([ + ["pg_dump (PostgreSQL) 16.4", 16], + ["pg_dump (PostgreSQL) 18.6 (Debian 18.6-1.pgdg13+1)", 18], + ["pg_restore (PostgreSQL) 19.0", 19], + ["pg_dump (PostgreSQL) 20.1", 20], + ["pg_dump (PostgreSQL) 19devel", 19], + ["pg_dump (PostgreSQL) 19beta2", 19], + ["pg_dump (PostgreSQL) 20rc1", 20], + ["pg_dump (PostgreSQL) 9.6.24", 9], + ["pg_dump (PostgreSQL) 18.6\n", 18], + ])("%s is %i", (line, major) => { + expect(clientMajorFromVersionLine(line)).toBe(major); + }); + + it.each([[null], [""], ["command not found"], ["pg_dump (PostgreSQL)"]])( + "%j names no major", + (line) => { + expect(clientMajorFromVersionLine(line)).toBeNull(); + }, + ); +}); + +describe("reading the server's major", () => { + it.each([ + [160004, 16], + [180006, 18], + [190000, 19], // 19devel and 19beta report the .0 + [190001, 19], + [200000, 20], + [90624, 9], + ])("%i is %i", (num, major) => { + expect(serverMajorFromVersionNum(num)).toBe(major); + }); + + it.each([[null], [0], [-1], [Number.NaN], [1.5]])("%s is unknown", (num) => { + expect(serverMajorFromVersionNum(num)).toBeNull(); + }); +}); + +describe("which pairs are refused", () => { + it.each([ + [19, 16], + [19, 18], + [19, 19], + [20, 19], + ])("client %i serves server %i", (client, server) => { + expect( + clientServerMismatch({ + tool: "pg_dump", + clientMajor: client, + serverMajor: server, + }), + ).toBeNull(); + }); + + it.each([ + [18, 19], + [19, 20], + [16, 18], + ])("client %i refuses server %i", (client, server) => { + expect( + clientServerMismatch({ + tool: "pg_dump", + clientMajor: client, + serverMajor: server, + }), + ).not.toBeNull(); + }); + + // An unknown side is not a reason to refuse: the tool runs and says what + // is wrong in its own words, as before the check existed. + it.each([ + [null, 20], + [19, null], + [null, null], + ])("client %s and server %s are not refused", (client, server) => { + expect( + clientServerMismatch({ + tool: "pg_dump", + clientMajor: client, + serverMajor: server, + }), + ).toBeNull(); + }); + + it("names both majors and the way out, in one message that reads back", () => { + const message = clientServerMismatch({ + tool: "pg_dump", + clientMajor: 19, + serverMajor: 20, + }); + expect(message).toMatch( + /^This image's PostgreSQL client \(pg_dump\) is 19; your server is 20\./, + ); + expect(message).toContain("PostgreSQL 19 and older"); + expect(message).toContain("client is 20 or newer"); + expect(message).toContain("keep the server on 19 or older"); + expect(message).toContain("docs/ops/postgres-major-upgrade.md"); + // The ledger keeps 500 characters of a failure. + expect(message!.length).toBeLessThanOrEqual(500); + expect(clientTooOldIn(message)).toEqual({ + tool: "pg_dump", + client: 19, + server: 20, + }); + }); + + it("reads no mismatch out of any other failure", () => { + expect(clientTooOldIn(null)).toBeNull(); + expect( + clientTooOldIn( + "pg_dump exited 1: pg_dump: error: aborting because of server version mismatch", + ), + ).toBeNull(); + }); +}); + +describe("the check before a tool runs", () => { + const server = (n: number | null) => ({ + query: async () => + n === null + ? { rows: [] } + : { rows: [{ v: `${Math.floor(n / 10000)}.0`, n }] }, + }); + + it("refuses a server newer than the client, before the tool is run", async () => { + const error = await assertClientServesServer(server(200000), "pg_dump", { + versionLine: async () => "pg_dump (PostgreSQL) 19.1", + }).catch((e: unknown) => e); + expect(error).toBeInstanceOf(ClientTooOldError); + expect((error as ClientTooOldError).clientMajor).toBe(19); + expect((error as ClientTooOldError).serverMajor).toBe(20); + expect((error as Error).message).toMatch( + /client \(pg_dump\) is 19; your server is 20/, + ); + }); + + it("lets an older or equal server through", async () => { + for (const n of [160004, 180006, 190001]) { + await expect( + assertClientServesServer(server(n), "pg_restore", { + versionLine: async () => "pg_restore (PostgreSQL) 19.1", + }), + ).resolves.toMatchObject({ clientMajor: 19 }); + } + }); + + it("lets the tool run when either major cannot be read", async () => { + await expect( + assertClientServesServer(server(null), "pg_dump", { + versionLine: async () => "pg_dump (PostgreSQL) 19.1", + }), + ).resolves.toEqual({ clientMajor: 19, serverMajor: null }); + await expect( + assertClientServesServer(server(200000), "pg_dump", { + versionLine: async () => null, + }), + ).resolves.toEqual({ clientMajor: null, serverMajor: 20 }); + }); +}); diff --git a/src/lib/database-backup/__tests__/dump-core.test.ts b/src/lib/database-backup/__tests__/dump-core.test.ts index f0fae08eb9..40625b486f 100644 --- a/src/lib/database-backup/__tests__/dump-core.test.ts +++ b/src/lib/database-backup/__tests__/dump-core.test.ts @@ -804,7 +804,11 @@ describe("an off-host copy read back by the restore", () => { ), keys: [key], }), - ).rejects.toThrow(/does not open/); + ).rejects.toMatchObject({ + name: "OffhostTagRefusedError", + code: "OFFHOST_TAG_REFUSED", + message: expect.stringMatching(/does not open/), + }); expect(await readdir(dir)).toEqual([name]); // Altered. diff --git a/src/lib/database-backup/dump-core.mjs b/src/lib/database-backup/dump-core.mjs index 565e408621..99b8df87a7 100644 --- a/src/lib/database-backup/dump-core.mjs +++ b/src/lib/database-backup/dump-core.mjs @@ -44,6 +44,7 @@ import { } from "node:fs"; import { readFile, rename, rm, stat, writeFile } from "node:fs/promises"; import { basename, dirname, join, resolve } from "node:path"; +import { Transform } from "node:stream"; import { pipeline } from "node:stream/promises"; import { createGunzip } from "node:zlib"; @@ -920,13 +921,119 @@ async function createPrivateFile(path) { /** `pg_dump (PostgreSQL) 18.6`, or null when it cannot be asked. */ export async function pgDumpVersion() { + return toolVersion("pg_dump"); +} + +/** + * A client tool's `--version` line, or null when it cannot be asked. + * @param {string} tool + */ +export async function toolVersion(tool) { try { - return (await runTool("pg_dump", ["--version"], { capture: true })).trim(); + return (await runTool(tool, ["--version"], { capture: true })).trim(); } catch { return null; } } +// ── The client's major caps the server's ─────────────────────────────────── +// +// `pg_dump` reads servers of its own major and older, and refuses a newer one +// with a version-mismatch line. So the client major in the image is the +// highest server major HealthLog can dump, and the dump before migrating +// gates the boot: a server moved past it took the app down at the next +// release with a migration, and the nightly dump failed with the same line +// (#1431). `pg_restore` is held to the same rule. Every path that runs either +// tool against a server checks the pair first and refuses with one message +// that names both majors and the way out. + +/** + * The major in a `--version` line: `pg_dump (PostgreSQL) 19.1` is 19, and so + * are `19devel`, `19beta2` and `19rc1`. Null when the line names none. + * + * @param {string | null | undefined} line + * @returns {number | null} + */ +export function clientMajorFromVersionLine(line) { + const match = /\(PostgreSQL\)\s+(\d+)/.exec(line ?? ""); + return match ? Number(match[1]) : null; +} + +/** + * The major in `server_version_num`: 190001 is 19. A development or beta + * build reports its major's `.0` (190000). Null for anything else. + * + * @param {number | null | undefined} num + * @returns {number | null} + */ +export function serverMajorFromVersionNum(num) { + return typeof num === "number" && Number.isSafeInteger(num) && num > 0 + ? Math.floor(num / 10000) + : null; +} + +/** + * The operator message for a client older than the server, or null when the + * pair works. A side that cannot be read is not refused: the tool runs and + * says what is wrong in its own words. + * + * The message opens with a fixed sentence `clientTooOldIn` (dump-problems.ts) + * reads back from a stored failure, and stays under the ledger's 500 + * characters. + * + * @param {{ tool: string; clientMajor: number | null; serverMajor: number | null }} pair + * @returns {string | null} + */ +export function clientServerMismatch({ tool, clientMajor, serverMajor }) { + if (clientMajor === null || serverMajor === null) return null; + if (serverMajor <= clientMajor) return null; + return ( + `This image's PostgreSQL client (${tool}) is ${clientMajor}; your server is ${serverMajor}. ` + + `${tool} cannot work with a server newer than its own major, so this image supports PostgreSQL ${clientMajor} and older. ` + + `Use a HealthLog image whose client is ${serverMajor} or newer, or keep the server on ${clientMajor} or older ` + + `(docs/ops/postgres-major-upgrade.md).` + ); +} + +/** A client tool older than the server it was about to run against. */ +export class ClientTooOldError extends Error { + /** + * @param {string} message + * @param {{ tool: string; clientMajor: number; serverMajor: number }} pair + */ + constructor(message, pair) { + super(message); + this.name = "ClientTooOldError"; + this.tool = pair.tool; + this.clientMajor = pair.clientMajor; + this.serverMajor = pair.serverMajor; + } +} + +/** + * The check before `tool` runs against the server `client` is connected to: + * throws `ClientTooOldError` when the server's major is newer than the + * tool's. Answers both majors, either null when it could not be read. + * + * @param {Queryable} client + * @param {string} tool + * @param {{ versionLine?: () => Promise }} [options] + * @returns {Promise<{ clientMajor: number | null; serverMajor: number | null }>} + */ +export async function assertClientServesServer(client, tool, options = {}) { + const [line, server] = await Promise.all([ + (options.versionLine ?? (() => toolVersion(tool)))(), + serverVersion(client).catch(() => null), + ]); + const clientMajor = clientMajorFromVersionLine(line); + const serverMajor = serverMajorFromVersionNum(server?.versionNum ?? null); + const message = clientServerMismatch({ tool, clientMajor, serverMajor }); + if (message !== null && clientMajor !== null && serverMajor !== null) { + throw new ClientTooOldError(message, { tool, clientMajor, serverMajor }); + } + return { clientMajor, serverMajor }; +} + /** * Read an archive's table of contents back. A file `pg_restore` cannot list * is not a dump, whatever its name. Answers the number of entries. @@ -1090,6 +1197,10 @@ export async function createDatabaseDump(options) { /** The files this call created, and only those, go on a failure. */ const created = []; try { + // Before anything is written: a server newer than this image's + // `pg_dump` is refused with the majors and the way out, not with the + // tool's own mismatch line. + await assertClientServesServer(client, "pg_dump"); await client.query("BEGIN ISOLATION LEVEL REPEATABLE READ, READ ONLY"); const { rows } = await client.query( "SELECT pg_export_snapshot() AS snapshot", @@ -1496,24 +1607,70 @@ export async function decryptOffhostFile(options) { const decipher = createDecipheriv("aes-256-gcm", key, header.iv); decipher.setAAD(Buffer.from(`${AAD_PREFIX}${options.objectKey}`, "utf8")); decipher.setAuthTag(tag); + // The tag is checked in `final()`. Its failure is told apart by where it + // was thrown, never by OpenSSL's wording, which differs between Node and + // OpenSSL versions ("unable to authenticate data", "bad decrypt", ...). + let tagRefused = false; + const opener = new Transform({ + transform(chunk, _encoding, callback) { + let out; + try { + out = decipher.update(chunk); + } catch (err) { + callback(err instanceof Error ? err : new Error(String(err))); + return; + } + callback(null, out); + }, + flush(callback) { + let last; + try { + last = decipher.final(); + } catch (cause) { + tagRefused = true; + callback( + cause instanceof Error ? cause : new Error(String(cause), { cause }), + ); + return; + } + callback(null, last); + }, + }); try { await pipeline( createReadStream(options.inPath, { start: header.length, end: size - TAG_LENGTH - 1, }), - decipher, + opener, createGunzip(), createWriteStream(options.outPath, { flags: "wx", mode: 0o600 }), ); } catch (err) { await rm(options.outPath, { force: true }); + if (tagRefused) { + throw new OffhostTagRefusedError( + "the off-host copy does not open with this key under this name (altered, renamed, or written with another key)", + { cause: err }, + ); + } const reason = err instanceof Error ? err.message : String(err); - throw new Error( - /auth|unable to authenticate/i.test(reason) - ? "the off-host copy does not open with this key under this name (altered, renamed, or written with another key)" - : `could not open the off-host copy: ${reason}`, - ); + throw new Error(`could not open the off-host copy: ${reason}`, { + cause: err, + }); + } +} + +/** An off-host copy whose GCM tag does not verify under the key and name given. */ +export class OffhostTagRefusedError extends Error { + /** + * @param {string} message + * @param {ErrorOptions} [options] + */ + constructor(message, options) { + super(message, options); + this.name = "OffhostTagRefusedError"; + this.code = "OFFHOST_TAG_REFUSED"; } } diff --git a/src/lib/database-backup/dump-problems.ts b/src/lib/database-backup/dump-problems.ts index e044625501..74da0db187 100644 --- a/src/lib/database-backup/dump-problems.ts +++ b/src/lib/database-backup/dump-problems.ts @@ -42,3 +42,21 @@ export function databaseDumpProblems( const isTheUpload = offhost !== null && failure?.at === offhost.at; return { failure: sinceGood && !isTheUpload ? failure : null, offhost }; } + +/** + * The majors in a failure `clientServerMismatch` (dump-core.mjs) wrote: the + * server is newer than this image's `pg_dump` or `pg_restore` (#1431). Null + * for any other failure. Read here rather than in the dump module, which + * runs client tools and cannot be bundled for the browser. + */ +export function clientTooOldIn( + text: string | null | undefined, +): { tool: string; client: number; server: number } | null { + const match = + /This image's PostgreSQL client \((pg_dump|pg_restore)\) is (\d+); your server is (\d+)\./.exec( + text ?? "", + ); + return match + ? { tool: match[1], client: Number(match[2]), server: Number(match[3]) } + : null; +} diff --git a/src/lib/documents/__tests__/rasterize-pdf-font-data.test.ts b/src/lib/documents/__tests__/rasterize-pdf-font-data.test.ts index d8a92fd1dd..cddeccf3c9 100644 --- a/src/lib/documents/__tests__/rasterize-pdf-font-data.test.ts +++ b/src/lib/documents/__tests__/rasterize-pdf-font-data.test.ts @@ -110,6 +110,11 @@ const renderHere = (data: Buffer) => minInkRatio: raster.RASTER_MIN_INK_RATIO, }); +// Every test here renders real pages through pdf.js and Skia: CPU work that +// takes well under a second alone and several on a loaded machine. The +// budget is sized for that work rather than for a unit test. +vi.setConfig({ testTimeout: 30_000 }); + describe("rasterizePdf font and decoder data (#1124)", () => { it("gives pdfjs its font, CMap and wasm directories and no system fonts", async () => { const result = await renderHere(fixture("fallback-fonts.pdf")); diff --git a/src/lib/documents/__tests__/rasterize-pdf.test.ts b/src/lib/documents/__tests__/rasterize-pdf.test.ts index 87ad875ae4..00866559e0 100644 --- a/src/lib/documents/__tests__/rasterize-pdf.test.ts +++ b/src/lib/documents/__tests__/rasterize-pdf.test.ts @@ -116,6 +116,11 @@ function sizedPdf(mediaBox: string): Buffer { ); } +// Every test here renders real pages through pdf.js and Skia: CPU work that +// takes well under a second alone and several on a loaded machine. The +// budget is sized for that work rather than for a unit test. +vi.setConfig({ testTimeout: 30_000 }); + describe("page resolution", () => { // The provider bound the edge cap answers to: OpenAI fits every image into // 2048 x 2048 before it reads it. diff --git a/src/lib/recovery/__tests__/readiness-model.test.ts b/src/lib/recovery/__tests__/readiness-model.test.ts index 35f0153e36..25e73908b7 100644 --- a/src/lib/recovery/__tests__/readiness-model.test.ts +++ b/src/lib/recovery/__tests__/readiness-model.test.ts @@ -8,6 +8,7 @@ */ import { describe, expect, it } from "vitest"; +import { clientServerMismatch } from "@/lib/database-backup/dump-core.mjs"; import type { DatabaseBackupHealth } from "@/lib/recovery/database-dump-health"; import { DUMP_FAILING_AFTER_HOURS, @@ -167,6 +168,47 @@ describe("database dump", () => { }); }); + // #1431: a server newer than the image's pg_dump fails every run until the + // client or the server changes. That is not "the last one failed, the one + // before is recent": it is failing from the first run, with both majors. + it("fails at once, naming both majors, when the server is newer than the client", () => { + const tooOld = clientServerMismatch({ + tool: "pg_dump", + clientMajor: 19, + serverMajor: 20, + }); + expect( + evalDump( + dump({ lastFailureAt: ago(HOUR), lastFailureReason: tooOld ?? "" }), + ), + ).toMatchObject({ + state: "failing", + reason: "client_too_old", + params: { client: 19, server: 20 }, + detail: tooOld, + }); + expect( + evalDump( + dump({ + lastGoodAt: null, + lastFailureAt: ago(HOUR), + lastFailureReason: tooOld ?? "", + }), + ), + ).toMatchObject({ state: "failing", reason: "client_too_old" }); + // A dump that worked after it (the image or the server was changed) is + // no longer this problem. + expect( + evalDump( + dump({ + lastGoodAt: ago(HOUR), + lastFailureAt: ago(2 * HOUR), + lastFailureReason: tooOld ?? "", + }), + ), + ).toMatchObject({ state: "ok", reason: "fresh" }); + }); + // The run that kept its dump here and failed its upload is the newest good // dump and the newest failure at the same instant; read as only those two, // it looked fresh while nothing reached the bucket. diff --git a/src/lib/recovery/readiness-model.ts b/src/lib/recovery/readiness-model.ts index 7293923dee..ec2d82517e 100644 --- a/src/lib/recovery/readiness-model.ts +++ b/src/lib/recovery/readiness-model.ts @@ -30,7 +30,10 @@ import { type OffhostBackupFreshness, } from "@/lib/jobs/offhost-backup-freshness"; import type { LifecycleVerdict } from "@/lib/jobs/offhost-lifecycle"; -import { databaseDumpProblems } from "@/lib/database-backup/dump-problems"; +import { + clientTooOldIn, + databaseDumpProblems, +} from "@/lib/database-backup/dump-problems"; import type { DatabaseBackupHealth } from "@/lib/recovery/database-dump-health"; import type { KitEntry } from "@/lib/recovery/kit-rules"; @@ -218,6 +221,20 @@ export function evaluateDatabaseDump( { directory: dump.directory }, ); } + // A server newer than the image's `pg_dump` fails every run until the + // image or the server changes (#1431): failing from the first run, not + // "the last one failed", and the sentence names both majors. + const tooOld = clientTooOldIn(failureReason); + if (tooOld) { + return signal( + id, + "failing", + "client_too_old", + lastGoodAt, + { client: tooOld.client, server: tooOld.server }, + failureReason, + ); + } const limitMs = DUMP_FAILING_AFTER_HOURS * HOUR_MS; const failedSinceGood = lastFailureAt !== null; if (lastGoodAt === null) { diff --git a/tests/integration/database-backup.test.ts b/tests/integration/database-backup.test.ts index e451b9dcff..ea53cfcca0 100644 --- a/tests/integration/database-backup.test.ts +++ b/tests/integration/database-backup.test.ts @@ -15,6 +15,7 @@ import { execFileSync } from "node:child_process"; import { chmodSync, existsSync, + mkdirSync, mkdtempSync, readFileSync, readdirSync, @@ -46,8 +47,45 @@ const OFFHOST_KEY = "e".repeat(64); const work = mkdtempSync(join(tmpdir(), "hl-db-backup-")); const backups = join(work, "backups"); const shims = join(work, "bin"); +const tooOldBin = join(work, "too-old-bin"); +const tooOldRan = join(work, "too-old-ran"); const originalPath = process.env.PATH; +/** The test server's major, from `server_version_num`. */ +async function testServerMajor(): Promise { + const client = await connect(process.env.DATABASE_URL ?? ""); + try { + const { rows } = await client.query( + "SELECT current_setting('server_version_num')::int AS n", + ); + return Math.floor(Number(rows[0].n) / 10000); + } finally { + await client.end(); + } +} + +/** + * `pg_dump` / `pg_restore` one major older than the test server (#1431). + * They answer `--version` and nothing else: any other call is written to + * `tooOldRan` and fails, so a case can prove the tool was never run. + */ +function writeTooOldClient(major: number): void { + mkdirSync(tooOldBin, { recursive: true }); + for (const tool of ["pg_dump", "pg_restore"]) { + const path = join(tooOldBin, tool); + writeFileSync( + path, + `#!/bin/sh +if [ "$1" = "--version" ]; then echo "${tool} (PostgreSQL) ${major}.4"; exit 0; fi +echo "${tool} $*" >> ${JSON.stringify(tooOldRan)} +echo "${tool}: error: aborting because of server version mismatch" >&2 +exit 1 +`, + ); + chmodSync(path, 0o755); + } +} + /** The id of the container that serves DATABASE_URL. */ function containerId(): string { const port = new URL(process.env.DATABASE_URL ?? "").port; @@ -170,6 +208,7 @@ beforeAll(async () => { mkdirSync(shims, { recursive: true }); mkdirSync(backups, { recursive: true }); writeShims(containerId()); + writeTooOldClient((await testServerMajor()) - 1); process.env.PATH = `${shims}:${originalPath}`; for (const name of ["dump-a", "dump-b", "dump-c"]) { await prisma.user.create({ @@ -716,6 +755,22 @@ describe("the dump before migrating", () => { ); expect(readdirSync(preDir).sort()).toEqual(before); }); + + it("stops the boot with its own code and both majors when the server is newer than the client", async () => { + await new Promise((r) => setTimeout(r, 1100)); + const before = readdirSync(preDir).sort(); + const major = await testServerMajor(); + process.env.PATH = `${tooOldBin}:${originalPath}`; + const { code, errors } = await preMigration({ DB_BACKUP_DIR: preDir }); + process.env.PATH = `${shims}:${originalPath}`; + expect(code, errors).toBe(3); + expect(errors).toContain( + `This image's PostgreSQL client (pg_dump) is ${major - 1}; your server is ${major}.`, + ); + expect(errors).not.toContain("version mismatch"); + expect(existsSync(tooOldRan)).toBe(false); + expect(readdirSync(preDir).sort()).toEqual(before); + }); }); describe("two dumps in the same second", () => { @@ -744,3 +799,126 @@ describe("two dumps in the same second", () => { ).toEqual(before); }); }); + +// #1431: the image's client major caps the server major. Against a real +// server, with a client one major older that answers only `--version`. +describe("a server newer than this image's client", () => { + const dir = join(work, "too-old"); + const target = `too_old_${process.pid}_${Date.now()}`; + let targetUrl = ""; + + beforeAll(async () => { + const { mkdirSync } = await import("node:fs"); + mkdirSync(dir, { recursive: true }); + // A good dump to restore, written with the real client first. + const { createDatabaseDump } = + await import("@/lib/database-backup/dump-core.mjs"); + await createDatabaseDump({ + databaseUrl: process.env.DATABASE_URL ?? "", + dir, + kind: "daily", + now: new Date("2026-12-30T01:30:00Z"), + }); + const admin = await connect(process.env.DATABASE_URL ?? ""); + await admin.query(`CREATE DATABASE ${target}`); + await admin.end(); + const url = new URL(process.env.DATABASE_URL ?? ""); + url.pathname = `/${target}`; + targetUrl = url.toString(); + process.env.PATH = `${tooOldBin}:${originalPath}`; + }); + + afterAll(async () => { + process.env.PATH = `${shims}:${originalPath}`; + const admin = await connect(process.env.DATABASE_URL ?? ""); + await admin.query(`DROP DATABASE IF EXISTS ${target} WITH (FORCE)`); + await admin.end(); + }); + + it("fails the nightly dump with both majors, writes nothing, and the readiness signal fails at once", async () => { + const major = await testServerMajor(); + const before = readdirSync(dir).sort(); + const now = new Date("2027-01-01T01:30:00Z"); + const report = await runDatabaseBackup(prisma, { + now, + env: { ...process.env, DB_BACKUP_DIR: dir }, + }); + expect(report.status).toBe("failed"); + expect(report.error).toMatch( + new RegExp( + `^This image's PostgreSQL client \\(pg_dump\\) is ${major - 1}; your server is ${major}\\.`, + ), + ); + expect(existsSync(tooOldRan)).toBe(false); + expect(readdirSync(dir).sort()).toEqual(before); + + const health = await getDatabaseBackupHealth( + new Date("2027-01-01T02:00:00Z"), + { ...process.env, DB_BACKUP_DIR: dir }, + ); + expect( + evaluateDatabaseDump({ + now: new Date("2027-01-01T02:00:00Z"), + dump: health, + dumpWatchedSince: null, + }), + ).toMatchObject({ + state: "failing", + reason: "client_too_old", + params: { client: major - 1, server: major }, + }); + }); + + it("refuses the restore into an empty database before pg_restore runs", async () => { + const major = await testServerMajor(); + const errors: string[] = []; + const spyErr = vi + .spyOn(console, "error") + .mockImplementation((l: string) => void errors.push(String(l))); + const spyLog = vi.spyOn(console, "log").mockImplementation(() => {}); + try { + const code = await restoreMain(["latest"], { + ...process.env, + DB_BACKUP_DIR: dir, + DATABASE_URL: targetUrl, + }); + expect(code, errors.join("\n")).toBe(1); + } finally { + spyErr.mockRestore(); + spyLog.mockRestore(); + } + expect(errors.join("\n")).toContain( + `This image's PostgreSQL client (pg_restore) is ${major - 1}; your server is ${major}.`, + ); + expect(existsSync(tooOldRan)).toBe(false); + const client = await connect(targetUrl); + try { + const { rows } = await client.query( + "SELECT count(*)::int AS n FROM pg_tables WHERE schemaname = 'public'", + ); + expect(rows[0].n).toBe(0); + } finally { + await client.end(); + } + }); + + it("warns at a boot with nothing to migrate, and lets it go on", async () => { + const { preMigrationDump } = await import("../../scripts/db-dump.mjs"); + const errors: string[] = []; + const spyErr = vi + .spyOn(console, "error") + .mockImplementation((l: string) => void errors.push(String(l))); + const spyLog = vi.spyOn(console, "log").mockImplementation(() => {}); + try { + expect( + await preMigrationDump({ ...process.env, DB_BACKUP_DIR: dir }), + ).toBe(0); + } finally { + spyErr.mockRestore(); + spyLog.mockRestore(); + } + expect(errors.join("\n")).toMatch( + /WARNING .*client \(pg_dump\) is \d+; your server is \d+\..*nightly database dump fails/, + ); + }); +});