Website 1.5.0: back up the photos and files too
The nightly backup (and Back up now) snapshots backend/uploads after the database, into backups/uploads-YYYYMMDD-HHMMSS/. Unchanged files are hard links to the last snapshot, so after the first full copy a night costs only the new files. Built in a partial folder and renamed when complete, refused up front when the disk hasn't room, kept to the same count as the database backups, with its own switch on Admin -> Backups. crosscode script: an uninstall keeps the Website's backups with rsync -aH, so the snapshots' shared files stay shared. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/website-backend",
|
||||
"version": "1.4.0",
|
||||
"version": "1.5.0",
|
||||
"description": "Church Website: the public site's content API, the admin API, publishing and uploads",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -7,6 +7,7 @@ import express from 'express';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { requireRole } from '../auth/sessions.js';
|
||||
import { backupPath, listBackups, retainCount, rotate, runBackup } from '../backups/backups.js';
|
||||
import { listUploadsSnapshots, rotateUploads, runUploadsBackup } from '../backups/uploads.js';
|
||||
import { ApiError, handle, sendError } from '../http.js';
|
||||
import { audit } from '../lib/audit.js';
|
||||
import { JobError, jobStatus, runNow, setOverride } from '../jobs.js';
|
||||
@@ -29,6 +30,12 @@ export function maintenanceRouter(ctx: Ctx, who: (req: express.Request) => Who)
|
||||
nightly: await ctx.settings.bool('backup_nightly', true),
|
||||
retain: await retainCount(ctx),
|
||||
lastError: await ctx.settings.get('backup_last_error'),
|
||||
// 1.5.0: the photos and files.
|
||||
uploads: {
|
||||
enabled: await ctx.settings.bool('backup_uploads', true),
|
||||
lastError: await ctx.settings.get('backup_uploads_last_error'),
|
||||
items: (await listUploadsSnapshots(ctx)).map((s) => ({ name: s.name, createdAt: s.createdAt, files: s.files, bytes: s.bytes, newFiles: s.newFiles, newBytes: s.newBytes })),
|
||||
},
|
||||
})));
|
||||
|
||||
r.post('/backups/run', admin, handle(async (req) => {
|
||||
@@ -38,20 +45,31 @@ export function maintenanceRouter(ctx: Ctx, who: (req: express.Request) => Who)
|
||||
} catch (e) {
|
||||
throw new ApiError(502, 'BACKUP_FAILED', `The backup didn't work: ${(e as Error).message}`);
|
||||
}
|
||||
let uploads: { name: string; newFiles: number } | null = null;
|
||||
let uploadsError: string | null = null;
|
||||
if (await ctx.settings.bool('backup_uploads', true)) {
|
||||
try {
|
||||
const s = await runUploadsBackup(ctx);
|
||||
uploads = { name: s.name, newFiles: s.newFiles };
|
||||
} catch (e) {
|
||||
uploadsError = (e as Error).message;
|
||||
}
|
||||
}
|
||||
const me = who(req);
|
||||
await audit(ctx, { actorId: me.id, actorRole: me.role, action: 'backup_made', targetType: 'backup', targetId: b.filename });
|
||||
return { filename: b.filename, size: b.size, createdAt: b.createdAt };
|
||||
await audit(ctx, { actorId: me.id, actorRole: me.role, action: 'backup_made', targetType: 'backup', targetId: b.filename, metadata: { uploads: uploads?.name ?? null } });
|
||||
return { filename: b.filename, size: b.size, createdAt: b.createdAt, uploads, uploadsError };
|
||||
}));
|
||||
|
||||
r.put('/backups/settings', admin, json, handle(async (req) => {
|
||||
const retain = Number(req.body?.retain);
|
||||
if (!Number.isInteger(retain) || retain < 1 || retain > 365) throw new ApiError(400, 'VALIDATION', 'Keep between 1 and 365 backups.', { retain: 'Between 1 and 365' });
|
||||
const nightly = req.body?.nightly !== false;
|
||||
await ctx.settings.setMany({ backup_retain_count: String(retain), backup_nightly: nightly ? 'true' : 'false' });
|
||||
const deleted = await rotate(ctx);
|
||||
const uploadsOn = req.body?.uploads !== false;
|
||||
await ctx.settings.setMany({ backup_retain_count: String(retain), backup_nightly: nightly ? 'true' : 'false', backup_uploads: uploadsOn ? 'true' : 'false' });
|
||||
const deleted = (await rotate(ctx)) + (await rotateUploads(ctx));
|
||||
const me = who(req);
|
||||
await audit(ctx, { actorId: me.id, actorRole: me.role, action: 'backup_settings_changed', targetType: 'setting', targetId: 'backup_retain_count', metadata: { retain, nightly, deleted } });
|
||||
return { retain, nightly, deleted };
|
||||
await audit(ctx, { actorId: me.id, actorRole: me.role, action: 'backup_settings_changed', targetType: 'setting', targetId: 'backup_retain_count', metadata: { retain, nightly, uploads: uploadsOn, deleted } });
|
||||
return { retain, nightly, uploads: uploadsOn, deleted };
|
||||
}));
|
||||
|
||||
// A download holds the whole site's content and its editors: audited, never cached.
|
||||
|
||||
@@ -93,7 +93,13 @@ export async function rotate(ctx: Ctx): Promise<number> {
|
||||
* Makes a backup now. A dump that fails part-way leaves no file behind (a truncated one would
|
||||
* look like a real backup). Records the outcome for the admin page.
|
||||
*/
|
||||
export async function runBackup(ctx: Ctx, dumper: Dumper = pgDump): Promise<Backup> {
|
||||
let defaultDumper: Dumper = pgDump;
|
||||
/** Tests: the dump the job and the admin's button use, instead of pg_dump. */
|
||||
export function useDumperForTest(d: Dumper | null): void {
|
||||
defaultDumper = d ?? pgDump;
|
||||
}
|
||||
|
||||
export async function runBackup(ctx: Ctx, dumper: Dumper = defaultDumper): Promise<Backup> {
|
||||
const url = ctx.config.databaseUrl;
|
||||
try {
|
||||
if (!url) throw new Error('DATABASE_URL isn\'t set, so there\'s no database to back up.');
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
/**
|
||||
* Backups of the uploads (1.5.0): the photos and files of the media library, which the database
|
||||
* backups (backups.ts) don't hold. Each is a folder `backups/uploads-YYYYMMDD-HHMMSS/` with the
|
||||
* uploads as they were, made right after the nightly database backup (and with "Back up now").
|
||||
*
|
||||
* Snapshots, not archives: a file that's the same as in the last snapshot (same size and time) is
|
||||
* a hard link to it, so after the first full copy a night costs only the files added since. An
|
||||
* uploaded file never changes (a new upload is a new file), so this is cheap and still a real
|
||||
* copy: deleting or damaging a file in uploads/ doesn't touch the snapshots. Deleting an old
|
||||
* snapshot frees only what no newer one shares.
|
||||
*
|
||||
* A snapshot is built in a `.uploads-…-partial` folder and renamed when complete, so a failed one
|
||||
* never looks like a backup. `.thumbnails` (made again on demand) and other dot entries are left
|
||||
* out. Kept: the same number as the database backups (`backup_retain_count`). Off with
|
||||
* `backup_uploads` = false. To restore: copy a snapshot's contents back into backend/uploads as
|
||||
* the site's user (`cp -a backups/uploads-…/. uploads/`).
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { uploadDir } from '../admin/media.js';
|
||||
import { DEFAULT_BACKUP_DIR, retainCount, runBackupJob } from './backups.js';
|
||||
|
||||
export const UPLOADS_SNAPSHOT = /^uploads-\d{8}-\d{6}$/;
|
||||
const MANIFEST = '.snapshot.json';
|
||||
|
||||
export type UploadsSnapshot = { name: string; createdAt: Date; files: number; bytes: number; newFiles: number; newBytes: number };
|
||||
|
||||
const dir = (ctx: Ctx) => ctx.config.backupDir ?? DEFAULT_BACKUP_DIR;
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
|
||||
/** uploads-20261127-022000, in the server's local time, as the database backups are named. */
|
||||
export function snapshotName(at: Date): string {
|
||||
return `uploads-${at.getFullYear()}${pad(at.getMonth() + 1)}${pad(at.getDate())}-${pad(at.getHours())}${pad(at.getMinutes())}${pad(at.getSeconds())}`;
|
||||
}
|
||||
|
||||
/** Every complete snapshot, newest first, with what its manifest says. */
|
||||
export async function listUploadsSnapshots(ctx: Ctx): Promise<UploadsSnapshot[]> {
|
||||
let names: string[];
|
||||
try {
|
||||
names = await fs.promises.readdir(dir(ctx));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const out: UploadsSnapshot[] = [];
|
||||
for (const name of names.filter((n) => UPLOADS_SNAPSHOT.test(n))) {
|
||||
const p = path.join(dir(ctx), name);
|
||||
const st = await fs.promises.stat(p).catch(() => null);
|
||||
if (!st?.isDirectory()) continue;
|
||||
const m = await fs.promises.readFile(path.join(p, MANIFEST), 'utf8').then((t) => JSON.parse(t) as Partial<UploadsSnapshot>).catch(() => ({} as Partial<UploadsSnapshot>));
|
||||
out.push({ name, createdAt: m.createdAt ? new Date(m.createdAt) : st.mtime, files: m.files ?? 0, bytes: m.bytes ?? 0, newFiles: m.newFiles ?? 0, newBytes: m.newBytes ?? 0 });
|
||||
}
|
||||
return out.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime() || b.name.localeCompare(a.name));
|
||||
}
|
||||
|
||||
/** The uploads' files, relative to the folder: no dot entries (.thumbnails), no links. */
|
||||
async function filesIn(root: string, rel = ''): Promise<{ rel: string; size: number; mtimeMs: number }[]> {
|
||||
let entries: fs.Dirent[];
|
||||
try {
|
||||
entries = await fs.promises.readdir(path.join(root, rel), { withFileTypes: true });
|
||||
} catch (e) {
|
||||
if ((e as NodeJS.ErrnoException).code === 'ENOENT' && !rel) return [];
|
||||
throw e;
|
||||
}
|
||||
const out: { rel: string; size: number; mtimeMs: number }[] = [];
|
||||
for (const e of entries) {
|
||||
if (e.name.startsWith('.')) continue;
|
||||
const r = path.join(rel, e.name);
|
||||
if (e.isDirectory()) out.push(...(await filesIn(root, r)));
|
||||
else if (e.isFile()) {
|
||||
const st = await fs.promises.stat(path.join(root, r));
|
||||
out.push({ rel: r, size: st.size, mtimeMs: st.mtimeMs });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Deletes the oldest snapshots beyond the number kept, and any partial one left by a crash. */
|
||||
export async function rotateUploads(ctx: Ctx): Promise<number> {
|
||||
const old = (await listUploadsSnapshots(ctx)).slice(await retainCount(ctx));
|
||||
for (const s of old) await fs.promises.rm(path.join(dir(ctx), s.name), { recursive: true, force: true });
|
||||
const names = await fs.promises.readdir(dir(ctx)).catch(() => [] as string[]);
|
||||
for (const n of names.filter((x) => /^\.uploads-\d{8}-\d{6}-partial$/.test(x))) await fs.promises.rm(path.join(dir(ctx), n), { recursive: true, force: true });
|
||||
return old.length;
|
||||
}
|
||||
|
||||
/** Free bytes on the backups' disk, or null where the system can't say. */
|
||||
async function freeBytes(p: string): Promise<number | null> {
|
||||
try {
|
||||
const s = await fs.promises.statfs(p);
|
||||
return Number(s.bavail) * Number(s.bsize);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Makes a snapshot of the uploads now. Records the outcome for the admin page. */
|
||||
export async function runUploadsBackup(ctx: Ctx): Promise<UploadsSnapshot> {
|
||||
try {
|
||||
const source = uploadDir(ctx);
|
||||
await fs.promises.mkdir(dir(ctx), { recursive: true, mode: 0o700 });
|
||||
const at = ctx.now().getTime();
|
||||
let name = snapshotName(new Date(at));
|
||||
for (let s = 1; fs.existsSync(path.join(dir(ctx), name)); s++) name = snapshotName(new Date(at + s * 1000));
|
||||
const partial = path.join(dir(ctx), `.${name}-partial`);
|
||||
const previous = (await listUploadsSnapshots(ctx))[0];
|
||||
const prevDir = previous ? path.join(dir(ctx), previous.name) : null;
|
||||
|
||||
const files = await filesIn(source);
|
||||
// What's the same as last time is linked; the rest is copied. Check there's room for that first.
|
||||
const same = async (f: { rel: string; size: number; mtimeMs: number }) => {
|
||||
if (!prevDir) return false;
|
||||
const st = await fs.promises.stat(path.join(prevDir, f.rel)).catch(() => null);
|
||||
return !!st && st.isFile() && st.size === f.size && Math.abs(st.mtimeMs - f.mtimeMs) < 1;
|
||||
};
|
||||
const plan = await Promise.all(files.map(async (f) => ({ ...f, link: await same(f) })));
|
||||
const needed = plan.filter((f) => !f.link).reduce((n, f) => n + f.size, 0);
|
||||
const free = await freeBytes(dir(ctx));
|
||||
if (free !== null && needed > free * 0.9) {
|
||||
throw new Error(`Not enough disk space for the photos and files: ${Math.ceil(needed / 1e6)} MB to copy, ${Math.floor(free / 1e6)} MB free.`);
|
||||
}
|
||||
|
||||
await fs.promises.rm(partial, { recursive: true, force: true });
|
||||
await fs.promises.mkdir(partial, { recursive: true, mode: 0o700 });
|
||||
let newFiles = 0;
|
||||
let newBytes = 0;
|
||||
try {
|
||||
for (const f of plan) {
|
||||
const dest = path.join(partial, f.rel);
|
||||
await fs.promises.mkdir(path.dirname(dest), { recursive: true });
|
||||
let linked = false;
|
||||
if (f.link) {
|
||||
linked = await fs.promises.link(path.join(prevDir!, f.rel), dest).then(() => true, () => false);
|
||||
}
|
||||
if (!linked) {
|
||||
await fs.promises.copyFile(path.join(source, f.rel), dest);
|
||||
// The source's time, so tomorrow's run sees it as the same file.
|
||||
const t = new Date(f.mtimeMs);
|
||||
await fs.promises.utimes(dest, t, t);
|
||||
newFiles++;
|
||||
newBytes += f.size;
|
||||
}
|
||||
}
|
||||
const snapshot: UploadsSnapshot = { name, createdAt: new Date(at), files: plan.length, bytes: plan.reduce((n, f) => n + f.size, 0), newFiles, newBytes };
|
||||
await fs.promises.writeFile(path.join(partial, MANIFEST), JSON.stringify(snapshot), { mode: 0o600 });
|
||||
await fs.promises.rename(partial, path.join(dir(ctx), name));
|
||||
await rotateUploads(ctx);
|
||||
await ctx.settings.set('backup_uploads_last_error', null);
|
||||
return snapshot;
|
||||
} catch (e) {
|
||||
await fs.promises.rm(partial, { recursive: true, force: true }).catch(() => {});
|
||||
throw e;
|
||||
}
|
||||
} catch (e) {
|
||||
await ctx.settings.set('backup_uploads_last_error', `${ctx.now().toISOString()} ${(e as Error).message}`.slice(0, 600));
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The nightly `backup` job (1.5.0): the database (skipped when nightly backups are off), then the
|
||||
* uploads (unless `backup_uploads` is off). The database backup is made even when the uploads'
|
||||
* fails; the job then fails too, so the run shows it (and the Hub's "jobs failing").
|
||||
*/
|
||||
export async function runNightlyBackups(ctx: Ctx) {
|
||||
const database = await runBackupJob(ctx);
|
||||
if ('skipped' in database) return { database };
|
||||
if (!(await ctx.settings.bool('backup_uploads', true))) return { database, uploads: { skipped: true } };
|
||||
const s = await runUploadsBackup(ctx);
|
||||
return { database, uploads: { name: s.name, files: s.files, newFiles: s.newFiles, newBytes: s.newBytes } };
|
||||
}
|
||||
@@ -11,7 +11,7 @@
|
||||
import { CronExpressionParser } from 'cron-parser';
|
||||
import PgBoss from 'pg-boss';
|
||||
import type { Ctx } from './context.js';
|
||||
import { runBackupJob } from './backups/backups.js';
|
||||
import { runNightlyBackups } from './backups/uploads.js';
|
||||
import { syncAll } from './feed/feed.js';
|
||||
import { heartbeat } from './hub/client.js';
|
||||
import { syncYoutube } from './site/youtube.js';
|
||||
@@ -19,8 +19,9 @@ import { syncYoutube } from './site/youtube.js';
|
||||
export type Job = { name: string; label: string; cron: string; env: string | null; run: (ctx: Ctx) => Promise<unknown> };
|
||||
|
||||
export const JOBS: Job[] = [
|
||||
// A database backup every night (Settings → Backups), after Accounts' at 02:00 on the same server.
|
||||
{ name: 'backup', label: 'Database backup', cron: '20 2 * * *', env: 'BACKUP_ENABLED', run: (ctx) => runBackupJob(ctx) },
|
||||
// A backup every night (Settings → Backups), after Accounts' at 02:00 on the same server: the
|
||||
// database, then (1.5.0) the photos and files.
|
||||
{ name: 'backup', label: 'Backup: the database, and the photos and files', cron: '20 2 * * *', env: 'BACKUP_ENABLED', run: (ctx) => runNightlyBackups(ctx) },
|
||||
{ name: 'hub-heartbeat', label: 'Cross Code Hub: heartbeat and licence refresh', cron: '*/15 * * * *', env: 'HUB_HEARTBEAT_ENABLED', run: (ctx) => heartbeat(ctx) },
|
||||
// ROADMAP-v3 §4: "consumers also poll every 15 minutes as a fallback".
|
||||
{ name: 'event-feed', label: 'Events from the church\'s other sites (Cross Events)', cron: '*/15 * * * *', env: 'FEED_JOB_ENABLED', run: (ctx) => syncAll(ctx) },
|
||||
|
||||
@@ -8,7 +8,8 @@ import path from 'node:path';
|
||||
import { Readable } from 'node:stream';
|
||||
import zlib from 'node:zlib';
|
||||
import request from 'supertest';
|
||||
import { BACKUP_FILE, backupName, backupPath, listBackups, runBackup, runBackupJob, type Dumper } from '../src/backups/backups.js';
|
||||
import { BACKUP_FILE, backupName, backupPath, listBackups, runBackup, runBackupJob, useDumperForTest, type Dumper } from '../src/backups/backups.js';
|
||||
import { listUploadsSnapshots, runNightlyBackups, runUploadsBackup, UPLOADS_SNAPSHOT } from '../src/backups/uploads.js';
|
||||
import { health } from '../src/hub/client.js';
|
||||
import { JOBS, cronFor, isEnabled, jobsHealth, runNow, useEnvForTest } from '../src/jobs.js';
|
||||
import { hashToken } from '../src/lib/crypto.js';
|
||||
@@ -19,7 +20,7 @@ type Role = 'owner' | 'admin' | 'editor';
|
||||
const dumpOf = (sql: string): Dumper => () => ({ stdout: Readable.from([sql]), done: Promise.resolve() });
|
||||
const failing: Dumper = () => ({ stdout: Readable.from(['-- half a dump']), done: Promise.reject(new Error('pg_dump stopped (exit 1): connection refused')) });
|
||||
|
||||
after(() => useEnvForTest(process.env));
|
||||
after(() => { useEnvForTest(process.env); useDumperForTest(null); });
|
||||
|
||||
async function site() {
|
||||
const h = await harness({ linked: false });
|
||||
@@ -103,7 +104,7 @@ describe('backups (1.4.0)', () => {
|
||||
|
||||
assert.equal((await admin.put('/backups/settings', { retain: 0, nightly: true })).status, 400);
|
||||
const saved = await admin.put('/backups/settings', { retain: 30, nightly: false });
|
||||
assert.deepEqual(saved.body, { retain: 30, nightly: false, deleted: 0 });
|
||||
assert.deepEqual(saved.body, { retain: 30, nightly: false, uploads: true, deleted: 0 });
|
||||
assert.equal(await h.ctx.settings.bool('backup_nightly', true), false);
|
||||
});
|
||||
|
||||
@@ -173,3 +174,80 @@ describe('background jobs (1.4.0)', () => {
|
||||
assert.deepEqual(ran.body, { queued: false, output: { added: 0, skipped: 'no source' } });
|
||||
});
|
||||
});
|
||||
|
||||
describe('backups of the photos and files (1.5.0)', () => {
|
||||
useDumperForTest(dumpOf('-- the database\n'));
|
||||
async function withUploads() {
|
||||
const h = await site();
|
||||
const up = fs.mkdtempSync(path.join(os.tmpdir(), 'ccw-up-'));
|
||||
h.ctx.config.uploadDir = up;
|
||||
fs.mkdirSync(path.join(up, 'demo'));
|
||||
fs.mkdirSync(path.join(up, '.thumbnails'));
|
||||
fs.writeFileSync(path.join(up, 'a.jpg'), 'photo a');
|
||||
fs.writeFileSync(path.join(up, 'demo', 'b.svg'), '<svg/>');
|
||||
fs.writeFileSync(path.join(up, '.thumbnails', 't.jpg'), 'made again on demand');
|
||||
return { ...h, up };
|
||||
}
|
||||
const ino = (p: string) => fs.statSync(p).ino;
|
||||
|
||||
it('a snapshot is a real copy of the uploads, without .thumbnails', async () => {
|
||||
const h = await withUploads();
|
||||
const s = await runUploadsBackup(h.ctx);
|
||||
assert.match(s.name, UPLOADS_SNAPSHOT);
|
||||
const snap = path.join(h.dir, s.name);
|
||||
assert.equal(fs.readFileSync(path.join(snap, 'a.jpg'), 'utf8'), 'photo a');
|
||||
assert.equal(fs.readFileSync(path.join(snap, 'demo', 'b.svg'), 'utf8'), '<svg/>');
|
||||
assert.ok(!fs.existsSync(path.join(snap, '.thumbnails')));
|
||||
assert.deepEqual([s.files, s.newFiles], [2, 2]);
|
||||
assert.notEqual(ino(path.join(snap, 'a.jpg')), ino(path.join(h.up, 'a.jpg')), 'not the live file itself');
|
||||
// Deleting the live file leaves the backup.
|
||||
fs.rmSync(path.join(h.up, 'a.jpg'));
|
||||
assert.equal(fs.readFileSync(path.join(snap, 'a.jpg'), 'utf8'), 'photo a');
|
||||
});
|
||||
|
||||
it('the next one links what\'s unchanged and copies only what\'s new', async () => {
|
||||
const h = await withUploads();
|
||||
const first = await runUploadsBackup(h.ctx);
|
||||
fs.writeFileSync(path.join(h.up, 'c.png'), 'new photo');
|
||||
const second = await runUploadsBackup(h.ctx);
|
||||
assert.notEqual(second.name, first.name);
|
||||
assert.deepEqual([second.files, second.newFiles, second.newBytes], [3, 1, 'new photo'.length]);
|
||||
assert.equal(ino(path.join(h.dir, second.name, 'a.jpg')), ino(path.join(h.dir, first.name, 'a.jpg')), 'unchanged: a hard link');
|
||||
assert.equal((await listUploadsSnapshots(h.ctx))[0]!.name, second.name);
|
||||
});
|
||||
|
||||
it('only the newest are kept, as the database backups; a crash leaves no half snapshot behind', async () => {
|
||||
const h = await withUploads();
|
||||
await h.ctx.settings.set('backup_retain_count', '2');
|
||||
fs.mkdirSync(path.join(h.dir, '.uploads-20200101-000000-partial'));
|
||||
for (let i = 0; i < 3; i++) await runUploadsBackup(h.ctx);
|
||||
assert.equal((await listUploadsSnapshots(h.ctx)).length, 2);
|
||||
assert.ok(!fs.existsSync(path.join(h.dir, '.uploads-20200101-000000-partial')));
|
||||
});
|
||||
|
||||
it('the nightly job backs up both, and leaves the uploads out when that\'s off', async () => {
|
||||
const h = await withUploads();
|
||||
const ran = await runNightlyBackups(h.ctx) as { database: { filename?: string }; uploads: { name?: string; skipped?: boolean } };
|
||||
assert.ok(ran.database.filename && ran.uploads.name, JSON.stringify(ran));
|
||||
await h.ctx.settings.set('backup_uploads', 'false');
|
||||
assert.deepEqual((await runNightlyBackups(h.ctx) as { uploads: unknown }).uploads, { skipped: true });
|
||||
await h.ctx.settings.set('backup_nightly', 'false');
|
||||
assert.deepEqual(await runNightlyBackups(h.ctx), { database: { skipped: true } });
|
||||
});
|
||||
|
||||
it('Back up now makes both; the page lists the snapshots; the switch is saved', async () => {
|
||||
const h = await withUploads();
|
||||
const admin = await h.as('admin');
|
||||
const made = await admin.post('/backups/run');
|
||||
assert.equal(made.status, 200, JSON.stringify(made.body));
|
||||
assert.equal(made.body.uploads.newFiles, 2);
|
||||
assert.equal(made.body.uploadsError, null);
|
||||
const list = await admin.get('/backups');
|
||||
assert.equal(list.body.uploads.enabled, true);
|
||||
assert.equal(list.body.uploads.items.length, 1);
|
||||
assert.equal(list.body.uploads.items[0].files, 2);
|
||||
const off = await admin.put('/backups/settings', { retain: 14, nightly: true, uploads: false });
|
||||
assert.equal(off.body.uploads, false);
|
||||
assert.equal(await h.ctx.settings.bool('backup_uploads', true), false);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user