Files
persionalBrand/deploy/backup-db.mjs
T
que01 015947f8fb
CI / Browser smoke (pull_request) Successful in 50s
CI / Static checks (pull_request) Successful in 52s
CI / API integration (pull_request) Successful in 1m23s
CI / Production build (pull_request) Successful in 1m48s
feat: 增加生产数据库每日备份与状态门禁
2026-10-23 17:54:27 +08:00

54 lines
1.8 KiB
JavaScript

import { mkdir, rm } from "node:fs/promises";
import path from "node:path";
import { spawnSync } from "node:child_process";
import {
backupPostgresDatabase,
pruneBackups,
scheduledBackupName,
verifyPostgresBackup,
} from "./database-backup.mjs";
const root = process.env.DEPLOY_ROOT;
if (!root || !path.isAbsolute(root)) throw new Error("DEPLOY_ROOT must be absolute");
process.loadEnvFile(path.join(root, "shared/.env.production"));
const container = process.env.POSTGRES_CONTAINER;
if (!container || !/^[a-zA-Z0-9_.-]+$/.test(container)) {
throw new Error("POSTGRES_CONTAINER is required");
}
const retentionDays = Number(process.env.BACKUP_RETENTION_DAYS ?? "14");
if (!Number.isInteger(retentionDays) || retentionDays < 1) {
throw new Error("BACKUP_RETENTION_DAYS must be a positive integer");
}
const directory = path.join(root, "shared/backups");
await mkdir(directory, { recursive: true });
const destination = path.join(directory, scheduledBackupName());
await backupPostgresDatabase({ container, destination });
try {
await verifyPostgresBackup({ container, file: destination });
} catch (error) {
await rm(destination, { force: true });
throw error;
}
await pruneBackups(directory, { retentionDays });
const offsiteTarget = process.env.BACKUP_OFFSITE_TARGET?.trim();
if (offsiteTarget) {
if (
!/^[a-zA-Z0-9_.@:/-]+$/.test(offsiteTarget) ||
offsiteTarget.startsWith("-") ||
offsiteTarget.includes("..")
) {
throw new Error("BACKUP_OFFSITE_TARGET contains unsupported characters");
}
const result = spawnSync("rsync", ["-a", "--partial", destination, offsiteTarget], {
stdio: "inherit",
env: process.env,
});
if (result.status !== 0) throw new Error("Offsite backup copy failed");
}
console.log(`scheduled backup written: ${destination}`);