A modern, self-hosted backup solution for secure, encrypted backups across local and cloud storage.
feat: add pre-backup free-space check on the destination
towfiqie8d9baad7721
diff --git a/backend/__tests__/managers/handlers/BackupHandler.test.ts b/backend/__tests__/managers/handlers/BackupHandler.test.tsindex 49800f2..2428a52 100644--- a/backend/__tests__/managers/handlers/BackupHandler.test.ts+++ b/backend/__tests__/managers/handlers/BackupHandler.test.ts@@ -762,6 +762,82 @@ describe('BackupHandler', () => {});});+ describe('canRun - destination space check', () => {+ const GiB = 1024 * 1024 * 1024;++ const localOptions = {+ ...baseOptions,+ storage: { ...baseOptions.storage, type: 'local' },+ storagePath: 'C:\\backups\\plan1',+ sourceId: 'main',+ };++ const dryRun = { data_added_packed: 500 * 1024 * 1024 };++ // statfs reports free bytes as bavail * bsize; use bsize = 1 so bavail is the byte count.+ const statfsWithAvailable = (available: number) =>+ ({ bsize: 1, bavail: available, blocks: 10 * GiB, bfree: available } as any);++ let statfsSpy: jest.SpyInstance;++ beforeEach(() => {+ jest.spyOn(os, 'freemem').mockReturnValue(2 * GiB);+ statfsSpy = jest.spyOn(fs.promises, 'statfs');+ });++ it('skips the check for non-local storage (s3)', async () => {+ const resticArgsAndEnv = handler.createResticBackupArgs('plan-1', baseOptions as any);+ const result = await handler.canRun(baseOptions, resticArgsAndEnv, dryRun);++ expect(result).toBe(true);+ expect(statfsSpy).not.toHaveBeenCalled();+ });++ it('skips the check for a remote device plan (sourceId !== main)', async () => {+ const remoteDeviceOptions = { ...localOptions, sourceId: 'device-1' };+ const resticArgsAndEnv = handler.createResticBackupArgs('plan-1', remoteDeviceOptions as any);+ const result = await handler.canRun(remoteDeviceOptions, resticArgsAndEnv, dryRun);++ expect(result).toBe(true);+ expect(statfsSpy).not.toHaveBeenCalled();+ });++ it('skips the check when no dry run occurred', async () => {+ const resticArgsAndEnv = handler.createResticBackupArgs('plan-1', localOptions as any);+ const result = await handler.canRun(localOptions, resticArgsAndEnv, undefined);++ expect(result).toBe(true);+ expect(statfsSpy).not.toHaveBeenCalled();+ });++ it('skips the check when the measurement fails', async () => {+ statfsSpy.mockRejectedValue(new Error('ENOENT'));++ const resticArgsAndEnv = handler.createResticBackupArgs('plan-1', localOptions as any);+ const result = await handler.canRun(localOptions, resticArgsAndEnv, dryRun);++ expect(result).toBe(true);+ });++ it('throws a non-retryable error when space is insufficient', async () => {+ statfsSpy.mockResolvedValue(statfsWithAvailable(100 * 1024 * 1024));++ const resticArgsAndEnv = handler.createResticBackupArgs('plan-1', localOptions as any);+ await expect(+ handler.canRun(localOptions, resticArgsAndEnv, dryRun)+ ).rejects.toMatchObject({ retryable: false });+ });++ it('passes when space is sufficient', async () => {+ statfsSpy.mockResolvedValue(statfsWithAvailable(5 * GiB));++ const resticArgsAndEnv = handler.createResticBackupArgs('plan-1', localOptions as any);+ const result = await handler.canRun(localOptions, resticArgsAndEnv, dryRun);++ expect(result).toBe(true);+ });+ });+describe('cancel', () => {it('should cancel backup and kill process', async () => {const result = await handler.cancel('plan-1', 'backup-1');diff --git a/backend/src/managers/handlers/BackupHandler.ts b/backend/src/managers/handlers/BackupHandler.tsindex 83db1bb..9aaaebd 100644--- a/backend/src/managers/handlers/BackupHandler.ts+++ b/backend/src/managers/handlers/BackupHandler.ts@@ -17,6 +17,7 @@ import { runScriptsForEvent } from '../../utils/executeUserScript';import { configService } from '../../services/ConfigService';import { ReplicationOrchestrator } from './ReplicationOrchestrator';import { BackupMirror, BackupRunConfig } from '../../types/backups';+import { formatBytes } from '../../utils/formatter';type ResticArgsAndEnv = {resticArgs: string[];@@ -264,7 +265,7 @@ export class BackupHandler {// Run pre-flight checksawait this.updateProgress(planId, backupId, 'pre-backup', 'PRE_BACKUP_CHECKS_START', false);- await this.canRun(options, resticArgsAndEnv);+ await this.canRun(options, resticArgsAndEnv, dryRunSummary);await this.updateProgress(planId, backupId, 'pre-backup', 'PRE_BACKUP_CHECKS_COMPLETE', true);// Run pre-backup scripts@@ -560,7 +561,11 @@ export class BackupHandler {* @param options - Options for the backup process.* @returns A promise that resolves to a boolean indicating if the backup can run.*/- async canRun(options: Record<string, any>, resticArgsAndEnv: ResticArgsAndEnv): Promise<boolean> {+ async canRun(+ options: Record<string, any>,+ resticArgsAndEnv: ResticArgsAndEnv,+ dryRunSummary?: false | Record<string, any>+ ): Promise<boolean> {// Check system resource availability// Use a fixed minimum (128MB) rather than scaling by CPU count.// Restic's memory usage doesn't scale linearly with cores, and on macOS@@ -595,9 +600,55 @@ export class BackupHandler {}}+ // Check the destination has enough free space before the backup starts.+ await this.checkDestinationSpace(options, dryRunSummary);+return true;}+ /**+ * Checks that the destination volume has enough free space for the backup.+ * Throws a non-retryable error if the space is not enough.+ */+ private async checkDestinationSpace(+ options: Record<string, any>,+ dryRunSummary?: false | Record<string, any>+ ): Promise<void> {+ // Only local storage on the Pluton host is measurable here.+ if (options.storage?.type !== 'local') return;+ // A remote-device plan would measure the Pluton server, not the device.+ if (options.sourceId !== 'main') return;+ if (!options.storagePath) return;+ // The dry run does not run (rescue method or skipDryRun), so no estimate.+ if (!dryRunSummary || dryRunSummary.dry_run_skipped || options.method === 'rescue') return;++ const estimated: number = dryRunSummary.data_added_packed || dryRunSummary.data_added || 0;+ if (estimated <= 0) return;++ // Measure the free space of the destination filesystem+ // destination must have the estimated backup size + a 256 MiB buffer for restic+ let available: number;+ try {+ const stats = await fs.promises.statfs(options.storagePath);+ available = stats.bavail * stats.bsize;+ if (!Number.isFinite(available) || available < 0) return;+ } catch {+ return;+ }++ const MiB = 1024 * 1024;+ const required = estimated * 1.2 + 256 * MiB;+ if (available >= required) return;++ const message =+ `Not enough space on the destination "${options.storagePath}". ` ++ `The backup needs about ${formatBytes(required)} but only ${formatBytes(available)} is free.`;++ const spaceError: Error & { retryable?: boolean } = new Error(message);+ spaceError.retryable = false;+ throw spaceError;+ }+/*** Cancels the backup process.* @param planId - The ID of the backup plan.