fix(backup): 关闭月度归档后不再改写旧归档的保留份数

This commit is contained in:
feeeei committed 2026-09-23 00:44:29 +08:00
1 parent a9ff663387
commit 8f8358cc67
4 files changed
+89 -6

No files matched your search

@@ -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())
+5 -3
View File
@@ -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
}
+16 -2
View File
@@ -488,8 +488,19 @@ const scheduleForm = ref<BackupScheduleConfig>({
})
const savingSchedule = ref(false)
const archiveForm = ref<BackupMonthlyArchiveConfig>({ 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<BackupMonthlyArchiveConfig>(cloneArchive(archiveForm.value))
const archivePayload = computed<BackupMonthlyArchiveConfig>(() =>
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'))
@@ -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 } })