From 8f8358cc671ede707c24fcd62fa14b7e3bf1a8b3 Mon Sep 17 00:00:00 2001 From: feeeei Date: Wed, 23 Sep 2026 00:44:29 +0800 Subject: [PATCH] =?UTF-8?q?fix(backup):=20=E5=85=B3=E9=97=AD=E6=9C=88?= =?UTF-8?q?=E5=BA=A6=E5=BD=92=E6=A1=A3=E5=90=8E=E4=B8=8D=E5=86=8D=E6=94=B9?= =?UTF-8?q?=E5=86=99=E6=97=A7=E5=BD=92=E6=A1=A3=E7=9A=84=E4=BF=9D=E7=95=99?= =?UTF-8?q?=E4=BB=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../internal/service/backup_retention_test.go | 40 ++++++++++++++++++- backend/internal/service/backup_service.go | 8 ++-- frontend/src/views/admin/BackupView.vue | 18 ++++++++- .../views/admin/__tests__/BackupView.spec.ts | 29 ++++++++++++++ 4 files changed, 89 insertions(+), 6 deletions(-) diff --git a/backend/internal/service/backup_retention_test.go b/backend/internal/service/backup_retention_test.go index 41b45bf80f..1b207f9f9b 100644 --- a/backend/internal/service/backup_retention_test.go +++ b/backend/internal/service/backup_retention_test.go @@ -145,7 +145,7 @@ func TestBackupRetention_CleanupSeparatePoolsAndPermanentProtection(t *testing.T store.objects[id] = []byte(id) require.NoError(t, svc.saveRecord(ctx, r)) } - cfg := &BackupScheduleConfig{RetainDays: 1, RetainCount: 1, MonthlyArchive: &BackupMonthlyArchiveConfig{RetainCount: 1}} + cfg := &BackupScheduleConfig{RetainDays: 1, RetainCount: 1, MonthlyArchive: &BackupMonthlyArchiveConfig{Enabled: true, RetainCount: 1}} require.NoError(t, svc.cleanupOldBackups(ctx, cfg)) for _, id := range []string{"running", "failed", "ordinary-new", "archive-new", "permanent", "restoring"} { _, err := svc.GetBackupRecord(ctx, id) @@ -167,6 +167,44 @@ func TestBackupRetention_CleanupSeparatePoolsAndPermanentProtection(t *testing.T require.NoError(t, err) } +func TestBackupRetention_DisabledRuleKeepsPersistedArchivePolicy(t *testing.T) { + repo := newMockSettingRepo() + seedS3Config(t, repo) + store := newMockObjectStore() + svc := newTestBackupService(repo, &mockDumper{}, store) + ctx := context.Background() + for id, started := range map[string]string{"newest": "2026-09-16T04:00:00Z", "middle": "2026-08-16T04:00:00Z", "oldest": "2026-07-16T04:00:00Z"} { + record := archiveRecord(id, started) + record.S3Key = id + record.MonthlyArchive = &BackupMonthlyArchive{RetainCount: 2} + store.objects[id] = []byte(id) + require.NoError(t, svc.saveRecord(ctx, record)) + } + // The settings form hides the archive count once the rule is disabled, so a + // saved payload may still carry a smaller limit. It must not reach old archives. + cfg := &BackupScheduleConfig{RetainDays: 14, RetainCount: 10, MonthlyArchive: &BackupMonthlyArchiveConfig{Enabled: false, Days: []int{1}, RetainCount: 1}} + require.NoError(t, svc.cleanupOldBackups(ctx, cfg)) + for _, id := range []string{"newest", "middle"} { + record, err := svc.GetBackupRecord(ctx, id) + require.NoError(t, err, id) + require.Equal(t, 2, record.MonthlyArchive.RetainCount, id) + require.Contains(t, store.objects, id) + } + // The persisted policy keeps applying while the rule is off. + _, err := svc.GetBackupRecord(ctx, "oldest") + require.ErrorIs(t, err, ErrBackupNotFound) + require.NotContains(t, store.objects, "oldest") + // Re-enabling the rule applies the new finite limit to the pool again. + cfg.MonthlyArchive.Enabled = true + require.NoError(t, svc.cleanupOldBackups(ctx, cfg)) + newest, err := svc.GetBackupRecord(ctx, "newest") + require.NoError(t, err) + require.Equal(t, 1, newest.MonthlyArchive.RetainCount) + _, err = svc.GetBackupRecord(ctx, "middle") + require.ErrorIs(t, err, ErrBackupNotFound) + require.NotContains(t, store.objects, "middle") +} + func TestBackupRetention_Over100ArchivesRemainDiscoverable(t *testing.T) { repo := newMockSettingRepo() svc := newTestBackupService(repo, &mockDumper{}, newMockObjectStore()) diff --git a/backend/internal/service/backup_service.go b/backend/internal/service/backup_service.go index 6e1d10ea74..39f1c36b99 100644 --- a/backend/internal/service/backup_service.go +++ b/backend/internal/service/backup_service.go @@ -1494,9 +1494,11 @@ func (s *BackupService) cleanupOldBackups(ctx context.Context, schedule *BackupS if r.MonthlyArchive != nil { if r.MonthlyArchive.RetainCount > 0 { archiveCount++ - // A new finite limit applies to the finite archive pool. Permanent - // archives remain protected even after the configuration changes. - if cfg := schedule.MonthlyArchive; cfg != nil && cfg.RetainCount > 0 && cfg.RetainCount != r.MonthlyArchive.RetainCount { + // A new finite limit applies to the finite archive pool only while the + // rule is enabled; a disabled rule leaves every archive on its persisted + // policy. Permanent archives remain protected even after the + // configuration changes. + if cfg := schedule.MonthlyArchive; cfg != nil && cfg.Enabled && cfg.RetainCount > 0 && cfg.RetainCount != r.MonthlyArchive.RetainCount { r.MonthlyArchive.RetainCount = cfg.RetainCount metadataChanged = true } diff --git a/frontend/src/views/admin/BackupView.vue b/frontend/src/views/admin/BackupView.vue index 3c2d92058d..b9f7600a19 100644 --- a/frontend/src/views/admin/BackupView.vue +++ b/frontend/src/views/admin/BackupView.vue @@ -488,8 +488,19 @@ const scheduleForm = ref({ }) const savingSchedule = ref(false) const archiveForm = ref({ enabled: false, days: [1], include_month_end: false, retain_count: 0 }) +// Disabling hides the archive parameters, so a save while disabled keeps the +// persisted parameters and only turns the rule off. +const savedArchive = ref(cloneArchive(archiveForm.value)) +const archivePayload = computed(() => + archiveForm.value.enabled ? cloneArchive(archiveForm.value) : { ...cloneArchive(savedArchive.value), enabled: false }, +) +function cloneArchive(config: BackupMonthlyArchiveConfig): BackupMonthlyArchiveConfig { + return { ...config, days: [...config.days] } +} const scheduleValidationError = computed(() => { - if (![scheduleForm.value.retain_days, scheduleForm.value.retain_count, archiveForm.value.retain_count].every(value => Number.isSafeInteger(value) && value >= 0)) { + const counts = [scheduleForm.value.retain_days, scheduleForm.value.retain_count] + if (archiveForm.value.enabled) counts.push(archiveForm.value.retain_count) + if (!counts.every(value => Number.isSafeInteger(value) && value >= 0)) { return t('admin.backup.archive.invalidRetention') } if (archiveForm.value.enabled && !archiveForm.value.days.length && !archiveForm.value.include_month_end) { @@ -753,6 +764,7 @@ async function loadSchedule() { include_month_end: cfg.monthly_archive?.include_month_end ?? false, retain_count: cfg.monthly_archive?.retain_count ?? 0, } + savedArchive.value = cloneArchive(archiveForm.value) } catch (error) { appStore.showError((error as { message?: string })?.message || t('errors.networkError')) } @@ -762,7 +774,9 @@ async function saveSchedule() { if (scheduleValidationError.value) return savingSchedule.value = true try { - await adminAPI.backup.updateSchedule({ ...scheduleForm.value, monthly_archive: { ...archiveForm.value, days: [...archiveForm.value.days] } }) + const archive = archivePayload.value + await adminAPI.backup.updateSchedule({ ...scheduleForm.value, monthly_archive: archive }) + savedArchive.value = cloneArchive(archive) appStore.showSuccess(t('admin.backup.schedule.saved')) } catch (error) { appStore.showError((error as { message?: string })?.message || t('errors.networkError')) diff --git a/frontend/src/views/admin/__tests__/BackupView.spec.ts b/frontend/src/views/admin/__tests__/BackupView.spec.ts index 62ba71713b..8c1e1563bc 100644 --- a/frontend/src/views/admin/__tests__/BackupView.spec.ts +++ b/frontend/src/views/admin/__tests__/BackupView.spec.ts @@ -219,6 +219,35 @@ describe('admin BackupView', () => { expect(updateSchedule).not.toHaveBeenCalled() }) + it('关闭月度归档后不提交隐藏的归档参数,重新启用时保留编辑值', async () => { + getSchedule.mockResolvedValue({ enabled: true, cron_expr: '0 4 * * *', retain_days: 14, retain_count: 10, + monthly_archive: { enabled: true, days: [1, 15], include_month_end: false, retain_count: 12 } }) + const wrapper = mountBackupView() + await flushPromises() + await wrapper.get('[data-testid="archive-count"]').setValue(1) + await wrapper.get('[data-testid="archive-enabled"]').setValue(false) + expect(wrapper.find('[data-testid="archive-count"]').exists()).toBe(false) + const save = wrapper.get('[data-testid="backup-schedule"] .btn-primary') + await save.trigger('click') + await flushPromises() + expect(updateSchedule).toHaveBeenLastCalledWith(expect.objectContaining({ monthly_archive: { enabled: false, days: [1, 15], include_month_end: false, retain_count: 12 } })) + await wrapper.get('[data-testid="archive-enabled"]').setValue(true) + expect((wrapper.get('[data-testid="archive-count"]').element as HTMLInputElement).value).toBe('1') + // A hidden invalid count neither blocks saving nor reaches the request. + await wrapper.get('[data-testid="archive-count"]').setValue('') + expect(save.attributes('disabled')).toBeDefined() + await wrapper.get('[data-testid="archive-enabled"]').setValue(false) + expect(save.attributes('disabled')).toBeUndefined() + await save.trigger('click') + await flushPromises() + expect(updateSchedule).toHaveBeenLastCalledWith(expect.objectContaining({ monthly_archive: { enabled: false, days: [1, 15], include_month_end: false, retain_count: 12 } })) + await wrapper.get('[data-testid="archive-enabled"]').setValue(true) + await wrapper.get('[data-testid="archive-count"]').setValue(1) + await save.trigger('click') + await flushPromises() + expect(updateSchedule).toHaveBeenLastCalledWith(expect.objectContaining({ monthly_archive: { enabled: true, days: [1, 15], include_month_end: false, retain_count: 1 } })) + }) + it('加载归档设置并支持键盘关闭日期选择器', async () => { getSchedule.mockResolvedValue({ enabled: true, cron_expr: '0 4 * * *', retain_days: 14, retain_count: 10, monthly_archive: { enabled: true, days: [1, 15], include_month_end: true, retain_count: 23 } })