Files
knowledge-governance/web/src/BackupScheduleSection.tsx
T
姚章浩 e95a50ca3a fix(backup): 保存后即时反映主机状态;最近一次备份不再重复同一时间戳
- 后端 handleSaveBackupSchedule 改为先下发、再组装投影:此前页面保存成功那几行仍是
  下发前的主机计划,看起来像没生效(需等下一次刷新)
- 前端 runMoment:清单里的 created_at 就是目录戳,同值不再重复显示(原为
  '20261009T060736Z · 20261009T060736Z')
- 前端补 runMoment 用例(171 个 vitest 全绿)

面板实测:保存后立即显示 每天 03:30 / 保留 7 天 / 已一致,cron 条目 30 03 * * *
2026-10-09 14:12:10 +08:00

223 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 <section className="settings-panel wide storage-settings-panel" id="settings-storage">
<div className="settings-section-heading"><div>
<h2>存储与备份</h2>
<p>整库逻辑备份(pg_dump 目录格式)在<strong>目标库所在主机</strong>上本地执行:这里设置定时时间与储存天数,保存即下发到主机 cron,并可读回主机上生效的计划与最近一次结果。</p>
</div><button onClick={onReload} disabled={loading || probing}>{loading || probing ? '读取中…' : '重新读取'}</button></div>
{error ? <p className="error-message" role="alert">{error}</p> : null}
<div className="storage-settings-grid">
<dl>
<dt>目标主机</dt><dd>{hostLine}</dd>
<dt>主机 cron</dt><dd>{schedule.host_cron_service ? `服务 ${schedule.host_cron_service}` : '—'}{schedule.host_script_present ? '' : ' · 备份脚本缺失'}</dd>
<dt>最近一次备份</dt><dd>{schedule.last_run_stamp || '—'}{runMoment(schedule) ? ` · ${runMoment(schedule)}` : ''}</dd>
<dt>备份耗时 / 体积</dt><dd>{schedule.last_run_stamp ? `${schedule.last_run_duration_seconds} 秒 · ${formatBackupBytes(schedule.last_run_total_bytes)}` : '—'}</dd>
</dl>
<dl>
<dt>覆盖的库</dt><dd>{schedule.last_run_databases.length ? schedule.last_run_databases.join('、') : '—'}</dd>
<dt>失败的库</dt><dd>{schedule.last_run_failed_databases.length ? schedule.last_run_failed_databases.join('、') : '无'}</dd>
<dt>主机上生效的计划</dt><dd>{schedule.host_schedule_enabled ? `每天 ${schedule.host_schedule_time} · 保留 ${schedule.host_keep_days} 天 · 每月 ${schedule.host_keep_months} 份` : schedule.host_configured ? '未启用定时' : '—'}</dd>
<dt>与设置是否一致</dt><dd>{schedule.in_sync ? '已一致' : '待下发'}</dd>
</dl>
</div>
{schedule.host_error ? <p className="hint">主机探测:{schedule.host_error}</p> : null}
{schedule.last_run_error ? <p className="hint">最近一次结果读取:{schedule.last_run_error}</p> : null}
{schedule.host_cron_lines.length ? <p className="hint">主机 cron 条目:<code>{schedule.host_cron_lines.join(' ; ')}</code></p> : null}
{schedule.last_applied_at ? <p className="hint">最后下发:{formatBackupMoment(schedule.last_applied_at)}{schedule.last_applied_summary ? ` · ${schedule.last_applied_summary}` : ''}</p> : null}
<p className="hint">留档分层:PG 行级留档(发布前,含 ES 文档)+ ES 快照仓 + OSS 版本控制 + 本节的整库逻辑备份 + RDS 托管备份(控制台配置)。详见 <code>docs/PRODUCTION_BACKUP_RECOVERY.md</code>。</p>
{isAdmin ? <div className="kb-binding-editor">
<label>定时时间 <input type="time" value={timeDraft} onChange={(event) => onTimeChange(event.target.value)} aria-label="定时时间" /></label>
<label>储存天数 <input type="number" min={1} max={365} value={daysDraft} onChange={(event) => onDaysChange(event.target.value)} aria-label="储存天数" /></label>
<label>每月归档保留 <input type="number" min={0} max={24} value={monthsDraft} onChange={(event) => onMonthsChange(event.target.value)} aria-label="每月归档保留" /></label>
<label className="checkbox-label"><input type="checkbox" checked={enabledDraft} onChange={(event) => onEnabledChange(event.target.checked)} /> 启用定时整库备份</label>
{!valid ? <p className="error-message">定时时间需为 HH:MM(00:00~23:59),储存天数 1~365,每月归档 0~24。</p> : null}
<button onClick={onSave} disabled={busy !== null || !valid || !dirty}>{busy === 'save' ? '正在保存并下发…' : '保存并下发到主机'}</button>
<button onClick={onApply} disabled={busy !== null || !schedule.host_configured}>{busy === 'apply' ? '正在下发…' : '重新下发当前设置'}</button>
<button onClick={onRunNow} disabled={busy !== null || !schedule.host_configured || schedule.running}>{schedule.running ? '备份进行中…' : '立即备份一次'}</button>
{message ? <p className="success-message" role="status">{message}</p> : null}
{schedule.running ? <p className="hint">正在备份({formatBackupMoment(schedule.running_started_at)} 开始),完成后自动刷新。</p> : null}
{schedule.run_last_error && !schedule.running ? <p className="error-message">上一次立即备份失败:{schedule.run_last_error}</p> : null}
</div> : <p className="hint">定时备份设置仅管理员可修改;当前设置:{schedule.enabled ? `每天 ${schedule.schedule_time} · 保留 ${schedule.retention_days} 天` : '未启用'}。</p>}
</section>
}
// 容器:读取 + 下发 + 在途轮询。真正执行备份的是目标库所在主机(同 VPC 直连 RDS)。
export function BackupScheduleSection() {
const auth = useOptionalAuth()
const isAdmin = auth?.identity?.role === 'admin'
const [schedule, setSchedule] = useState<BackupSchedule | null>(null)
const [loading, setLoading] = useState(true)
const [probing, setProbing] = useState(false)
const [busy, setBusy] = useState<'save' | 'apply' | 'run' | null>(null)
const [error, setError] = useState<string | null>(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<number | null>(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 <section className="settings-panel wide storage-settings-panel" id="settings-storage">
<div className="settings-section-heading"><div><h2>存储与备份</h2></div></div>
{error ? <p className="error-message" role="alert">{error}</p> : null}
<p className="hint">{loading ? '正在读取备份计划…' : '备份计划暂不可用。'}</p>
</section>
}
return <BackupScheduleView
schedule={schedule} isAdmin={isAdmin} loading={loading} probing={probing} busy={busy}
error={error} message={message}
enabledDraft={enabledDraft} timeDraft={timeDraft} daysDraft={daysDraft} monthsDraft={monthsDraft}
onEnabledChange={setEnabledDraft} onTimeChange={setTimeDraft}
onDaysChange={setDaysDraft} onMonthsChange={setMonthsDraft}
onSave={() => void save()} onApply={() => void apply()} onRunNow={() => void runNow()}
onReload={() => void load()}
/>
}