A modern, self-hosted backup solution for secure, encrypted backups across local and cloud storage.
feat: adds the ability to check Backup Integrity
towfiqi165999b1bd3f
diff --git a/backend/__tests__/controllers/PlanController.test.ts b/backend/__tests__/controllers/PlanController.test.tsindex 93a94df..fbebf7c 100644--- a/backend/__tests__/controllers/PlanController.test.ts+++ b/backend/__tests__/controllers/PlanController.test.ts@@ -422,4 +422,64 @@ describe('PlanController', () => {expect(mockPipe).toHaveBeenCalledWith(mockResponse);});});++ describe('checkIntegrity', () => {+ it('should return 400 if plan ID is missing', async () => {+ mockRequest.params = {};++ await planController.checkIntegrity(mockRequest as Request, mockResponse as Response);++ expect(mockStatus).toHaveBeenCalledWith(400);+ expect(mockJson).toHaveBeenCalledWith({+ success: false,+ error: 'Plan ID is required',+ });+ });++ it('should return 200 when integrity check succeeds', async () => {+ mockRequest.params = { id: 'plan-1' };+ mockPlanService.checkIntegrity.mockResolvedValue({+ success: true,+ result: { primary: 'no errors found' },+ });++ await planController.checkIntegrity(mockRequest as Request, mockResponse as Response);++ expect(mockPlanService.checkIntegrity).toHaveBeenCalledWith('plan-1');+ expect(mockStatus).toHaveBeenCalledWith(200);+ expect(mockJson).toHaveBeenCalledWith({+ success: true,+ result: { primary: 'no errors found' },+ });+ });++ it('should return 500 when integrity check result is not successful', async () => {+ mockRequest.params = { id: 'plan-1' };+ mockPlanService.checkIntegrity.mockResolvedValue({+ success: false,+ result: { primary: 'No Backup schedule found' },+ });++ await planController.checkIntegrity(mockRequest as Request, mockResponse as Response);++ expect(mockStatus).toHaveBeenCalledWith(500);+ expect(mockJson).toHaveBeenCalledWith({+ success: false,+ result: { primary: 'No Backup schedule found' },+ });+ });++ it('should return 500 if service throws an error', async () => {+ mockRequest.params = { id: 'plan-1' };+ mockPlanService.checkIntegrity.mockRejectedValue(new Error('Internal error'));++ await planController.checkIntegrity(mockRequest as Request, mockResponse as Response);++ expect(mockStatus).toHaveBeenCalledWith(500);+ expect(mockJson).toHaveBeenCalledWith({+ success: false,+ error: 'Internal Server Error',+ });+ });+ });});diff --git a/backend/__tests__/managers/BaseBackupManager.test.ts b/backend/__tests__/managers/BaseBackupManager.test.tsindex 3c36f0a..840470f 100644--- a/backend/__tests__/managers/BaseBackupManager.test.ts+++ b/backend/__tests__/managers/BaseBackupManager.test.ts@@ -68,7 +68,7 @@ jest.mock('../../src/managers/handlers/PruneHandler', () => {});jest.mock('../../src/utils/restic/helpers', () => ({- generateResticRepoPath: (name: string, p: string) => `rclone:${name}:${p}`,+ generateResticRepoPath: jest.fn((name: string, p: string) => `rclone:${name}:${p}`),}));jest.mock('../../src/jobs/JobQueue', () => ({@@ -93,9 +93,11 @@ jest.mock('../../src/services/ConfigService', () => ({import { BaseBackupManager } from '../../src/managers/BaseBackupManager';import { BackupPlanArgs } from '../../src/types/plans';import { EventEmitter } from 'events';+import { generateResticRepoPath } from '#core-backend/utils/restic/helpers';describe('BaseBackupManager', () => {let mgr: BaseBackupManager;+ let mockGenerateResticRepoPath: jest.Mock;const baseOptions: any = {id: 'plan-xyz',@@ -136,6 +138,8 @@ describe('BaseBackupManager', () => {},};+ const planId = baseOptions.id;+beforeEach(() => {jest.clearAllMocks();uidCounter = 0;@@ -181,6 +185,8 @@ describe('BaseBackupManager', () => {],});+ mockGenerateResticRepoPath = generateResticRepoPath as jest.Mock;+backupHandlerExecuteMock.mockResolvedValue('EXECUTED');backupHandlerCancelMock.mockResolvedValue(true);pruneHandlerPruneMock.mockResolvedValue({ success: true, result: 'Pruned' });@@ -862,4 +868,447 @@ describe('BaseBackupManager', () => {expect(mockJobQueue.add).toHaveBeenCalled();});});++ // -------------------------+ // Tests for checkIntegrity+ // -------------------------+ describe('checkIntegrity', () => {+ const mockSchedule = {+ type: 'backup',+ options: {+ storage: { name: 'local-storage' },+ storagePath: '/storage/backups',+ settings: {+ encryption: true,+ integrity: {+ method: '10%',+ },+ },+ },+ };++ it('should successfully check integrity with percentage method', async () => {+ // Arrange+ mockGetSchedule.mockResolvedValue([mockSchedule]);+ mockRunResticCommand.mockResolvedValue('no errors found');++ const emitSpy = jest.spyOn(mgr, 'emit');++ // Act+ const result = await mgr.checkIntegrity(planId);++ // Assert+ expect(mockGetSchedule).toHaveBeenCalledWith(planId);+ expect(mockGenerateResticRepoPath).toHaveBeenCalledWith('local-storage', '/storage/backups');+ expect(mockRunResticCommand).toHaveBeenCalledWith(+ ['check', '-r', 'rclone:local-storage:/storage/backups', '--read-data-subset', '10%'],+ { RESTIC_PASSWORD: 'secret-key' }+ );+ expect(emitSpy).toHaveBeenCalledWith('integrity_start', { planId });+ expect(emitSpy).toHaveBeenCalledWith('integrity_end', {+ planId,+ result: { primary: 'no errors found' },+ });+ expect(result).toEqual({+ success: true,+ result: { primary: 'no errors found' },+ });+ });++ it('should check integrity with full method', async () => {+ // Arrange+ const scheduleWithFullMethod = {+ ...mockSchedule,+ options: {+ ...mockSchedule.options,+ settings: {+ ...mockSchedule.options.settings,+ integrity: { method: 'full' },+ },+ },+ };++ mockGetSchedule.mockResolvedValue([scheduleWithFullMethod]);+ mockRunResticCommand.mockResolvedValue('integrity check passed');++ // Act+ const result = await mgr.checkIntegrity(planId);++ // Assert+ expect(mockRunResticCommand).toHaveBeenCalledWith(+ ['check', '-r', 'rclone:local-storage:/storage/backups', '--read-data'],+ { RESTIC_PASSWORD: 'secret-key' }+ );+ expect(result.success).toBe(true);+ });++ it('should check integrity with 5% method', async () => {+ // Arrange+ const scheduleWith5Percent = {+ ...mockSchedule,+ options: {+ ...mockSchedule.options,+ settings: {+ ...mockSchedule.options.settings,+ integrity: { method: '5%' },+ },+ },+ };++ mockGetSchedule.mockResolvedValue([scheduleWith5Percent]);+ mockRunResticCommand.mockResolvedValue('check complete');++ // Act+ await mgr.checkIntegrity(planId);++ // Assert+ expect(mockRunResticCommand).toHaveBeenCalledWith(+ ['check', '-r', 'rclone:local-storage:/storage/backups', '--read-data-subset', '5%'],+ { RESTIC_PASSWORD: 'secret-key' }+ );+ });++ it('should check integrity with 25% method', async () => {+ // Arrange+ const scheduleWith25Percent = {+ ...mockSchedule,+ options: {+ ...mockSchedule.options,+ settings: {+ ...mockSchedule.options.settings,+ integrity: { method: '25%' },+ },+ },+ };++ mockGetSchedule.mockResolvedValue([scheduleWith25Percent]);+ mockRunResticCommand.mockResolvedValue('check complete');++ // Act+ await mgr.checkIntegrity(planId);++ // Assert+ expect(mockRunResticCommand).toHaveBeenCalledWith(+ ['check', '-r', 'rclone:local-storage:/storage/backups', '--read-data-subset', '25%'],+ { RESTIC_PASSWORD: 'secret-key' }+ );+ });++ it('should check integrity with 50% method', async () => {+ // Arrange+ const scheduleWith50Percent = {+ ...mockSchedule,+ options: {+ ...mockSchedule.options,+ settings: {+ ...mockSchedule.options.settings,+ integrity: { method: '50%' },+ },+ },+ };++ mockGetSchedule.mockResolvedValue([scheduleWith50Percent]);+ mockRunResticCommand.mockResolvedValue('check complete');++ // Act+ await mgr.checkIntegrity(planId);++ // Assert+ expect(mockRunResticCommand).toHaveBeenCalledWith(+ ['check', '-r', 'rclone:local-storage:/storage/backups', '--read-data-subset', '50%'],+ { RESTIC_PASSWORD: 'secret-key' }+ );+ });++ it('should check integrity without method specified', async () => {+ // Arrange+ const scheduleWithoutMethod = {+ ...mockSchedule,+ options: {+ ...mockSchedule.options,+ settings: {+ encryption: true,+ },+ },+ };++ mockGetSchedule.mockResolvedValue([scheduleWithoutMethod]);+ mockRunResticCommand.mockResolvedValue('check complete');++ // Act+ await mgr.checkIntegrity(planId);++ // Assert - default method is '5%'+ expect(mockRunResticCommand).toHaveBeenCalledWith(+ ['check', '-r', 'rclone:local-storage:/storage/backups', '--read-data-subset', '5%'],+ { RESTIC_PASSWORD: 'secret-key' }+ );+ });++ it('should use empty password when encryption is false', async () => {+ // Arrange+ const scheduleNoEncryption = {+ ...mockSchedule,+ options: {+ ...mockSchedule.options,+ settings: {+ encryption: false,+ },+ },+ };++ mockGetSchedule.mockResolvedValue([scheduleNoEncryption]);+ mockRunResticCommand.mockResolvedValue('check complete');++ // Act+ await mgr.checkIntegrity(planId);++ // Assert - default method is '5%'+ expect(mockRunResticCommand).toHaveBeenCalledWith(+ ['check', '-r', 'rclone:local-storage:/storage/backups', '--read-data-subset', '5%'],+ { RESTIC_PASSWORD: '' }+ );+ });++ it('should return failure when no storage name is provided', async () => {+ // Arrange+ const scheduleNoStorage = {+ ...mockSchedule,+ options: {+ ...mockSchedule.options,+ storage: {},+ },+ };++ mockGetSchedule.mockResolvedValue([scheduleNoStorage]);++ // Act+ const result = await mgr.checkIntegrity(planId);++ // Assert+ expect(result).toEqual({+ success: false,+ result: { primary: 'No storage name found' },+ });+ expect(mockRunResticCommand).not.toHaveBeenCalled();+ });++ it('should return failure when no backup schedule is found', async () => {+ // Arrange+ mockGetSchedule.mockResolvedValue([]);++ // Act+ const result = await mgr.checkIntegrity(planId);++ // Assert+ expect(result).toEqual({+ success: false,+ result: { primary: 'No Backup schedule found' },+ });+ expect(mockRunResticCommand).not.toHaveBeenCalled();+ });++ it('should return failure when schedules is null', async () => {+ // Arrange+ mockGetSchedule.mockResolvedValue(null);++ // Act+ const result = await mgr.checkIntegrity(planId);++ // Assert+ expect(result).toEqual({+ success: false,+ result: { primary: 'No Backup schedule found' },+ });+ });++ it('should handle errors during integrity check and emit event', async () => {+ // Arrange+ const errorMessage = 'Repository corrupted';+ mockGetSchedule.mockResolvedValue([mockSchedule]);+ mockRunResticCommand.mockRejectedValue(new Error(errorMessage));++ const emitSpy = jest.spyOn(mgr, 'emit');++ // Act+ const result = await mgr.checkIntegrity(planId);++ // Assert+ expect(emitSpy).toHaveBeenCalledWith('integrity_start', { planId });+ expect(emitSpy).toHaveBeenCalledWith('integrity_end', {+ planId,+ result: { primary: errorMessage },+ });+ expect(result).toEqual({+ success: true,+ result: { primary: errorMessage },+ });+ });++ it('should handle non-Error exceptions during integrity check', async () => {+ // Arrange+ mockGetSchedule.mockResolvedValue([mockSchedule]);+ mockRunResticCommand.mockRejectedValue('String error');++ const emitSpy = jest.spyOn(mgr, 'emit');++ // Act+ const result = await mgr.checkIntegrity(planId);++ // Assert+ expect(emitSpy).toHaveBeenCalledWith('integrity_end', {+ planId,+ result: { primary: 'Unknown Error' },+ });+ expect(result).toEqual({+ success: true,+ result: { primary: 'Unknown Error' },+ });+ });++ it('should check integrity for primary and replication mirror storages', async () => {+ // Arrange+ const scheduleWithMirrors = {+ ...mockSchedule,+ options: {+ ...mockSchedule.options,+ settings: {+ ...mockSchedule.options.settings,+ replication: {+ enabled: true,+ storages: [+ {+ replicationId: 'rep-001',+ storageId: 'mirror-storage-1',+ storageName: 'Mirror S3',+ storagePath: '/mirror/path',+ },+ ],+ },+ },+ },+ };++ mockGetSchedule.mockResolvedValue([scheduleWithMirrors]);+ mockGenerateResticRepoPath+ .mockReturnValueOnce('/storage/local-storage') // primary+ .mockReturnValueOnce('Mirror S3:/mirror/path'); // mirror+ mockRunResticCommand+ .mockResolvedValueOnce('no errors found') // primary check+ .mockResolvedValueOnce('no errors found'); // mirror check++ const emitSpy = jest.spyOn(mgr, 'emit');++ // Act+ const result = await mgr.checkIntegrity(planId);++ // Assert+ expect(mockRunResticCommand).toHaveBeenCalledTimes(2);+ expect(mockGenerateResticRepoPath).toHaveBeenCalledTimes(2);+ expect(emitSpy).toHaveBeenCalledWith('integrity_end', {+ planId,+ result: {+ 'primary': 'no errors found',+ 'mirror_mirror-storage-1': 'no errors found',+ },+ });+ expect(result).toEqual({+ success: true,+ result: {+ 'primary': 'no errors found',+ 'mirror_mirror-storage-1': 'no errors found',+ },+ });+ });++ it('should handle mirror storage failure while primary succeeds', async () => {+ // Arrange+ const scheduleWithMirrors = {+ ...mockSchedule,+ options: {+ ...mockSchedule.options,+ settings: {+ ...mockSchedule.options.settings,+ replication: {+ enabled: true,+ storages: [+ {+ replicationId: 'rep-001',+ storageId: 'mirror-storage-1',+ storageName: 'Mirror S3',+ storagePath: '/mirror/path',+ },+ ],+ },+ },+ },+ };++ mockGetSchedule.mockResolvedValue([scheduleWithMirrors]);+ mockGenerateResticRepoPath+ .mockReturnValueOnce('/storage/local-storage')+ .mockReturnValueOnce('Mirror S3:/mirror/path');+ mockRunResticCommand+ .mockResolvedValueOnce('no errors found')+ .mockRejectedValueOnce(new Error('Mirror repository corrupted'));++ const emitSpy = jest.spyOn(mgr, 'emit');++ // Act+ const result = await mgr.checkIntegrity(planId);++ // Assert+ expect(result).toEqual({+ success: true,+ result: {+ 'primary': 'no errors found',+ 'mirror_mirror-storage-1': 'Mirror repository corrupted',+ },+ });+ expect(emitSpy).toHaveBeenCalledWith('integrity_end', {+ planId,+ result: {+ 'primary': 'no errors found',+ 'mirror_mirror-storage-1': 'Mirror repository corrupted',+ },+ });+ });++ it('should return failure when mirror storage has no storage name', async () => {+ // Arrange+ const scheduleWithBadMirror = {+ ...mockSchedule,+ options: {+ ...mockSchedule.options,+ settings: {+ ...mockSchedule.options.settings,+ replication: {+ enabled: true,+ storages: [+ {+ replicationId: 'rep-001',+ storageId: 'mirror-storage-1',+ storageName: '',+ storagePath: '/mirror/path',+ },+ ],+ },+ },+ },+ };++ mockGetSchedule.mockResolvedValue([scheduleWithBadMirror]);+ mockRunResticCommand.mockResolvedValue('no errors found');++ // Act+ const result = await mgr.checkIntegrity(planId);++ // Assert - primary succeeds, but mirror has no storage name. The code checks primary first.+ // Since primary has a storage name, it runs. Then the mirror has no storageName → returns failure.+ expect(result).toEqual({+ success: false,+ result: { 'mirror_mirror-storage-1': 'No storage name found' },+ });+ });+ });});diff --git a/backend/__tests__/routes/plans.test.ts b/backend/__tests__/routes/plans.test.tsindex 1533071..ea4a0cd 100644--- a/backend/__tests__/routes/plans.test.ts+++ b/backend/__tests__/routes/plans.test.ts@@ -60,6 +60,8 @@ describe('Plan Routes', () => {pauseBackup: jest.fn(),pruneBackups: jest.fn(),unlockRepo: jest.fn(),+ checkIntegrity: jest.fn(),+ deleteReplicationStorage: jest.fn(),} as any;planController = new PlanController(mockPlanService);@@ -293,4 +295,37 @@ describe('Plan Routes', () => {expect(mockPlanService.unlockRepo).toHaveBeenCalledWith('plan-1');});});++ describe('POST /api/plans/:id/action/checkintegrity', () => {+ it('should return 401 if not authenticated', async () => {+ setupAuthMock(false);++ const response = await request(app).post('/api/plans/plan-1/action/checkintegrity');++ expect(response.status).toBe(401);+ });++ it('should check integrity for a plan when authenticated', async () => {+ mockPlanService.checkIntegrity.mockResolvedValue({+ success: true,+ result: { primary: 'no errors found' },+ });++ const response = await request(app).post('/api/plans/plan-1/action/checkintegrity');++ expect(response.status).toBe(200);+ expect(mockPlanService.checkIntegrity).toHaveBeenCalledWith('plan-1');+ });++ it('should return 500 when integrity check fails', async () => {+ mockPlanService.checkIntegrity.mockResolvedValue({+ success: false,+ result: { primary: 'No Backup schedule found' },+ });++ const response = await request(app).post('/api/plans/plan-1/action/checkintegrity');++ expect(response.status).toBe(500);+ });+ });});diff --git a/backend/__tests__/services/PlanService.test.ts b/backend/__tests__/services/PlanService.test.tsindex 6add4d8..18f053e 100644--- a/backend/__tests__/services/PlanService.test.ts+++ b/backend/__tests__/services/PlanService.test.ts@@ -853,4 +853,64 @@ describe('PlanService', () => {await expect(privateMethodCall()).rejects.toHaveProperty('statusCode', 404);});});++ // --------------------------------+ // Tests for checking integrity+ // --------------------------------++ describe('checkIntegrity', () => {+ const planId = 'plan-to-check';+ const mockPlan = { id: planId, sourceId: 'main' } as any;++ it('should successfully call checkIntegrity on the strategy', async () => {+ // Arrange+ mockPlanStore.getById.mockResolvedValue(mockPlan);+ mockStrategy.checkIntegrity = jest+ .fn()+ .mockResolvedValue({ success: true, result: { primary: 'no errors found' } });++ // Act+ const result = await planService.checkIntegrity(planId);++ // Assert+ expect(mockPlanStore.getById).toHaveBeenCalledWith(planId);+ expect(mockStrategy.checkIntegrity).toHaveBeenCalledWith(planId);+ expect(result).toEqual({ success: true, result: { primary: 'no errors found' } });+ });++ it('should throw an error if the plan does not exist', async () => {+ // Arrange+ mockPlanStore.getById.mockResolvedValue(null);++ // Act & Assert+ await expect(planService.checkIntegrity(planId)).rejects.toThrow();+ });++ it('should throw an AppError if the strategy throws', async () => {+ // Arrange+ mockPlanStore.getById.mockResolvedValue(mockPlan);+ mockStrategy.checkIntegrity = jest.fn().mockRejectedValue(new Error('Strategy check failed'));++ // Act & Assert+ await expect(planService.checkIntegrity(planId)).rejects.toThrow();+ });++ it('should propagate the result when strategy returns failure', async () => {+ // Arrange+ mockPlanStore.getById.mockResolvedValue(mockPlan);+ mockStrategy.checkIntegrity = jest.fn().mockResolvedValue({+ success: false,+ result: { primary: 'No Backup schedule found' },+ });++ // Act+ const result = await planService.checkIntegrity(planId);++ // Assert+ expect(result).toEqual({+ success: false,+ result: { primary: 'No Backup schedule found' },+ });+ });+ });});diff --git a/backend/src/controllers/PlanController.ts b/backend/src/controllers/PlanController.tsindex a16cc0d..50dda4b 100644--- a/backend/src/controllers/PlanController.ts+++ b/backend/src/controllers/PlanController.ts@@ -342,4 +342,26 @@ export class PlanController {});}}++ async checkIntegrity(req: Request, res: Response): Promise<void> {+ if (!req.params.id) {+ res.status(400).json({+ success: false,+ error: 'Plan ID is required',+ });+ return;+ }++ try {+ const result = await this.planService.checkIntegrity(req.params.id);+ res.status(result.success ? 200 : 500).json(result);+ } catch (error) {+ console.log('[checkIntegrity] error :', error);+ res.status(500).json({+ success: false,+ error: 'Internal Server Error',+ });+ return;+ }+ }}diff --git a/backend/src/managers/BaseBackupManager.ts b/backend/src/managers/BaseBackupManager.tsindex 33f0806..21668d0 100644--- a/backend/src/managers/BaseBackupManager.ts+++ b/backend/src/managers/BaseBackupManager.ts@@ -534,7 +534,86 @@ export class BaseBackupManager extends EventEmitter {}}- testFunc() {- console.log('BaseBackupManager testFunc called');+ async checkIntegrity(+ planId: string+ ): Promise<{ success: boolean; result: Record<string, string | null> }> {+ const schedules = await this.cronManager.getSchedule(planId);+ const backupSchedule = schedules?.find(s => s.type === 'backup');+ if (backupSchedule) {+ this.emit('integrity_start', { planId: planId });+ const { storage, storagePath, settings } = backupSchedule?.options as Record<string, any>;+ const repSettings = settings?.replication;+ const hasMirrors =+ repSettings?.enabled && repSettings.storages && repSettings.storages.length > 0;+ const replicationStorages = hasMirrors ? repSettings.storages : [];+ const allStorages =+ replicationStorages.length > 0+ ? [+ { storageName: storage.name, storagePath, storageId: storage.id },+ ...replicationStorages,+ ]+ : [{ storageName: storage.name, storagePath, storageId: storage.id }];++ const errorMsg: Record<string, string | null> = { primary: null } as Record<+ string,+ string | null+ >;+ const resultObj: Record<string, string | null> = { primary: null } as Record<+ string,+ string | null+ >;+ for (const theStorage of allStorages) {+ const index =+ theStorage.storageId === storage.id ? 'primary' : 'mirror_' + theStorage.storageId;+ errorMsg[index] = null;+ resultObj[index] = null;++ const resticArgs = ['check'];+ const repoPassword = settings.encryption+ ? (configService.config.ENCRYPTION_KEY as string)+ : '';++ if (theStorage.storageName) {+ const repoPath = generateResticRepoPath(+ theStorage.storageName,+ theStorage.storagePath || ''+ );+ resticArgs.push('-r', repoPath);+ } else {+ return { success: false, result: { [index]: 'No storage name found' } };+ }++ // Read Method+ const method = settings.integrity?.method || '5%';+ if (['5%', '10%', '25%', '50%'].includes(method)) {+ resticArgs.push('--read-data-subset', method);+ }+ if (method === 'full') {+ resticArgs.push('--read-data');+ }++ // resticArgs.push('--json');+ try {+ const checkRes = await runResticCommand(resticArgs, { RESTIC_PASSWORD: repoPassword });+ resultObj[index] = checkRes;+ } catch (error: any) {+ const errMsg = (error instanceof Error && error.message) || 'Unknown Error';+ errorMsg[index] = errMsg;+ resultObj[index] = errMsg;+ }+ }++ this.emit('integrity_end', { planId: planId, result: resultObj });+ return {+ success: true,+ result: resultObj,+ };+ }++ this.emit('integrity_failed', {+ planId: planId,+ result: { primary: 'No backup schedule found' },+ });+ return { success: false, result: { primary: 'No Backup schedule found' } };}}diff --git a/backend/src/routes/plans.ts b/backend/src/routes/plans.tsindex aed79ad..d06fea2 100644--- a/backend/src/routes/plans.ts+++ b/backend/src/routes/plans.ts@@ -16,6 +16,7 @@ export function createPlanRouter(controller: PlanController, router: Router = Rorouter.post('/:id/action/pause', authM, controller.pauseBackup.bind(controller));router.post('/:id/action/prune', authM, controller.pruneBackup.bind(controller));router.post('/:id/action/unlock', authM, controller.unlockRepo.bind(controller));+ router.post('/:id/action/checkintegrity', authM, controller.checkIntegrity.bind(controller));router.post('/:id/action/delete-replication-storage',authM,diff --git a/backend/src/services/PlanService.ts b/backend/src/services/PlanService.tsindex 638fd4b..d5d476c 100644--- a/backend/src/services/PlanService.ts+++ b/backend/src/services/PlanService.ts@@ -97,7 +97,7 @@ export class PlanService {throw new NotFoundError('Source device not found');}const isRemote = sourceId !== 'main';- const targetOS = isRemote ? device.os ?? undefined : undefined;+ const targetOS = isRemote ? (device.os ?? undefined) : undefined;const theStoragePath = sanitizeStoragePath(storagePath, planStorage.type, targetOS);let newPlanData: NewPlan = {@@ -337,6 +337,32 @@ export class PlanService {planLogger('update', planId).info('Plan resumed.');}+ /**+ * Checks the integrity of a backup plan's repository.+ * This can be a long-running operation, so it's designed to be called asynchronously and returns progress updates via events.+ */++ async checkIntegrity(planId: string): Promise<{ success: boolean; result: Record<string, any> }> {+ try {+ const plan = await this.planStore.getById(planId);+ if (!plan) {+ throw new NotFoundError('Plan not found');+ }+ try {+ const planID = plan.id;+ const strategy = this.getStrategy(plan);+ const result = await strategy.checkIntegrity(planID);+ return result;+ } catch (error: any) {+ console.log('[checkIntegrity] error :', error);+ throw new AppError(500, error?.message || 'Internal Server Error');+ }+ } catch (error: any) {+ console.log('[checkIntegrity] error :', error);+ throw new AppError(500, error?.message || 'Internal Server Error');+ }+ }+/*** Removes a replication storage from a plan's replication settings.* Optionally purges the replicated data from the remote storage.diff --git a/backend/src/services/events/BackupEventService.ts b/backend/src/services/events/BackupEventService.tsindex 4df4e3d..ef7d6cb 100644--- a/backend/src/services/events/BackupEventService.ts+++ b/backend/src/services/events/BackupEventService.ts@@ -18,6 +18,9 @@ import {// BackupProgressEvent,BackupStatUpdateEvent,} from '../../types/events';+import { generateResticRepoPath } from '../../utils/restic/helpers';+import { BackupVerifiedResult, PlanReplicationStorage, PlanStorageItem } from '../../types/plans';+import { handleResticCheckResult } from '../../utils/restic/restic';export class BackupEventService {protected backupNotification: BackupNotification;@@ -407,4 +410,95 @@ export class BackupEventService {);}}++ async onIntegrityStart(data: { planId: string }) {+ console.log('onIntegrityStart :', data);+ const startedAt = new Date().getTime();+ try {+ await this.planStore.update(data.planId, {+ verified: {+ status: 'running',+ startedAt,+ endedAt: null,+ hasError: false,+ },+ });+ planLogger('integrity_check', data.planId).info(`Started Integrity Check for Backup Plan.`);+ } catch (error: any) {+ planLogger('integrity_check', data.planId).error(+ `Error starting Integrity Check for Backup Plan. Reason : ${+ error?.message.toString() || 'Unknown Error'+ }`+ );+ }+ }++ async onIntegrityEnd(data: { planId: string; result: Record<string, string | null> }) {+ console.log('onIntegrityEnd :', data);+ const endedAt = new Date().getTime();+ try {+ const thePlan = await this.planStore.getById(data.planId);+ if (thePlan && thePlan.storage?.name && thePlan.device?.id) {+ const parsedResult: Record<string, BackupVerifiedResult> = {};+ let hasIntegrityIssue = false;++ Object.keys(data.result).forEach(async key => {+ const theStorage =+ key === 'primary'+ ? thePlan.storage+ : thePlan.settings.replication?.storages?.find(+ m => m.storageId === key.replace('mirror_', '')+ );+ const storageName =+ key === 'primary'+ ? (theStorage as PlanStorageItem)?.name+ : (theStorage as PlanReplicationStorage)?.storageName || key;+ const storagePath =+ key === 'primary'+ ? thePlan.storagePath+ : (theStorage as PlanReplicationStorage)?.storagePath || '';+ const repoPath = generateResticRepoPath(storageName, storagePath || '');+ const checkResult = handleResticCheckResult(data.result[key] || '', {+ repo: repoPath,+ device: `${thePlan.device?.name}${thePlan.device?.id !== 'main' && thePlan.device?.hostname ? ` (${thePlan.device.hostname})` : ''}`,+ });+ parsedResult[key] = checkResult;+ if (checkResult.hasError) {+ hasIntegrityIssue = true;+ }+ });++ await this.planStore.update(data.planId, {+ verified: {+ status: 'completed',+ startedAt: thePlan.verified?.startedAt || endedAt,+ result: parsedResult as any,+ hasError: hasIntegrityIssue,+ endedAt,+ },+ });+ planLogger('integrity_check', data.planId).info(+ `Completed Integrity Check for Backup Plan.`+ );+ } else {+ planLogger('integrity_check', data.planId).error(`Backup Plan not found.`);+ }+ } catch (error: any) {+ planLogger('integrity_check', data.planId).error(+ `Error completing Integrity Check for Backup Plan. Reason : ${+ error?.message || 'Unknown Error'+ }`+ );+ }+ }++ async onIntegrityFailed(data: { planId: string; error: string }) {+ console.log('onIntegrityFailed :', data);+ const thePlan = await this.planStore.getById(data.planId);+ if (thePlan && thePlan.storage?.name && thePlan.device?.id) {+ planLogger('integrity_check', data.planId).error(`Failed Integrity Check for Backup Plan.`);+ } else {+ planLogger('integrity_check', data.planId).error(`Backup Plan not found.`);+ }+ }}diff --git a/backend/src/services/listeners/BackupEventListener.ts b/backend/src/services/listeners/BackupEventListener.tsindex a2a7603..75358d7 100644--- a/backend/src/services/listeners/BackupEventListener.ts+++ b/backend/src/services/listeners/BackupEventListener.ts@@ -61,6 +61,18 @@ export class BackupEventListener {(event: BackupReplicationMirrorSizeUpdateEvent) => this.onMirrorSizesUpdate(event));this.localAgent.on('pruneEnd', (event: PruneEndEvent) => this.onPruneEnd(event));++ this.localAgent.on('integrity_start', (event: { planId: string }) =>+ this.onIntegrityStart(event)+ );+ this.localAgent.on(+ 'integrity_end',+ (event: { planId: string; result: Record<string, string | null> }) =>+ this.onIntegrityEnd(event)+ );+ jobProcessor.on('integrity_failed', (event: any) => {+ this.onIntegrityCheckFailure(event);+ });}protected async onBackupStart(data: BackupStartEvent): Promise<void> {@@ -114,17 +126,18 @@ export class BackupEventListener {await this.backupEventService.onPruneEnd(data);}- /**- * Called after a job has permanently failed. Implemented in the PRO version.- * @param planId - The ID of the plan that failed.- * @param backupId - The ID of the backup that failed.- * @param error - The error that caused the failure.+ async onIntegrityStart(data: { planId: string }) {+ console.log('onIntegrityStart :', data);+ await this.backupEventService.onIntegrityStart(data);+ }- * @protected- */- protected async afterPermanentFailure(- planId: string,- backupId: string,- error: string- ): Promise<void> {}+ async onIntegrityEnd(data: { planId: string; result: Record<string, string | null> }) {+ console.log('onIntegrityEnd :', data);+ await this.backupEventService.onIntegrityEnd(data);+ }++ async onIntegrityCheckFailure(data: { planId: string; error: string }) {+ console.log('onIntegrityCheckFailure :', data);+ await this.backupEventService.onIntegrityFailed(data);+ }}diff --git a/backend/src/strategies/backup/BackupStrategy.ts b/backend/src/strategies/backup/BackupStrategy.tsindex 3e17fc3..dc668a4 100644--- a/backend/src/strategies/backup/BackupStrategy.ts+++ b/backend/src/strategies/backup/BackupStrategy.ts@@ -52,6 +52,7 @@ export interface BackupStrategy {storageId: string,newStorageName: string): Promise<{ success: boolean; result: string }>;+ checkIntegrity(planId: string): Promise<{ success: boolean; result: any }>;}export type BackupStrategyTypes = StrategyMethodTypes<BackupStrategy>;diff --git a/backend/src/strategies/backup/LocalStrategy.ts b/backend/src/strategies/backup/LocalStrategy.tsindex 30b6c91..6d69733 100644--- a/backend/src/strategies/backup/LocalStrategy.ts+++ b/backend/src/strategies/backup/LocalStrategy.ts@@ -79,6 +79,10 @@ export class LocalStrategy implements BackupStrategy {return await this.localAgent.updatePlanStorageName(storageId, newStorageName);}+ async checkIntegrity(planId: string): Promise<{ success: boolean; result: any }> {+ return await this.localAgent.checkIntegrity(planId);+ }+async getBackupProgress(planId: string, backupId: string) {try {const filename = `backup-${backupId}.json`;diff --git a/backend/src/strategies/backup/RemoteStrategy.ts b/backend/src/strategies/backup/RemoteStrategy.tsindex 15a59ee..8d19b11 100644--- a/backend/src/strategies/backup/RemoteStrategy.ts+++ b/backend/src/strategies/backup/RemoteStrategy.ts@@ -68,6 +68,10 @@ export class RemoteStrategy implements BackupStrategy {return await this.publishCommand('UPDATE_PLAN_STORAGE_NAME', { storageId, newStorageName });}+ async checkIntegrity(planId: string): Promise<{ success: boolean; result: any }> {+ return await this.publishCommand('CHECK_INTEGRITY', { planId });+ }+publishCommand(action: string, payload: any): Promise<{ success: boolean; result: any }> {return new Promise((resolve, reject) => {resolve({ success: true, result: null });diff --git a/backend/src/utils/restic/restic.ts b/backend/src/utils/restic/restic.tsindex e9e623b..3865d28 100644--- a/backend/src/utils/restic/restic.ts+++ b/backend/src/utils/restic/restic.ts@@ -8,6 +8,7 @@ import { appPaths } from '../AppPaths';import { generateResticRepoPath } from './helpers';import { configService } from '../../services/ConfigService';import { buildResticEnvFromSettings, buildRcloneEnvFromSettings } from '../globalSettings';+import { BackupVerifiedResult } from '../../types/plans';export function runResticCommand(args: string[],@@ -228,3 +229,54 @@ export async function getSnapshotByTag(};}}++export function handleResticCheckResult(+ output: string,+ { repo, device }: { repo: string; device: string }+): BackupVerifiedResult {+ let message = '';+ let hasError = true;+ let fix = '';+ const logs: string[] = [];++ if (output.includes('The repository contains damaged pack files')) {+ message = 'A Pack file of a snapshot was damaged.';+ const packFileID = output.match(/pack ([a-f0-9]{64}):/)?.[1];+ fix = `Login to your Machine ${device}.+ Run this command to first to try and repair the pack file:+ \`restic repair -r ${repo} packs ${packFileID}\`+ Then run this command to fix the snapshots if they are still damaged:+ \`restic repair -r ${repo} snapshots --forget \`+ When asked for the password, use the Pluton Encryption key.+ `;+ }+ if (output.includes('The repository index is damaged')) {+ message = 'The repository index is damaged.';+ fix = `Login to your Machine ${device}.+ Run this command:+ \`restic repair index -r ${repo}\`+ When asked for the password, use the Pluton Encryption key.+ `;+ }+ if (output.includes('ciphertext verification failed')) {+ message = 'Ciphertext verification failed.';+ fix =+ 'Ciphertext verification issue is hard to fix. Please ask for help in the Restic forum or their IRC channel. These errors are often caused by hardware problems which must be investigated and fixed. Otherwise, the backup will be damaged again and again.';+ }+ if (output.includes('failed to authorize account')) {+ message = 'Storage Authorization failed.';+ hasError = false;+ }+ if (output.includes('no errors were found')) {+ message = 'No Issue Detected.';+ hasError = false;+ }++ output.split('\n').forEach((line: string) => {+ if (line.trim() !== '') {+ logs.push(line);+ }+ });++ return { message, logs, hasError, fix };+}diff --git a/frontend/src/components/Plan/PlanIntegrity/PlanIntegrity.module.scss b/frontend/src/components/Plan/PlanIntegrity/PlanIntegrity.module.scssnew file mode 100644index 0000000..7dc9aae--- /dev/null+++ b/frontend/src/components/Plan/PlanIntegrity/PlanIntegrity.module.scss@@ -0,0 +1,110 @@+.integrityMessage {+ :global(.label) {+ font-size: 0.9em;+ border-radius: 6px;+ padding: 10px;+ }+}++.fixSuggestion {+ border-radius: 6px;+ border: 1px solid var(--line-color);+ box-sizing: border-box;+ margin: 0 5px;+ margin-top: 12px;+ h4 {+ padding: 12px;+ font-weight: 600;+ margin: 0;+ border-bottom: 1px solid var(--line-color);+ }+ .fixSuggestionContent {+ padding: 0 12px;+ font-size: 0.9em;+ code {+ background: var(--line-color);+ padding: 5px;+ border-radius: 4px;+ display: block;+ font-family: monospace;+ }+ }+}++.integrityLogs {+ border-radius: 6px;+ border: 1px solid var(--line-color);+ box-sizing: border-box;+ margin: 0 5px;+ margin-top: 12px;++ .integrityLogsHeader {+ padding: 12px;+ font-weight: 600;+ border-bottom: 1px solid var(--line-color);+ display: flex;+ justify-content: space-between;+ & > div:nth-child(2) {+ font-weight: normal;+ color: var(--content-text-color-light);+ }+ }+ .integrityLogMessages {+ font-family: monospace;+ background-color: var(--background-color);+ line-height: 1.3rem;+ max-height: 300px;+ overflow: auto;+ span {+ display: block;+ padding: 4px 12px;+ line-break: anywhere;+ &:nth-child(even) {+ background: rgba(0, 0, 0, 0.03);+ }+ }+ }+}++.integrityResult {+ &.withReplications {+ border: 1px solid var(--line-color);+ border-radius: 6px;+ .replicationResult {+ h4 {+ margin: 0;+ padding: 12px;+ cursor: pointer;+ display: flex;+ justify-content: space-between;+ border-bottom: 1px solid var(--line-color);+ i {+ background-color: var(--background-color);+ color: var(--content-text-color-light);+ padding: 1px 12px;+ border-radius: 20px;+ font-size: 0.7rem;+ font-weight: normal;+ font-style: normal;+ display: inline-block;+ margin-left: 6px;+ }+ img {+ max-width: 14px;+ vertical-align: middle;+ margin-right: 6px;+ }+ }+ .replicationResultContent {+ padding: 12px;+ border-bottom: 1px solid var(--line-color);+ }+ }+ }+}++@media only screen and (max-width: 768px) {+ .integrityLogs .integrityLogsHeader {+ flex-direction: column;+ }+}diff --git a/frontend/src/components/Plan/PlanIntegrity/PlanIntegrity.tsx b/frontend/src/components/Plan/PlanIntegrity/PlanIntegrity.tsxnew file mode 100644index 0000000..3a83251--- /dev/null+++ b/frontend/src/components/Plan/PlanIntegrity/PlanIntegrity.tsx@@ -0,0 +1,186 @@+import { useState } from 'react';+import { ActionModal, Icon } from '@plutonhq/core-frontend/components';+import classes from './PlanIntegrity.module.scss';+import { PlanVerifiedResult, Plan, PlanReplicationStorage } from '@plutonhq/core-frontend/@types/plans';+import { formatDateTime, timeAgo } from '@plutonhq/core-frontend/utils';+import { useCheckPlanIntegrity } from '../../../services';++interface PlanIntegrityProps {+ planId: string;+ taskPending: boolean;+ verificationData: Plan['verified'];+ storage: { name: string; type: string; id: string };+ replicationStorages: PlanReplicationStorage[];+ onClose: () => void;+}++const PlanIntegrity = ({ planId, taskPending, verificationData, storage, replicationStorages = [], onClose }: PlanIntegrityProps) => {+ const [showContent, setShowContent] = useState('primary');+ const integrityCheckMutation = useCheckPlanIntegrity();++ const integrityResultLoaded = verificationData && verificationData?.result;+ const hasReplications = replicationStorages && replicationStorages.length > 0;++ const getBackupResultByStorage = (storageType: string): PlanVerifiedResult | null => {+ if (!verificationData?.result) return null;++ const replicationResult = verificationData.result as Record<string, PlanVerifiedResult>;+ return replicationResult[storageType] ?? null;+ };++ const renderLogs = (storageType: string) => {+ if (integrityCheckMutation.isPending) return null;+ const backupResData = getBackupResultByStorage(storageType);+ const messages = backupResData?.logs;+ if (!messages?.length) return null;++ return (+ <div className={classes.integrityLogs}>+ <div className={classes.integrityLogsHeader}>+ <div>Integrity Check Output Logs</div>+ <div title={formatDateTime(verificationData.endedAt || verificationData.startedAt)}>+ <Icon type="clock" size={14} /> {timeAgo(new Date(verificationData.endedAt || verificationData.startedAt))}+ </div>+ </div>+ <div className={classes.integrityLogMessages}>+ {messages.map((message, index) => (+ <span key={index}>{message}</span>+ ))}+ </div>+ </div>+ );+ };++ const renderBackupFixSuggestion = (storageType: string) => {+ if (!integrityResultLoaded) return null;+ if (integrityCheckMutation.isPending) return null;+ const backupResData = getBackupResultByStorage(storageType);+ if (!backupResData?.hasError) return null;++ return (+ <div className={classes.fixSuggestion}>+ <h4>Fix Suggestion</h4>+ <div className={classes.fixSuggestionContent}>+ {backupResData.fix &&+ backupResData.fix+ .split('\n')+ .map((line, index) => <p key={index}>{line.includes('`') ? <code>{line.replace(/`/g, '')}</code> : line}</p>)}+ {!backupResData.fix && <p>No Suggestion for this issue.</p>}+ <p>+ Learn more about fixing restic repo issues{' '}+ <a+ href="https://restic.readthedocs.io/en/latest/077_troubleshooting.html#find-out-what-is-damaged"+ target="_blank"+ rel="noreferrer"+ >+ here.+ </a>+ </p>+ </div>+ </div>+ );+ };++ const renderBackupStatus = (storageType: string) => {+ if (!integrityResultLoaded) return null;+ if (integrityCheckMutation.isPending) return null;+ const backupResData = getBackupResultByStorage(storageType);+ const backupHasError = backupResData?.hasError;+ const backupMessage = backupResData?.message;++ if (!backupHasError && backupMessage?.includes('No Issue Detected')) {+ return <div className="label success">🥳 Yoohoo! No Corruption or Bit rot found. Your backup snapshots are completely restorable.</div>;+ }++ return <div className="label error">⛔ Error Found. {backupMessage}</div>;+ };++ const renderResultWithReplications = () => {+ return (+ <div className={`${classes.integrityResult} ${classes.withReplications}`}>+ {verificationData &&+ Object.entries(verificationData.result as Record<string, PlanVerifiedResult>).map(([storageType]) => {+ let theStorage = storage;+ if (storageType !== 'primary') {+ const mirror = replicationStorages.find((s) => s.storageId === storageType.replace('mirror_', ''));+ if (mirror) {+ theStorage = { name: mirror.storageName as string, type: mirror?.storageType as string, id: mirror?.storageId as string };+ }+ }+ if (!theStorage) return null;+ const backupResData = getBackupResultByStorage(storageType);+ const backupHasError = backupResData?.hasError;+ return (+ <div key={storageType} className={classes.replicationResult}>+ <h4 onClick={() => setShowContent(storageType)} className={showContent === storageType ? classes.active : ''}>+ <span>+ <img src={`/providers/${theStorage.type}.png`} />+ {theStorage.name} <i>{storageType === 'primary' ? 'Primary' : `Mirror`}</i>+ </span>+ <span>+ {backupHasError ? (+ <Icon type="error-circle-filled" size={14} color="#ff4d4f" />+ ) : (+ <Icon type="check-circle-filled" size={14} color="#06ba9f" />+ )}+ </span>+ </h4>+ {showContent === storageType && (+ <div className={classes.replicationResultContent}>+ {renderBackupStatus(storageType)}+ {renderLogs(storageType)}+ {renderBackupFixSuggestion(storageType)}+ </div>+ )}+ </div>+ );+ })}+ </div>+ );+ };++ return (+ <ActionModal+ title="Check Backup Integrity"+ message={+ <div className={classes.integrityMessage}>+ {!integrityResultLoaded && <p>Check the integrity of the backup snapshots now to check if they are restorable?</p>}+ {integrityResultLoaded && (+ <div>+ {!hasReplications ? (+ <div className={classes.integrityResult}>+ {renderBackupStatus('primary')}+ {renderLogs('primary')}+ {renderBackupFixSuggestion('primary')}+ </div>+ ) : (+ renderResultWithReplications()+ )}+ </div>+ )}+ {integrityCheckMutation.isPending && (+ <div className="label in_progress">+ <Icon type="loading" size={14} />+ Checking integrity...+ </div>+ )}+ </div>+ }+ errorMessage={integrityCheckMutation.error?.message}+ closeModal={() => onClose()}+ width="600px"+ primaryAction={{+ title: integrityResultLoaded ? 'Check Again' : 'Check Now',+ type: 'default',+ isPending: integrityCheckMutation.isPending,+ action: () => !taskPending && integrityCheckMutation.mutate({ planId }),+ }}+ secondaryAction={{+ title: 'Close',+ action: () => onClose(),+ }}+ />+ );+};++export default PlanIntegrity;diff --git a/frontend/src/components/Plan/PlanPendingBackup/PlanPendingBackup.tsx b/frontend/src/components/Plan/PlanPendingBackup/PlanPendingBackup.tsxindex 747960c..df67f07 100644--- a/frontend/src/components/Plan/PlanPendingBackup/PlanPendingBackup.tsx+++ b/frontend/src/components/Plan/PlanPendingBackup/PlanPendingBackup.tsx@@ -4,13 +4,13 @@ import { useCheckActiveBackupsOrRestore } from '../../../services/plans';import classes from './PlanPendingBackup.module.scss';import Icon from '../../common/Icon/Icon';-interface PlanPendingBackup {+interface PlanPendingBackupProps {planId: string;type?: 'backup' | 'restore';onPendingDetect: () => void;}-const PlanPendingBackup = ({ planId, type = 'backup', onPendingDetect }: PlanPendingBackup) => {+const PlanPendingBackup = ({ planId, type = 'backup', onPendingDetect }: PlanPendingBackupProps) => {const [, setSearchParams] = useSearchParams();const checkActivesMutation = useCheckActiveBackupsOrRestore();diff --git a/frontend/src/components/index.ts b/frontend/src/components/index.tsindex 333d6ad..e14e41c 100644--- a/frontend/src/components/index.ts+++ b/frontend/src/components/index.ts@@ -88,6 +88,7 @@ export { default as PlanStrategySettings } from './Plan/PlanSettings/PlanStrategexport { default as PlanTypeSettings } from './Plan/PlanSettings/PlanTypeSettings';export { default as PlanStats } from './Plan/PlanStats/PlanStats';export { default as PlanUnlockModal } from './Plan/PlanUnlockModal/PlanUnlockModal';+export { default as PlanIntegrity } from './Plan/PlanIntegrity/PlanIntegrity';// Mirror/Replication componentsexport { default as MirrorStatusBadge } from './Plan/Mirrors/MirrorStatusBadge';diff --git a/frontend/src/routes/PlanSingle/PlanSingle.tsx b/frontend/src/routes/PlanSingle/PlanSingle.tsxindex 2aacf19..85b4df8 100644--- a/frontend/src/routes/PlanSingle/PlanSingle.tsx+++ b/frontend/src/routes/PlanSingle/PlanSingle.tsx@@ -14,9 +14,11 @@ import PlanUnlockModal from '../../components/Plan/PlanUnlockModal/PlanUnlockModimport PlanRemoveModal from '../../components/Plan/PlanRemoveModal/PlanRemoveModal';import PlanProgress from '../../components/Plan/PlanProgress/PlanProgress';import PlanBackups from '../../components/Plan/PlanBackups/PlanBackups';+import PlanIntegrity from '../../components/Plan/PlanIntegrity/PlanIntegrity';const PlanSingle = () => {const [showMoreOptions, setShowMoreOptions] = useState(false);+ const [showIntegrityModal, setShowIntegrityModal] = useState(false);const { id } = useParams();const EditPlanModal = useComponentOverride('EditPlan', EditPlan);@@ -126,6 +128,15 @@ const PlanSingle = () => {<Icon size={14} type="unlock" /> Unlock</li>)}+ <li+ className={classes.actionBtn}+ onClick={() => {+ setShowIntegrityModal(true);+ setShowMoreOptions(false);+ }}+ >+ <Icon size={14} type="integrity" /> Check Integrity+ </li><liclassName={classes.actionBtn}onClick={() => {@@ -174,6 +185,16 @@ const PlanSingle = () => {close={() => setShowPruneModal(false)}/>)}+ {showIntegrityModal && !isSync && (+ <PlanIntegrity+ planId={plan.id}+ taskPending={taskPending}+ verificationData={plan.verified}+ storage={plan.storage}+ replicationStorages={plan.settings.replication?.enabled ? plan.settings.replication.storages : []}+ onClose={() => setShowIntegrityModal(false)}+ />+ )}{showDeleteModal && (<PlanRemoveModal planId={id} taskPending={taskPending} actionInProgress={actionInProgress} close={() => setShowDeleteModal(false)} />)}diff --git a/frontend/src/services/plans.ts b/frontend/src/services/plans.tsindex 05db359..8b45013 100644--- a/frontend/src/services/plans.ts+++ b/frontend/src/services/plans.ts@@ -437,3 +437,33 @@ export function useDeleteReplicationStorage() {},});}++export async function checkPlanIntegrity({ planId }: { planId: string }) {+ // const header = new Headers({ 'Content-Type': 'application/json', Accept: 'application/json' });+ const res = await fetch(`${API_URL}/plans/${planId}/action/checkintegrity`, {+ method: 'POST',+ credentials: 'include',+ // headers: header,+ });+ // Check if response is ok+ const data = await res.json();+ if (!data.success) {+ throw new Error(data.error);+ }+ return data;+}++export function useCheckPlanIntegrity() {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: checkPlanIntegrity,+ onSuccess: (res, payload) => {+ queryClient.invalidateQueries({ queryKey: ['plan', payload.planId] });+ console.log('res :', payload, res);+ },+ onError: (error, payload) => {+ console.error('Error checking plan integrity for planId:', payload.planId, error);+ toast.error(`Error checking plan integrity. ${error instanceof Error ? error.message : 'Unknown error'}`, { autoClose: false });+ },+ });+}