feat(settings): 存储与备份只读摘要页对齐验收 #30
@@ -52,6 +52,14 @@ services:
|
||||
# 「整库版本」页:只读已封存的整库候选产物。归档根由 `libraryctl capture`
|
||||
# 在主机上写入(私有 0700),这里只挂只读;留空 = 未接线(页面降级展示原因)。
|
||||
LIBRARY_ARCHIVE_ROOT: "${LIBRARY_ARCHIVE_ROOT:-/var/lib/knowledge-governance/library}"
|
||||
# 「存储与备份」摘要页的归档配额(字节)。留空 = 未设置,页面显示"配额未设置";
|
||||
# 显式写 0 会被 appconfig 拒绝(必须为正整数),所以只能用空串表示未设置。
|
||||
LIBRARY_CAPACITY_BUDGET_BYTES: "${LIBRARY_CAPACITY_BUDGET_BYTES:-}"
|
||||
# 宿主每 5 分钟上报的整库备份元数据快照(collector 写入,平台只读)。
|
||||
# 留空 = 未接线,页面按验收显示"主机未上报";路径必须是宿主机侧绝对路径。
|
||||
BACKUP_HOST_METADATA_PATH: "${BACKUP_HOST_METADATA_PATH:-}"
|
||||
BACKUP_HOST_METADATA_MAX_AGE: "${BACKUP_HOST_METADATA_MAX_AGE:-15m}"
|
||||
BACKUP_HOST_READONLY_HOST_PATH: "${BACKUP_HOST_READONLY_HOST_PATH:-}"
|
||||
# 主机侧封存 agent 的 unix socket:api 只用它判断"能不能从页面发起",
|
||||
# worker 用它投递作业。容器里没有 Docker socket,也没有来源凭据。
|
||||
LIBRARY_AGENT_SOCKET: "${LIBRARY_AGENT_SOCKET:-/run/library-agent/agent.sock}"
|
||||
|
||||
@@ -1,717 +0,0 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import {
|
||||
BackupScheduleView,
|
||||
backupDaysValid,
|
||||
backupMonthsValid,
|
||||
backupTimeValid,
|
||||
copyBackupPath,
|
||||
formatBackupBytes,
|
||||
inventoryAlerts,
|
||||
inventorySnapshotState,
|
||||
inventoryUsage,
|
||||
runMoment,
|
||||
storageAlerts,
|
||||
storageAlertSummary,
|
||||
storageUsage,
|
||||
} from './BackupScheduleSection'
|
||||
import type { StorageDiskObservation } from './BackupScheduleSection'
|
||||
import type { BackupInventory } from './backupInventory'
|
||||
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_endpoint: '100.85.111.121:22',
|
||||
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 GiB = 1024 * 1024 * 1024
|
||||
|
||||
const diskFixture = (overrides: Partial<StorageDiskObservation> = {}): StorageDiskObservation => ({
|
||||
total_bytes: 240 * GiB,
|
||||
free_bytes: 48 * GiB,
|
||||
backup_bytes: 62 * GiB,
|
||||
other_volume_backup_bytes: 0,
|
||||
quota_bytes: 100 * GiB,
|
||||
reserve_bytes: 10 * GiB,
|
||||
estimate_bytes: 12 * GiB,
|
||||
sampled_at: '2026-11-19T02:00:00Z',
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const inventoryFixture = (overrides: Partial<BackupInventory> = {}): BackupInventory => {
|
||||
const baseInventory: BackupInventory = {
|
||||
wired: true,
|
||||
metadata: {
|
||||
configured: true,
|
||||
present: true,
|
||||
valid: true,
|
||||
fresh: true,
|
||||
complete: true,
|
||||
path: '/var/lib/knowledge-governance/backup-host/metadata.json',
|
||||
collected_at: '2026-11-19T03:30:00Z',
|
||||
age_seconds: 10,
|
||||
max_age_seconds: 900,
|
||||
schema_version: 1,
|
||||
generation: '20261119T033000Z-abc123',
|
||||
host: 'weknora-test',
|
||||
collector_version: 'backup-metadata/1',
|
||||
error: '',
|
||||
},
|
||||
root: '/srv/kb-backups/rds-logical',
|
||||
host_root: '/srv/kb-backups/rds-logical',
|
||||
source: 'weknora-test:/srv/kb-backups/rds-logical',
|
||||
observed_at: '2026-11-19T03:30:10Z',
|
||||
error: '',
|
||||
measurement: 'host_collector',
|
||||
mount: {
|
||||
container_root: '',
|
||||
mount_verified: true,
|
||||
lives_on_container_root: false,
|
||||
read_only: true,
|
||||
evidence: '宿主采集器:/dev/sdb1 挂在 /srv/kb-backups(ext4),API 不遍历备份目录',
|
||||
mount_point: '/srv/kb-backups',
|
||||
device: '/dev/sdb1',
|
||||
fs_type: 'ext4',
|
||||
},
|
||||
capacity: {
|
||||
measured: true,
|
||||
total_bytes: 240 * GiB,
|
||||
free_bytes: 48 * GiB,
|
||||
available_bytes: 45 * GiB,
|
||||
used_bytes: 192 * GiB,
|
||||
},
|
||||
batches: [
|
||||
{
|
||||
stamp: '20261118T193001Z',
|
||||
path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z',
|
||||
host_path: '/srv/kb-backups/rds-logical/20261118T193001Z',
|
||||
manifest_state: 'ok',
|
||||
manifest_path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z/MANIFEST.json',
|
||||
kind: 'rds-logical-backup',
|
||||
created_at: '20261118T193001Z',
|
||||
started_at: '20261118T192908Z',
|
||||
duration_seconds: 53,
|
||||
manifest_total_bytes: 1_393_646_469,
|
||||
apparent_bytes: 1_393_646_469,
|
||||
actual_bytes: 1_500_000_000,
|
||||
file_count: 214,
|
||||
sizes_complete: true,
|
||||
databases: [
|
||||
{
|
||||
name: 'weknora_v090prod',
|
||||
dir_name: 'weknora_v090prod.dir',
|
||||
path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z/weknora_v090prod.dir',
|
||||
host_path: '/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir',
|
||||
present: true,
|
||||
failed: false,
|
||||
in_manifest: true,
|
||||
apparent_bytes: 700_000,
|
||||
actual_bytes: 720_896,
|
||||
file_count: 12,
|
||||
},
|
||||
{
|
||||
name: 'weknora_test',
|
||||
dir_name: 'weknora_test.dir',
|
||||
path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z/weknora_test.dir',
|
||||
host_path: '/srv/kb-backups/rds-logical/20261118T193001Z/weknora_test.dir',
|
||||
present: true,
|
||||
failed: true,
|
||||
in_manifest: true,
|
||||
apparent_bytes: 10,
|
||||
actual_bytes: 4096,
|
||||
file_count: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
stamp: '20261117T193001Z',
|
||||
path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261117T193001Z',
|
||||
host_path: '/srv/kb-backups/rds-logical/20261117T193001Z',
|
||||
manifest_state: 'invalid',
|
||||
manifest_path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261117T193001Z/MANIFEST.json',
|
||||
manifest_error: '清单无法解析:unexpected end of JSON input',
|
||||
kind: '',
|
||||
created_at: '',
|
||||
started_at: '',
|
||||
duration_seconds: 0,
|
||||
manifest_total_bytes: 0,
|
||||
apparent_bytes: 2048,
|
||||
actual_bytes: 4096,
|
||||
file_count: 1,
|
||||
sizes_complete: true,
|
||||
databases: [
|
||||
{
|
||||
name: 'weknora_archive',
|
||||
dir_name: 'weknora_archive.dir',
|
||||
path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261117T193001Z/weknora_archive.dir',
|
||||
host_path: '/srv/kb-backups/rds-logical/20261117T193001Z/weknora_archive.dir',
|
||||
present: false,
|
||||
failed: false,
|
||||
in_manifest: false,
|
||||
apparent_bytes: 0,
|
||||
actual_bytes: 0,
|
||||
file_count: 0,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
totals: {
|
||||
batch_count: 2,
|
||||
database_count: 3,
|
||||
apparent_bytes: 1_393_648_517,
|
||||
actual_bytes: 1_500_004_096,
|
||||
latest_stamp: '20261118T193001Z',
|
||||
latest_actual_bytes: 1_500_000_000,
|
||||
complete: true,
|
||||
},
|
||||
incomplete_count: 1,
|
||||
skipped: [{ name: 'junk', reason: '不是批次目录' }],
|
||||
truncated: false,
|
||||
}
|
||||
return { ...baseInventory, ...overrides }
|
||||
}
|
||||
|
||||
const view = (
|
||||
overrides: Partial<BackupSchedule> = {},
|
||||
extra: Record<string, unknown> = {},
|
||||
disk: StorageDiskObservation | null = null
|
||||
) => {
|
||||
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()}
|
||||
disk={disk}
|
||||
inventory={(extra.inventory as BackupInventory) ?? null}
|
||||
inventoryLoading={(extra.inventoryLoading as boolean) ?? false}
|
||||
inventoryError={(extra.inventoryError as string | null) ?? null}
|
||||
onReloadInventory={vi.fn()}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
describe('BackupScheduleView', () => {
|
||||
it('按真实契约给出范围与读写方向,并把立即备份限定为整批', () => {
|
||||
const html = view()
|
||||
for (const text of [
|
||||
'存储与备份',
|
||||
'数据库整库逻辑备份',
|
||||
'范围与读写方向',
|
||||
'备份执行主机 weknora-test 本机直连 RDS',
|
||||
'最近批次含 2 个数据库',
|
||||
'元数据快照未读取',
|
||||
'元数据快照未读取:目录不可验证,不按设置推定',
|
||||
'整批 · 2 个数据库(weknora_test、dobotai_prod)',
|
||||
'100.85.111.121:22',
|
||||
'立即备份一次(整批 2 个数据库)',
|
||||
'不开放单库动作',
|
||||
'仅备份该库(不可用)',
|
||||
])
|
||||
expect(html).toContain(text)
|
||||
// 不存在把整批接口包装成单库操作的按钮文案。
|
||||
expect(html).not.toContain('>立即备份</button>')
|
||||
expect(html).not.toContain('生产 090')
|
||||
expect(html).not.toContain('weknora_v090prod')
|
||||
})
|
||||
|
||||
it('策略区分主机生效状态与编辑草稿,保留期与时间仍是真实可保存字段', () => {
|
||||
const html = view({}, { timeDraft: '05:10', daysDraft: '14' })
|
||||
expect(html).toContain('主机生效:每天 03:30 · 保留 7 天 · 每月 3 份 · 与设置已一致')
|
||||
expect(html).toContain('最后下发(历史)')
|
||||
expect(html).toContain('只记录当时下发结果,不能代表当前主机计划或执行状态')
|
||||
expect(html).toContain('编辑草稿:每天 05:10 · 保留 14 天')
|
||||
expect(html).toContain('有未保存修改,主机仍按生效计划执行')
|
||||
expect(html).toContain('type="time"')
|
||||
expect(html).toContain('value="05:10"')
|
||||
expect(html).toContain('储存天数')
|
||||
expect(html).toContain('每月归档保留')
|
||||
expect(html).toContain('保存并下发到主机')
|
||||
expect(html).toContain('重新下发当前设置')
|
||||
})
|
||||
|
||||
it('目录/配额/预留没有后端字段:控件禁用并写明原因,不会假装可保存', () => {
|
||||
const html = view()
|
||||
expect(html).toContain('备份主机上的目录')
|
||||
expect(html).toContain('元数据快照未读取')
|
||||
expect(html).toContain('检查目录(不可用)')
|
||||
expect(html).toContain('备份总配额(GiB)')
|
||||
expect(html).toContain('磁盘预留(GiB)')
|
||||
expect(html).toContain('不会被保存')
|
||||
expect(html).toContain('保存只提交后端契约里的四项')
|
||||
expect(html).toContain('disabled')
|
||||
})
|
||||
|
||||
it('宿主快照:展示全部批次、MANIFEST 状态、子库完整路径与实际占盘', () => {
|
||||
const html = view({}, { inventory: inventoryFixture() })
|
||||
for (const text of [
|
||||
'备份记录',
|
||||
'2 批 · 元数据快照',
|
||||
'最近批次 20261118T193001Z',
|
||||
'清单完整',
|
||||
'清单损坏',
|
||||
'批次戳 20261118T193001Z',
|
||||
'实际占盘',
|
||||
'weknora_v090prod',
|
||||
'weknora_test',
|
||||
'已写入',
|
||||
'失败',
|
||||
'目录缺失',
|
||||
'/srv/kb-backups/rds-logical/20261118T193001Z',
|
||||
'/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir',
|
||||
'/srv/kb-backups/rds-logical/20261117T193001Z/weknora_archive.dir',
|
||||
'复制子库目录',
|
||||
'清单无法解析',
|
||||
'有 1 个',
|
||||
'junk(不是批次目录)',
|
||||
'恢复验证:未接线',
|
||||
])
|
||||
expect(html).toContain(text)
|
||||
expect(html).not.toContain('子库路径待接口返回')
|
||||
expect(html).not.toContain('复制目录(不可用)')
|
||||
})
|
||||
|
||||
it('没有快照:不展示任何历史批次或伪造路径', () => {
|
||||
const html = view()
|
||||
expect(html).toContain('尚未读取宿主元数据快照')
|
||||
expect(html).not.toContain('批次戳')
|
||||
expect(html).not.toContain('/srv/kb-backups/rds-logical')
|
||||
})
|
||||
|
||||
it('快照未接线:说明与 SSH 计划读回独立,未读到不等于没有备份', () => {
|
||||
const base = inventoryFixture()
|
||||
const html = view(
|
||||
{},
|
||||
{
|
||||
inventory: inventoryFixture({
|
||||
wired: false,
|
||||
metadata: {
|
||||
...base.metadata,
|
||||
configured: false,
|
||||
present: false,
|
||||
valid: false,
|
||||
fresh: false,
|
||||
complete: false,
|
||||
error: '元数据快照未接线(BACKUP_HOST_METADATA_PATH 未设置)',
|
||||
},
|
||||
error: '元数据快照未接线(BACKUP_HOST_METADATA_PATH 未设置)',
|
||||
batches: [],
|
||||
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
|
||||
}),
|
||||
}
|
||||
)
|
||||
expect(html).toContain('元数据快照未接线')
|
||||
expect(html).toContain('未读到批次不等于没有备份')
|
||||
expect(html).not.toContain('/srv/kb-backups/rds-logical/20261118T193001Z')
|
||||
})
|
||||
|
||||
it('快照可读但没有批次时说明不能据此判断成功/失败', () => {
|
||||
const html = view(
|
||||
{
|
||||
last_run_stamp: '',
|
||||
last_run_created_at: '',
|
||||
last_run_databases: [],
|
||||
last_run_total_bytes: 0,
|
||||
host_reachable: false,
|
||||
},
|
||||
{
|
||||
inventory: inventoryFixture({
|
||||
batches: [],
|
||||
totals: {
|
||||
batch_count: 0,
|
||||
database_count: 0,
|
||||
apparent_bytes: 0,
|
||||
actual_bytes: 0,
|
||||
latest_stamp: '',
|
||||
latest_actual_bytes: 0,
|
||||
complete: true,
|
||||
},
|
||||
}),
|
||||
}
|
||||
)
|
||||
expect(html).toContain('宿主快照可读,但没有批次目录')
|
||||
expect(html).toContain('不能证明备份成功或失败')
|
||||
})
|
||||
|
||||
it('非管理员只读:没有保存/下发/立即备份按钮,只给当前设置', () => {
|
||||
const html = view({}, { isAdmin: false })
|
||||
expect(html).toContain('定时备份设置仅管理员可修改')
|
||||
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('远端 cron 可能仍在执行')
|
||||
expect(html).toContain('历史下发不能代替实时状态')
|
||||
expect(html).toContain('最后下发(历史)')
|
||||
expect(html).toContain('只记录当时下发结果,不能代表当前主机计划或执行状态')
|
||||
expect(html).toContain('无法比对(未读取主机计划)')
|
||||
expect(html).toContain('未探测(平台未挂载主机凭据)')
|
||||
expect(html).toContain('目标主机凭据未挂载')
|
||||
// 没读到主机就断言"不会执行"是同类误报。
|
||||
expect(html).not.toContain('不会执行')
|
||||
expect(html).not.toContain('未接通备份执行主机')
|
||||
expect(html).toContain('disabled')
|
||||
})
|
||||
|
||||
it('主机已接线但尚未探测:区分"连不上"与"还没读",不按设置推定', () => {
|
||||
const html = view({ host_reachable: false, host_error: '', host_checked_at: '', in_sync: false })
|
||||
expect(html).toContain('weknora-test · 尚未探测')
|
||||
expect(html).not.toContain('weknora-test · 连接失败')
|
||||
expect(html).toContain('尚未探测当前主机计划:不能按设置或历史下发推定')
|
||||
expect(html).toContain('尚未比对')
|
||||
expect(html).toContain('尚未探测主机,无法确认下一次执行')
|
||||
})
|
||||
|
||||
it('连不上主机:报连接失败与拨号地址,脚本状态写未知而不是"缺失"', () => {
|
||||
const html = view({
|
||||
host_reachable: false,
|
||||
host_endpoint: '120.76.217.51:22',
|
||||
host_error:
|
||||
'目标主机 weknora-test 不可达(ssh: connect to host 120.76.217.51 port 22: Operation timed out);未执行任何主机侧脚本,脚本与计划状态未知(拨号地址 120.76.217.51:22)',
|
||||
in_sync: false,
|
||||
host_script_present: false,
|
||||
})
|
||||
expect(html).toContain('weknora-test · 连接失败')
|
||||
expect(html).toContain('120.76.217.51:22')
|
||||
expect(html).toContain('未知(未连上主机,未执行主机侧脚本)')
|
||||
expect(html).not.toContain('<dt>备份脚本</dt><dd>缺失</dd>')
|
||||
expect(html).toContain('主机连不上:以下"主机生效"状态未知')
|
||||
expect(html).toContain('无法比对(主机不可达)')
|
||||
})
|
||||
|
||||
it('已连上且脚本真的不在:这时才显示"缺失"', () => {
|
||||
const html = view({ host_reachable: true, host_script_present: false, in_sync: false })
|
||||
expect(html).toContain('weknora-test · 已连接')
|
||||
expect(html).toContain('缺失')
|
||||
expect(html).not.toContain('未知(未连上主机')
|
||||
})
|
||||
|
||||
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('正在备份')
|
||||
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('最近一次备份不重复显示同一个时间戳', () => {
|
||||
expect(runMoment({ last_run_stamp: '20261009T060736Z', last_run_created_at: '20261009T060736Z' })).toBe('')
|
||||
expect(runMoment({ last_run_stamp: '20261009T060736Z', last_run_created_at: '' })).toBe('')
|
||||
expect(runMoment({ last_run_stamp: '20261009T060736Z', last_run_created_at: '2026-10-09T06:07:36Z' })).not.toBe('')
|
||||
})
|
||||
|
||||
it('体积格式化:未知与零分开', () => {
|
||||
expect(formatBackupBytes(0)).toBe('0 B')
|
||||
expect(formatBackupBytes(null)).toBe('—')
|
||||
expect(formatBackupBytes(undefined)).toBe('—')
|
||||
expect(formatBackupBytes(1024 * 1024)).toBe('1.0 MiB')
|
||||
expect(formatBackupBytes(4096)).toBe('4.0 KiB')
|
||||
expect(formatBackupBytes(720896)).toBe('0.7 MiB')
|
||||
expect(formatBackupBytes(2 * 1024 * 1024 * 1024)).toBe('2.00 GiB')
|
||||
})
|
||||
})
|
||||
|
||||
describe('整盘占用与告警', () => {
|
||||
it('没有快照时:不显示示例容量,四条告警只报未知原因', () => {
|
||||
const html = view()
|
||||
expect(html).toContain('占盘未知 · 不使用部分字节')
|
||||
expect(html).toContain('宿主单项元数据采集器')
|
||||
expect(html).toContain('无法判定')
|
||||
expect(html).toContain('整盘总量 / 空闲 / 备份实际占盘:未接线')
|
||||
// 原型里的示例容量不能被当成产品事实带进来。
|
||||
expect(html).not.toContain('总容量 240 GiB')
|
||||
expect(html).not.toContain('总容量 500 GiB')
|
||||
expect(html).not.toContain('可再写')
|
||||
})
|
||||
|
||||
it('四段色带按真实读数计算:系统其他、备份已用、配额内空闲、配额外空闲', () => {
|
||||
const usage = storageUsage(diskFixture())
|
||||
expect(usage.system_other).toBe(130 * GiB) // 240 - 48 - 62
|
||||
expect(usage.backup).toBe(62 * GiB)
|
||||
expect(usage.quota_free).toBe(38 * GiB)
|
||||
expect(usage.beyond_quota_free).toBe(10 * GiB) // 48 - 38
|
||||
expect(usage.allowance).toBe(38 * GiB)
|
||||
const html = view({}, {}, diskFixture())
|
||||
expect(html).toContain('系统其他占用 130 GiB')
|
||||
expect(html).toContain('备份已用 62 GiB')
|
||||
expect(html).toContain('配额内空闲 38 GiB')
|
||||
expect(html).toContain('配额外空闲 10 GiB')
|
||||
expect(html).toContain('四项均正常')
|
||||
})
|
||||
|
||||
it('磁盘不足:只剩磁盘告警,差值与预计新增都来自读数', () => {
|
||||
const alerts = storageAlerts(diskFixture({ free_bytes: 20 * GiB, quota_bytes: 80 * GiB }))
|
||||
expect(alerts.find((item) => item.code === 'disk_low')?.active).toBe(true)
|
||||
expect(alerts.find((item) => item.code === 'quota_low')?.active).toBe(false)
|
||||
expect(alerts.find((item) => item.code === 'both_low')?.active).toBe(false)
|
||||
expect(storageAlertSummary(alerts)).toBe('磁盘不足')
|
||||
const html = view({}, {}, diskFixture({ free_bytes: 20 * GiB, quota_bytes: 80 * GiB }))
|
||||
expect(html).toContain('差 2 GiB')
|
||||
})
|
||||
|
||||
it('配额不足:磁盘够、配额差 7 GiB', () => {
|
||||
const alerts = storageAlerts(diskFixture({ backup_bytes: 95 * GiB }))
|
||||
expect(alerts.find((item) => item.code === 'quota_low')?.active).toBe(true)
|
||||
expect(alerts.find((item) => item.code === 'disk_low')?.active).toBe(false)
|
||||
expect(alerts.find((item) => item.code === 'quota_low')?.detail).toContain('差 7 GiB')
|
||||
expect(storageAlertSummary(alerts)).toBe('配额不足')
|
||||
})
|
||||
|
||||
it('两者同时不足:第三条告警成立', () => {
|
||||
const alerts = storageAlerts(diskFixture({ free_bytes: 20 * GiB, backup_bytes: 95 * GiB }))
|
||||
expect(alerts.find((item) => item.code === 'both_low')?.active).toBe(true)
|
||||
expect(storageAlertSummary(alerts)).toContain('磁盘与配额同时不足')
|
||||
})
|
||||
|
||||
it('配额超出物理空闲:配额余量大于盘上空闲时单独告警', () => {
|
||||
const alerts = storageAlerts(diskFixture({ quota_bytes: 200 * GiB }))
|
||||
expect(alerts.find((item) => item.code === 'quota_over_physical')?.active).toBe(true)
|
||||
expect(alerts.find((item) => item.code === 'quota_over_physical')?.detail).toContain('超出部分画不进磁盘')
|
||||
})
|
||||
|
||||
it('缺下次新增体积时,磁盘/配额判定保持未知而不是默认正常', () => {
|
||||
const alerts = storageAlerts(diskFixture({ estimate_bytes: null }))
|
||||
expect(alerts.filter((item) => !item.known).map((item) => item.code)).toEqual(['disk_low', 'quota_low', 'both_low'])
|
||||
})
|
||||
|
||||
it('真实快照:整盘色带取采集器容量与 st_blocks 实际占盘', () => {
|
||||
const inventory = inventoryFixture()
|
||||
const usage = inventoryUsage(inventory)
|
||||
expect(usage).not.toBeNull()
|
||||
expect(usage!.total).toBe(240 * GiB)
|
||||
expect(usage!.free).toBe(45 * GiB)
|
||||
expect(usage!.backup).toBe(1_500_004_096)
|
||||
expect(usage!.system_other).toBe(192 * GiB - 1_500_004_096)
|
||||
const alerts = inventoryAlerts(inventory)
|
||||
expect(alerts.find((item) => item.code === 'disk_low')?.known).toBe(true)
|
||||
expect(alerts.find((item) => item.code === 'disk_low')?.active).toBe(false)
|
||||
expect(alerts.find((item) => item.code === 'quota_low')?.known).toBe(false)
|
||||
expect(storageAlertSummary(alerts)).toBe('磁盘项正常 · 配额字段未接线')
|
||||
const html = view({}, { inventory })
|
||||
for (const text of [
|
||||
'宿主采集器实测',
|
||||
'系统其他占用',
|
||||
'备份实际占盘',
|
||||
'可用',
|
||||
'配额内/外 —(无配额字段)',
|
||||
'文件系统已用',
|
||||
'采集时间',
|
||||
'读回时间',
|
||||
'(API 读回)',
|
||||
'备份文件系统必须由备份主机可写',
|
||||
'空间预测仅以上次整批实际占盘 1.40 GiB',
|
||||
'宿主采集器:/dev/sdb1 挂在 /srv/kb-backups',
|
||||
'磁盘项正常 · 配额字段未接线',
|
||||
'0.7 MiB',
|
||||
'重新盘点(仅重读快照)',
|
||||
])
|
||||
expect(html).toContain(text)
|
||||
expect(html).not.toContain('挂载可写')
|
||||
expect(html).not.toContain('不是只读')
|
||||
expect(html).not.toContain('缺主机磁盘读数')
|
||||
expect(html).not.toContain('0.0 MiB')
|
||||
})
|
||||
|
||||
it('过期快照:目录与历史标已过期,不显示未接线,也不沿用旧批次/旧容量', () => {
|
||||
const base = inventoryFixture()
|
||||
const stale = inventoryFixture({
|
||||
metadata: {
|
||||
...base.metadata,
|
||||
valid: false,
|
||||
fresh: false,
|
||||
complete: false,
|
||||
age_seconds: 1200,
|
||||
error: '元数据已陈旧:采集于 2026-11-19T03:30:00Z,超过 15m0s',
|
||||
},
|
||||
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
|
||||
totals: { ...base.totals, apparent_bytes: null, actual_bytes: null, latest_actual_bytes: null, complete: false },
|
||||
// 即使 API 意外保留旧批次,页面也不得用过期快照的路径/容量。
|
||||
batches: base.batches,
|
||||
})
|
||||
expect(inventorySnapshotState(stale)).toBe('stale')
|
||||
expect(inventoryUsage(stale)).toBeNull()
|
||||
const alerts = inventoryAlerts(stale)
|
||||
expect(alerts.find((item) => item.code === 'disk_low')?.known).toBe(false)
|
||||
expect(alerts.find((item) => item.code === 'disk_low')?.detail).toContain('陈旧')
|
||||
const html = view({}, { inventory: stale })
|
||||
for (const text of [
|
||||
'元数据快照已过期',
|
||||
'采集时间',
|
||||
'年龄 1200 秒 / 上限 900 秒',
|
||||
'已过期',
|
||||
'读回时间',
|
||||
'(API 读回)',
|
||||
'不展示旧批次',
|
||||
'元数据快照已过期:目录不可验证,不沿用旧路径',
|
||||
'等待宿主重新采集',
|
||||
'旧批次、旧目录与旧容量都不再展示',
|
||||
])
|
||||
expect(html).toContain(text)
|
||||
expect(html).not.toContain('元数据快照未接线')
|
||||
expect(html).not.toContain('/20261118T193001Z')
|
||||
expect(html).not.toContain('实际占盘 1.40 GiB')
|
||||
expect(html).not.toContain('文件系统已用')
|
||||
})
|
||||
|
||||
it('未配置快照:明确未接线,不能冒充过期或展示目录/历史', () => {
|
||||
const base = inventoryFixture()
|
||||
const unconfigured = inventoryFixture({
|
||||
wired: false,
|
||||
metadata: {
|
||||
...base.metadata,
|
||||
configured: false,
|
||||
present: false,
|
||||
valid: false,
|
||||
fresh: false,
|
||||
complete: false,
|
||||
error: '元数据快照未接线(BACKUP_HOST_METADATA_PATH 未设置)',
|
||||
},
|
||||
source: '',
|
||||
root: '',
|
||||
host_root: '',
|
||||
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
|
||||
totals: { ...base.totals, apparent_bytes: null, actual_bytes: null, latest_actual_bytes: null, complete: false },
|
||||
batches: [],
|
||||
})
|
||||
expect(inventorySnapshotState(unconfigured)).toBe('unconfigured')
|
||||
const html = view({}, { inventory: unconfigured })
|
||||
expect(html).toContain('元数据快照未接线')
|
||||
expect(html).toContain('目录不可证明')
|
||||
expect(html).not.toContain('元数据快照已过期')
|
||||
expect(html).not.toContain('不展示旧目录路径')
|
||||
})
|
||||
|
||||
it('快照请求失败:与未配置/过期分开,不展示目录或旧批次', () => {
|
||||
const html = view({}, { inventoryError: 'HTTP 503' })
|
||||
expect(html).toContain('元数据快照读取失败')
|
||||
expect(html).toContain('快照请求失败:HTTP 503')
|
||||
expect(html).toContain('目录不可验证')
|
||||
expect(html).not.toContain('元数据快照未接线')
|
||||
expect(html).not.toContain('元数据快照已过期')
|
||||
})
|
||||
|
||||
it('不完整快照:容量图与占盘不使用部分字节', () => {
|
||||
const base = inventoryFixture()
|
||||
const inventory = inventoryFixture({
|
||||
metadata: {
|
||||
...base.metadata,
|
||||
complete: false,
|
||||
error: '采集不完整:遍历失败:PermissionError: Permission denied',
|
||||
},
|
||||
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
|
||||
totals: { ...base.totals, apparent_bytes: null, actual_bytes: null, latest_actual_bytes: null, complete: false },
|
||||
batches: base.batches.map((batch) => ({
|
||||
...batch,
|
||||
apparent_bytes: null,
|
||||
actual_bytes: null,
|
||||
file_count: null,
|
||||
sizes_complete: false,
|
||||
sizes_error: '宿主采集器该项不完整,占盘未知',
|
||||
databases: batch.databases.map((database) => ({
|
||||
...database,
|
||||
apparent_bytes: null,
|
||||
actual_bytes: null,
|
||||
file_count: null,
|
||||
})),
|
||||
})),
|
||||
})
|
||||
expect(inventoryUsage(inventory)).toBeNull()
|
||||
const alerts = inventoryAlerts(inventory)
|
||||
expect(alerts.find((item) => item.code === 'disk_low')?.known).toBe(false)
|
||||
expect(alerts.find((item) => item.code === 'disk_low')?.detail).toContain('不完整')
|
||||
expect(storageAlertSummary(alerts)).toBe('无法判定(缺读数与配额字段)')
|
||||
const html = view({}, { inventory })
|
||||
expect(html).toContain('占盘未知 · 不使用部分字节')
|
||||
expect(html).toContain('采集快照不完整:所有批次占盘与容量未知')
|
||||
expect(html).toContain('占盘未知(采集不完整)')
|
||||
expect(html).not.toContain('备份实际占盘 1.40 GiB')
|
||||
expect(html).not.toContain('缺主机磁盘读数')
|
||||
})
|
||||
|
||||
it('复制路径:空值与不可用按钮不谎报成功', async () => {
|
||||
expect(await copyBackupPath('')).toBe(false)
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,175 +0,0 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { fetchLibraryStorage, formatBytes, type LibraryStorage } from './librarySnapshots'
|
||||
import './libraryStorage.css'
|
||||
|
||||
// 系统设置 → 存储管理:只读展示整库归档的真实口径。
|
||||
// 保留策略、依赖保护、清理预览都只是"如果清理会怎样",没有任何删除动作;
|
||||
// 自动清理恒为关闭,策略未设置时不生成候选。
|
||||
export function LibraryStorageSection() {
|
||||
const [data, setData] = useState<LibraryStorage | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController()
|
||||
fetchLibraryStorage(controller.signal)
|
||||
.then((value) => {
|
||||
setData(value)
|
||||
setError(null)
|
||||
})
|
||||
.catch((loadError) => {
|
||||
if ((loadError as Error).name === 'AbortError') return
|
||||
setError(loadError instanceof Error ? loadError.message : '读取存储用量失败')
|
||||
})
|
||||
.finally(() => setLoading(false))
|
||||
return () => controller.abort()
|
||||
}, [])
|
||||
|
||||
const plan = data?.plan
|
||||
const policyConfigured = Boolean(plan?.policy_configured)
|
||||
|
||||
return (
|
||||
<section className="library-storage" aria-label="存储管理">
|
||||
<header>
|
||||
<h3>归档占用(版本快照,不是数据库备份)</h3>
|
||||
<p>
|
||||
只读口径:被版本引用的去重内容、blob 文件表观/实际分配字节、未被引用对象、清单文件。
|
||||
这些归档文件与上面的整库数据库备份分开计量,不能相加。
|
||||
</p>
|
||||
</header>
|
||||
{loading ? <p className="library-storage-hint">读取中…</p> : null}
|
||||
{error ? (
|
||||
<div className="library-storage-blocked">
|
||||
<strong>读取失败</strong>
|
||||
<p>{error}</p>
|
||||
</div>
|
||||
) : null}
|
||||
{data && !data.available ? <p className="library-storage-hint">{data.reason || '归档未接线'}</p> : null}
|
||||
|
||||
{data?.available ? (
|
||||
<>
|
||||
<dl className="library-storage-grid">
|
||||
<div>
|
||||
<dt>版本数</dt>
|
||||
<dd>{data.versions.length}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>被版本引用的去重内容</dt>
|
||||
<dd>{formatBytes(data.content_bytes)}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>blob 文件(表观)</dt>
|
||||
<dd>{formatBytes(data.blob_file_bytes)}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>blob 实际分配</dt>
|
||||
<dd>{formatBytes(data.blob_allocated_bytes)}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>未被任何版本引用</dt>
|
||||
<dd>
|
||||
{data.unreferenced_blobs} 个 / {formatBytes(data.unreferenced_bytes)}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>清单文件</dt>
|
||||
<dd>{formatBytes(data.manifest_file_bytes)}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<div className="library-storage-panel">
|
||||
<h4>容量门禁</h4>
|
||||
{data.capacity.configured ? (
|
||||
<p>
|
||||
预算 {formatBytes(data.capacity.budget_bytes)} · 当前 {formatBytes(data.capacity.current_bytes)} ·
|
||||
目标版本约 {formatBytes(data.capacity.required_bytes)} →{' '}
|
||||
{data.capacity.ok ? '可写入' : `阻断:${data.capacity.reason}`}
|
||||
</p>
|
||||
) : (
|
||||
<p className="library-storage-warn">
|
||||
容量预算未设置(LIBRARY_CAPACITY_BUDGET_BYTES):无法证明装得下,生产写入按阻断处理。
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<details className="settings-details" open={!policyConfigured}>
|
||||
<summary>保留策略与清理预览(未设置时按“全部保留”处理)</summary>
|
||||
<div className="library-storage-panel">
|
||||
<h4>保留与依赖保护</h4>
|
||||
<p>
|
||||
{policyConfigured
|
||||
? `策略:${[
|
||||
plan && plan.policy.keep_versions > 0 ? `保留最近 ${plan.policy.keep_versions} 个版本` : '',
|
||||
plan && plan.policy.keep_days > 0 ? `保留 ${plan.policy.keep_days} 天` : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' + ')}`
|
||||
: '策略:未设置(不生成清理候选)'}
|
||||
</p>
|
||||
<p>
|
||||
受保护版本 {plan?.protected.length ?? 0} 个:生产生效、每库最近封存、每次生产预备份、运行中作业引用,
|
||||
不论多久都不会进入候选。
|
||||
</p>
|
||||
{data.versions.filter((item) => item.protected).length > 0 ? (
|
||||
<ul className="library-storage-versions">
|
||||
{data.versions
|
||||
.filter((item) => item.protected)
|
||||
.map((item) => (
|
||||
<li key={item.id}>
|
||||
<code>{item.id.slice(0, 12)}</code> {item.kind} · {(item.protected_by ?? []).join('、')}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="library-storage-panel">
|
||||
<h4>清理预览</h4>
|
||||
{policyConfigured ? (
|
||||
plan && plan.candidates.length > 0 ? (
|
||||
<>
|
||||
<p>
|
||||
按策略可考虑清理 {plan.candidates.length} 个版本,独占字节上限{' '}
|
||||
{formatBytes(plan.reclaim_preview_bytes)}(共享归档文件不会因此释放,这不是可回收空间)。
|
||||
</p>
|
||||
<ul className="library-storage-versions">
|
||||
{plan.candidates.map((item) => (
|
||||
<li key={item.id}>
|
||||
<code>{item.id.slice(0, 12)}</code> {item.kind} · {item.reason.join(';')} ·{' '}
|
||||
{formatBytes(item.exclusive_bytes)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
) : (
|
||||
<p>按当前策略没有可清理的候选版本。</p>
|
||||
)
|
||||
) : (
|
||||
<p className="library-storage-warn">
|
||||
保留数量与天数都未设置,按「全部保留」处理:不生成候选,也不提供默认值。
|
||||
</p>
|
||||
)}
|
||||
{plan?.blocked.length ? (
|
||||
<ul className="library-storage-blocked-list">
|
||||
{plan.blocked.map((item) => (
|
||||
<li key={item}>{item}</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<ul className="library-storage-limits">
|
||||
<li>自动清理:{data.automatic_cleanup ? '开启' : '保持关闭'}(页面不提供删除动作)</li>
|
||||
<li>实际删除需要单独授权,本页只给预览</li>
|
||||
<li>以上数字都不是「可回收空间」,不能用来估算清理收益</li>
|
||||
{data.notes.map((note) => (
|
||||
// 服务端注记里的 blob 指归档文件:页面统一术语,不把实现细节甩给操作者。
|
||||
<li key={note}>{note.replace(/blob/gi, '归档文件')}</li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
</>
|
||||
) : null}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { StorageBackupSummary } from './StorageBackupSummary'
|
||||
import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
|
||||
import type { LibraryStorage } from './librarySnapshots'
|
||||
|
||||
const GIB = 1024 ** 3
|
||||
const TB = 1024 * GIB
|
||||
|
||||
const batch = (index: number, overrides: Partial<BackupInventoryBatch> = {}): BackupInventoryBatch => {
|
||||
const stamp = `202611${String(24 - Math.floor(index / 24)).padStart(2, '0')}T${String(index % 24).padStart(2, '0')}0000Z`
|
||||
const created = `2026-11-${String(24 - Math.floor(index / 24)).padStart(2, '0')}T${String(index % 24).padStart(2, '0')}:00:00Z`
|
||||
return {
|
||||
stamp,
|
||||
path: `/srv/kb-backups/rds-logical/${stamp}`,
|
||||
host_path: `/srv/kb-backups/rds-logical/${stamp}`,
|
||||
manifest_state: 'ok',
|
||||
manifest_path: `/srv/kb-backups/rds-logical/${stamp}/MANIFEST.json`,
|
||||
kind: 'rds',
|
||||
created_at: created,
|
||||
started_at: created,
|
||||
duration_seconds: 240,
|
||||
manifest_total_bytes: 10 * GIB,
|
||||
apparent_bytes: 10 * GIB,
|
||||
actual_bytes: 9 * GIB,
|
||||
file_count: 120,
|
||||
sizes_complete: true,
|
||||
databases: [
|
||||
{
|
||||
name: 'weknora',
|
||||
dir_name: 'weknora.dir',
|
||||
path: `/srv/kb-backups/rds-logical/${stamp}/weknora.dir`,
|
||||
host_path: `/srv/kb-backups/rds-logical/${stamp}/weknora.dir`,
|
||||
present: true,
|
||||
failed: false,
|
||||
in_manifest: true,
|
||||
apparent_bytes: 10 * GIB,
|
||||
actual_bytes: 9 * GIB,
|
||||
file_count: 120,
|
||||
},
|
||||
],
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
const inventory = (overrides: Partial<BackupInventory> = {}): BackupInventory => ({
|
||||
wired: true,
|
||||
metadata: {
|
||||
configured: true,
|
||||
present: true,
|
||||
valid: true,
|
||||
fresh: true,
|
||||
complete: true,
|
||||
path: '/var/lib/kb-backups/metadata.json',
|
||||
collected_at: '2026-11-24T10:17:00Z',
|
||||
age_seconds: 60,
|
||||
max_age_seconds: 900,
|
||||
schema_version: 1,
|
||||
generation: 'g-1',
|
||||
host: 'backup-host',
|
||||
collector_version: '1',
|
||||
error: '',
|
||||
},
|
||||
root: '/srv/kb-backups/rds-logical',
|
||||
host_root: '/srv/kb-backups/rds-logical',
|
||||
source: 'host',
|
||||
observed_at: '2026-11-24T10:18:00Z',
|
||||
measurement: 'host-reported',
|
||||
mount: {
|
||||
container_root: '',
|
||||
mount_verified: true,
|
||||
lives_on_container_root: false,
|
||||
read_only: true,
|
||||
evidence: '',
|
||||
mount_point: '/srv/kb-backups',
|
||||
device: '/dev/sdb1',
|
||||
fs_type: 'ext4',
|
||||
},
|
||||
capacity: {
|
||||
measured: true,
|
||||
total_bytes: 2 * TB,
|
||||
free_bytes: 1.2 * TB,
|
||||
available_bytes: 1.2 * TB,
|
||||
used_bytes: 0.8 * TB,
|
||||
},
|
||||
batches: [batch(0), batch(1, { manifest_state: 'invalid' })],
|
||||
totals: {
|
||||
batch_count: 2,
|
||||
database_count: 2,
|
||||
apparent_bytes: 20 * GIB,
|
||||
actual_bytes: 18 * GIB,
|
||||
latest_stamp: '20261124T000000Z',
|
||||
latest_actual_bytes: 9 * GIB,
|
||||
complete: true,
|
||||
},
|
||||
incomplete_count: 0,
|
||||
skipped: [],
|
||||
truncated: false,
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const archive: LibraryStorage = {
|
||||
available: true,
|
||||
archive_root: '/var/lib/knowledge-governance/library',
|
||||
versions: [],
|
||||
content_bytes: 41_231_686_042,
|
||||
blob_file_bytes: 0,
|
||||
blob_allocated_bytes: 0,
|
||||
unreferenced_blobs: 0,
|
||||
unreferenced_bytes: 0,
|
||||
manifest_file_bytes: 0,
|
||||
policy: { keep_versions: 0, keep_days: 0 },
|
||||
capacity: {
|
||||
budget_bytes: 100 * GIB,
|
||||
current_bytes: 41_231_686_042,
|
||||
required_bytes: 0,
|
||||
projected_bytes: 41_231_686_042,
|
||||
configured: true,
|
||||
ok: true,
|
||||
},
|
||||
automatic_cleanup: false,
|
||||
notes: [],
|
||||
}
|
||||
|
||||
let root: Root
|
||||
let container: HTMLDivElement
|
||||
let fetcher: ReturnType<typeof vi.fn<(path: string, init?: RequestInit) => Promise<Response>>>
|
||||
|
||||
const paths = (): string[] => fetcher.mock.calls.map((call) => String(call[0]))
|
||||
const flush = async () => {
|
||||
await act(async () => {
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
})
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement('div')
|
||||
document.body.append(container)
|
||||
root = createRoot(container)
|
||||
fetcher = vi.fn(async (path: string) => {
|
||||
if (path.endsWith('/inventory')) {
|
||||
return new Response(JSON.stringify({ data: inventory() }), { status: 200 })
|
||||
}
|
||||
return new Response(JSON.stringify(archive), { status: 200 })
|
||||
})
|
||||
vi.stubGlobal('fetch', fetcher)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root.unmount())
|
||||
container.remove()
|
||||
vi.unstubAllGlobals()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
describe('StorageBackupSummary', () => {
|
||||
it('renders directory, recent outcomes, archive usage, disk and the alert table', async () => {
|
||||
act(() => root.render(<StorageBackupSummary />))
|
||||
await flush()
|
||||
const text = container.textContent || ''
|
||||
expect(text).toContain('备份目录')
|
||||
expect(text).toContain('/srv/kb-backups/rds-logical')
|
||||
expect(text).toContain('最近成功')
|
||||
expect(text).toContain('最近失败')
|
||||
expect(text).toContain('归档占用')
|
||||
expect(text).toContain('38.4 GB')
|
||||
expect(text).toContain('配额 100 GB')
|
||||
expect(text).toContain('磁盘剩余')
|
||||
expect(text).toContain('1.2 TB')
|
||||
expect(text).toContain('上次上报')
|
||||
expect(text).toContain('清单损坏')
|
||||
expect(container.querySelectorAll('tbody tr')).toHaveLength(2)
|
||||
expect(container.querySelectorAll('.storage-alerts li')).toHaveLength(4)
|
||||
expect(text).not.toContain('无法判定')
|
||||
expect(text).not.toContain('未接线')
|
||||
expect(text).not.toContain('示例')
|
||||
})
|
||||
|
||||
it('asks for both read-only endpoints and refreshes once per 60 seconds while visible', async () => {
|
||||
vi.useFakeTimers()
|
||||
act(() => root.render(<StorageBackupSummary />))
|
||||
await flush()
|
||||
expect(paths().filter((path) => path.endsWith('/inventory'))).toHaveLength(1)
|
||||
expect(paths().filter((path) => path.endsWith('/library/storage'))).toHaveLength(1)
|
||||
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(60_000)
|
||||
})
|
||||
await flush()
|
||||
expect(paths().filter((path) => path.endsWith('/inventory'))).toHaveLength(2)
|
||||
|
||||
Object.defineProperty(document, 'visibilityState', { value: 'hidden', configurable: true })
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(60_000)
|
||||
})
|
||||
await flush()
|
||||
expect(paths().filter((path) => path.endsWith('/inventory'))).toHaveLength(2)
|
||||
Object.defineProperty(document, 'visibilityState', { value: 'visible', configurable: true })
|
||||
})
|
||||
|
||||
it('shows 主机未上报 with the last report time and no zero placeholders when the host is unwired', async () => {
|
||||
fetcher.mockImplementation(async (path: string) => {
|
||||
if (path.endsWith('/inventory')) {
|
||||
const wired = inventory()
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
data: {
|
||||
...wired,
|
||||
wired: false,
|
||||
root: '',
|
||||
host_root: '',
|
||||
batches: [],
|
||||
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
|
||||
metadata: { ...wired.metadata, present: false, valid: false, fresh: false, collected_at: '' },
|
||||
},
|
||||
}),
|
||||
{ status: 200 }
|
||||
)
|
||||
}
|
||||
return new Response(
|
||||
JSON.stringify({ ...archive, available: false, capacity: { ...archive.capacity, configured: false } }),
|
||||
{
|
||||
status: 200,
|
||||
}
|
||||
)
|
||||
})
|
||||
act(() => root.render(<StorageBackupSummary />))
|
||||
await flush()
|
||||
const text = container.textContent || ''
|
||||
expect(text).toContain('主机未上报')
|
||||
expect(text).toContain('上次上报 —')
|
||||
expect(text).toContain('未接入宿主上报')
|
||||
expect(text).not.toContain('0 B')
|
||||
expect(text).not.toContain('0 GB')
|
||||
expect(container.querySelectorAll('tbody tr')).toHaveLength(0)
|
||||
expect(text).toContain('主机未上报(上次上报 —)')
|
||||
})
|
||||
|
||||
it('copies a path once the browser grants clipboard access', async () => {
|
||||
const writeText = vi.fn().mockResolvedValue(undefined)
|
||||
Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true })
|
||||
act(() => root.render(<StorageBackupSummary />))
|
||||
await flush()
|
||||
const button = container.querySelector<HTMLButtonElement>('button[aria-label="复制备份目录"]')
|
||||
expect(button).not.toBeNull()
|
||||
await act(async () => {
|
||||
button!.click()
|
||||
await Promise.resolve()
|
||||
})
|
||||
expect(writeText).toHaveBeenCalledWith('/srv/kb-backups/rds-logical')
|
||||
expect(button!.textContent).toBe('已复制')
|
||||
})
|
||||
|
||||
it('pages long batch lists 20 at a time', async () => {
|
||||
fetcher.mockImplementation(async (path: string) => {
|
||||
if (path.endsWith('/inventory')) {
|
||||
const batches = Array.from({ length: 25 }, (_, index) => batch(index))
|
||||
return new Response(
|
||||
JSON.stringify({ data: { ...inventory(), batches, totals: { ...inventory().totals, batch_count: 25 } } }),
|
||||
{ status: 200 }
|
||||
)
|
||||
}
|
||||
return new Response(JSON.stringify(archive), { status: 200 })
|
||||
})
|
||||
act(() => root.render(<StorageBackupSummary />))
|
||||
await flush()
|
||||
expect(container.querySelectorAll('tbody tr')).toHaveLength(20)
|
||||
const more = container.querySelector<HTMLButtonElement>('.storage-more')
|
||||
expect(more?.textContent).toContain('剩余 5 个')
|
||||
await act(async () => {
|
||||
more!.click()
|
||||
})
|
||||
expect(container.querySelectorAll('tbody tr')).toHaveLength(25)
|
||||
expect(container.querySelector('.storage-more')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,271 @@
|
||||
// 「系统设置 → 存储与备份」只读摘要页:目录、最近成功/失败、归档占用、磁盘剩余、
|
||||
// 四条容量告警和批次列表。数据只来自宿主每 5 分钟上报的快照与归档库接口,
|
||||
// 本页没有任何写操作;读不到的量显示"主机未上报"或"—",不用 0 占位。
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
|
||||
import { fetchBackupInventory } from './backupInventory'
|
||||
import type { BackupInventory } from './backupInventory'
|
||||
import { fetchLibraryStorage } from './librarySnapshots'
|
||||
import type { LibraryStorage } from './librarySnapshots'
|
||||
import {
|
||||
UNKNOWN,
|
||||
batchOutcome,
|
||||
batchWhen,
|
||||
formatSize,
|
||||
formatWhen,
|
||||
hostState,
|
||||
hostValueLabel,
|
||||
pendingAlertCount,
|
||||
storageAlerts,
|
||||
summaryCards,
|
||||
} from './storageSummary'
|
||||
import type { HostState } from './storageSummary'
|
||||
import './storageBackup.css'
|
||||
|
||||
export const REFRESH_INTERVAL_MS = 60_000
|
||||
const BATCH_PAGE = 20
|
||||
|
||||
export async function copyText(value: string): Promise<boolean> {
|
||||
if (!value) return false
|
||||
try {
|
||||
await navigator.clipboard.writeText(value)
|
||||
return true
|
||||
} catch {
|
||||
// 内网 http 页面没有 clipboard 权限时退回选中,不谎报"已复制"。
|
||||
const area = document.createElement('textarea')
|
||||
area.value = value
|
||||
area.setAttribute('readonly', '')
|
||||
area.style.position = 'fixed'
|
||||
area.style.opacity = '0'
|
||||
document.body.append(area)
|
||||
area.focus()
|
||||
area.select()
|
||||
const copied = document.execCommand('copy')
|
||||
area.remove()
|
||||
return copied
|
||||
}
|
||||
}
|
||||
|
||||
const hostStateLabel = (state: HostState): string => {
|
||||
switch (state) {
|
||||
case 'unwired':
|
||||
return '未接入宿主上报'
|
||||
case 'missing':
|
||||
return '尚无上报表'
|
||||
case 'stale':
|
||||
return '上次上报已过期'
|
||||
case 'invalid':
|
||||
return '上次上报不可用'
|
||||
case 'incomplete':
|
||||
return '本次上报不完整'
|
||||
default:
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
export function StorageBackupSummary() {
|
||||
const [inventory, setInventory] = useState<BackupInventory | null>(null)
|
||||
const [archive, setArchive] = useState<LibraryStorage | null>(null)
|
||||
const [archiveFailed, setArchiveFailed] = useState(false)
|
||||
const [errors, setErrors] = useState<string[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [visible, setVisible] = useState(BATCH_PAGE)
|
||||
const [copied, setCopied] = useState('')
|
||||
const inFlight = useRef(false)
|
||||
const copiedTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (inFlight.current) return
|
||||
inFlight.current = true
|
||||
const [inventoryResult, archiveResult] = await Promise.allSettled([fetchBackupInventory(), fetchLibraryStorage()])
|
||||
const nextErrors: string[] = []
|
||||
if (inventoryResult.status === 'fulfilled') {
|
||||
setInventory(inventoryResult.value)
|
||||
} else {
|
||||
nextErrors.push(inventoryResult.reason instanceof Error ? inventoryResult.reason.message : '读取备份元数据失败')
|
||||
}
|
||||
if (archiveResult.status === 'fulfilled') {
|
||||
setArchive(archiveResult.value)
|
||||
setArchiveFailed(archiveResult.value === null)
|
||||
if (archiveResult.value === null) nextErrors.push('读取归档占用失败')
|
||||
} else {
|
||||
setArchiveFailed(true)
|
||||
nextErrors.push(archiveResult.reason instanceof Error ? archiveResult.reason.message : '读取归档占用失败')
|
||||
}
|
||||
setErrors(nextErrors)
|
||||
setLoading(false)
|
||||
inFlight.current = false
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
void load()
|
||||
const timer = setInterval(() => {
|
||||
if (document.visibilityState === 'hidden') return
|
||||
void load()
|
||||
}, REFRESH_INTERVAL_MS)
|
||||
return () => {
|
||||
clearInterval(timer)
|
||||
clearTimeout(copiedTimer.current)
|
||||
}
|
||||
}, [load])
|
||||
|
||||
const state = hostState(inventory)
|
||||
const alerts = storageAlerts(inventory, archive, archiveFailed)
|
||||
const cards = summaryCards(inventory, archive, archiveFailed)
|
||||
const batches = inventory?.batches ?? []
|
||||
const shown = batches.slice(0, visible)
|
||||
|
||||
const handleCopy = (key: string, value: string) => {
|
||||
void copyText(value).then((ok) => {
|
||||
if (!ok) return
|
||||
setCopied(key)
|
||||
clearTimeout(copiedTimer.current)
|
||||
copiedTimer.current = setTimeout(() => setCopied(''), 2000)
|
||||
})
|
||||
}
|
||||
|
||||
const lastReport = formatWhen(inventory?.metadata.collected_at)
|
||||
const stateNote = hostStateLabel(state)
|
||||
|
||||
return (
|
||||
<section className="settings-panel storage-summary" aria-label="存储与备份">
|
||||
<header className="storage-summary-head">
|
||||
<div>
|
||||
<h2>存储与备份</h2>
|
||||
{stateNote ? <p className="storage-summary-state">{stateNote}</p> : null}
|
||||
</div>
|
||||
<div className="storage-summary-meta">
|
||||
<span>上次上报 {lastReport || UNKNOWN}</span>
|
||||
<button type="button" className="storage-refresh" onClick={() => void load()} disabled={loading}>
|
||||
刷新
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{errors.length > 0 ? (
|
||||
<p className="storage-summary-error" role="alert">
|
||||
{errors.join(';')}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{loading ? (
|
||||
<p className="storage-summary-loading">正在读取存储与备份…</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="storage-cards">
|
||||
{cards.map((card) => (
|
||||
<div className={card.key === 'root' ? 'storage-card storage-card-root' : 'storage-card'} key={card.key}>
|
||||
<span className="storage-card-label">{card.label}</span>
|
||||
<span className={card.unknown ? 'storage-card-value is-unknown' : 'storage-card-value'}>
|
||||
{card.value}
|
||||
</span>
|
||||
<span className="storage-card-note">
|
||||
{card.note}
|
||||
{card.copy ? (
|
||||
<button
|
||||
type="button"
|
||||
className="storage-copy"
|
||||
onClick={() => handleCopy(card.key, card.copy!)}
|
||||
aria-label={`复制${card.label}`}
|
||||
>
|
||||
{copied === card.key ? '已复制' : '复制'}
|
||||
</button>
|
||||
) : null}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<section className="storage-alerts" aria-label="容量告警">
|
||||
<header>
|
||||
<h3>容量告警</h3>
|
||||
<span
|
||||
className={pendingAlertCount(alerts) > 0 ? 'storage-alert-count is-pending' : 'storage-alert-count'}
|
||||
>
|
||||
{pendingAlertCount(alerts)} 项需处理
|
||||
</span>
|
||||
</header>
|
||||
<ul>
|
||||
{alerts.map((alert) => (
|
||||
<li key={alert.key} data-tone={alert.tone}>
|
||||
<span className="storage-alert-label">{alert.label}</span>
|
||||
<span className="storage-alert-value">{alert.value}</span>
|
||||
<span className="storage-alert-conclusion" data-tone={alert.tone}>
|
||||
{alert.conclusion}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section className="storage-batches" aria-label="备份批次">
|
||||
<header>
|
||||
<h3>备份批次</h3>
|
||||
<span>{batches.length > 0 ? `共 ${batches.length} 个` : ''}</span>
|
||||
</header>
|
||||
{batches.length === 0 ? (
|
||||
<p className="storage-batches-empty">
|
||||
{state === 'ready' || state === 'incomplete'
|
||||
? '暂无批次'
|
||||
: `${hostValueLabel(state)}(上次上报 ${lastReport || UNKNOWN})`}
|
||||
</p>
|
||||
) : (
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>时间</th>
|
||||
<th>结果</th>
|
||||
<th>大小</th>
|
||||
<th>批次</th>
|
||||
<th>路径</th>
|
||||
<th aria-label="复制" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{shown.map((batch) => {
|
||||
const outcome = batchOutcome(batch)
|
||||
return (
|
||||
<tr key={batch.stamp}>
|
||||
<td className="storage-batch-time">{batchWhen(batch)}</td>
|
||||
<td>
|
||||
<span
|
||||
className={outcome.failed ? 'storage-batch-result is-failed' : 'storage-batch-result is-ok'}
|
||||
>
|
||||
{outcome.failed ? '失败' : '成功'}
|
||||
</span>
|
||||
{outcome.reasons.length > 0 ? (
|
||||
<p className="storage-batch-reason">{outcome.reasons.join(';')}</p>
|
||||
) : null}
|
||||
</td>
|
||||
<td className="storage-batch-size">{formatSize(batch.actual_bytes)}</td>
|
||||
<td className="storage-batch-stamp">{batch.stamp}</td>
|
||||
<td className="storage-batch-path" title={batch.path}>
|
||||
<span>{batch.path}</span>
|
||||
</td>
|
||||
<td>
|
||||
<button
|
||||
type="button"
|
||||
className="storage-copy"
|
||||
onClick={() => handleCopy(batch.stamp, batch.path)}
|
||||
aria-label={`复制路径 ${batch.stamp}`}
|
||||
>
|
||||
{copied === batch.stamp ? '已复制' : '复制'}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
{visible < batches.length ? (
|
||||
<button type="button" className="storage-more" onClick={() => setVisible((value) => value + BATCH_PAGE)}>
|
||||
加载更多(剩余 {batches.length - visible} 个)
|
||||
</button>
|
||||
) : null}
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -256,9 +256,9 @@ describe('SystemSettingsView', () => {
|
||||
initialSection="storage"
|
||||
/>
|
||||
)
|
||||
// 存储与备份分区已换成真实功能(整库逻辑备份的定时计划),静态占位文案不再存在。
|
||||
// 存储与备份分区是只读摘要页:SSR 先给加载态,静态占位文案不再存在。
|
||||
expect(storageHtml).toContain('存储与备份')
|
||||
expect(storageHtml).toContain('正在读取备份计划…')
|
||||
expect(storageHtml).toContain('正在读取存储与备份…')
|
||||
expect(storageHtml).not.toContain('仅保存凭据引用,不可回读')
|
||||
const refreshHtml = renderToStaticMarkup(
|
||||
<SystemSettingsView
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
|
||||
import { BackupScheduleSection } from './BackupScheduleSection'
|
||||
import { LibraryStorageSection } from './LibraryStorageSection'
|
||||
import { StorageBackupSummary } from './StorageBackupSummary'
|
||||
import { QAModelSettings } from './QAModelSettings'
|
||||
import { MembersSection } from './MembersSection'
|
||||
import { DingtalkAccountStatus, SourceManagementDetails, SourceSettingsCard } from './SourceManagement'
|
||||
@@ -242,12 +241,7 @@ export function SystemSettingsView({
|
||||
</details>
|
||||
</>
|
||||
) : null}
|
||||
{section === 'storage' ? (
|
||||
<>
|
||||
<BackupScheduleSection />
|
||||
<LibraryStorageSection />
|
||||
</>
|
||||
) : null}
|
||||
{section === 'storage' ? <StorageBackupSummary /> : null}
|
||||
{section === 'members' && identity?.role === 'admin' ? <MembersSection /> : null}
|
||||
{section === 'refresh' && settings ? (
|
||||
<section className="settings-panel wide" id="settings-refresh">
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
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 })
|
||||
})
|
||||
})
|
||||
@@ -1,187 +0,0 @@
|
||||
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_endpoint 是这条别名真实拨号的 host:port(来自挂载的 ssh 配置)。
|
||||
host_endpoint: string
|
||||
host_reachable: boolean
|
||||
host_error: string
|
||||
host_schedule_enabled: boolean
|
||||
host_schedule_time: string
|
||||
// 主机若没有返回真实 next-run,保持空串;页面不得用历史下发时间推算。
|
||||
host_next_run?: string
|
||||
host_checked_at?: 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_endpoint: asString(item.host_endpoint),
|
||||
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_next_run: asString(item.host_next_run),
|
||||
host_checked_at: asString(item.host_checked_at),
|
||||
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 }
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
.library-storage {
|
||||
border: 1px solid var(--border-base, #e2e8f0);
|
||||
border-radius: 10px;
|
||||
padding: 16px 18px;
|
||||
margin-bottom: 18px;
|
||||
background: #fff;
|
||||
}
|
||||
.library-storage header h3 {
|
||||
margin: 0 0 4px;
|
||||
font-size: 16px;
|
||||
}
|
||||
.library-storage header p {
|
||||
margin: 0 0 12px;
|
||||
font-size: 12px;
|
||||
color: var(--ink-mute, #64748b);
|
||||
line-height: 1.6;
|
||||
}
|
||||
.library-storage-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
||||
gap: 10px;
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
.library-storage-grid div {
|
||||
border: 1px solid #e6edf2;
|
||||
border-radius: 8px;
|
||||
padding: 9px 11px;
|
||||
}
|
||||
.library-storage-grid dt {
|
||||
font-size: 11px;
|
||||
color: var(--ink-mute, #64748b);
|
||||
}
|
||||
.library-storage-grid dd {
|
||||
margin: 3px 0 0;
|
||||
font-size: 16px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.library-storage-limits {
|
||||
margin: 0;
|
||||
padding-left: 18px;
|
||||
font-size: 12px;
|
||||
color: #986b24;
|
||||
line-height: 1.8;
|
||||
}
|
||||
.library-storage-hint {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
color: var(--ink-mute, #64748b);
|
||||
}
|
||||
.library-storage-blocked {
|
||||
border: 1px solid #f3c2b8;
|
||||
background: #fff6f3;
|
||||
border-radius: 8px;
|
||||
padding: 10px 12px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.library-storage-blocked strong {
|
||||
display: block;
|
||||
font-size: 12px;
|
||||
color: #a03a1e;
|
||||
}
|
||||
.library-storage-blocked p {
|
||||
margin: 2px 0 0;
|
||||
font-size: 12px;
|
||||
color: #7c2d12;
|
||||
}
|
||||
|
||||
.library-storage-panel {
|
||||
border: 1px solid #e6edf2;
|
||||
border-radius: 8px;
|
||||
padding: 10px 12px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.library-storage-panel h4 {
|
||||
margin: 0 0 6px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.library-storage-panel p {
|
||||
margin: 0 0 6px;
|
||||
font-size: 12px;
|
||||
line-height: 1.7;
|
||||
color: #3f5566;
|
||||
}
|
||||
.library-storage-warn {
|
||||
color: #986b24 !important;
|
||||
}
|
||||
.library-storage-versions {
|
||||
margin: 4px 0 0;
|
||||
padding-left: 18px;
|
||||
font-size: 12px;
|
||||
line-height: 1.8;
|
||||
color: #3f5566;
|
||||
}
|
||||
.library-storage-blocked-list {
|
||||
margin: 4px 0 0;
|
||||
padding-left: 18px;
|
||||
font-size: 12px;
|
||||
color: #a03a1e;
|
||||
}
|
||||
+320
-372
@@ -1,424 +1,372 @@
|
||||
/* 「系统设置 → 存储与备份」:数据库整库逻辑备份。
|
||||
原型里的单条整盘图与告警在这里保留位置;真实读数未接线时用虚底而不是假容量。 */
|
||||
.storage-settings-panel {
|
||||
/* 存储与备份:只读摘要页。全部颜色走 tokens,状态色沿用全局 fail/warn/done。 */
|
||||
.storage-summary {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
gap: 18px;
|
||||
}
|
||||
.storage-settings-panel .settings-section-heading p {
|
||||
|
||||
.storage-summary-head {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.storage-summary-head h2 {
|
||||
margin: 0;
|
||||
max-width: 78ch;
|
||||
color: var(--ink-mute, #64748b);
|
||||
font-size: 11px;
|
||||
line-height: 1.7;
|
||||
font-size: 16px;
|
||||
color: var(--ink-strong);
|
||||
}
|
||||
/* 主机读回用两栏事实表;窄列时自动落成一栏,避免 dd 把 dt 挤成竖排。 */
|
||||
.settings-panel .storage-settings-grid {
|
||||
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
|
||||
|
||||
.storage-summary-state {
|
||||
margin: 4px 0 0;
|
||||
font-size: 12px;
|
||||
color: var(--c-warn);
|
||||
}
|
||||
.settings-panel .storage-settings-grid > dl {
|
||||
grid-template-columns: minmax(104px, max-content) minmax(0, 1fr);
|
||||
|
||||
.storage-summary-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
font-size: 12px;
|
||||
color: var(--ink-mute);
|
||||
}
|
||||
.storage-settings-panel code {
|
||||
|
||||
.storage-refresh,
|
||||
.storage-more {
|
||||
border: 1px solid var(--border-strong);
|
||||
background: var(--bg-panel);
|
||||
border-radius: 6px;
|
||||
padding: 5px 12px;
|
||||
font-size: 12px;
|
||||
color: var(--ink-base);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.storage-refresh:hover,
|
||||
.storage-more:hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
.storage-refresh:disabled {
|
||||
color: var(--ink-faint);
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.storage-summary-error {
|
||||
margin: 0;
|
||||
padding: 8px 12px;
|
||||
border-radius: 6px;
|
||||
border: 1px solid var(--c-fail-border);
|
||||
background: var(--c-fail-bg);
|
||||
color: var(--c-fail);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.storage-summary-loading {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
color: var(--ink-mute);
|
||||
}
|
||||
|
||||
.storage-cards {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(190px, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.storage-card {
|
||||
border: 1px solid var(--border-base);
|
||||
border-radius: 10px;
|
||||
background: var(--bg-panel);
|
||||
padding: 14px 16px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.storage-card-label {
|
||||
font-size: 12px;
|
||||
color: var(--ink-mute);
|
||||
}
|
||||
|
||||
.storage-card-value {
|
||||
font-size: 24px;
|
||||
font-weight: 600;
|
||||
line-height: 1.15;
|
||||
color: var(--ink-strong);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.storage-block {
|
||||
border-top: 1px solid var(--border-base, #e2e8f0);
|
||||
padding-top: 12px;
|
||||
|
||||
.storage-card-value.is-unknown {
|
||||
font-size: 15px;
|
||||
font-weight: 500;
|
||||
color: var(--ink-mute);
|
||||
}
|
||||
.storage-block-heading {
|
||||
|
||||
/* 备份目录是配置事实而不是指标:独占一行、字号收小,避免长路径撑爆卡片。 */
|
||||
.storage-card-root {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
.storage-card-root .storage-card-value {
|
||||
font-size: 16px;
|
||||
line-height: 1.35;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.storage-card-note {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 12px;
|
||||
color: var(--ink-mute);
|
||||
min-height: 18px;
|
||||
}
|
||||
|
||||
.storage-copy {
|
||||
border: 1px solid var(--border-base);
|
||||
background: var(--bg-soft);
|
||||
border-radius: 5px;
|
||||
padding: 1px 7px;
|
||||
font-size: 11px;
|
||||
color: var(--ink-mute);
|
||||
cursor: pointer;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.storage-copy:hover {
|
||||
background: var(--bg-hover);
|
||||
color: var(--ink-base);
|
||||
}
|
||||
|
||||
.storage-alerts,
|
||||
.storage-batches {
|
||||
border: 1px solid var(--border-base);
|
||||
border-radius: 10px;
|
||||
background: var(--bg-panel);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.storage-alerts > header,
|
||||
.storage-batches > header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px 14px;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 6px;
|
||||
gap: 12px;
|
||||
padding: 12px 16px;
|
||||
border-bottom: 1px solid var(--border-soft);
|
||||
}
|
||||
.storage-block-heading h3 {
|
||||
|
||||
.storage-alerts h3,
|
||||
.storage-batches h3 {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
color: var(--ink-base);
|
||||
color: var(--ink-strong);
|
||||
}
|
||||
.storage-block-heading button {
|
||||
font: inherit;
|
||||
font-size: 10px;
|
||||
padding: 3px 9px;
|
||||
border-radius: 5px;
|
||||
border: 1px solid var(--border-base, #cbd5e1);
|
||||
background: var(--bg-panel, #fff);
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
|
||||
.storage-batches > header span,
|
||||
.storage-alert-count {
|
||||
font-size: 12px;
|
||||
color: var(--ink-mute);
|
||||
}
|
||||
.storage-block-heading button:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: default;
|
||||
}
|
||||
.storage-chip {
|
||||
border-radius: 999px;
|
||||
padding: 2px 9px;
|
||||
font-size: 10px;
|
||||
border: 1px solid var(--border-base, #e2e8f0);
|
||||
color: var(--ink-mute, #64748b);
|
||||
}
|
||||
.storage-chip.ok {
|
||||
color: #17695a;
|
||||
border-color: #a9d5c8;
|
||||
background: #effaf5;
|
||||
}
|
||||
.storage-chip.warn {
|
||||
color: #985d10;
|
||||
border-color: #f0d3a4;
|
||||
background: #fff8ec;
|
||||
}
|
||||
.storage-chip.off {
|
||||
color: var(--ink-mute, #64748b);
|
||||
background: var(--bg-soft, #f6f8fa);
|
||||
}
|
||||
.settings-panel .storage-facts {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(96px, max-content) minmax(0, 1fr);
|
||||
gap: 5px 14px;
|
||||
margin: 6px 0;
|
||||
font-size: 11px;
|
||||
color: var(--ink-mute, #64748b);
|
||||
}
|
||||
.settings-panel .storage-facts dd {
|
||||
margin: 0;
|
||||
color: var(--ink-base);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.storage-inline-note {
|
||||
display: block;
|
||||
color: var(--ink-mute, #64748b);
|
||||
font-size: 10px;
|
||||
}
|
||||
.storage-block-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px 12px;
|
||||
flex-wrap: wrap;
|
||||
margin: 7px 0;
|
||||
}
|
||||
.storage-block-actions .hint {
|
||||
max-width: 72ch;
|
||||
}
|
||||
.storage-block-actions button {
|
||||
font: inherit;
|
||||
font-size: 11px;
|
||||
padding: 5px 11px;
|
||||
border-radius: 6px;
|
||||
border: 1px solid var(--border-base, #cbd5e1);
|
||||
background: var(--bg-panel, #fff);
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
.storage-block-actions button:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: default;
|
||||
}
|
||||
.storage-block-actions button.primary {
|
||||
background: #185f78;
|
||||
border-color: #185f78;
|
||||
color: #fff;
|
||||
}
|
||||
.storage-progress {
|
||||
margin: 6px 0;
|
||||
}
|
||||
.storage-running {
|
||||
margin: 0 0 5px;
|
||||
font-size: 11px;
|
||||
color: var(--ink-base);
|
||||
}
|
||||
.storage-progress-bar {
|
||||
width: 100%;
|
||||
height: 10px;
|
||||
}
|
||||
.storage-disk-track {
|
||||
display: flex;
|
||||
height: 22px;
|
||||
margin: 8px 0;
|
||||
border-radius: 5px;
|
||||
overflow: hidden;
|
||||
background: #e4e9ef;
|
||||
outline: 1px solid #aab9c1;
|
||||
}
|
||||
.storage-disk-other {
|
||||
background: #77889a;
|
||||
}
|
||||
.storage-disk-zone {
|
||||
display: flex;
|
||||
background: #c0dfed;
|
||||
box-shadow: inset 0 0 0 1px #6191a8;
|
||||
}
|
||||
.storage-disk-used {
|
||||
background: #19698c;
|
||||
}
|
||||
.storage-disk-blank {
|
||||
background: #e4e9ef;
|
||||
}
|
||||
.storage-disk-track-unknown {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: repeating-linear-gradient(45deg, #eef2f5 0 6px, #e1e7eb 6px 12px);
|
||||
border: 1px dashed #aab9c1;
|
||||
outline: none;
|
||||
color: #576674;
|
||||
font-size: 10px;
|
||||
}
|
||||
.storage-disk-low .storage-disk-other {
|
||||
background: #9d625d;
|
||||
}
|
||||
.storage-disk-low .storage-disk-used {
|
||||
background: #be6c10;
|
||||
}
|
||||
.storage-disk-low .storage-disk-zone {
|
||||
background: #ffe0a8;
|
||||
}
|
||||
.storage-disk-legend {
|
||||
display: flex;
|
||||
gap: 6px 16px;
|
||||
flex-wrap: wrap;
|
||||
font-size: 10px;
|
||||
color: #3f5566;
|
||||
}
|
||||
.storage-dot {
|
||||
display: inline-block;
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
margin-right: 4px;
|
||||
border-radius: 2px;
|
||||
vertical-align: -1px;
|
||||
}
|
||||
.storage-dot.other {
|
||||
background: #77889a;
|
||||
}
|
||||
.storage-dot.used {
|
||||
background: #19698c;
|
||||
}
|
||||
.storage-dot.zone {
|
||||
background: #c0dfed;
|
||||
}
|
||||
.storage-dot.blank {
|
||||
background: #e4e9ef;
|
||||
outline: 1px solid #c4ced6;
|
||||
}
|
||||
.storage-metric {
|
||||
margin: 6px 0 2px;
|
||||
font-size: 11px;
|
||||
|
||||
.storage-alert-count.is-pending {
|
||||
color: var(--c-fail);
|
||||
font-weight: 600;
|
||||
}
|
||||
.storage-manifest {
|
||||
font-size: 10px;
|
||||
padding: 1px 7px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid var(--border-base, #e2e8f0);
|
||||
}
|
||||
.storage-manifest.ok {
|
||||
color: #17695a;
|
||||
border-color: #a9d5c8;
|
||||
background: #effaf5;
|
||||
}
|
||||
.storage-manifest.missing,
|
||||
.storage-manifest.invalid {
|
||||
color: #a03a1e;
|
||||
border-color: #f3c2b8;
|
||||
background: #fff6f3;
|
||||
}
|
||||
.storage-path-row {
|
||||
display: grid;
|
||||
grid-template-columns: max-content minmax(0, 1fr) max-content;
|
||||
gap: 4px 8px;
|
||||
align-items: center;
|
||||
margin: 5px 0;
|
||||
}
|
||||
.storage-path-row small {
|
||||
color: var(--ink-mute, #64748b);
|
||||
}
|
||||
.storage-path-row code {
|
||||
font-size: 10px;
|
||||
padding: 3px 6px;
|
||||
border-radius: 4px;
|
||||
background: var(--bg-soft, #f6f8fa);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.storage-path-row button,
|
||||
.storage-sublibraries button {
|
||||
font: inherit;
|
||||
font-size: 10px;
|
||||
padding: 3px 8px;
|
||||
border-radius: 5px;
|
||||
border: 1px solid var(--border-base, #cbd5e1);
|
||||
background: var(--bg-panel, #fff);
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
.storage-path-row button:disabled,
|
||||
.storage-sublibraries button:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: default;
|
||||
}
|
||||
.storage-sublibrary-path {
|
||||
margin: 2px 0 0;
|
||||
grid-template-columns: minmax(0, 1fr) max-content;
|
||||
}
|
||||
.storage-alert-summary {
|
||||
margin: 8px 0 0;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
color: #3f5566;
|
||||
}
|
||||
.storage-alerts {
|
||||
|
||||
.storage-alerts ul {
|
||||
list-style: none;
|
||||
margin: 8px 0 0;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: grid;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.storage-alerts li {
|
||||
display: grid;
|
||||
grid-template-columns: max-content max-content minmax(0, 1fr);
|
||||
gap: 4px 10px;
|
||||
align-items: baseline;
|
||||
font-size: 10px;
|
||||
padding: 4px 8px;
|
||||
border-radius: 6px;
|
||||
background: var(--bg-soft, #f6f8fa);
|
||||
grid-template-columns: 180px minmax(0, 1fr) 84px;
|
||||
gap: 12px;
|
||||
align-items: center;
|
||||
padding: 10px 16px;
|
||||
border-bottom: 1px solid var(--border-soft);
|
||||
font-size: 13px;
|
||||
}
|
||||
.storage-alerts li strong {
|
||||
font-size: 11px;
|
||||
|
||||
.storage-alerts li:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
.storage-alerts li small {
|
||||
color: var(--ink-mute, #64748b);
|
||||
|
||||
.storage-alert-label {
|
||||
color: var(--ink-base);
|
||||
}
|
||||
|
||||
.storage-alert-value {
|
||||
color: var(--ink-mute);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.storage-alerts .alert-on {
|
||||
background: #fff1ec;
|
||||
color: #a03a1e;
|
||||
|
||||
.storage-alert-conclusion {
|
||||
justify-self: end;
|
||||
border-radius: 999px;
|
||||
padding: 2px 10px;
|
||||
font-size: 12px;
|
||||
border: 1px solid var(--border-base);
|
||||
color: var(--ink-mute);
|
||||
background: var(--bg-soft);
|
||||
}
|
||||
.storage-alerts .alert-ok {
|
||||
background: #f0faf6;
|
||||
color: #17695a;
|
||||
|
||||
.storage-alert-conclusion[data-tone='ok'] {
|
||||
color: var(--c-done);
|
||||
border-color: var(--c-done-border);
|
||||
background: var(--c-done-bg);
|
||||
}
|
||||
.storage-alerts .alert-unknown {
|
||||
background: #f8f5ee;
|
||||
color: #715c2c;
|
||||
|
||||
.storage-alert-conclusion[data-tone='warn'] {
|
||||
color: var(--c-warn);
|
||||
border-color: var(--c-warn-border);
|
||||
background: var(--c-warn-bg);
|
||||
}
|
||||
.storage-plan {
|
||||
margin: 4px 0;
|
||||
font-size: 11px;
|
||||
color: #3f5566;
|
||||
|
||||
.storage-alert-conclusion[data-tone='bad'] {
|
||||
color: var(--c-fail);
|
||||
border-color: var(--c-fail-border);
|
||||
background: var(--c-fail-bg);
|
||||
}
|
||||
.storage-policy-editor {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
.storage-policy-editor > label {
|
||||
display: grid;
|
||||
gap: 3px;
|
||||
font-size: 10px;
|
||||
color: var(--ink-mute, #64748b);
|
||||
}
|
||||
.storage-policy-editor input[type='text'],
|
||||
.storage-policy-editor input[type='time'],
|
||||
.storage-policy-editor input[type='number'] {
|
||||
|
||||
.storage-batches table {
|
||||
width: 100%;
|
||||
max-width: 320px;
|
||||
font: inherit;
|
||||
font-size: 11px;
|
||||
padding: 5px 8px;
|
||||
border-radius: 5px;
|
||||
border: 1px solid var(--border-base, #cbd5e1);
|
||||
background: var(--bg-panel, #fff);
|
||||
color: inherit;
|
||||
border-collapse: collapse;
|
||||
font-size: 12px;
|
||||
table-layout: fixed;
|
||||
}
|
||||
.storage-policy-editor input:disabled {
|
||||
background: var(--bg-soft, #f1f4f6);
|
||||
color: var(--ink-mute, #64748b);
|
||||
|
||||
.storage-batches th {
|
||||
text-align: left;
|
||||
font-weight: 500;
|
||||
color: var(--ink-mute);
|
||||
padding: 8px 16px;
|
||||
border-bottom: 1px solid var(--border-soft);
|
||||
}
|
||||
.storage-checkbox {
|
||||
display: flex !important;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 11px !important;
|
||||
color: var(--ink-base) !important;
|
||||
|
||||
.storage-batches td {
|
||||
padding: 10px 16px;
|
||||
border-bottom: 1px solid var(--border-soft);
|
||||
vertical-align: top;
|
||||
color: var(--ink-base);
|
||||
}
|
||||
.storage-policy-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
|
||||
gap: 8px 12px;
|
||||
|
||||
.storage-batches th:nth-child(1),
|
||||
.storage-batches td:nth-child(1) {
|
||||
width: 96px;
|
||||
}
|
||||
.storage-policy-grid label {
|
||||
display: grid;
|
||||
gap: 3px;
|
||||
font-size: 10px;
|
||||
color: var(--ink-mute, #64748b);
|
||||
|
||||
.storage-batches th:nth-child(2),
|
||||
.storage-batches td:nth-child(2) {
|
||||
width: 200px;
|
||||
}
|
||||
.storage-policy-grid input {
|
||||
width: 100%;
|
||||
|
||||
.storage-batches th:nth-child(3),
|
||||
.storage-batches td:nth-child(3) {
|
||||
width: 88px;
|
||||
}
|
||||
.storage-batch {
|
||||
border: 1px solid var(--border-base, #e2e8f0);
|
||||
border-radius: 8px;
|
||||
padding: 8px 10px;
|
||||
|
||||
.storage-batches th:nth-child(4),
|
||||
.storage-batches td:nth-child(4) {
|
||||
width: 170px;
|
||||
}
|
||||
|
||||
.storage-batches th:nth-child(6),
|
||||
.storage-batches td:nth-child(6) {
|
||||
width: 64px;
|
||||
}
|
||||
|
||||
.storage-batch-time,
|
||||
.storage-batch-stamp {
|
||||
font-variant-numeric: tabular-nums;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.storage-batch-size {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.storage-batch-result {
|
||||
display: inline-block;
|
||||
border-radius: 999px;
|
||||
padding: 1px 9px;
|
||||
border: 1px solid var(--border-base);
|
||||
font-size: 11px;
|
||||
}
|
||||
.storage-batch summary {
|
||||
display: flex;
|
||||
gap: 6px 14px;
|
||||
flex-wrap: wrap;
|
||||
align-items: baseline;
|
||||
cursor: pointer;
|
||||
|
||||
.storage-batch-result.is-ok {
|
||||
color: var(--c-done);
|
||||
border-color: var(--c-done-border);
|
||||
background: var(--c-done-bg);
|
||||
}
|
||||
.storage-batch summary strong.ok {
|
||||
color: #17695a;
|
||||
|
||||
.storage-batch-result.is-failed {
|
||||
color: var(--c-fail);
|
||||
border-color: var(--c-fail-border);
|
||||
background: var(--c-fail-bg);
|
||||
}
|
||||
.storage-batch summary strong.off {
|
||||
color: #a03a1e;
|
||||
|
||||
.storage-batch-reason {
|
||||
margin: 4px 0 0;
|
||||
font-size: 11px;
|
||||
color: var(--c-fail);
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.storage-batch p {
|
||||
margin: 6px 0;
|
||||
color: #3f5566;
|
||||
|
||||
/* 长路径中间截断:保留结尾(批次目录名),从开头省略。 */
|
||||
.storage-batch-path {
|
||||
min-width: 0;
|
||||
}
|
||||
.storage-sublibraries {
|
||||
list-style: none;
|
||||
margin: 6px 0;
|
||||
padding: 0;
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
|
||||
.storage-batch-path > span {
|
||||
display: block;
|
||||
direction: rtl;
|
||||
unicode-bidi: plaintext;
|
||||
text-align: left;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
color: var(--ink-mute);
|
||||
}
|
||||
.storage-sublibraries li {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(120px, max-content) max-content minmax(0, 1fr);
|
||||
gap: 4px 10px;
|
||||
align-items: baseline;
|
||||
padding: 3px 6px;
|
||||
border-radius: 5px;
|
||||
background: var(--bg-soft, #f6f8fa);
|
||||
|
||||
.storage-batches-empty {
|
||||
margin: 0;
|
||||
padding: 24px 16px;
|
||||
font-size: 13px;
|
||||
color: var(--ink-mute);
|
||||
text-align: center;
|
||||
}
|
||||
.storage-sublibrary-path {
|
||||
grid-column: 1 / -1;
|
||||
|
||||
.storage-more {
|
||||
display: block;
|
||||
margin: 12px auto;
|
||||
}
|
||||
.storage-sublibraries .ok {
|
||||
color: #17695a;
|
||||
}
|
||||
.storage-sublibraries .off {
|
||||
color: #a03a1e;
|
||||
}
|
||||
.storage-sublibraries small {
|
||||
color: var(--ink-mute, #64748b);
|
||||
}
|
||||
.storage-verify {
|
||||
margin: 6px 0 0;
|
||||
color: #715c2c;
|
||||
font-size: 10px;
|
||||
}
|
||||
@media (max-width: 700px) {
|
||||
.storage-facts,
|
||||
.storage-sublibraries li,
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.storage-alerts li {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
grid-template-columns: minmax(0, 1fr) 84px;
|
||||
}
|
||||
|
||||
.storage-alerts .storage-alert-value {
|
||||
grid-column: 1 / -1;
|
||||
grid-row: 2;
|
||||
}
|
||||
|
||||
.storage-batches table {
|
||||
table-layout: auto;
|
||||
}
|
||||
|
||||
.storage-batches th:nth-child(4),
|
||||
.storage-batches td:nth-child(4),
|
||||
.storage-batches th:nth-child(5),
|
||||
.storage-batches td:nth-child(5) {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,308 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
|
||||
import type { LibraryStorage } from './librarySnapshots'
|
||||
import {
|
||||
DISK_CRITICAL_AVAILABLE_PERCENT,
|
||||
batchOutcome,
|
||||
formatSize,
|
||||
formatWhen,
|
||||
hostState,
|
||||
orderedBatches,
|
||||
pendingAlertCount,
|
||||
recentOutcome,
|
||||
storageAlerts,
|
||||
summaryCards,
|
||||
} from './storageSummary'
|
||||
|
||||
const GIB = 1024 ** 3
|
||||
const TB = 1024 * GIB
|
||||
|
||||
export const batch = (overrides: Partial<BackupInventoryBatch> = {}): BackupInventoryBatch => ({
|
||||
stamp: '20261124T020000Z',
|
||||
path: '/srv/kb-backups/rds-logical/20261124T020000Z',
|
||||
host_path: '/srv/kb-backups/rds-logical/20261124T020000Z',
|
||||
manifest_state: 'ok',
|
||||
manifest_path: '/srv/kb-backups/rds-logical/20261124T020000Z/MANIFEST.json',
|
||||
kind: 'rds',
|
||||
created_at: '2026-11-24T02:00:00Z',
|
||||
started_at: '2026-11-24T02:00:00Z',
|
||||
duration_seconds: 240,
|
||||
manifest_total_bytes: 10 * GIB,
|
||||
apparent_bytes: 10 * GIB,
|
||||
actual_bytes: 9 * GIB,
|
||||
file_count: 120,
|
||||
sizes_complete: true,
|
||||
databases: [
|
||||
{
|
||||
name: 'weknora',
|
||||
dir_name: 'weknora.dir',
|
||||
path: '/srv/kb-backups/rds-logical/20261124T020000Z/weknora.dir',
|
||||
host_path: '/srv/kb-backups/rds-logical/20261124T020000Z/weknora.dir',
|
||||
present: true,
|
||||
failed: false,
|
||||
in_manifest: true,
|
||||
apparent_bytes: 10 * GIB,
|
||||
actual_bytes: 9 * GIB,
|
||||
file_count: 120,
|
||||
},
|
||||
],
|
||||
...overrides,
|
||||
})
|
||||
|
||||
export const inventory = (overrides: Partial<BackupInventory> = {}): BackupInventory => ({
|
||||
wired: true,
|
||||
metadata: {
|
||||
configured: true,
|
||||
present: true,
|
||||
valid: true,
|
||||
fresh: true,
|
||||
complete: true,
|
||||
path: '/var/lib/kb-backups/metadata.json',
|
||||
collected_at: '2026-11-24T10:17:00Z',
|
||||
age_seconds: 60,
|
||||
max_age_seconds: 900,
|
||||
schema_version: 1,
|
||||
generation: 'g-1',
|
||||
host: 'backup-host',
|
||||
collector_version: '1',
|
||||
error: '',
|
||||
},
|
||||
root: '/srv/kb-backups/rds-logical',
|
||||
host_root: '/srv/kb-backups/rds-logical',
|
||||
source: 'host',
|
||||
observed_at: '2026-11-24T10:18:00Z',
|
||||
measurement: 'host-reported',
|
||||
mount: {
|
||||
container_root: '',
|
||||
mount_verified: true,
|
||||
lives_on_container_root: false,
|
||||
read_only: true,
|
||||
evidence: '',
|
||||
mount_point: '/srv/kb-backups',
|
||||
device: '/dev/sdb1',
|
||||
fs_type: 'ext4',
|
||||
},
|
||||
capacity: {
|
||||
measured: true,
|
||||
total_bytes: 2 * TB,
|
||||
free_bytes: 1.2 * TB,
|
||||
available_bytes: 1.2 * TB,
|
||||
used_bytes: 0.8 * TB,
|
||||
},
|
||||
batches: [batch()],
|
||||
totals: {
|
||||
batch_count: 1,
|
||||
database_count: 1,
|
||||
apparent_bytes: 10 * GIB,
|
||||
actual_bytes: 9 * GIB,
|
||||
latest_stamp: '20261124T020000Z',
|
||||
latest_actual_bytes: 9 * GIB,
|
||||
complete: true,
|
||||
},
|
||||
incomplete_count: 0,
|
||||
skipped: [],
|
||||
truncated: false,
|
||||
...overrides,
|
||||
})
|
||||
|
||||
export const archive = (overrides: Partial<LibraryStorage> = {}): LibraryStorage => ({
|
||||
available: true,
|
||||
archive_root: '/var/lib/knowledge-governance/library',
|
||||
versions: [],
|
||||
content_bytes: 41_231_686_042,
|
||||
blob_file_bytes: 0,
|
||||
blob_allocated_bytes: 0,
|
||||
unreferenced_blobs: 0,
|
||||
unreferenced_bytes: 0,
|
||||
manifest_file_bytes: 0,
|
||||
policy: { keep_versions: 0, keep_days: 0 },
|
||||
capacity: {
|
||||
budget_bytes: 100 * GIB,
|
||||
current_bytes: 41_231_686_042,
|
||||
required_bytes: 0,
|
||||
projected_bytes: 41_231_686_042,
|
||||
configured: true,
|
||||
ok: true,
|
||||
},
|
||||
automatic_cleanup: false,
|
||||
notes: [],
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const unreported = (): BackupInventory =>
|
||||
inventory({
|
||||
wired: false,
|
||||
metadata: {
|
||||
configured: false,
|
||||
present: false,
|
||||
valid: false,
|
||||
fresh: false,
|
||||
complete: false,
|
||||
path: '',
|
||||
collected_at: '',
|
||||
age_seconds: 0,
|
||||
max_age_seconds: 900,
|
||||
schema_version: 0,
|
||||
generation: '',
|
||||
host: '',
|
||||
collector_version: '',
|
||||
error: '元数据快照未接线(BACKUP_HOST_METADATA_PATH 未设置)',
|
||||
},
|
||||
root: '',
|
||||
host_root: '',
|
||||
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
|
||||
batches: [],
|
||||
totals: {
|
||||
batch_count: 0,
|
||||
database_count: 0,
|
||||
apparent_bytes: null,
|
||||
actual_bytes: null,
|
||||
latest_stamp: '',
|
||||
latest_actual_bytes: null,
|
||||
complete: false,
|
||||
},
|
||||
})
|
||||
|
||||
describe('formatSize', () => {
|
||||
it('keeps one decimal below 100 units and never calls an unknown value zero', () => {
|
||||
expect(formatSize(41_231_686_042)).toBe('38.4 GB')
|
||||
expect(formatSize(100 * GIB)).toBe('100 GB')
|
||||
expect(formatSize(1.2 * TB)).toBe('1.2 TB')
|
||||
expect(formatSize(2 * TB)).toBe('2 TB')
|
||||
expect(formatSize(0)).toBe('0 B')
|
||||
expect(formatSize(null)).toBe('—')
|
||||
expect(formatSize(undefined)).toBe('—')
|
||||
})
|
||||
})
|
||||
|
||||
describe('hostState', () => {
|
||||
it('separates unreported, stale, incomplete and ready snapshots', () => {
|
||||
expect(hostState(null)).toBe('loading')
|
||||
expect(hostState(unreported())).toBe('unwired')
|
||||
expect(hostState(inventory({ metadata: { ...inventory().metadata, present: false } }))).toBe('missing')
|
||||
expect(hostState(inventory({ metadata: { ...inventory().metadata, fresh: false } }))).toBe('stale')
|
||||
expect(hostState(inventory({ metadata: { ...inventory().metadata, complete: false } }))).toBe('incomplete')
|
||||
expect(hostState(inventory())).toBe('ready')
|
||||
})
|
||||
})
|
||||
|
||||
describe('batchOutcome', () => {
|
||||
it('reports manifest damage and failed databases as failure reasons', () => {
|
||||
expect(batchOutcome(batch())).toEqual({ failed: false, reasons: [] })
|
||||
expect(batchOutcome(batch({ manifest_state: 'missing' })).reasons).toEqual(['清单缺失'])
|
||||
expect(
|
||||
batchOutcome(
|
||||
batch({
|
||||
manifest_state: 'invalid',
|
||||
manifest_error: 'MANIFEST.json 无法解析',
|
||||
databases: [{ ...batch().databases[0], failed: true }],
|
||||
})
|
||||
)
|
||||
).toEqual({ failed: true, reasons: ['清单损坏', 'MANIFEST.json 无法解析', '子库失败:weknora'] })
|
||||
})
|
||||
})
|
||||
|
||||
describe('recentOutcome', () => {
|
||||
it('uses the newest batch per outcome and counts only the 7 day window', () => {
|
||||
const now = Date.parse('2026-11-24T12:00:00Z')
|
||||
const outcome = recentOutcome(
|
||||
[
|
||||
batch({ stamp: '20261124T020000Z', created_at: '2026-11-24T02:00:00Z' }),
|
||||
batch({ stamp: '20261123T020000Z', created_at: '2026-11-23T02:00:00Z', manifest_state: 'invalid' }),
|
||||
batch({ stamp: '20261101T020000Z', created_at: '2026-11-01T02:00:00Z', manifest_state: 'missing' }),
|
||||
],
|
||||
now
|
||||
)
|
||||
expect(outcome.latestSuccessAt).toBe(formatWhen('2026-11-24T02:00:00Z'))
|
||||
expect(outcome.latestFailureAt).toBe(formatWhen('2026-11-23T02:00:00Z'))
|
||||
expect(outcome.successCount).toBe(1)
|
||||
expect(outcome.failureCount).toBe(1)
|
||||
})
|
||||
|
||||
it('orders batches by time even when the host sends them unsorted', () => {
|
||||
const ordered = orderedBatches([
|
||||
batch({ stamp: '20261122T020000Z', created_at: '2026-11-22T02:00:00Z' }),
|
||||
batch({ stamp: '20261124T020000Z', created_at: '2026-11-24T02:00:00Z' }),
|
||||
])
|
||||
expect(ordered.map((item) => item.stamp)).toEqual(['20261124T020000Z', '20261122T020000Z'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('summaryCards', () => {
|
||||
it('shows real values when the host reported and the archive is available', () => {
|
||||
const cards = summaryCards(inventory(), archive(), false)
|
||||
const byKey = Object.fromEntries(cards.map((card) => [card.key, card.value]))
|
||||
expect(byKey.root).toBe('/srv/kb-backups/rds-logical')
|
||||
expect(byKey.success).toBe(formatWhen('2026-11-24T02:00:00Z'))
|
||||
expect(byKey.failure).toBe('无')
|
||||
expect(byKey.archive).toBe('38.4 GB')
|
||||
expect(byKey.disk).toBe('1.2 TB')
|
||||
expect(cards.find((card) => card.key === 'archive')?.note).toBe('配额 100 GB')
|
||||
})
|
||||
|
||||
it('shows 主机未上报 with the last report time instead of 0 when the host never reported', () => {
|
||||
const cards = summaryCards(unreported(), archive({ available: false }), false)
|
||||
for (const key of ['root', 'success', 'failure', 'disk']) {
|
||||
const card = cards.find((item) => item.key === key)!
|
||||
expect(card.value).toBe('主机未上报')
|
||||
expect(card.note).toBe('上次上报 —')
|
||||
}
|
||||
expect(cards.find((card) => card.key === 'archive')?.value).toBe('—')
|
||||
expect(cards.some((card) => card.value === '0 B')).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps paths readable but leaves sizes empty for an incomplete report', () => {
|
||||
const cards = summaryCards(inventory({ metadata: { ...inventory().metadata, complete: false } }), archive(), false)
|
||||
expect(cards.find((card) => card.key === 'root')?.value).toBe('/srv/kb-backups/rds-logical')
|
||||
expect(cards.find((card) => card.key === 'disk')?.value).toBe('—')
|
||||
expect(cards.find((card) => card.key === 'disk')?.note).toBe('本次上报不完整')
|
||||
})
|
||||
})
|
||||
|
||||
describe('storageAlerts', () => {
|
||||
it('judges disk and quota independently and counts pending rows', () => {
|
||||
const healthy = storageAlerts(inventory(), archive(), false)
|
||||
expect(healthy.map((row) => row.conclusion)).toEqual(['正常', '正常', '正常', '正常'])
|
||||
expect(pendingAlertCount(healthy)).toBe(0)
|
||||
|
||||
const nearQuota = storageAlerts(
|
||||
inventory(),
|
||||
archive({
|
||||
capacity: { ...archive().capacity, current_bytes: 95 * GIB, budget_bytes: 100 * GIB },
|
||||
}),
|
||||
false
|
||||
)
|
||||
expect(nearQuota.find((row) => row.key === 'quota_low')?.tone).toBe('warn')
|
||||
expect(nearQuota.find((row) => row.key === 'both_low')?.conclusion).toBe('正常')
|
||||
expect(pendingAlertCount(nearQuota)).toBe(1)
|
||||
})
|
||||
|
||||
it('flags both-insufficient and quota larger than physical free space', () => {
|
||||
const tight = storageAlerts(
|
||||
inventory({
|
||||
capacity: {
|
||||
measured: true,
|
||||
total_bytes: 2 * TB,
|
||||
free_bytes: 0.01 * TB,
|
||||
available_bytes: 0.01 * TB,
|
||||
used_bytes: 1.99 * TB,
|
||||
},
|
||||
}),
|
||||
archive({ capacity: { ...archive().capacity, current_bytes: 100 * GIB, budget_bytes: 100 * GIB } }),
|
||||
false
|
||||
)
|
||||
expect(tight.find((row) => row.key === 'disk_low')?.tone).toBe('bad')
|
||||
expect(tight.find((row) => row.key === 'both_low')?.conclusion).toBe('需处理')
|
||||
expect(tight.find((row) => row.key === 'quota_over_physical')?.conclusion).toBe('需处理')
|
||||
expect(pendingAlertCount(tight)).toBe(4)
|
||||
expect(DISK_CRITICAL_AVAILABLE_PERCENT).toBe(5)
|
||||
})
|
||||
|
||||
it('never claims a conclusion without numbers', () => {
|
||||
const alerts = storageAlerts(unreported(), null, true)
|
||||
expect(alerts.every((row) => row.conclusion === '未知')).toBe(true)
|
||||
expect(alerts.find((row) => row.key === 'disk_low')?.value).toBe('主机未上报')
|
||||
expect(alerts.some((row) => row.value.includes('无法判定'))).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,348 @@
|
||||
// 「存储与备份」只读摘要的纯逻辑:数据源只有两个只读接口——
|
||||
// /api/v1/backup-schedule/inventory (宿主每 5 分钟上报的元数据快照)
|
||||
// /api/v1/library/storage (归档库自身的占用与配额)
|
||||
// 页面不提供任何写操作。读不到的量一律留空("主机未上报" / "—"),不用 0 冒充。
|
||||
import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
|
||||
import type { LibraryStorage } from './librarySnapshots'
|
||||
|
||||
// 阈值(与 docs/STORAGE_BACKUP_READONLY_API.md 的「页面口径」一致):
|
||||
// 磁盘:可用空间 < 5% 红,< 10% 黄
|
||||
// 配额:已用 >= 100% 红,>= 90% 黄
|
||||
export const DISK_CRITICAL_AVAILABLE_PERCENT = 5
|
||||
export const DISK_WARN_AVAILABLE_PERCENT = 10
|
||||
export const QUOTA_CRITICAL_USED_PERCENT = 100
|
||||
export const QUOTA_WARN_USED_PERCENT = 90
|
||||
export const RECENT_WINDOW_DAYS = 7
|
||||
|
||||
export type Tone = 'ok' | 'warn' | 'bad' | 'none'
|
||||
|
||||
export type HostState = 'loading' | 'unwired' | 'missing' | 'stale' | 'invalid' | 'incomplete' | 'ready'
|
||||
|
||||
// 陈旧在先:stale 的快照会被后端判为 invalid,但"上次上报时间"仍然可读。
|
||||
export const hostState = (inventory: BackupInventory | null): HostState => {
|
||||
if (!inventory) return 'loading'
|
||||
if (!inventory.wired) return 'unwired'
|
||||
if (!inventory.metadata.present) return 'missing'
|
||||
if (!inventory.metadata.fresh) return 'stale'
|
||||
if (!inventory.metadata.valid) return 'invalid'
|
||||
if (!inventory.metadata.complete) return 'incomplete'
|
||||
return 'ready'
|
||||
}
|
||||
|
||||
export const UNREPORTED = '主机未上报'
|
||||
// 没有可用的上报表时的说法要和真实原因一致:未接入/从未上报、过期、不可用是三件事。
|
||||
export const hostValueLabel = (state: HostState): string => {
|
||||
switch (state) {
|
||||
case 'unwired':
|
||||
case 'missing':
|
||||
return UNREPORTED
|
||||
case 'stale':
|
||||
return '上报已过期'
|
||||
case 'invalid':
|
||||
return '上报不可用'
|
||||
default:
|
||||
return UNKNOWN
|
||||
}
|
||||
}
|
||||
export const UNKNOWN = '—'
|
||||
// 结论未知与数值缺失是两件事:数值缺用“—”,无法判断结论用“未知”。
|
||||
export const UNKNOWN_STATE = '未知'
|
||||
|
||||
const UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] as const
|
||||
|
||||
export function formatSize(bytes: number | null | undefined): string {
|
||||
if (bytes === null || bytes === undefined || !Number.isFinite(bytes) || bytes < 0) return UNKNOWN
|
||||
if (bytes === 0) return '0 B'
|
||||
let value = bytes
|
||||
let index = 0
|
||||
while (value >= 1024 && index < UNITS.length - 1) {
|
||||
value /= 1024
|
||||
index += 1
|
||||
}
|
||||
const digits = index === 0 || value >= 100 ? 0 : 1
|
||||
const text = value.toFixed(digits).replace(/\.0$/, '')
|
||||
return `${text} ${UNITS[index]}`
|
||||
}
|
||||
|
||||
// 本地时间 MM/DD HH:mm;无法解析时返回空串,由调用方显示 "—"。
|
||||
export function formatWhen(value: string | null | undefined): string {
|
||||
if (!value) return ''
|
||||
const date = new Date(value)
|
||||
if (Number.isNaN(date.getTime())) return ''
|
||||
return `${String(date.getMonth() + 1).padStart(2, '0')}/${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
|
||||
}
|
||||
|
||||
const STAMP = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z?$/
|
||||
|
||||
const stampTime = (stamp: string): number => {
|
||||
const match = STAMP.exec(stamp)
|
||||
if (!match) return 0
|
||||
return Date.UTC(+match[1], +match[2] - 1, +match[3], +match[4], +match[5], +match[6])
|
||||
}
|
||||
|
||||
export function batchWhen(batch: BackupInventoryBatch): string {
|
||||
const iso = formatWhen(batch.created_at) || formatWhen(batch.started_at)
|
||||
if (iso) return iso
|
||||
const parsed = stampTime(batch.stamp)
|
||||
return parsed ? formatWhen(new Date(parsed).toISOString()) || UNKNOWN : UNKNOWN
|
||||
}
|
||||
|
||||
const batchTime = (batch: BackupInventoryBatch): number => {
|
||||
const created = Date.parse(batch.created_at)
|
||||
if (!Number.isNaN(created)) return created
|
||||
const started = Date.parse(batch.started_at)
|
||||
if (!Number.isNaN(started)) return started
|
||||
return stampTime(batch.stamp)
|
||||
}
|
||||
|
||||
export function orderedBatches(batches: BackupInventoryBatch[]): BackupInventoryBatch[] {
|
||||
return [...batches].sort((left, right) => batchTime(right) - batchTime(left))
|
||||
}
|
||||
|
||||
export interface BatchOutcome {
|
||||
failed: boolean
|
||||
reasons: string[]
|
||||
}
|
||||
|
||||
// 失败判定:任一子库失败、清单缺失或损坏都算失败。宿主上报里没有自由文本原因,
|
||||
// 页面只写能证明的事实(清单状态、失败子库名),不编造原因。
|
||||
export function batchOutcome(batch: BackupInventoryBatch): BatchOutcome {
|
||||
const reasons: string[] = []
|
||||
if (batch.manifest_state === 'missing') reasons.push('清单缺失')
|
||||
if (batch.manifest_state === 'invalid') reasons.push('清单损坏')
|
||||
const manifestError = batch.manifest_error?.trim()
|
||||
if (manifestError) reasons.push(manifestError)
|
||||
const failedDatabases = batch.databases.filter((database) => database.failed).map((database) => database.name)
|
||||
if (failedDatabases.length > 0) reasons.push(`子库失败:${failedDatabases.join('、')}`)
|
||||
return { failed: reasons.length > 0, reasons }
|
||||
}
|
||||
|
||||
export interface RecentOutcome {
|
||||
latestSuccessAt: string
|
||||
latestFailureAt: string
|
||||
successCount: number
|
||||
failureCount: number
|
||||
}
|
||||
|
||||
export function recentOutcome(batches: BackupInventoryBatch[], now: number = Date.now()): RecentOutcome {
|
||||
const windowStart = now - RECENT_WINDOW_DAYS * 24 * 60 * 60 * 1000
|
||||
let latestSuccessAt = ''
|
||||
let latestFailureAt = ''
|
||||
let successCount = 0
|
||||
let failureCount = 0
|
||||
for (const batch of orderedBatches(batches)) {
|
||||
const failed = batchOutcome(batch).failed
|
||||
const when = batchWhen(batch)
|
||||
const at = batchTime(batch)
|
||||
if (failed) {
|
||||
if (!latestFailureAt) latestFailureAt = when
|
||||
} else if (!latestSuccessAt) {
|
||||
latestSuccessAt = when
|
||||
}
|
||||
if (at >= windowStart) {
|
||||
if (failed) failureCount += 1
|
||||
else successCount += 1
|
||||
}
|
||||
}
|
||||
return { latestSuccessAt, latestFailureAt, successCount, failureCount }
|
||||
}
|
||||
|
||||
export interface SummaryCard {
|
||||
key: string
|
||||
label: string
|
||||
value: string
|
||||
note: string
|
||||
copy?: string
|
||||
unknown: boolean
|
||||
}
|
||||
|
||||
const lastReportNote = (inventory: BackupInventory): string =>
|
||||
`上次上报 ${formatWhen(inventory.metadata.collected_at) || UNKNOWN}`
|
||||
|
||||
export function summaryCards(
|
||||
inventory: BackupInventory | null,
|
||||
archive: LibraryStorage | null,
|
||||
archiveFailed: boolean
|
||||
): SummaryCard[] {
|
||||
const state = hostState(inventory)
|
||||
const facts = state === 'ready' || state === 'incomplete'
|
||||
const sizes = state === 'ready'
|
||||
const pending = Boolean(inventory) && state !== 'loading'
|
||||
const recent = inventory && facts ? recentOutcome(inventory.batches) : null
|
||||
|
||||
const hostValue = pending && !facts ? hostValueLabel(state) : UNKNOWN
|
||||
const hostNote = pending ? lastReportNote(inventory!) : UNKNOWN
|
||||
const partialNote = facts && !sizes ? '本次上报不完整' : hostNote
|
||||
|
||||
const root = inventory ? inventory.host_root || inventory.root : ''
|
||||
const rootKnown = facts && Boolean(root)
|
||||
|
||||
const capacity = inventory?.capacity
|
||||
const diskKnown = sizes && Boolean(capacity?.measured) && (capacity?.total_bytes ?? 0) > 0
|
||||
const availablePercent = diskKnown ? Math.round((capacity!.available_bytes / capacity!.total_bytes) * 100) : 0
|
||||
|
||||
const archiveKnown = Boolean(archive?.available) && !archiveFailed
|
||||
|
||||
return [
|
||||
{
|
||||
key: 'root',
|
||||
label: '备份目录',
|
||||
value: rootKnown ? root : hostValue,
|
||||
note: rootKnown ? inventory!.metadata.host || UNKNOWN : partialNote,
|
||||
copy: rootKnown ? root : undefined,
|
||||
unknown: !rootKnown,
|
||||
},
|
||||
{
|
||||
key: 'success',
|
||||
label: '最近成功',
|
||||
value: recent ? recent.latestSuccessAt || '无' : hostValue,
|
||||
note: recent ? `近 ${RECENT_WINDOW_DAYS} 天 ${recent.successCount} 次` : partialNote,
|
||||
unknown: !recent,
|
||||
},
|
||||
{
|
||||
key: 'failure',
|
||||
label: '最近失败',
|
||||
value: recent ? recent.latestFailureAt || '无' : hostValue,
|
||||
note: recent ? `近 ${RECENT_WINDOW_DAYS} 天 ${recent.failureCount} 次` : partialNote,
|
||||
unknown: !recent,
|
||||
},
|
||||
{
|
||||
key: 'archive',
|
||||
label: '归档占用',
|
||||
value: archiveKnown ? formatSize(archive!.capacity.current_bytes) : UNKNOWN,
|
||||
note: archiveFailed
|
||||
? '归档读取失败'
|
||||
: !archive || !archive.available
|
||||
? '归档不可用'
|
||||
: archive.capacity.configured
|
||||
? `配额 ${formatSize(archive.capacity.budget_bytes)}`
|
||||
: '配额未设置',
|
||||
unknown: !archiveKnown,
|
||||
},
|
||||
{
|
||||
key: 'disk',
|
||||
label: '磁盘剩余',
|
||||
value: diskKnown ? formatSize(capacity!.available_bytes) : sizes ? UNKNOWN : hostValue,
|
||||
note: diskKnown
|
||||
? `共 ${formatSize(capacity!.total_bytes)} · 可用 ${availablePercent}%`
|
||||
: sizes
|
||||
? '容量未上报'
|
||||
: partialNote,
|
||||
unknown: !diskKnown,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
export interface SummaryAlert {
|
||||
key: string
|
||||
label: string
|
||||
value: string
|
||||
tone: Tone
|
||||
conclusion: string
|
||||
}
|
||||
|
||||
export interface StorageFacts {
|
||||
diskAvailableBytes: number | null
|
||||
diskTotalBytes: number | null
|
||||
archiveUsedBytes: number | null
|
||||
archiveBudgetBytes: number | null
|
||||
}
|
||||
|
||||
export function storageFacts(
|
||||
inventory: BackupInventory | null,
|
||||
archive: LibraryStorage | null,
|
||||
archiveFailed: boolean
|
||||
): StorageFacts {
|
||||
const capacity = inventory?.capacity
|
||||
const diskKnown = hostState(inventory) === 'ready' && Boolean(capacity?.measured) && (capacity?.total_bytes ?? 0) > 0
|
||||
const archiveCapacity = archive?.available && !archiveFailed ? archive.capacity : null
|
||||
return {
|
||||
diskAvailableBytes: diskKnown ? capacity!.available_bytes : null,
|
||||
diskTotalBytes: diskKnown ? capacity!.total_bytes : null,
|
||||
archiveUsedBytes: archiveCapacity ? archiveCapacity.current_bytes : null,
|
||||
archiveBudgetBytes: archiveCapacity?.configured ? archiveCapacity.budget_bytes : null,
|
||||
}
|
||||
}
|
||||
|
||||
const tonePercent = (value: number, warn: number, critical: number): Tone =>
|
||||
value >= critical ? 'bad' : value >= warn ? 'warn' : 'ok'
|
||||
|
||||
const conclusionText = (tone: Tone): string =>
|
||||
tone === 'ok' ? '正常' : tone === 'warn' ? '注意' : tone === 'bad' ? '需处理' : UNKNOWN_STATE
|
||||
|
||||
export function storageAlerts(
|
||||
inventory: BackupInventory | null,
|
||||
archive: LibraryStorage | null,
|
||||
archiveFailed: boolean
|
||||
): SummaryAlert[] {
|
||||
const state = hostState(inventory)
|
||||
const facts = storageFacts(inventory, archive, archiveFailed)
|
||||
const diskKnown = facts.diskAvailableBytes !== null && (facts.diskTotalBytes ?? 0) > 0
|
||||
const availablePercent = diskKnown ? Math.round((facts.diskAvailableBytes! / facts.diskTotalBytes!) * 100) : 0
|
||||
const diskTone: Tone = diskKnown
|
||||
? availablePercent < DISK_CRITICAL_AVAILABLE_PERCENT
|
||||
? 'bad'
|
||||
: availablePercent < DISK_WARN_AVAILABLE_PERCENT
|
||||
? 'warn'
|
||||
: 'ok'
|
||||
: 'none'
|
||||
|
||||
const quotaKnown = facts.archiveUsedBytes !== null && (facts.archiveBudgetBytes ?? 0) > 0
|
||||
const usedPercent = quotaKnown ? Math.round((facts.archiveUsedBytes! / facts.archiveBudgetBytes!) * 100) : 0
|
||||
const quotaTone: Tone = quotaKnown
|
||||
? tonePercent(usedPercent, QUOTA_WARN_USED_PERCENT, QUOTA_CRITICAL_USED_PERCENT)
|
||||
: 'none'
|
||||
const bothTone: Tone =
|
||||
diskTone === 'none' || quotaTone === 'none' ? 'none' : diskTone !== 'ok' && quotaTone !== 'ok' ? 'bad' : 'ok'
|
||||
const overPhysical: Tone =
|
||||
diskKnown && facts.archiveBudgetBytes !== null
|
||||
? facts.archiveBudgetBytes > facts.diskAvailableBytes!
|
||||
? 'bad'
|
||||
: 'ok'
|
||||
: 'none'
|
||||
|
||||
const hostValue = hostValueLabel(state)
|
||||
|
||||
return [
|
||||
{
|
||||
key: 'disk_low',
|
||||
label: '磁盘不足',
|
||||
value: diskKnown ? `${formatSize(facts.diskAvailableBytes)}(可用 ${availablePercent}%)` : hostValue,
|
||||
tone: diskTone,
|
||||
conclusion: diskKnown ? conclusionText(diskTone) : UNKNOWN_STATE,
|
||||
},
|
||||
{
|
||||
key: 'quota_low',
|
||||
label: '配额不足',
|
||||
value: quotaKnown
|
||||
? `${formatSize(facts.archiveUsedBytes)} / ${formatSize(facts.archiveBudgetBytes)}(${usedPercent}%)`
|
||||
: archiveFailed
|
||||
? UNKNOWN
|
||||
: archive?.available
|
||||
? '配额未设置'
|
||||
: UNKNOWN,
|
||||
tone: quotaTone,
|
||||
conclusion: quotaKnown ? conclusionText(quotaTone) : UNKNOWN_STATE,
|
||||
},
|
||||
{
|
||||
key: 'both_low',
|
||||
label: '磁盘与配额同时不足',
|
||||
value: diskKnown && quotaKnown ? `磁盘可用 ${availablePercent}% · 配额已用 ${usedPercent}%` : hostValue,
|
||||
tone: bothTone,
|
||||
conclusion: diskKnown && quotaKnown ? conclusionText(bothTone) : UNKNOWN_STATE,
|
||||
},
|
||||
{
|
||||
key: 'quota_over_physical',
|
||||
label: '配额超出物理空闲',
|
||||
value:
|
||||
diskKnown && facts.archiveBudgetBytes !== null
|
||||
? `配额 ${formatSize(facts.archiveBudgetBytes)} · 可用 ${formatSize(facts.diskAvailableBytes)}`
|
||||
: UNKNOWN,
|
||||
tone: overPhysical,
|
||||
conclusion: diskKnown && facts.archiveBudgetBytes !== null ? conclusionText(overPhysical) : UNKNOWN_STATE,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
export const pendingAlertCount = (alerts: SummaryAlert[]): number =>
|
||||
alerts.filter((alert) => alert.tone === 'warn' || alert.tone === 'bad').length
|
||||
Reference in New Issue
Block a user