feat(backup): 系统设置里的存储与备份——定时时间与储存天数可配、下发到目标主机 cron
需求:整库逻辑备份做定时,但要在「系统设置 → 存储与备份」里设置定时时间与储存天数。 后端 - migration 000045 backup_schedule(单行:enabled/schedule_time/retention_days/retention_months/ last_applied_*),store + 领域校验(HH:MM、1~365 天、0~24 月,非法值 400 且不落库不下发) - internal/backuphost:通过 ssh 在目标主机上读回/下发计划并立即备份(未接线时 Available=false, 页面降级提示;主机侧错误带输出回传)。最近一次只认有 MANIFEST.json 的完整目录,跳 *.incomplete - 接口 GET/PUT /api/v1/backup-schedule、GET …/host、POST …/apply、POST …/run; 写操作经 classifyRole 限管理员;run 为异步 202 + 在途单飞(http 写超时 30s,备份约 35s) - openapi.yaml 补齐 5 条路由(契约测试要求每条都写 400/500) 主机侧 - scripts/install_backup_schedule.sh(幂等):写 /etc/knowledge-governance/backup-schedule.env 与 /etc/cron.d/kb-logical-backup,参数校验,--show/--disable,最后一行 SCHEDULE_APPLIED 供平台核对 - logical-backup.sh 从该文件读保留策略;失败或被中断把目录改名 *.incomplete,不留'像成功'的半成品 - install --show 只回显计划行(原先把 SHELL=/PATH= 当计划显示) 前端 - web/src/backupSchedule.ts(严格解析:缺计划字段即报错,不把默认值伪装成设置) - BackupScheduleSection:容器 + 纯视图(管理员表单/只读、已一致/待下发、在途轮询) 运行前提(已落实):运行镜像加 openssh-client,且容器 uid 1000 在 /etc/passwd 有名字 (否则 ssh 报 No user exists for uid 1000);凭据只读挂载 secrets/backup-host(git 忽略) 实测:主机 cron 每天 03:30 / 保留 7 天 / 每月 3 份;立即备份一次 34 秒 / 742.7 MiB / 失败 0; Go 与前端测试全绿(170 vitest)。
This commit is contained in:
@@ -0,0 +1,97 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { BackupScheduleView, backupDaysValid, backupMonthsValid, backupTimeValid, formatBackupBytes } from './BackupScheduleSection'
|
||||
import type { BackupSchedule } from './backupSchedule'
|
||||
|
||||
const base: BackupSchedule = {
|
||||
enabled: true, schedule_time: '03:30', retention_days: 7, retention_months: 3,
|
||||
updated_by: 'yaozhanghao', updated_at: '2026-10-09T12:00:00Z',
|
||||
last_applied_at: '2026-10-09T12:00:00Z', last_applied_summary: '每天 03:30 · 保留 7 天 · 每月归档 3 份',
|
||||
host_configured: true, host_target: 'weknora-test', host_reachable: true, host_error: '',
|
||||
host_schedule_enabled: true, host_schedule_time: '03:30', host_keep_days: 7, host_keep_months: 3,
|
||||
host_cron_lines: ['30 03 * * * root /bin/bash /opt/weknora-test/logical-backup.sh >> /srv/kb-backups/logs/logical-backup.log 2>&1'],
|
||||
host_cron_service: 'active', host_script_present: true,
|
||||
last_run_stamp: '20261009T052909Z', last_run_created_at: '2026-10-09T05:29:09Z', last_run_duration_seconds: 33,
|
||||
last_run_total_bytes: 778_502_144, last_run_databases: ['weknora_test', 'dobotai_prod'],
|
||||
last_run_failed_databases: [], last_run_error: '', in_sync: true,
|
||||
applied: true, apply_error: '', running: false, running_started_at: '', run_last_error: '',
|
||||
}
|
||||
|
||||
const view = (overrides: Partial<BackupSchedule> = {}, extra: Record<string, unknown> = {}) => {
|
||||
const schedule = { ...base, ...overrides }
|
||||
return renderToStaticMarkup(<BackupScheduleView
|
||||
schedule={schedule}
|
||||
isAdmin={(extra.isAdmin as boolean) ?? true}
|
||||
loading={false} probing={false} busy={(extra.busy as 'save' | 'apply' | 'run' | null) ?? null}
|
||||
error={(extra.error as string | null) ?? null} message={(extra.message as string) ?? ''}
|
||||
enabledDraft={(extra.enabledDraft as boolean) ?? schedule.enabled}
|
||||
timeDraft={(extra.timeDraft as string) ?? schedule.schedule_time}
|
||||
daysDraft={(extra.daysDraft as string) ?? String(schedule.retention_days)}
|
||||
monthsDraft={(extra.monthsDraft as string) ?? String(schedule.retention_months)}
|
||||
onEnabledChange={vi.fn()} onTimeChange={vi.fn()} onDaysChange={vi.fn()} onMonthsChange={vi.fn()}
|
||||
onSave={vi.fn()} onApply={vi.fn()} onRunNow={vi.fn()} onReload={vi.fn()} />)
|
||||
}
|
||||
|
||||
describe('BackupScheduleView', () => {
|
||||
it('管理员看到定时时间/储存天数与下发按钮,并显示主机上生效的计划与最近一次结果', () => {
|
||||
const html = view()
|
||||
for (const text of ['存储与备份', '目标库所在主机', '定时时间', '储存天数', '每月归档保留',
|
||||
'保存并下发到主机', '重新下发当前设置', '立即备份一次', 'weknora-test · 已连接',
|
||||
'每天 03:30 · 保留 7 天 · 每月 3 份', '已一致', '20261009T052909Z', '33 秒', '742.4 MiB',
|
||||
'weknora_test、dobotai_prod']) expect(html).toContain(text)
|
||||
expect(html).toContain('type="time"')
|
||||
expect(html).toContain('value="03:30"')
|
||||
})
|
||||
|
||||
it('非管理员只读:没有保存/下发/立即备份按钮,只给当前设置', () => {
|
||||
const html = view({}, { isAdmin: false })
|
||||
expect(html).toContain('定时备份设置仅管理员可修改')
|
||||
expect(html).not.toContain('保存并下发到主机')
|
||||
expect(html).not.toContain('立即备份一次')
|
||||
})
|
||||
|
||||
it('未接线:显式说明缺少主机凭据,下发与立即备份不可点', () => {
|
||||
const html = view({ host_configured: false, host_reachable: false, host_error: '目标主机凭据未挂载(BACKUP_HOST_SSH_CONFIG / BACKUP_HOST_TARGET)', in_sync: false })
|
||||
expect(html).toContain('未接线(缺少主机凭据)')
|
||||
expect(html).toContain('待下发')
|
||||
expect(html).toContain('目标主机凭据未挂载')
|
||||
expect(html).toContain('disabled')
|
||||
})
|
||||
|
||||
it('待下发(主机上的计划与设置不一致)时提示', () => {
|
||||
const html = view({ host_schedule_time: '05:00', in_sync: false })
|
||||
expect(html).toContain('待下发')
|
||||
expect(html).toContain('每天 05:00')
|
||||
})
|
||||
|
||||
it('在途备份:按钮变"备份进行中…"并给出开始时间', () => {
|
||||
const html = view({ running: true, running_started_at: '2026-10-09T12:30:00Z' })
|
||||
expect(html).toContain('备份进行中…')
|
||||
expect(html).toContain('正在备份')
|
||||
})
|
||||
|
||||
it('非法输入就地拦截,且保存按钮在未改动时不可点', () => {
|
||||
const html = view({}, { timeDraft: '25:99', daysDraft: '0' })
|
||||
expect(html).toContain('定时时间需为 HH:MM(00:00~23:59),储存天数 1~365,每月归档 0~24。')
|
||||
expect(html).toContain('disabled')
|
||||
expect(backupTimeValid('03:30')).toBe(true)
|
||||
expect(backupTimeValid('24:00')).toBe(false)
|
||||
expect(backupDaysValid(0)).toBe(false)
|
||||
expect(backupDaysValid(365)).toBe(true)
|
||||
expect(backupMonthsValid(0)).toBe(true)
|
||||
expect(backupMonthsValid(25)).toBe(false)
|
||||
})
|
||||
|
||||
it('展示失败的库与最近一次读取错误', () => {
|
||||
const html = view({ last_run_failed_databases: ['rdsadmin'], last_run_error: '清单无法解析' })
|
||||
expect(html).toContain('rdsadmin')
|
||||
expect(html).toContain('清单无法解析')
|
||||
})
|
||||
|
||||
it('体积格式化:MiB/GiB', () => {
|
||||
expect(formatBackupBytes(0)).toBe('—')
|
||||
expect(formatBackupBytes(1024 * 1024)).toBe('1.0 MiB')
|
||||
expect(formatBackupBytes(2 * 1024 * 1024 * 1024)).toBe('2.00 GiB')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,216 @@
|
||||
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 })
|
||||
}
|
||||
|
||||
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 || '—'}{schedule.last_run_created_at ? ` · ${formatBackupMoment(schedule.last_run_created_at)}` : ''}</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()}
|
||||
/>
|
||||
}
|
||||
@@ -32,8 +32,10 @@ describe('SystemSettingsView',()=>{
|
||||
const servicesHtml=renderToStaticMarkup(<SystemSettingsView sources={sources} connections={connections} monitor={monitor} settings={settings} productionEnabled={false} routingCapabilities={{internal_enabled:true,external_enabled:true}} loading={false} saving={false} error={null} saveMessage={null} onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} initialSection="services" />)
|
||||
for(const text of ['测试 WeKnora','生产 WeKnora','测试地址','生产地址','生产 ID','知识库 ID'])expect(servicesHtml).toContain(text)
|
||||
const storageHtml=renderToStaticMarkup(<SystemSettingsView sources={sources} connections={connections} monitor={monitor} settings={settings} productionEnabled={false} routingCapabilities={{internal_enabled:true,external_enabled:true}} loading={false} saving={false} error={null} saveMessage={null} onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} initialSection="storage" />)
|
||||
expect(storageHtml).toContain('生产发布请求')
|
||||
expect(storageHtml).toContain('仅保存凭据引用,不可回读')
|
||||
// 存储与备份分区已换成真实功能(整库逻辑备份的定时计划),静态占位文案不再存在。
|
||||
expect(storageHtml).toContain('存储与备份')
|
||||
expect(storageHtml).toContain('正在读取备份计划…')
|
||||
expect(storageHtml).not.toContain('仅保存凭据引用,不可回读')
|
||||
const refreshHtml=renderToStaticMarkup(<SystemSettingsView sources={sources} connections={connections} monitor={monitor} settings={settings} productionEnabled={false} routingCapabilities={{internal_enabled:true,external_enabled:true}} loading={false} saving={false} error={null} saveMessage="刷新与告警参数已验证并启用:文档15秒、资源30秒、停滞30分钟、finalizing 2小时" onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} initialSection="refresh" />)
|
||||
for(const text of ['刷新与告警参数已验证并启用','停滞30分钟','finalizing 2小时','文档状态刷新间隔','15秒','解析停滞判定','30分钟','保存并应用刷新与告警参数'])expect(refreshHtml).toContain(text)
|
||||
expect(visibleSaveMessage('已保存',true)).toBeNull();expect(visibleSaveMessage('已保存',false)).toBe('已保存')
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
|
||||
import { BackupScheduleSection } from './BackupScheduleSection'
|
||||
import { MembersSection } from './MembersSection'
|
||||
import { DingtalkSessionControl } from './DingtalkSessionControl'
|
||||
import { RoutingBindingsSection } from './RoutingBindingsSection'
|
||||
@@ -264,10 +265,7 @@ export function SystemSettingsView({ sources, connections, monitor, settings, pr
|
||||
</section> : null}
|
||||
{section === 'bindings' ? <RoutingBindingsSection /> : null}
|
||||
{section === 'production-bindings' ? <ProductionBindingsSection /> : null}
|
||||
{section === 'storage' ? <section className="settings-panel wide storage-settings-panel" id="settings-storage">
|
||||
<div className="settings-section-heading"><div><h2>存储与备份</h2><p>文件资源与生产发布前快照使用独立受限配置。</p></div></div>
|
||||
<div className="storage-settings-grid"><dl><dt>Endpoint / Bucket</dt><dd>尚未配置</dd><dt>AccessKey / Secret</dt><dd>仅保存凭据引用,不可回读</dd><dt>CDN / 公开访问域名</dt><dd>尚未配置</dd><dt>临时签名有效期</dt><dd>待配置</dd></dl><dl><dt>测试备份前缀</dt><dd>/backup/weknora/test/</dd><dt>生产备份前缀</dt><dd>/backup/weknora/prod/</dd><dt>快照保留</dt><dd>最近 30 个生产快照</dd><dt>恢复验证</dt><dd>由生产门禁读回</dd></dl><ul className="target-list"><li>PostgreSQL <b>未配置</b></li><li>Elasticsearch <b>未配置</b></li><li>对象存储 <b>未配置</b></li><li>Neo4j <b>未配置</b></li><li>生产发布请求 <b>{productionEnabled ? '等待管理员核对' : '关闭'}</b></li><li>Release Worker <b>网页不可启用</b></li></ul></div>
|
||||
</section> : null}
|
||||
{section === 'storage' ? <BackupScheduleSection /> : null}
|
||||
{section === 'members' && identity?.role === 'admin' ? <MembersSection /> : null}
|
||||
{section === 'refresh' ? <section className="settings-panel wide" id="settings-refresh">
|
||||
<div className="settings-section-heading"><div><h2>刷新策略</h2><p>这些值保存在服务器活动版本中;保存不会修改端点、凭据或生产开关。</p></div><span className="safe-badge">当前活动版本</span></div>
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { fetchBackupSchedule, fetchBackupScheduleHost, runBackupNow, saveBackupSchedule } from './backupSchedule'
|
||||
|
||||
const payload = {
|
||||
enabled: true, schedule_time: '03:30', retention_days: 7, retention_months: 3,
|
||||
updated_by: 'yaozhanghao', updated_at: '2026-10-09T12:00:00Z', last_applied_at: '', last_applied_summary: '',
|
||||
host_configured: true, host_target: 'weknora-test', host_reachable: true, host_error: '',
|
||||
host_schedule_enabled: true, host_schedule_time: '03:30', host_keep_days: 7, host_keep_months: 3,
|
||||
host_cron_lines: ['30 03 * * * root …'], host_cron_service: 'active', host_script_present: true,
|
||||
last_run_stamp: '20261009T052909Z', last_run_created_at: '2026-10-09T05:29:09Z',
|
||||
last_run_duration_seconds: 33, last_run_total_bytes: 778502144,
|
||||
last_run_databases: ['weknora_test'], last_run_failed_databases: [], last_run_error: '',
|
||||
in_sync: true, applied: true, apply_error: '', running: false, running_started_at: '', run_last_error: '',
|
||||
}
|
||||
|
||||
const jsonResponse = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } })
|
||||
|
||||
afterEach(() => { vi.unstubAllGlobals() })
|
||||
|
||||
describe('backupSchedule 客户端', () => {
|
||||
it('解析计划三要素与主机回执', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ data: payload })))
|
||||
const schedule = await fetchBackupSchedule()
|
||||
expect(schedule.schedule_time).toBe('03:30')
|
||||
expect(schedule.retention_days).toBe(7)
|
||||
expect(schedule.host_cron_lines).toHaveLength(1)
|
||||
expect(schedule.last_run_failed_databases).toEqual([])
|
||||
})
|
||||
|
||||
it('缺计划字段就报错,绝不把默认值伪装成真实设置', async () => {
|
||||
const broken = { ...payload } as Record<string, unknown>
|
||||
delete broken.retention_days
|
||||
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ data: broken })))
|
||||
await expect(fetchBackupScheduleHost()).rejects.toThrow('存储与备份响应缺少计划字段')
|
||||
})
|
||||
|
||||
it('保存失败时把后端的中文原因透出来', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ error: '储存天数需在 1~365 之间,收到 0' }, 400)))
|
||||
await expect(saveBackupSchedule({ enabled: true, schedule_time: '03:30', retention_days: 0, retention_months: 3 }))
|
||||
.rejects.toThrow('储存天数需在 1~365 之间,收到 0')
|
||||
})
|
||||
|
||||
it('立即备份返回 202 时识别为已启动', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ data: { started: true, running: true } }, 202)))
|
||||
await expect(runBackupNow()).resolves.toEqual({ started: true, running: true })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,163 @@
|
||||
import { newOperationID } from './operationKey'
|
||||
|
||||
// 「系统设置 → 存储与备份」:整库逻辑备份的定时计划(时间 + 储存天数)与主机回执。
|
||||
export interface BackupSchedule {
|
||||
enabled: boolean
|
||||
schedule_time: string
|
||||
retention_days: number
|
||||
retention_months: number
|
||||
updated_by: string
|
||||
updated_at: string
|
||||
last_applied_at: string
|
||||
last_applied_summary: string
|
||||
host_configured: boolean
|
||||
host_target: string
|
||||
host_reachable: boolean
|
||||
host_error: string
|
||||
host_schedule_enabled: boolean
|
||||
host_schedule_time: string
|
||||
host_keep_days: number
|
||||
host_keep_months: number
|
||||
host_cron_lines: string[]
|
||||
host_cron_service: string
|
||||
host_script_present: boolean
|
||||
last_run_stamp: string
|
||||
last_run_created_at: string
|
||||
last_run_duration_seconds: number
|
||||
last_run_total_bytes: number
|
||||
last_run_databases: string[]
|
||||
last_run_failed_databases: string[]
|
||||
last_run_error: string
|
||||
in_sync: boolean
|
||||
applied: boolean
|
||||
apply_error: string
|
||||
running: boolean
|
||||
running_started_at: string
|
||||
run_last_error: string
|
||||
}
|
||||
|
||||
export interface BackupRunStart {
|
||||
started: boolean
|
||||
running: boolean
|
||||
}
|
||||
|
||||
const record = (value: unknown): value is Record<string, unknown> =>
|
||||
Boolean(value) && typeof value === 'object' && !Array.isArray(value)
|
||||
|
||||
const asString = (value: unknown): string => (typeof value === 'string' ? value : '')
|
||||
const asNumber = (value: unknown): number => (typeof value === 'number' && Number.isFinite(value) ? value : 0)
|
||||
const asStringList = (value: unknown): string[] =>
|
||||
Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : []
|
||||
|
||||
// 严格解析:计划三要素(时间/天数/月数)必须是正确类型,缺一个就整块报错,
|
||||
// 而不是让界面显示成"默认 03:30 / 7 天"这种假状态。
|
||||
function scheduleProjection(item: Record<string, unknown>): BackupSchedule {
|
||||
if (typeof item.schedule_time !== 'string' || typeof item.retention_days !== 'number' || typeof item.retention_months !== 'number') {
|
||||
throw new Error('存储与备份响应缺少计划字段(schedule_time / retention_days / retention_months)')
|
||||
}
|
||||
return {
|
||||
enabled: item.enabled === true,
|
||||
schedule_time: item.schedule_time,
|
||||
retention_days: item.retention_days,
|
||||
retention_months: item.retention_months,
|
||||
updated_by: asString(item.updated_by),
|
||||
updated_at: asString(item.updated_at),
|
||||
last_applied_at: asString(item.last_applied_at),
|
||||
last_applied_summary: asString(item.last_applied_summary),
|
||||
host_configured: item.host_configured === true,
|
||||
host_target: asString(item.host_target),
|
||||
host_reachable: item.host_reachable === true,
|
||||
host_error: asString(item.host_error),
|
||||
host_schedule_enabled: item.host_schedule_enabled === true,
|
||||
host_schedule_time: asString(item.host_schedule_time),
|
||||
host_keep_days: asNumber(item.host_keep_days),
|
||||
host_keep_months: asNumber(item.host_keep_months),
|
||||
host_cron_lines: asStringList(item.host_cron_lines),
|
||||
host_cron_service: asString(item.host_cron_service),
|
||||
host_script_present: item.host_script_present === true,
|
||||
last_run_stamp: asString(item.last_run_stamp),
|
||||
last_run_created_at: asString(item.last_run_created_at),
|
||||
last_run_duration_seconds: asNumber(item.last_run_duration_seconds),
|
||||
last_run_total_bytes: asNumber(item.last_run_total_bytes),
|
||||
last_run_databases: asStringList(item.last_run_databases),
|
||||
last_run_failed_databases: asStringList(item.last_run_failed_databases),
|
||||
last_run_error: asString(item.last_run_error),
|
||||
in_sync: item.in_sync === true,
|
||||
applied: item.applied === true,
|
||||
apply_error: asString(item.apply_error),
|
||||
running: item.running === true,
|
||||
running_started_at: asString(item.running_started_at),
|
||||
run_last_error: asString(item.run_last_error),
|
||||
}
|
||||
}
|
||||
|
||||
async function readSchedule(path: string, failure: string, signal?: AbortSignal): Promise<BackupSchedule> {
|
||||
const response = await fetch(path, { signal, headers: { Accept: 'application/json' } })
|
||||
if (!response.ok) throw new Error(`${failure}(HTTP ${response.status})`)
|
||||
const value = await response.json() as unknown
|
||||
if (!record(value) || !record(value.data)) throw new Error('存储与备份响应无效')
|
||||
return scheduleProjection(value.data)
|
||||
}
|
||||
|
||||
export function fetchBackupSchedule(signal?: AbortSignal): Promise<BackupSchedule> {
|
||||
return readSchedule('/api/v1/backup-schedule', '读取备份计划失败', signal)
|
||||
}
|
||||
|
||||
// host 端点会 SSH 探测目标主机(计划 + 最近一次结果),单独调用以免拖慢首屏。
|
||||
export function fetchBackupScheduleHost(signal?: AbortSignal): Promise<BackupSchedule> {
|
||||
return readSchedule('/api/v1/backup-schedule/host', '读取目标主机上的备份状态失败', signal)
|
||||
}
|
||||
|
||||
async function writeSchedule(path: string, method: string, body: unknown, failure: string, signal?: AbortSignal): Promise<BackupSchedule> {
|
||||
const response = await fetch(path, {
|
||||
method, signal,
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'Idempotency-Key': newOperationID() },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
})
|
||||
if (!response.ok) {
|
||||
let reason = `${failure}(HTTP ${response.status})`
|
||||
try {
|
||||
const payload = await response.json() as unknown
|
||||
if (record(payload) && typeof payload.error === 'string') reason = payload.error
|
||||
} catch { /* keep the status text */ }
|
||||
throw new Error(reason)
|
||||
}
|
||||
const value = await response.json() as unknown
|
||||
if (!record(value) || !record(value.data)) throw new Error('存储与备份响应无效')
|
||||
return scheduleProjection(value.data)
|
||||
}
|
||||
|
||||
export interface BackupScheduleInput {
|
||||
enabled: boolean
|
||||
schedule_time: string
|
||||
retention_days: number
|
||||
retention_months: number
|
||||
// 默认 true:保存后立刻下发到目标主机(页面按钮"保存并下发")。
|
||||
apply?: boolean
|
||||
}
|
||||
|
||||
export function saveBackupSchedule(input: BackupScheduleInput, signal?: AbortSignal): Promise<BackupSchedule> {
|
||||
return writeSchedule('/api/v1/backup-schedule', 'PUT', input, '保存备份计划失败', signal)
|
||||
}
|
||||
|
||||
export function applyBackupSchedule(signal?: AbortSignal): Promise<BackupSchedule> {
|
||||
return writeSchedule('/api/v1/backup-schedule/apply', 'POST', undefined, '下发备份计划失败', signal)
|
||||
}
|
||||
|
||||
export async function runBackupNow(signal?: AbortSignal): Promise<BackupRunStart> {
|
||||
const response = await fetch('/api/v1/backup-schedule/run', {
|
||||
method: 'POST', signal,
|
||||
headers: { Accept: 'application/json', 'Idempotency-Key': newOperationID() },
|
||||
})
|
||||
if (!response.ok) {
|
||||
let reason = `触发备份失败(HTTP ${response.status})`
|
||||
try {
|
||||
const payload = await response.json() as unknown
|
||||
if (record(payload) && typeof payload.error === 'string') reason = payload.error
|
||||
} catch { /* keep the status text */ }
|
||||
throw new Error(reason)
|
||||
}
|
||||
const value = await response.json() as unknown
|
||||
if (!record(value) || !record(value.data)) throw new Error('触发备份响应无效')
|
||||
return { started: value.data.started === true, running: value.data.running === true }
|
||||
}
|
||||
Reference in New Issue
Block a user