import { useCallback, useEffect, useRef, useState } from 'react' import { useOptionalAuth } from './auth' import { applyBackupSchedule, fetchBackupSchedule, fetchBackupScheduleHost, runBackupNow, saveBackupSchedule } from './backupSchedule' import type { BackupSchedule } from './backupSchedule' export const formatBackupBytes = (bytes: number): string => { if (!bytes) return '—' const mib = bytes / (1024 * 1024) return mib >= 1024 ? `${(mib / 1024).toFixed(2)} GiB` : `${mib.toFixed(1)} MiB` } export const formatBackupMoment = (value: string): string => { if (!value) return '—' const parsed = new Date(value) return Number.isNaN(parsed.getTime()) ? value : parsed.toLocaleString('zh-CN', { hour12: false }) } // 清单里的 created_at 就是目录戳(如 20261009T060736Z),同值时不再重复显示一遍。 export const runMoment = (schedule: { last_run_stamp: string; last_run_created_at: string }): string => { const createdAt = schedule.last_run_created_at.trim() if (!createdAt || createdAt === schedule.last_run_stamp.trim()) return '' return formatBackupMoment(createdAt) } export const backupTimeValid = (value: string): boolean => /^([01][0-9]|2[0-3]):[0-5][0-9]$/.test(value) export const backupDaysValid = (value: number): boolean => Number.isInteger(value) && value >= 1 && value <= 365 export const backupMonthsValid = (value: number): boolean => Number.isInteger(value) && value >= 0 && value <= 24 export interface BackupScheduleViewProps { schedule: BackupSchedule isAdmin: boolean loading: boolean probing: boolean busy: 'save' | 'apply' | 'run' | null error: string | null message: string enabledDraft: boolean timeDraft: string daysDraft: string monthsDraft: string onEnabledChange: (next: boolean) => void onTimeChange: (next: string) => void onDaysChange: (next: string) => void onMonthsChange: (next: string) => void onSave: () => void onApply: () => void onRunNow: () => void onReload: () => void } // 纯视图:所有状态由 props 驱动,便于在测试里直接渲染各种状态(管理员/只读、已一致/待下发、在途)。 export function BackupScheduleView(props: BackupScheduleViewProps) { const { schedule, isAdmin, loading, probing, busy, error, message, enabledDraft, timeDraft, daysDraft, monthsDraft, onEnabledChange, onTimeChange, onDaysChange, onMonthsChange, onSave, onApply, onRunNow, onReload, } = props const days = Number(daysDraft) const months = Number(monthsDraft) const valid = backupTimeValid(timeDraft) && backupDaysValid(days) && backupMonthsValid(months) const dirty = enabledDraft !== schedule.enabled || timeDraft !== schedule.schedule_time || days !== schedule.retention_days || months !== schedule.retention_months const hostLine = !schedule.host_configured ? '未接线(缺少主机凭据)' : schedule.host_reachable ? `${schedule.host_target} · 已连接` : `${schedule.host_target} · 连接失败` return

存储与备份

整库逻辑备份(pg_dump 目录格式)在目标库所在主机上本地执行:这里设置定时时间与储存天数,保存即下发到主机 cron,并可读回主机上生效的计划与最近一次结果。

{error ?

{error}

: null}
目标主机
{hostLine}
主机 cron
{schedule.host_cron_service ? `服务 ${schedule.host_cron_service}` : '—'}{schedule.host_script_present ? '' : ' · 备份脚本缺失'}
最近一次备份
{schedule.last_run_stamp || '—'}{runMoment(schedule) ? ` · ${runMoment(schedule)}` : ''}
备份耗时 / 体积
{schedule.last_run_stamp ? `${schedule.last_run_duration_seconds} 秒 · ${formatBackupBytes(schedule.last_run_total_bytes)}` : '—'}
覆盖的库
{schedule.last_run_databases.length ? schedule.last_run_databases.join('、') : '—'}
失败的库
{schedule.last_run_failed_databases.length ? schedule.last_run_failed_databases.join('、') : '无'}
主机上生效的计划
{schedule.host_schedule_enabled ? `每天 ${schedule.host_schedule_time} · 保留 ${schedule.host_keep_days} 天 · 每月 ${schedule.host_keep_months} 份` : schedule.host_configured ? '未启用定时' : '—'}
与设置是否一致
{schedule.in_sync ? '已一致' : '待下发'}
{schedule.host_error ?

主机探测:{schedule.host_error}

: null} {schedule.last_run_error ?

最近一次结果读取:{schedule.last_run_error}

: null} {schedule.host_cron_lines.length ?

主机 cron 条目:{schedule.host_cron_lines.join(' ; ')}

: null} {schedule.last_applied_at ?

最后下发:{formatBackupMoment(schedule.last_applied_at)}{schedule.last_applied_summary ? ` · ${schedule.last_applied_summary}` : ''}

: null}

留档分层:PG 行级留档(发布前,含 ES 文档)+ ES 快照仓 + OSS 版本控制 + 本节的整库逻辑备份 + RDS 托管备份(控制台配置)。详见 docs/PRODUCTION_BACKUP_RECOVERY.md。

{isAdmin ?
{!valid ?

定时时间需为 HH:MM(00:00~23:59),储存天数 1~365,每月归档 0~24。

: null} {message ?

{message}

: null} {schedule.running ?

正在备份({formatBackupMoment(schedule.running_started_at)} 开始),完成后自动刷新。

: null} {schedule.run_last_error && !schedule.running ?

上一次立即备份失败:{schedule.run_last_error}

: null}
:

定时备份设置仅管理员可修改;当前设置:{schedule.enabled ? `每天 ${schedule.schedule_time} · 保留 ${schedule.retention_days} 天` : '未启用'}。

}
} // 容器:读取 + 下发 + 在途轮询。真正执行备份的是目标库所在主机(同 VPC 直连 RDS)。 export function BackupScheduleSection() { const auth = useOptionalAuth() const isAdmin = auth?.identity?.role === 'admin' const [schedule, setSchedule] = useState(null) const [loading, setLoading] = useState(true) const [probing, setProbing] = useState(false) const [busy, setBusy] = useState<'save' | 'apply' | 'run' | null>(null) const [error, setError] = useState(null) const [message, setMessage] = useState('') const [enabledDraft, setEnabledDraft] = useState(false) const [timeDraft, setTimeDraft] = useState('03:30') const [daysDraft, setDaysDraft] = useState('7') const [monthsDraft, setMonthsDraft] = useState('3') const polling = useRef(null) const adopt = useCallback((next: BackupSchedule) => { setSchedule(next) setEnabledDraft(next.enabled) setTimeDraft(next.schedule_time || '03:30') setDaysDraft(String(next.retention_days ?? 7)) setMonthsDraft(String(next.retention_months ?? 3)) }, []) const load = useCallback(async () => { setLoading(true); setError(null) try { adopt(await fetchBackupSchedule()) setProbing(true) try { adopt(await fetchBackupScheduleHost()) } catch (cause) { setError(cause instanceof Error ? cause.message : '读取目标主机上的备份状态失败') } finally { setProbing(false) } } catch (cause) { setError(cause instanceof Error ? cause.message : '读取备份计划失败') } finally { setLoading(false) } }, [adopt]) useEffect(() => { void load() }, [load]) // 立即备份约 30~60 秒:在途时轮询主机状态,直到 running 转假并出现新的最近一次结果。 useEffect(() => { if (!schedule?.running) { if (polling.current !== null) { window.clearInterval(polling.current); polling.current = null } return } if (polling.current !== null) return polling.current = window.setInterval(() => { void fetchBackupScheduleHost().then(adopt).catch(() => undefined) }, 5000) return () => { if (polling.current !== null) { window.clearInterval(polling.current); polling.current = null } } }, [schedule?.running, adopt]) const save = async () => { setBusy('save'); setError(null); setMessage('') try { const next = await saveBackupSchedule({ enabled: enabledDraft, schedule_time: timeDraft, retention_days: Number(daysDraft), retention_months: Number(monthsDraft), apply: true, }) adopt(next) if (!next.host_configured) { setMessage('计划已保存。目标主机凭据未挂载,因此还不能下发到主机上的 cron。') } else if (next.applied) { setMessage(`计划已保存并下发:每天 ${next.schedule_time} 执行,保留 ${next.retention_days} 天(每月另留 ${next.retention_months} 份)。`) } else { setMessage(`计划已保存,但下发失败:${next.apply_error}`) } } catch (cause) { setError(cause instanceof Error ? cause.message : '保存备份计划失败') } finally { setBusy(null) } } const apply = async () => { setBusy('apply'); setError(null); setMessage('') try { const next = await applyBackupSchedule() adopt(next) setMessage(next.applied ? '已按当前设置重新下发到目标主机。' : `下发失败:${next.apply_error}`) } catch (cause) { setError(cause instanceof Error ? cause.message : '下发备份计划失败') } finally { setBusy(null) } } const runNow = async () => { setBusy('run'); setError(null); setMessage('') try { const start = await runBackupNow() setMessage(start.started ? '已在目标主机上开始备份(整库 pg_dump,约 30~60 秒),下方会自动刷新结果。' : '已有一个备份任务在执行中。') adopt(await fetchBackupScheduleHost()) } catch (cause) { setError(cause instanceof Error ? cause.message : '触发备份失败') } finally { setBusy(null) } } if (!schedule) { return

存储与备份

{error ?

{error}

: null}

{loading ? '正在读取备份计划…' : '备份计划暂不可用。'}

} return void save()} onApply={() => void apply()} onRunNow={() => void runNow()} onReload={() => void load()} /> }