A modern, self-hosted backup solution for secure, encrypted backups across local and cloud storage.
feat: add ability to resume snapshot downloads
towfiqi6fab420f76b5
diff --git a/backend/__tests__/controllers/BackupController.test.ts b/backend/__tests__/controllers/BackupController.test.tsindex 341cf6f..b340e76 100644--- a/backend/__tests__/controllers/BackupController.test.ts+++ b/backend/__tests__/controllers/BackupController.test.ts@@ -12,7 +12,7 @@ describe('BackupController', () => {let mockJson: jest.Mock;let mockStatus: jest.Mock;let mockSetHeader: jest.Mock;- let mockPipe: jest.Mock;+ let mockDownload: jest.Mock;beforeEach(() => {jest.clearAllMocks();@@ -29,12 +29,13 @@ describe('BackupController', () => {mockJson = jest.fn().mockReturnThis();mockStatus = jest.fn().mockReturnValue({ json: mockJson });mockSetHeader = jest.fn();- mockPipe = jest.fn();+ mockDownload = jest.fn();mockResponse = {json: mockJson,status: mockStatus,setHeader: mockSetHeader,+ download: mockDownload,};mockRequest = {@@ -58,24 +59,61 @@ describe('BackupController', () => {});});- it('should successfully stream backup download', async () => {- const mockFileStream = { pipe: mockPipe, on: jest.fn() };+ it('should send the backup file with res.download', async () => {mockRequest.params = { id: 'backup-123' };mockBackupService.getBackupDownload.mockResolvedValue({fileName: 'backup.tar',- fileStream: mockFileStream as any,+ filePath: '/downloads/backup.tar',});await backupController.getBackupDownload(mockRequest as Request, mockResponse as Response);expect(mockBackupService.getBackupDownload).toHaveBeenCalledWith('backup-123');- expect(mockSetHeader).toHaveBeenCalledWith('Content-Type', 'application/x-tar');- expect(mockSetHeader).toHaveBeenCalledWith(- 'Content-Disposition',- 'attachment; filename=backup.tar'+ expect(mockDownload).toHaveBeenCalledWith(+ '/downloads/backup.tar',+ 'backup.tar',+ { dotfiles: 'allow' },+ expect.any(Function));- expect(mockSetHeader).toHaveBeenCalledWith('Transfer-Encoding', 'chunked');- expect(mockPipe).toHaveBeenCalledWith(mockResponse);+ expect(mockStatus).not.toHaveBeenCalled();+ });++ it('should return an error if res.download fails before headers are sent', async () => {+ mockRequest.params = { id: 'backup-123' };+ mockBackupService.getBackupDownload.mockResolvedValue({+ fileName: 'backup.tar',+ filePath: '/downloads/backup.tar',+ });++ await backupController.getBackupDownload(mockRequest as Request, mockResponse as Response);++ const callback = mockDownload.mock.calls[0][3];+ const error: any = new Error('File not found');+ error.statusCode = 404;+ callback(error);++ expect(mockStatus).toHaveBeenCalledWith(404);+ expect(mockJson).toHaveBeenCalledWith({+ success: false,+ error: 'Failed to get Downloaded file. File not found',+ });+ });++ it('should not send an error if res.download fails after headers are sent', async () => {+ mockRequest.params = { id: 'backup-123' };+ mockBackupService.getBackupDownload.mockResolvedValue({+ fileName: 'backup.tar',+ filePath: '/downloads/backup.tar',+ });+ (mockResponse as any).headersSent = true;++ await backupController.getBackupDownload(mockRequest as Request, mockResponse as Response);++ const callback = mockDownload.mock.calls[0][3];+ callback(new Error('Connection reset'));++ expect(mockStatus).not.toHaveBeenCalled();+ expect(mockJson).not.toHaveBeenCalled();});it('should return 500 if service throws an error', async () => {diff --git a/backend/__tests__/managers/BaseSnapshotManager.test.ts b/backend/__tests__/managers/BaseSnapshotManager.test.tsindex d6f9288..23f0643 100644--- a/backend/__tests__/managers/BaseSnapshotManager.test.ts+++ b/backend/__tests__/managers/BaseSnapshotManager.test.ts@@ -113,9 +113,9 @@ describe('BaseSnapshotManager', () => {});describe('getSnapshotDownload', () => {- it('should return file stream info from handler', async () => {+ it('should return file info from handler', async () => {const mgr = new BaseSnapshotManager();- const mockResult = { fileName: 'backup-1.tar', fileStream: {} };+ const mockResult = { fileName: 'backup-1.tar', filePath: '/downloads/backup-1.tar' };downloadHandlerMock.get.mockResolvedValue(mockResult);const out = await mgr.getSnapshotDownload('plan-1', 'backup-1');diff --git a/backend/__tests__/managers/handlers/DownloadHandler.test.ts b/backend/__tests__/managers/handlers/DownloadHandler.test.tsindex 7b7552f..a53ebc2 100644--- a/backend/__tests__/managers/handlers/DownloadHandler.test.ts+++ b/backend/__tests__/managers/handlers/DownloadHandler.test.ts@@ -5,7 +5,6 @@ import path from 'path';jest.mock('fs', () => ({...jest.requireActual('fs'),- createReadStream: jest.fn(() => ({ fake: 'stream' })),existsSync: jest.fn(() => true),}));@@ -67,7 +66,10 @@ jest.mock('../../../src/services/ConfigService', () => ({},}));-import { DownloadHandler } from '../../../src/managers/handlers/DownloadHandler';+import {+ DownloadHandler,+ DOWNLOAD_NOT_FOUND_ERROR,+} from '../../../src/managers/handlers/DownloadHandler';import { processManager } from '../../../src/managers/ProcessManager';import { runResticCommand } from '../../../src/utils/restic/restic';import { appPaths } from '../../../src/utils/AppPaths';@@ -139,11 +141,15 @@ describe('DownloadHandler', () => {expect(res).toBeTruthy();});- test('get: returns filename and stream', async () => {+ test('get: returns filename and file path', async () => {const out = await handler.get('plan1', 'backup4');expect(out.fileName).toBe('backup-backup4.tar');- expect(fs.createReadStream).toHaveBeenCalled();- expect(out.fileStream).toEqual({ fake: 'stream' });+ expect(out.filePath).toBe(path.join(appPaths.getDownloadsDir(), 'backup-backup4.tar'));+ });++ test('get: throws when the download file is missing', async () => {+ (fs.existsSync as jest.Mock).mockReturnValueOnce(false);+ await expect(handler.get('plan1', 'missing')).rejects.toThrow(DOWNLOAD_NOT_FOUND_ERROR);});test('download: emits progress events when restic writes progress', async () => {diff --git a/backend/__tests__/services/BackupServices.test.ts b/backend/__tests__/services/BackupServices.test.tsindex 0ea8056..3938ae9 100644--- a/backend/__tests__/services/BackupServices.test.ts+++ b/backend/__tests__/services/BackupServices.test.ts@@ -148,9 +148,9 @@ describe('BackupService', () => {method: 'backup',} as any;- it('should successfully get a backup download stream', async () => {+ it('should successfully get a backup download file', async () => {// Arrange- const mockStreamData = { fileName: 'backup.tar', fileStream: 'stream_object' };+ const mockStreamData = { fileName: 'backup.tar', filePath: '/downloads/backup.tar' };mockBackupStore.getById.mockResolvedValue(mockBackup);mockSnapshotStrategy.getSnapshotDownload.mockResolvedValue({success: true,diff --git a/backend/src/controllers/BackupController.ts b/backend/src/controllers/BackupController.tsindex d89222e..3adb64f 100644--- a/backend/src/controllers/BackupController.ts+++ b/backend/src/controllers/BackupController.ts@@ -14,29 +14,16 @@ export class BackupController {}try {- const downloadResult = await this.backupService.getBackupDownload(req.params.id);- const { fileName, fileStream } = downloadResult;-- // Set headers for streaming- res.setHeader('Content-Type', 'application/x-tar');- res.setHeader('Content-Disposition', `attachment; filename=${fileName}`);- res.setHeader('Transfer-Encoding', 'chunked');-- fileStream.on('error', (error: Error) => {- if (res.headersSent) {- res.destroy(error);- return;- }- res.removeHeader('Content-Disposition');- res.removeHeader('Transfer-Encoding');- res.status(500).type('json').json({+ const { fileName, filePath } = await this.backupService.getBackupDownload(req.params.id);++ // dotfiles 'allow': send checks every segment of an absolute path (e.g. ~/.pluton)+ res.download(filePath, fileName, { dotfiles: 'allow' }, (error: any) => {+ if (!error || res.headersSent) return;+ res.status(error.statusCode || error.status || 500).json({success: false,error: 'Failed to get Downloaded file. ' + (error.message || ''),});});-- // Pipe the stream directly to response- fileStream.pipe(res);return;} catch (error: any) {res.status(error.statusCode || 500).json({diff --git a/backend/src/managers/handlers/DownloadHandler.ts b/backend/src/managers/handlers/DownloadHandler.tsindex a5f8b17..aefe476 100644--- a/backend/src/managers/handlers/DownloadHandler.ts+++ b/backend/src/managers/handlers/DownloadHandler.ts@@ -1,7 +1,7 @@import { EventEmitter } from 'events';import { mkdir, rm, readFile, readdir } from 'fs/promises';import path from 'path';-import { existsSync, createReadStream } from 'fs';+import { existsSync } from 'fs';import { unlink } from 'fs/promises';import { runResticCommand } from '../../utils/restic/restic';import { generateResticRepoPath } from '../../utils/restic/helpers';@@ -139,8 +139,7 @@ export class DownloadHandler {throw new Error(DOWNLOAD_NOT_FOUND_ERROR);}- const fileStream = createReadStream(zipPath);- return { fileName, fileStream };+ return { fileName, filePath: zipPath };} catch (error: any) {throw new Error('Error Getting Downloaded File. ' + error?.message || '');}diff --git a/backend/src/strategies/snapshot/SnapshotStrategy.ts b/backend/src/strategies/snapshot/SnapshotStrategy.tsindex 63fe07d..612a7bd 100644--- a/backend/src/strategies/snapshot/SnapshotStrategy.ts+++ b/backend/src/strategies/snapshot/SnapshotStrategy.ts@@ -1,6 +1,5 @@import { SnapShotFile } from '../../types/restic';import { StrategyMethodTypes } from '../../types/strategy';-import { ReadStream } from 'fs';export interface SnapshotStrategy {removeSnapshot(@@ -29,7 +28,7 @@ export interface SnapshotStrategy {getSnapshotDownload(planId: string,backupId: string- ): Promise<{ success: boolean; result: string | { fileName: string; fileStream: ReadStream } }>;+ ): Promise<{ success: boolean; result: string | { fileName: string; filePath: string } }>;cancelSnapshotDownload(planId: string,backupId: stringdiff --git a/frontend/src/services/backups.ts b/frontend/src/services/backups.tsindex 95bef67..4a0cf76 100644--- a/frontend/src/services/backups.ts+++ b/frontend/src/services/backups.ts@@ -32,44 +32,20 @@ export function useDownloadBackup() {// Get Downloadexport async function getBackupDownload(id: string) {- // const header = new Headers({ 'Content-Type': 'application/json', Accept: 'application/json' });- const res = await fetch(`${API_URL}/backups/${id}/action/download`, {- method: 'GET',- credentials: 'include',- // headers: header,- });- // Check if response is ok+ const url = `${API_URL}/backups/${id}/action/download`;+ // HEAD pre-check so errors show a toast instead of a failed browser download+ const res = await fetch(url, { method: 'HEAD', credentials: 'include' });if (!res.ok) {- const data = await res.json();- throw new Error(data.error);+ throw new Error(res.status === 404 ? 'Download file not found. Please generate the download again.' : 'Download Failed!');}- const filename = res.headers.get('content-disposition')?.split('filename=')[1] || `backup-${id}.tar`;-- // Use streams API- const reader = res.body?.getReader();- const stream = new ReadableStream({- async start(controller) {- while (true) {- const { done, value } = await reader!.read();- if (done) break;- controller.enqueue(value);- }- controller.close();- reader!.releaseLock();- },- });-- // Create download from stream- const blob = await new Response(stream).blob();- const url = window.URL.createObjectURL(blob);+ // Native browser download: shows size/progress and does not hold the file in memoryconst link = document.createElement('a');link.href = url;- link.download = filename;+ link.download = `backup-${id}.tar`;document.body.appendChild(link);link.click();link.remove();- window.URL.revokeObjectURL(url);}export function useGetBackupDownload() {diff --git a/frontend/vite.config.ts b/frontend/vite.config.tsindex fd4ed43..d7a0182 100644--- a/frontend/vite.config.ts+++ b/frontend/vite.config.ts@@ -82,6 +82,8 @@ export default defineConfig(({ mode }) => {workbox: {// This will cache all your assets (JS, CSS, images, fonts)globPatterns: ['**/*.{js,css,html,ico,png,svg,woff,woff2}'],+ // Let /api navigations (e.g. file downloads) reach the server, not index.html+ navigateFallbackDenylist: [/^\/api\//],},// For development testing