A modern, self-hosted backup solution for secure, encrypted backups across local and cloud storage.
fix: fail a stuck backup instead of locking the job queue
towfiqi1ee6167c45ee
diff --git a/backend/__tests__/managers/handlers/BackupHandler.test.ts b/backend/__tests__/managers/handlers/BackupHandler.test.tsindex 2428a52..dde0f0d 100644--- a/backend/__tests__/managers/handlers/BackupHandler.test.ts+++ b/backend/__tests__/managers/handlers/BackupHandler.test.ts@@ -881,7 +881,9 @@ describe('BackupHandler', () => {expect.any(Object),expect.any(Function),expect.any(Function),- expect.any(Function)+ expect.any(Function),+ undefined,+ expect.objectContaining({ stallTimeout: expect.any(Number) }));});@@ -907,7 +909,9 @@ describe('BackupHandler', () => {expect.any(Object),expect.any(Function),expect.any(Function),- expect.any(Function)+ expect.any(Function),+ undefined,+ expect.objectContaining({ stallTimeout: expect.any(Number) }));});});@@ -975,7 +979,8 @@ describe('BackupHandler', () => {expect.any(Function),expect.any(Function),expect.any(Function),- expect.any(Function)+ expect.any(Function),+ expect.objectContaining({ stallTimeout: expect.any(Number) }));expect(mockTrackProcess).toHaveBeenCalledWith('backup-backup-1', mockProcess);@@ -996,7 +1001,8 @@ describe('BackupHandler', () => {expect.any(Function),expect.any(Function),expect.any(Function),- expect.any(Function)+ expect.any(Function),+ expect.objectContaining({ stallTimeout: expect.any(Number) }));});});@@ -1465,7 +1471,9 @@ describe('BackupHandler', () => {expect.objectContaining({ RESTIC_PASSWORD: 'test-encryption-key' }),expect.any(Function),expect.any(Function),- expect.any(Function)+ expect.any(Function),+ undefined,+ expect.objectContaining({ stallTimeout: expect.any(Number) }));});@@ -1481,7 +1489,9 @@ describe('BackupHandler', () => {expect.any(Object),expect.any(Function),expect.any(Function),- expect.any(Function)+ expect.any(Function),+ undefined,+ expect.objectContaining({ stallTimeout: expect.any(Number) }));});@@ -1556,7 +1566,8 @@ describe('BackupHandler', () => {expect.any(Function),expect.any(Function),expect.any(Function),- expect.any(Function)+ expect.any(Function),+ expect.objectContaining({ stallTimeout: expect.any(Number) }));});diff --git a/backend/__tests__/utils/restic/restic.test.ts b/backend/__tests__/utils/restic/restic.test.tsindex c696251..4e00929 100644--- a/backend/__tests__/utils/restic/restic.test.ts+++ b/backend/__tests__/utils/restic/restic.test.ts@@ -11,6 +11,9 @@ jest.mock('../../../src/utils/AppPaths', () => ({},}));jest.mock('../../../src/utils/restic/helpers');+jest.mock('../../../src/utils/processTree', () => ({+ killProcessTree: jest.fn(),+}));jest.mock('../../../src/services/ConfigService', () => ({configService: {config: {@@ -31,8 +34,10 @@ import { getBinaryPath } from '../../../src/utils/binaryPathResolver';import { getRcloneConfigPath } from '../../../src/utils/rclone/helpers';import { appPaths } from '../../../src/utils/AppPaths';import { generateResticRepoPath } from '../../../src/utils/restic/helpers';+import { killProcessTree } from '../../../src/utils/processTree';const mockSpawn = spawn as jest.MockedFunction<typeof spawn>;+const mockKillProcessTree = killProcessTree as jest.MockedFunction<typeof killProcessTree>;const mockGetBinaryPath = getBinaryPath as jest.MockedFunction<typeof getBinaryPath>;const mockGetRcloneConfigPath = getRcloneConfigPath as jest.MockedFunction<typeof getRcloneConfigPath@@ -474,6 +479,54 @@ describe('runResticCommand', () => {expect.any(Object));});++ describe('stall watchdog', () => {+ beforeEach(() => jest.useFakeTimers());+ afterEach(() => jest.useRealTimers());++ it('trips after the full inactivity period and kills the process tree', async () => {+ const promise = runResticCommand(+ ['backup', '/test'],+ undefined,+ jest.fn(),+ undefined,+ undefined,+ undefined,+ { stallTimeout: 60_000 }+ );+ // Attach a catch synchronously so the rejection is never unhandled.+ const settled = expect(promise).rejects.toMatchObject({ stalled: true });++ // One poll (60 s) with no stdout/stderr activity trips the watchdog.+ await jest.advanceTimersByTimeAsync(60_000);++ await settled;+ expect(mockKillProcessTree).toHaveBeenCalledTimes(1);+ });++ it('does not trip while stderr keeps emitting activity', async () => {+ const promise = runResticCommand(+ ['backup', '/test'],+ undefined,+ jest.fn(),+ undefined,+ undefined,+ undefined,+ { stallTimeout: 120_000 }+ );++ // Emit activity before each 60 s poll, so inactivity never reaches 120 s.+ await jest.advanceTimersByTimeAsync(59_000);+ mockProcess.stderr.emit('data', Buffer.from('transferring'));+ await jest.advanceTimersByTimeAsync(59_000);+ mockProcess.stderr.emit('data', Buffer.from('transferring'));+ await jest.advanceTimersByTimeAsync(59_000);++ mockProcess.emit('close', 0);+ await expect(promise).resolves.toBeDefined();+ expect(mockKillProcessTree).not.toHaveBeenCalled();+ });+ });});describe('getBackupPlanStats', () => {diff --git a/backend/src/managers/handlers/BackupHandler.ts b/backend/src/managers/handlers/BackupHandler.tsindex 7b6e6af..235d2e1 100644--- a/backend/src/managers/handlers/BackupHandler.ts+++ b/backend/src/managers/handlers/BackupHandler.ts@@ -24,6 +24,10 @@ type ResticArgsAndEnv = {resticEnv: Record<string, string>;};+// A backup that gives no output for one hour is stuck (sleep, VPN drop, NAS offline).+// The watchdog kills it so the job queue does not lock forever.+const RESTIC_STALL_TIMEOUT_MS = 60 * 60 * 1000;+export class BackupHandler {private runningBackups = new Set<string>();private cancelledBackups = new Set<string>();@@ -327,7 +331,8 @@ export class BackupHandler {handlers.onProgress,handlers.onError,handlers.onComplete,- process => processManager.trackProcess('backup-' + backupId, process)+ process => processManager.trackProcess('backup-' + backupId, process),+ { stallTimeout: RESTIC_STALL_TIMEOUT_MS });if (!this.cancelledBackups.has(planId + backupId)) {// Exit code 3: snapshot created with warnings. Log this as a warning@@ -813,7 +818,9 @@ export class BackupHandler {dryRunEnv,handlers.onProgress,handlers.onError,- handlers.onComplete+ handlers.onComplete,+ undefined,+ { stallTimeout: RESTIC_STALL_TIMEOUT_MS });const outputLines = dryRunOutput.split('\n').filter(line => line.trim() !== '');const summaryLine = outputLines[outputLines.length - 1];diff --git a/backend/src/utils/restic/restic.ts b/backend/src/utils/restic/restic.tsindex 6943ca5..f22776e 100644--- a/backend/src/utils/restic/restic.ts+++ b/backend/src/utils/restic/restic.ts@@ -11,12 +11,13 @@ import { buildResticEnvFromSettings, buildRcloneEnvFromSettings } from '../globaimport { BackupVerifiedResult } from '../../types/plans';import { runHelper } from '../linuxHelper';import { ResticExitCode } from './exitCodes';-import { KillableProcess } from '../processTree';+import { KillableProcess, killProcessTree } from '../processTree';export type ResticCommandError = Error & {code?: number;stderr?: string;timedOut?: boolean;+ stalled?: boolean;};// Cap retained stdout/stderr to avoid exceeding V8's max string size on long@@ -35,7 +36,7 @@ export function runResticCommand(onError?: (data: Buffer) => void,onComplete?: (code: number) => void,onProcess?: (process: any) => void,- options?: { timeout?: number }+ options?: { timeout?: number; stallTimeout?: number }): Promise<string> {let lastProgressTime = 0;const THROTTLE_INTERVAL = 2000; // 2 seconds@@ -108,13 +109,21 @@ export function runResticCommand(// When a timeout is provided we kill the process and reject with a `timedOut` error.let timedOut = false;+ let stalled = false;let timeoutHandle: NodeJS.Timeout | undefined;+ let stallInterval: NodeJS.Timeout | undefined;+ let lastActivity = Date.now();const timeoutMs = options?.timeout;- const clearTimeoutTimer = () => {+ const stallTimeoutMs = options?.stallTimeout;+ const clearTimers = () => {if (timeoutHandle) {clearTimeout(timeoutHandle);timeoutHandle = undefined;}+ if (stallInterval) {+ clearInterval(stallInterval);+ stallInterval = undefined;+ }};if (timeoutMs && timeoutMs > 0) {@@ -135,10 +144,28 @@ export function runResticCommand(}, timeoutMs);}+ // Watchdog: if the child gives no output for stallTimeout, it is stuck+ // (sleep, VPN drop, NAS offline). Kill it so the job queue does not lock.+ if (stallTimeoutMs && stallTimeoutMs > 0) {+ const STALL_POLL_INTERVAL = 60_000;+ stallInterval = setInterval(() => {+ if (Date.now() - lastActivity < stallTimeoutMs) return;+ stalled = true;+ clearTimers();+ // Kill the whole tree so the stuck rclone releases the repo lock.+ killProcessTree(resticProcess as KillableProcess, 'SIGTERM');+ const stallError: ResticCommandError = new Error(+ `Restic command stalled: no output for ${Math.round(stallTimeoutMs / 60000)} minute(s)`+ );+ stallError.stalled = true;+ reject(stallError);+ }, STALL_POLL_INTERVAL);+ }+// Handle User exit gracefullyresticProcess.on('exit', (code, signal) => {- clearTimeoutTimer();- if (timedOut) return;+ clearTimers();+ if (timedOut || stalled) return;// On Windows taskkill reports code 1 / signal null, so also check the// marker that killProcessTree sets on the tracked process.if (signal === 'SIGTERM' || (resticProcess as KillableProcess).__plutonKilled) {@@ -150,8 +177,8 @@ export function runResticCommand(// Handle Restic Run ErrorsresticProcess.on('error', error => {- clearTimeoutTimer();- if (timedOut) return;+ clearTimers();+ if (timedOut || stalled) return;const errorMsg = `Failed to run restic : ${error.message}`;onError?.(Buffer.from(errorMsg));reject(new Error(errorMsg));@@ -159,6 +186,7 @@ export function runResticCommand(// Handle Restic Output MessagesresticProcess.stdout?.on('data', (data: Buffer) => {+ lastActivity = Date.now();const stdoutText = data.toString();if (!isStreaming) {output += stdoutText;@@ -194,6 +222,7 @@ export function runResticCommand(// Handle Error MessagesresticProcess.stderr?.on('data', (data: Buffer) => {+ lastActivity = Date.now();if (!wasCancelled) {console.log('restic output Error :', data.toString());errorOutput = appendBounded(errorOutput, data.toString());@@ -207,8 +236,8 @@ export function runResticCommand(// Handle Process ExitresticProcess.on('close', (code: number) => {// console.log('Restic Process exited with code:', code);- clearTimeoutTimer();- if (timedOut) return;+ clearTimers();+ if (timedOut || stalled) return;if (!wasCancelled) {onComplete?.(code);const isBackupWarning = cmd === 'backup' && code === ResticExitCode.IncompleteBackup;