fix(backup): a restore that migrates no longer breaks the request it runs in

Restoring a backup whose database was behind the running version migrated it inside the admin's HTTP request. A MikroORM migration's getEntityManager() pins the migration's transaction on the EntityManager of the context it runs in, which was the request's. Once the migrations committed, every later read on that request failed with "Transaction is already committed": the storage registry reload kept the pre-restore config (uploads, including the archive's own, went to the old backend), and the restore's audit row was lost.

Both engines now run their migrations in a request context of their own (runSchemaBootstrap on SQLite, bootstrapPostgresSchema on Postgres), so the transaction stays on a throwaway EntityManager, at boot and on restore alike. RESTORE-002 restores a file six migrations behind head inside a request and reads on through that request's EntityManager.

Closes #3264
This commit is contained in:
Maurice
2026-11-29 12:00:08 +01:00
parent f89ebf6882
commit 67049c1065
3 changed files with 54 additions and 7 deletions
@@ -1,4 +1,5 @@
import type { DbEngineSettings } from '../../../app-config/db-settings';
import { withRequestContext } from '../../../nest/database/request-context';
import { NO_SAFETY_NET } from '../../legacy-baseline';
import { finishSchemaBootstrap, type AnyOrm } from '../../orm';
import type { DatabaseEngine } from '../engine';
@@ -74,7 +75,12 @@ export class PostgresEngine implements DatabaseEngine {
/** `snapshot: false` (a restore, whose archive is the copy) migrates without a pg_dump first. */
async schemaBootstrap(orm: AnyOrm, options: { snapshot: boolean }): Promise<void> {
const deps = this.bootstrapDeps(this.settings.url);
await bootstrapPostgresSchema(orm, options.snapshot ? deps : { ...deps, safetyNet: NO_SAFETY_NET });
// Migrated in a request context of its own, so the migrations' transaction
// never lands on a caller's EntityManager (a restore's request, #3264; see
// runSchemaBootstrap).
await withRequestContext(orm, () =>
bootstrapPostgresSchema(orm, options.snapshot ? deps : { ...deps, safetyNet: NO_SAFETY_NET }),
);
await finishSchemaBootstrap(orm);
}
+14 -6
View File
@@ -40,12 +40,20 @@ export async function runSchemaBootstrap(orm: AnyOrm, { snapshot }: { snapshot:
// what it already has is recorded in the same transaction as the run, or the
// run would replay the whole history over it (see legacy-baseline.ts). Every
// other database just gets its pending migrations.
await migrateToHead(
connection,
migrator,
undefined,
undefined,
snapshot ? preMigrateSnapshot(connection) : NO_SAFETY_NET,
//
// In a request context of its own (#3264): a migration's getEntityManager()
// pins the migration's transaction on the EntityManager of the context it
// runs in. A restore migrates inside the admin's HTTP request, so that was
// the request's, which then failed every later read with "Transaction is
// already committed" (the storage registry reload, the audit row).
await withRequestContext(orm, () =>
migrateToHead(
connection,
migrator,
undefined,
undefined,
snapshot ? preMigrateSnapshot(connection) : NO_SAFETY_NET,
),
);
await finishSchemaBootstrap(orm);
}
@@ -1,4 +1,6 @@
import { runSchemaBootstrap } from '../../../src/db/orm';
import { withRequestContext } from '../../../src/nest/database/request-context';
import { RequestContext } from '@mikro-orm/core';
import { Migrator } from '@mikro-orm/migrations';
import { SeedManager } from '@mikro-orm/seeder';
import { MikroORM } from '@mikro-orm/sqlite';
@@ -91,4 +93,35 @@ describe('a restored database is migrated forward', () => {
after.close();
}
}, 60_000);
it('RESTORE-002: migrating a restored file inside a request leaves that request free to read on (#3264)', async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'trek-restore-'));
const dbFile = path.join(tmpDir, 'behind.db');
// A backup a few migrations behind head: those run on restore, and nearly
// every migration reaches the platform through the migration-utils helpers.
const stale = await ormFor(dbFile);
const staleMigrator = stale.config.getExtension('@mikro-orm/migrator') as Migrator;
const all = await staleMigrator.getPending();
await staleMigrator.up({ to: all[all.length - 6].name });
await stale.close(true);
// A restore reopens and migrates the file inside the admin's HTTP request;
// what that request does next (reload the storage registry, write the audit
// row) reads through the same EntityManager.
const restored = await ormFor(dbFile);
try {
await withRequestContext(restored, async () => {
const em = RequestContext.getEntityManager();
await runSchemaBootstrap(restored, { snapshot: false });
expect(em?.getTransactionContext()).toBeUndefined();
const rows = (await em?.getConnection().execute('select count(*) as c from mikro_orm_migrations')) as
Array<{ c: number }> | undefined;
expect(rows?.[0]?.c).toBe(all.length);
await expect(em?.execute('select 1 as one')).resolves.toEqual([{ one: 1 }]);
});
} finally {
await restored.close(true);
}
}, 60_000);
});