A modern, self-hosted backup solution for secure, encrypted backups across local and cloud storage.
fix: resolves missing storage removal failure notice on plan removal
towfiqifd5736cecdcc
diff --git a/backend/__tests__/controllers/PlanController.test.ts b/backend/__tests__/controllers/PlanController.test.tsindex 07d848a..e61aada 100644--- a/backend/__tests__/controllers/PlanController.test.ts+++ b/backend/__tests__/controllers/PlanController.test.ts@@ -275,7 +275,11 @@ describe('PlanController', () => {it('should successfully delete a plan', async () => {mockRequest.params = { id: 'plan-1' };- mockPlanService.deletePlan.mockResolvedValue(true);+ mockPlanService.deletePlan.mockResolvedValue({+ deleted: true,+ unremovedPaths: [],+ unremovedReason: '',+ });await planController.deletePlan(mockRequest as Request, mockResponse as Response);@@ -284,6 +288,28 @@ describe('PlanController', () => {expect(mockJson).toHaveBeenCalledWith({success: true,message: 'Plan deleted successfully',+ unremovedPaths: [],+ unremovedReason: '',+ });+ });++ it('should report storage paths that could not be removed, and why', async () => {+ mockRequest.params = { id: 'plan-1' };+ const unremovedPaths = [{ storageName: 'wasabi', storagePath: 'pluton/laptop-01' }];+ mockPlanService.deletePlan.mockResolvedValue({+ deleted: true,+ unremovedPaths,+ unremovedReason: 'The device could not be reached.',+ });++ await planController.deletePlan(mockRequest as Request, mockResponse as Response);++ expect(mockStatus).toHaveBeenCalledWith(200);+ expect(mockJson).toHaveBeenCalledWith({+ success: true,+ message: 'Plan deleted successfully',+ unremovedPaths,+ unremovedReason: 'The device could not be reached.',});});});diff --git a/backend/__tests__/managers/BaseBackupManager.test.ts b/backend/__tests__/managers/BaseBackupManager.test.tsindex 6437f16..c4c370b 100644--- a/backend/__tests__/managers/BaseBackupManager.test.ts+++ b/backend/__tests__/managers/BaseBackupManager.test.ts@@ -574,7 +574,7 @@ describe('BaseBackupManager', () => {expect(res.result).toContain('Deleted 100 files');});- it('handles rclone errors during purge', async () => {+ it('reports a failed purge instead of stranding the plan', async () => {mockRunRcloneCommand.mockRejectedValueOnce(new Error('Purge failed'));const res = await mgr.removeBackup('plan-purge-fail', {storageName: 'remote',@@ -582,8 +582,61 @@ describe('BaseBackupManager', () => {removeRemoteData: true,encryption: false,});- expect(res.success).toBe(false);- expect(res.result).toMatch(/Purge failed/);+ // The plan must still be removable; the caller shows the path to the user.+ expect(res.success).toBe(true);+ expect(res.unremovedPaths).toEqual([{ storageName: 'remote', storagePath: 'path' }]);+ expect(res.unremovedReason).toMatch(/Purge failed/);+ });++ it('reports a failed replication purge that used to be swallowed', async () => {+ mockRunRcloneCommand+ .mockResolvedValueOnce('') // primary purge succeeds+ .mockRejectedValueOnce(new Error('Mirror unreachable'));++ const res = await mgr.removeBackup('plan-replica-fail', {+ storageName: 'remote',+ storagePath: 'path',+ removeRemoteData: true,+ encryption: false,+ replicationStorages: [{ storageName: 'b2-mirror', storagePath: 'mirrors/path' }],+ });++ expect(res.success).toBe(true);+ expect(res.unremovedPaths).toEqual([+ { storageName: 'b2-mirror', storagePath: 'mirrors/path' },+ ]);+ expect(res.unremovedReason).toMatch(/Mirror unreachable/);+ });++ it('reports every path when the primary and a replication both fail', async () => {+ mockRunRcloneCommand+ .mockRejectedValueOnce(new Error('Primary down'))+ .mockRejectedValueOnce(new Error('Mirror down'));++ const res = await mgr.removeBackup('plan-all-fail', {+ storageName: 'remote',+ storagePath: 'path',+ removeRemoteData: true,+ encryption: false,+ replicationStorages: [{ storageName: 'b2-mirror', storagePath: 'mirrors/path' }],+ });++ expect(res.unremovedPaths).toHaveLength(2);+ // The first failure is the reason shown to the user.+ expect(res.unremovedReason).toMatch(/Primary down/);+ });++ it('reports nothing unremoved when every purge succeeds', async () => {+ const res = await mgr.removeBackup('plan-ok', {+ storageName: 'remote',+ storagePath: 'path',+ removeRemoteData: true,+ encryption: false,+ replicationStorages: [{ storageName: 'b2-mirror', storagePath: 'mirrors/path' }],+ });++ expect(res.unremovedPaths).toEqual([]);+ expect(res.unremovedReason).toBe('');});});diff --git a/backend/__tests__/routes/plans.test.ts b/backend/__tests__/routes/plans.test.tsindex 8268201..3698ff7 100644--- a/backend/__tests__/routes/plans.test.ts+++ b/backend/__tests__/routes/plans.test.ts@@ -199,7 +199,11 @@ describe('Plan Routes', () => {});it('should delete a plan when authenticated', async () => {- mockPlanService.deletePlan.mockResolvedValue(true);+ mockPlanService.deletePlan.mockResolvedValue({+ deleted: true,+ unremovedPaths: [],+ unremovedReason: '',+ });const response = await request(app).delete('/api/plans/plan-1');diff --git a/backend/__tests__/services/PlanService.test.ts b/backend/__tests__/services/PlanService.test.tsindex 5e07a05..2cd286b 100644--- a/backend/__tests__/services/PlanService.test.ts+++ b/backend/__tests__/services/PlanService.test.ts@@ -534,7 +534,31 @@ describe('PlanService', () => {});expect(mockBackupStore.deleteByPlanId).toHaveBeenCalledWith(planId);expect(mockPlanStore.delete).toHaveBeenCalledWith(planId);- expect(result).toBe(true);+ expect(result).toEqual({ deleted: true, unremovedPaths: [], unremovedReason: '' });+ });++ it('should still delete the plan when storage data could not be removed', async () => {+ // Arrange+ mockPlanStore.getById.mockResolvedValue(mockPlan);+ mockStrategy.removeBackup.mockResolvedValue({+ success: true,+ result: 'purge failed',+ unremovedPaths: [{ storageName: 'Test Storage', storagePath: '/backups/delete' }],+ unremovedReason: 'The device could not be reached.',+ });+ mockBackupStore.deleteByPlanId.mockResolvedValue(true);+ mockPlanStore.delete.mockResolvedValue(true);++ // Act+ const result = await planService.deletePlan(planId, true);++ // Assert+ expect(mockPlanStore.delete).toHaveBeenCalledWith(planId);+ expect(result).toEqual({+ deleted: true,+ unremovedPaths: [{ storageName: 'Test Storage', storagePath: '/backups/delete' }],+ unremovedReason: 'The device could not be reached.',+ });});it('should throw a NotFoundError if the plan does not exist', async () => {diff --git a/backend/src/controllers/PlanController.ts b/backend/src/controllers/PlanController.tsindex 1b4b4bb..fc8e623 100644--- a/backend/src/controllers/PlanController.ts+++ b/backend/src/controllers/PlanController.ts@@ -142,10 +142,15 @@ export class PlanController {return;}const removeRemoteData = req.query.removeData === 'true';- await this.planService.deletePlan(req.params.id, removeRemoteData);+ const { unremovedPaths, unremovedReason } = await this.planService.deletePlan(+ req.params.id,+ removeRemoteData+ );res.status(200).json({success: true,message: 'Plan deleted successfully',+ unremovedPaths,+ unremovedReason,});} catch (error: unknown) {const appError = error as AppError;diff --git a/backend/src/managers/BaseBackupManager.ts b/backend/src/managers/BaseBackupManager.tsindex bd7b5d6..e68a1cc 100644--- a/backend/src/managers/BaseBackupManager.ts+++ b/backend/src/managers/BaseBackupManager.ts@@ -8,6 +8,8 @@ import {BackupVerifiedResult,PlanAddRunSettings,PlanPrune,+ PlanStoragePath,+ RemoveBackupResult,} from '../types/plans';import { BackupHandler } from './handlers/BackupHandler';import { PruneHandler } from './handlers/PruneHandler';@@ -149,44 +151,44 @@ export class BaseBackupManager extends EventEmitter {encryption: boolean;replicationStorages?: { storageName: string; storagePath: string }[];}- ): Promise<{ success: boolean; result: string }> {+ ): Promise<RemoveBackupResult> {try {// Stop all cron jobs for this backup and remove the cron scheduleawait this.cronManager.removeSchedule(planId);- let removeResult = 'Successfully Removed';+ } catch (error: any) {+ return { success: false, result: error.message };+ }- // Remove the primary storage data when necessary- if (options.storagePath && options.removeRemoteData) {- const output = await runRcloneCommand([- 'purge',- `${options.storageName}:${options.storagePath}`,- ]);- removeResult += output;- }+ let removeResult = 'Successfully Removed';+ const unremovedPaths: PlanStoragePath[] = [];+ let unremovedReason = '';- // Also remove data from replication storages- if (options.removeRemoteData && options.replicationStorages?.length) {- for (const replica of options.replicationStorages) {- try {- const output = await runRcloneCommand([- 'purge',- `${replica.storageName}:${replica.storagePath}`,- ]);- removeResult += ` | Replication ${replica.storageName}: ${output}`;- } catch (error: any) {- // Log but don't fail the entire removal if a replication storage purge fails- console.warn(- `[removeBackup] Failed to purge replication storage ${replica.storageName}:${replica.storagePath}: ${error.message}`- );- removeResult += ` | Replication ${replica.storageName} purge failed: ${error.message}`;- }- }+ // On purge failure let the user know so they can manually remove the data.+ const purge = async (storageName: string, storagePath: string, label?: string) => {+ try {+ const output = await runRcloneCommand(['purge', `${storageName}:${storagePath}`]);+ removeResult += label ? ` | ${label}: ${output}` : output;+ } catch (error: any) {+ console.warn(+ `[removeBackup] Failed to purge ${storageName}:${storagePath}: ${error.message}`+ );+ removeResult += ` | ${label || storageName} purge failed: ${error.message}`;+ unremovedPaths.push({ storageName, storagePath });+ unremovedReason = unremovedReason || error.message;}+ };- return { success: true, result: removeResult };- } catch (error: any) {- return { success: false, result: error.message };+ if (options.removeRemoteData) {+ if (options.storagePath) {+ await purge(options.storageName, options.storagePath);+ }+ for (const replica of options.replicationStorages || []) {+ if (!replica.storagePath) continue;+ await purge(replica.storageName, replica.storagePath, `Replication ${replica.storageName}`);+ }}++ return { success: true, result: removeResult, unremovedPaths, unremovedReason };}/**diff --git a/backend/src/services/PlanService.ts b/backend/src/services/PlanService.tsindex f974e57..d5551b3 100644--- a/backend/src/services/PlanService.ts+++ b/backend/src/services/PlanService.ts@@ -17,6 +17,7 @@ import {PlanLogItem,PlanNotification,PlanNotificationType,+ PlanStoragePath,} from '../types/plans';import { planLogger } from '../utils/logger';import { generateUID, normalizeStorageName } from '../utils/helpers';@@ -327,8 +328,17 @@ export class PlanService {/*** Deletes a plan and instructs the execution engine to remove its schedule and data.+ * Storage data the engine could not remove does not stop the plan being deleted: those+ * locations come back in `unremovedPaths`, with `unremovedReason` saying why.*/- public async deletePlan(planId: string, removeRemoteData: boolean): Promise<boolean> {+ public async deletePlan(+ planId: string,+ removeRemoteData: boolean+ ): Promise<{+ deleted: boolean;+ unremovedPaths: PlanStoragePath[];+ unremovedReason: string;+ }> {const plan = await this.planStore.getById(planId);if (!plan) throw new NotFoundError('Plan not found.');const storageName = plan.storage?.name || '';@@ -362,7 +372,11 @@ export class PlanService {planLogger('delete', planId).info('Plan and associated data successfully deleted.');- return deleteRes;+ return {+ deleted: deleteRes,+ unremovedPaths: deleteResult.unremovedPaths || [],+ unremovedReason: deleteResult.unremovedReason || '',+ };}/**diff --git a/backend/src/strategies/backup/BackupStrategy.ts b/backend/src/strategies/backup/BackupStrategy.tsindex 771c9d9..3ac9dc9 100644--- a/backend/src/strategies/backup/BackupStrategy.ts+++ b/backend/src/strategies/backup/BackupStrategy.ts@@ -1,5 +1,10 @@import { StrategyMethodTypes } from '../../types/strategy';-import { BackupPlanArgs, BackupVerifiedResult, PlanAddRunSettings } from '../../types/plans';+import {+ BackupPlanArgs,+ BackupVerifiedResult,+ PlanAddRunSettings,+ RemoveBackupResult,+} from '../../types/plans';import { BackupRunConfig } from '../../types/backups';export interface BackupStrategy {@@ -25,7 +30,7 @@ export interface BackupStrategy {encryption: boolean;replicationStorages?: { storageName: string; storagePath: string }[];}- ): Promise<{ success: boolean; result: string }>;+ ): Promise<RemoveBackupResult>;removeReplicationStorage(planId: string,options: {diff --git a/backend/src/types/plans.ts b/backend/src/types/plans.tsindex 4092c7e..82ebccf 100644--- a/backend/src/types/plans.ts+++ b/backend/src/types/plans.ts@@ -232,6 +232,15 @@ export interface BackupPlanArgs extends NewPlan {cronExpression: string;}+export type PlanStoragePath = { storageName: string; storagePath: string };++export type RemoveBackupResult = {+ success: boolean;+ result: string;+ unremovedPaths?: PlanStoragePath[];+ unremovedReason?: string;+};+export type PlanChildItem = Pick<Plan,'id' | 'title' | 'createdAt' | 'isActive' | 'stats' | 'method'diff --git a/frontend/src/components/Plan/PlanRemoveModal/PlanRemoveModal.tsx b/frontend/src/components/Plan/PlanRemoveModal/PlanRemoveModal.tsxindex a50506e..0d816a1 100644--- a/frontend/src/components/Plan/PlanRemoveModal/PlanRemoveModal.tsx+++ b/frontend/src/components/Plan/PlanRemoveModal/PlanRemoveModal.tsx@@ -2,6 +2,7 @@ import { useState } from 'react';import { toast } from 'react-toastify';import { useNavigate } from 'react-router';import ActionModal from '../../common/ActionModal/ActionModal';+import UnremovedPathsNotice from './UnremovedPathsNotice';import { useDeletePlan } from '../../../services/plans';import Toggle from '../../common/form/Toggle/Toggle';import classes from './PlanRemoveModal.module.scss';@@ -33,9 +34,17 @@ const PlanRemoveModal = ({ planId, taskPending, actionInProgress, close }: PlanRconsole.log('error :', error?.message);toast.error(error.message || `Error Removing Plan!`);},- onSuccess: (data: any) => {+ onSuccess: (data) => {console.log('Success :', data);- toast.success(`Removed Backup Plan Successfully!`, { autoClose: 5000 });+ if (data.unremovedPaths?.length) {+ toast.warning(<UnremovedPathsNotice paths={data.unremovedPaths} reason={data.unremovedReason} />, {+ autoClose: false,+ closeOnClick: false,+ style: { minWidth: '360px' },+ });+ } else {+ toast.success(`Removed Backup Plan Successfully!`, { autoClose: 5000 });+ }navigate('/');},},diff --git a/frontend/src/components/Plan/PlanRemoveModal/UnremovedPathsNotice.module.scss b/frontend/src/components/Plan/PlanRemoveModal/UnremovedPathsNotice.module.scssnew file mode 100644index 0000000..45510f9--- /dev/null+++ b/frontend/src/components/Plan/PlanRemoveModal/UnremovedPathsNotice.module.scss@@ -0,0 +1,51 @@+.unremovedNotice {+ strong {+ color: var(--content-title-color);+ }+ p {+ margin: 6px 0 0;+ }+}++.reason {+ font-weight: 600;+}++.paths {+ margin: 8px 0 0;+ padding: 0;+ list-style: none;+ // Keeps a long list from filling the screen inside a toast.+ max-height: 180px;+ overflow-y: auto;++ li {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 8px;+ padding: 5px 8px;+ margin-bottom: 4px;+ border-radius: 4px;+ // Neutral so it reads on both the light and dark toast themes.+ background: rgba(128, 128, 128, 0.18);+ font-family: monospace;+ font-size: 0.85em;+ word-break: break-all;++ button {+ flex-shrink: 0;+ display: flex;+ padding: 2px;+ border: 0;+ background: none;+ color: inherit;+ cursor: pointer;+ opacity: 0.6;++ &:hover {+ opacity: 1;+ }+ }+ }+}diff --git a/frontend/src/components/Plan/PlanRemoveModal/UnremovedPathsNotice.tsx b/frontend/src/components/Plan/PlanRemoveModal/UnremovedPathsNotice.tsxnew file mode 100644index 0000000..884d1f5--- /dev/null+++ b/frontend/src/components/Plan/PlanRemoveModal/UnremovedPathsNotice.tsx@@ -0,0 +1,47 @@+import { useState } from 'react';+import Icon from '../../common/Icon/Icon';+import { UnremovedStoragePath } from '../../../services/plans';+import classes from './UnremovedPathsNotice.module.scss';++interface UnremovedPathsNoticeProps {+ paths: UnremovedStoragePath[];+ reason?: string;+}++/**+ * Rendered inside a toast, so it outlives the plan page it was triggered from and keeps its+ * own copy state.+ */+const UnremovedPathsNotice = ({ paths, reason }: UnremovedPathsNoticeProps) => {+ const [copiedPath, setCopiedPath] = useState<string>('');++ const copyPath = (path: string) => {+ navigator.clipboard.writeText(path).then(+ () => setCopiedPath(path),+ () => setCopiedPath(''),+ );+ };++ return (+ <div className={classes.unremovedNotice}>+ <strong>Plan Removed</strong>+ {reason && <p className={classes.reason}>Warning: {reason}</p>}+ <p>The storage data could not be removed. You will have to remove these storage paths yourself:</p>+ <ul className={classes.paths}>+ {paths.map(({ storageName, storagePath }) => {+ const fullPath = `${storageName}:${storagePath}`;+ return (+ <li key={fullPath}>+ <span>{fullPath}</span>+ <button type="button" onClick={() => copyPath(fullPath)} title="Copy path">+ <Icon type={copiedPath === fullPath ? 'check' : 'copy'} size={13} />+ </button>+ </li>+ );+ })}+ </ul>+ </div>+ );+};++export default UnremovedPathsNotice;diff --git a/frontend/src/services/plans.ts b/frontend/src/services/plans.tsindex 9722559..f87632e 100644--- a/frontend/src/services/plans.ts+++ b/frontend/src/services/plans.ts@@ -207,7 +207,16 @@ export function useUpdatePlan() {}// Remove Plan-export async function deletePlan({ id, removeRemoteData }: { id: string; removeRemoteData: boolean }) {+export type UnremovedStoragePath = { storageName: string; storagePath: string };++export type DeletePlanResult = {+ success: boolean;+ message: string;+ unremovedPaths?: UnremovedStoragePath[];+ unremovedReason?: string;+};++export async function deletePlan({ id, removeRemoteData }: { id: string; removeRemoteData: boolean }): Promise<DeletePlanResult> {const header = new Headers({ 'Content-Type': 'application/json', Accept: 'application/json' });const res = await fetch(`${API_URL}/plans/${id}?removeData=${removeRemoteData}`, {method: 'DELETE',@@ -225,8 +234,10 @@ export function useDeletePlan() {const queryClient = useQueryClient();return useMutation({mutationFn: deletePlan,- onSuccess: (res) => {+ onSuccess: (res, variables) => {console.log('# Plan Removed! :', res);+ // Drop the deleted plan's query, or it keeps refetching a record that now 404s.+ queryClient.removeQueries({ queryKey: ['plan', variables.id], exact: true });queryClient.invalidateQueries({ queryKey: ['plans'] });},});