Skip to content

A modern, self-hosted backup solution for secure, encrypted backups across local and cloud storage.

feat: add pre-restore free-space check on the destination

towfiqi83aaea46fb9b
diff --git a/backend/__tests__/managers/handlers/RestoreHandler.test.ts b/backend/__tests__/managers/handlers/RestoreHandler.test.ts
index 51f2ea4..e98d73f 100644
--- a/backend/__tests__/managers/handlers/RestoreHandler.test.ts
+++ b/backend/__tests__/managers/handlers/RestoreHandler.test.ts
@@ -459,6 +459,53 @@ describe('RestoreHandler', () => {
});
});
+ describe('canRun - destination space check', () => {
+ const GiB = 1024 * 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);
+
+ const stats = { total_bytes: 500 * 1024 * 1024, bytes_restored: 500 * 1024 * 1024 };
+
+ let statfsSpy: jest.SpyInstance;
+
+ beforeEach(() => {
+ jest.spyOn(os, 'freemem').mockReturnValue(2 * GiB);
+ jest.spyOn(os, 'cpus').mockReturnValue(new Array(4));
+ statfsSpy = jest.spyOn(require('fs').promises, 'statfs');
+ });
+
+ it('skips the check when target is root', async () => {
+ const result = await handler.canRun({ ...baseOptions, target: '/' }, stats);
+
+ expect(result).toBe(true);
+ expect(statfsSpy).not.toHaveBeenCalled();
+ });
+
+ it('skips the check when there are no dry-run stats', async () => {
+ const result = await handler.canRun(baseOptions);
+
+ expect(result).toBe(true);
+ expect(statfsSpy).not.toHaveBeenCalled();
+ });
+
+ it('throws a non-retryable error when space is insufficient', async () => {
+ statfsSpy.mockResolvedValue(statfsWithAvailable(100 * 1024 * 1024));
+
+ await expect(handler.canRun(baseOptions, stats)).rejects.toMatchObject({
+ retryable: false,
+ });
+ });
+
+ it('passes when space is sufficient', async () => {
+ statfsSpy.mockResolvedValue(statfsWithAvailable(5 * GiB));
+
+ const result = await handler.canRun(baseOptions, stats);
+ expect(result).toBe(true);
+ });
+ });
+
describe('cancel', () => {
it('should cancel restore and kill process', async () => {
const result = await handler.cancel('plan-1', 'restore-1');
diff --git a/backend/__tests__/utils/checkDestinationSpace.test.ts b/backend/__tests__/utils/checkDestinationSpace.test.ts
new file mode 100644
index 0000000..19c2af7
--- /dev/null
+++ b/backend/__tests__/utils/checkDestinationSpace.test.ts
@@ -0,0 +1,60 @@
+import fs from 'fs';
+import { checkDestinationSpace } from '../../src/utils/checkDestinationSpace';
+
+describe('checkDestinationSpace', () => {
+ let statfsSpy: jest.SpyInstance;
+
+ // 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 * 1024 * 1024 * 1024, bfree: available } as any);
+
+ beforeEach(() => {
+ statfsSpy = jest.spyOn(fs.promises, 'statfs');
+ });
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ it('skips when there is no target path', async () => {
+ await expect(
+ checkDestinationSpace({ targetPath: '', estimatedBytes: 1000 })
+ ).resolves.toBeUndefined();
+ expect(statfsSpy).not.toHaveBeenCalled();
+ });
+
+ it('skips when the estimate is zero', async () => {
+ await expect(
+ checkDestinationSpace({ targetPath: 'C:\\backups', estimatedBytes: 0 })
+ ).resolves.toBeUndefined();
+ expect(statfsSpy).not.toHaveBeenCalled();
+ });
+
+ it('skips when the measurement fails', async () => {
+ statfsSpy.mockRejectedValue(new Error('ENOENT'));
+ await expect(
+ checkDestinationSpace({ targetPath: 'C:\\backups', estimatedBytes: 1000 })
+ ).resolves.toBeUndefined();
+ });
+
+ it('passes when the space is sufficient', async () => {
+ statfsSpy.mockResolvedValue(statfsWithAvailable(5 * 1024 * 1024 * 1024));
+ await expect(
+ checkDestinationSpace({ targetPath: 'C:\\backups', estimatedBytes: 500 * 1024 * 1024 })
+ ).resolves.toBeUndefined();
+ });
+
+ it('throws a non-retryable error when the space is insufficient', async () => {
+ statfsSpy.mockResolvedValue(statfsWithAvailable(100 * 1024 * 1024));
+ await expect(
+ checkDestinationSpace({ targetPath: 'C:\\backups', estimatedBytes: 500 * 1024 * 1024 })
+ ).rejects.toMatchObject({ retryable: false });
+ });
+
+ it('uses the label in the error message', async () => {
+ statfsSpy.mockResolvedValue(statfsWithAvailable(1));
+ await expect(
+ checkDestinationSpace({ targetPath: '/mnt/data', estimatedBytes: 1000, label: 'restore' })
+ ).rejects.toThrow(/The restore needs about/);
+ });
+});
diff --git a/backend/src/managers/handlers/BackupHandler.ts b/backend/src/managers/handlers/BackupHandler.ts
index 9aaaebd..4b92b71 100644
--- a/backend/src/managers/handlers/BackupHandler.ts
+++ b/backend/src/managers/handlers/BackupHandler.ts
@@ -17,7 +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';
+import { checkDestinationSpace } from '../../utils/checkDestinationSpace';
type ResticArgsAndEnv = {
resticArgs: string[];
@@ -601,16 +601,17 @@ export class BackupHandler {
}
// Check the destination has enough free space before the backup starts.
- await this.checkDestinationSpace(options, dryRunSummary);
+ await this.checkBackupDestinationSpace(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.
+ * Throws a non-retryable error if the space is not enough. The skip
+ * conditions are backup-specific; the measurement is the shared util.
*/
- private async checkDestinationSpace(
+ private async checkBackupDestinationSpace(
options: Record<string, any>,
dryRunSummary?: false | Record<string, any>
): Promise<void> {
@@ -623,30 +624,12 @@ export class BackupHandler {
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;
+ await checkDestinationSpace({
+ targetPath: options.storagePath,
+ estimatedBytes: estimated,
+ label: 'backup',
+ });
}
/**
diff --git a/backend/src/managers/handlers/RestoreHandler.ts b/backend/src/managers/handlers/RestoreHandler.ts
index d237472..3de3f5c 100644
--- a/backend/src/managers/handlers/RestoreHandler.ts
+++ b/backend/src/managers/handlers/RestoreHandler.ts
@@ -25,6 +25,7 @@ import {
isPermissionDeniedError,
runHelper,
} from '../../utils/linuxHelper';
+import { checkDestinationSpace } from '../../utils/checkDestinationSpace';
export class RestoreHandler {
private runningRestores = new Set<string>();
@@ -236,7 +237,9 @@ export class RestoreHandler {
// Run pre-flight checks
await this.updateProgress(planId, restoreId, 'pre-restore', 'PRE_RESTORE_CHECKS_START', false);
- await this.canRun(options);
+ const dryRunStats =
+ typeof restoreStats.result === 'object' ? restoreStats.result.stats : undefined;
+ await this.canRun(options, dryRunStats);
await this.updateProgress(
planId,
restoreId,
@@ -489,7 +492,7 @@ export class RestoreHandler {
});
}
- async canRun(options: RestoreOptions) {
+ async canRun(options: RestoreOptions, dryRunStats?: Record<string, any>) {
// 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
@@ -536,9 +539,36 @@ export class RestoreHandler {
}
}
+ // Check the target has enough free space before the restore starts.
+ await this.checkRestoreDestinationSpace(options, dryRunStats);
+
return true;
}
+ /**
+ * Checks that the restore target has enough free space.
+ * Throws a non-retryable error if the space is not enough. The skip
+ * conditions are restore-specific; the measurement is the shared util.
+ */
+ private async checkRestoreDestinationSpace(
+ options: RestoreOptions,
+ dryRunStats?: Record<string, any>
+ ): Promise<void> {
+ const target = options.target;
+ // Skip original-path and root restores (Windows temp+move, or restore to
+ // the original locations): there is no single measurable target volume.
+ if (!target || target === '/') return;
+ if (!dryRunStats) return;
+
+ const estimated: number = dryRunStats.bytes_restored || dryRunStats.total_bytes || 0;
+
+ await checkDestinationSpace({
+ targetPath: target,
+ estimatedBytes: estimated,
+ label: 'restore',
+ });
+ }
+
createResticRestoreArgs(
backupId: string,
snapshotId: string,
diff --git a/backend/src/utils/checkDestinationSpace.ts b/backend/src/utils/checkDestinationSpace.ts
new file mode 100644
index 0000000..f025501
--- /dev/null
+++ b/backend/src/utils/checkDestinationSpace.ts
@@ -0,0 +1,45 @@
+import fs from 'fs';
+import { formatBytes } from './formatter';
+
+export interface DestinationSpaceParams {
+ targetPath: string;
+ estimatedBytes: number;
+ label?: string; // used in the error message, e.g. 'backup' or 'restore'
+}
+
+/**
+ * Throws a non-retryable error when the target filesystem does not have enough
+ * free space for the estimated write. Uses the native fs.statfs, so it needs no
+ * external process and works on Windows, Linux, and macOS.
+ *
+ * It is a silent no-op (returns) when there is nothing to measure or the
+ * measurement fails. Never stop an operation because the measurement failed.
+ */
+export async function checkDestinationSpace({
+ targetPath,
+ estimatedBytes,
+ label = 'backup',
+}: DestinationSpaceParams): Promise<void> {
+ if (!targetPath || estimatedBytes <= 0) return;
+
+ let available: number;
+ try {
+ const stats = await fs.promises.statfs(targetPath);
+ available = stats.bavail * stats.bsize;
+ if (!Number.isFinite(available) || available < 0) return;
+ } catch {
+ return;
+ }
+
+ const MiB = 1024 * 1024;
+ const required = estimatedBytes * 1.2 + 256 * MiB; // 256 MiB buffer for temporary files and overhead
+ if (available >= required) return;
+
+ const message =
+ `Not enough space on the destination "${targetPath}". ` +
+ `The ${label} needs about ${formatBytes(required)} but only ${formatBytes(available)} is free.`;
+
+ const spaceError: Error & { retryable?: boolean } = new Error(message);
+ spaceError.retryable = false;
+ throw spaceError;
+}