mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-23 21:33:19 +00:00
fix(backup): restore Postgres backups into PostgreSQL 14, 15 and 16
pg_restore 17 and later write SET transaction_timeout at the top of every script, which older servers refuse under ON_ERROR_STOP. The restore now leaves settings the target server does not know out of the script while it streams.
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
import { execFile, spawn } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { Transform } from 'node:stream';
|
||||
import { PassThrough, Transform } from 'node:stream';
|
||||
import { pipeline } from 'node:stream/promises';
|
||||
import { promisify } from 'node:util';
|
||||
|
||||
@@ -239,8 +239,8 @@ type Ending = { code: number | null; signal: NodeJS.Signals | null } | { error:
|
||||
/**
|
||||
* Runs `tool` and streams its stdout into `target` (which must exist; its mode
|
||||
* is kept), stopping the tool with {@link PgOutputLimitError} once more than
|
||||
* `maxBytes` have come out. The caller removes `target` on failure. A failure
|
||||
* of the tool itself throws as `run` does.
|
||||
* `maxBytes` have come out, through `filter` when one is given. The caller
|
||||
* removes `target` on failure. A failure of the tool itself throws as `run` does.
|
||||
*/
|
||||
export async function runToFile(
|
||||
tool: PgTool,
|
||||
@@ -249,6 +249,7 @@ export async function runToFile(
|
||||
env: Record<string, string>,
|
||||
target: string,
|
||||
maxBytes: number,
|
||||
filter: Transform = new PassThrough(),
|
||||
): Promise<void> {
|
||||
const binary = locate(tool, binDir);
|
||||
await refuseSystemRootCertOnOldClient(tool, binary, env);
|
||||
@@ -271,7 +272,7 @@ export async function runToFile(
|
||||
},
|
||||
});
|
||||
try {
|
||||
await pipeline(child.stdout, limit, fs.createWriteStream(target, { flags: 'w' }));
|
||||
await pipeline(child.stdout, limit, filter, fs.createWriteStream(target, { flags: 'w' }));
|
||||
} catch (err) {
|
||||
child.kill('SIGKILL');
|
||||
await ended;
|
||||
|
||||
@@ -3,6 +3,7 @@ import { CLEAR_SCHEMA_SQL, pluginSchemasSql } from './clear-schema';
|
||||
import { pgConnectionEnv, PgOutputLimitError, refuseClientOlderThanServer, run, runToFile } from './pg-process';
|
||||
import { isPluginSchemaName, PLUGIN_SCHEMA_PREFIX } from './plugin-schema';
|
||||
import { refuseToolsWithoutRestrict } from './restore-safety';
|
||||
import { withoutUnknownSettings } from './script-settings';
|
||||
import { PRIVILEGED_ROLE_DESCRIPTION, PRIVILEGED_ROLE_SQL, serverMajor } from './server-checks';
|
||||
|
||||
import fs from 'node:fs';
|
||||
@@ -144,18 +145,23 @@ async function scriptHoldsTrekSchema(script: string, schema: PgSchema): Promise<
|
||||
}
|
||||
}
|
||||
|
||||
/** pg_restore's script for the dump at `source`, written to `script` and held to `maxBytes`. */
|
||||
/**
|
||||
* pg_restore's script for the dump at `source`, written to `script` and held
|
||||
* to `maxBytes`, without the settings a server of major `serverMajor` does
|
||||
* not know.
|
||||
*/
|
||||
async function writeRestoreScript(
|
||||
source: string,
|
||||
script: string,
|
||||
schemas: readonly string[],
|
||||
binDir: string | undefined,
|
||||
maxBytes: number,
|
||||
limits: { maxBytes: number; serverMajor: number },
|
||||
): Promise<void> {
|
||||
const { maxBytes, serverMajor } = limits;
|
||||
const only = schemas.map((name) => `--schema=${name}`);
|
||||
const args = ['--no-owner', '--no-privileges', ...only, '--file=-', '--', source];
|
||||
try {
|
||||
await runToFile('pg_restore', binDir, args, {}, script, maxBytes);
|
||||
await runToFile('pg_restore', binDir, args, {}, script, maxBytes, withoutUnknownSettings(serverMajor));
|
||||
} catch (err) {
|
||||
if (!(err instanceof PgOutputLimitError)) throw err;
|
||||
throw new Error(
|
||||
@@ -202,7 +208,10 @@ export async function pgRestore(
|
||||
const pluginSchemas = await dumpPluginSchemas(source, path.join(workDir, 'toc.txt'), binDir);
|
||||
fs.writeFileSync(clear, CLEAR_SCHEMA_SQL + pluginSchemasSql(pluginSchemas), { mode: 0o600 });
|
||||
createPrivateFile(script);
|
||||
await writeRestoreScript(source, script, [schema.name, ...pluginSchemas], binDir, maxScriptBytes);
|
||||
await writeRestoreScript(source, script, [schema.name, ...pluginSchemas], binDir, {
|
||||
maxBytes: maxScriptBytes,
|
||||
serverMajor: major,
|
||||
});
|
||||
if (!(await scriptHoldsTrekSchema(script, schema))) {
|
||||
throw new Error(`The backup holds no TREK tables in the schema "${schema.name}"; nothing was replaced.`);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { Transform } from 'node:stream';
|
||||
|
||||
/**
|
||||
* The settings a newer pg_restore writes at the start of every script, with
|
||||
* the first server major that knows each. pg_restore 17 and later set
|
||||
* `transaction_timeout` whatever server the script is for.
|
||||
*/
|
||||
const SETTING_SINCE: Readonly<Record<string, number>> = { transaction_timeout: 17 };
|
||||
|
||||
/** A line of the settings block before the script's first object: blank, a comment, a psql command or a setting. */
|
||||
const PREAMBLE_LINE = /^(?:$|--|\\|SET |SELECT pg_catalog\.set_config\()/;
|
||||
|
||||
const SET_LINE = /^SET (\w+) = /;
|
||||
|
||||
/**
|
||||
* Leaves out the `SET` lines of a restore script's settings block that a
|
||||
* server of major `serverMajor` does not know, so psql under ON_ERROR_STOP does
|
||||
* not refuse the whole script on its first lines. Only the lines before the
|
||||
* first object are looked at; from there on every chunk passes as it comes,
|
||||
* so a script's COPY data is never split into lines.
|
||||
*/
|
||||
export function withoutUnknownSettings(serverMajor: number): Transform {
|
||||
const unknown = new Set(
|
||||
Object.entries(SETTING_SINCE)
|
||||
.filter(([, since]) => serverMajor < since)
|
||||
.map(([name]) => name),
|
||||
);
|
||||
let inPreamble = unknown.size > 0;
|
||||
let pending = Buffer.alloc(0);
|
||||
|
||||
const dropped = (line: string): boolean => unknown.has(SET_LINE.exec(line)?.[1] ?? '');
|
||||
|
||||
return new Transform({
|
||||
transform(chunk: Buffer, _encoding, callback) {
|
||||
if (!inPreamble) {
|
||||
callback(null, chunk);
|
||||
return;
|
||||
}
|
||||
pending = Buffer.concat([pending, chunk]);
|
||||
const kept: Buffer[] = [];
|
||||
let start = 0;
|
||||
for (let end = pending.indexOf(0x0a, start); end >= 0; end = pending.indexOf(0x0a, start)) {
|
||||
const line = pending.toString('utf8', start, end).replace(/\r$/, '');
|
||||
if (!PREAMBLE_LINE.test(line)) {
|
||||
inPreamble = false;
|
||||
break;
|
||||
}
|
||||
if (!dropped(line)) kept.push(pending.subarray(start, end + 1));
|
||||
start = end + 1;
|
||||
}
|
||||
const rest = pending.subarray(start);
|
||||
if (inPreamble) {
|
||||
pending = Buffer.from(rest);
|
||||
} else {
|
||||
kept.push(rest);
|
||||
pending = Buffer.alloc(0);
|
||||
}
|
||||
callback(null, Buffer.concat(kept));
|
||||
},
|
||||
flush(callback) {
|
||||
const last = pending.toString('utf8');
|
||||
callback(null, inPreamble && dropped(last) ? Buffer.alloc(0) : pending);
|
||||
},
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user