feat(backup): 只读盘点真实批次、子库路径与容量

为什么:28189 验收里历史批次/子库路径/容量都没有真实接口,页面只能占位;
用户要求修实际接口而不是继续改文案,同时不得写主机或触发备份。

怎么改:新增 GET /api/v1/backup-schedule/inventory,只读盘点 statfs 实测容量、
st_blocks 实际占盘、全部批次与 MANIFEST 状态、每个子库完整主机路径。目录必须
只读挂载;用设备号区分挂载文件系统与容器根盘,同设备时不给主机容量。清单
missing/invalid、未接线、不可读分别展示。SSH 计划读回与盘点独立加载。
前端消费该接口:整盘色带、批次列表、子库路径复制、清单失败与容器根盘提示。

怎么验:Go 单测覆盖清单/占盘/符号链接/容器根盘;handler 契约;appconfig 接线校验;
vitest 627 项、tsc、vite build、prettier 通过;本地页面夹具核对 8 批与路径复制,
1440/1024/768 无横向溢出。未连接真实主机、未执行备份、未改真实计划。
This commit is contained in:
姚章浩
2026-11-20 00:58:18 +08:00
parent 9eacf6473e
commit 033f702d41
18 changed files with 2317 additions and 118 deletions
+252 -31
View File
@@ -6,13 +6,17 @@ import {
backupDaysValid,
backupMonthsValid,
backupTimeValid,
copyBackupPath,
formatBackupBytes,
inventoryAlerts,
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 = {
@@ -67,6 +71,118 @@ const diskFixture = (overrides: Partial<StorageDiskObservation> = {}): StorageDi
...overrides,
})
const inventoryFixture = (overrides: Partial<BackupInventory> = {}): BackupInventory => {
const baseInventory: BackupInventory = {
wired: true,
root: '/var/lib/knowledge-governance/backup-host/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: '',
mount: {
container_root: '/',
mount_verified: true,
lives_on_container_root: false,
read_only: true,
evidence: '挂载设备 20 与容器根盘 10 不同:容量按挂载文件系统计量',
},
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: 696_320,
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,
},
incomplete_count: 1,
skipped: [{ name: 'junk', reason: '不是批次目录' }],
truncated: false,
}
return { ...baseInventory, ...overrides }
}
const view = (
overrides: Partial<BackupSchedule> = {},
extra: Record<string, unknown> = {},
@@ -95,6 +211,10 @@ const view = (
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()}
/>
)
}
@@ -109,7 +229,7 @@ describe('BackupScheduleView', () => {
'备份执行主机 weknora-test 本机直连 RDS',
'最近批次含 2 个数据库',
'weknora-test 本地备份根目录',
'具体根目录未由接口返回',
'备份目录未接线或不可读,不在页面猜测',
'整批 · 2 个数据库(weknora_test、dobotai_prod)',
'100.85.111.121:22',
'立即备份一次(整批 2 个数据库)',
@@ -141,7 +261,7 @@ describe('BackupScheduleView', () => {
it('目录/配额/预留没有后端字段:控件禁用并写明原因,不会假装可保存', () => {
const html = view()
expect(html).toContain('备份主机上的目录')
expect(html).toContain('接口未提供备份目录')
expect(html).toContain('只读盘点未接线')
expect(html).toContain('检查目录(不可用)')
expect(html).toContain('备份总配额(GiB)')
expect(html).toContain('磁盘预留(GiB)')
@@ -150,34 +270,85 @@ describe('BackupScheduleView', () => {
expect(html).toContain('disabled')
})
it('最近批次只展示接口真实字段;子库路径/复制/恢复验证明确未接线', () => {
const html = view({ last_run_failed_databases: ['dobotai_prod'] })
expect(html).toContain('备份记录')
expect(html).toContain('接口只返回最近一批')
expect(html).toContain('批次戳 20261009T052909Z')
expect(html).toContain('耗时 33 秒')
expect(html).toContain('742.4 MiB')
expect(html).toContain('weknora_test')
expect(html).toContain('dobotai_prod')
expect(html).toContain('失败')
expect(html).toContain('子库目录与单库字节未由接口返回')
expect(html).toContain('复制目录(不可用)')
expect(html).toContain('恢复验证:未接线')
// 不拼造历史批次或示例子目录。
expect(html).not.toContain('/srv/kb-backups/rds-logical')
expect(html).not.toContain('11 月 19 日 03:30')
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({
last_run_stamp: '',
last_run_created_at: '',
last_run_databases: [],
last_run_total_bytes: 0,
host_reachable: false,
})
expect(html).toContain('还没有读到任何批次')
expect(html).toContain('不能据此判断备份成功或失败')
it('没有只读盘点:不展示任何历史批次或伪造路径', () => {
const html = view()
expect(html).toContain('尚未读取只读盘点')
expect(html).not.toContain('批次戳')
expect(html).not.toContain('/srv/kb-backups/rds-logical')
})
it('盘点未接线:说明与 SSH 计划读回独立,未读到不等于没有备份', () => {
const html = view(
{},
{
inventory: inventoryFixture({
wired: false,
error: '只读盘点未接线(BACKUP_HOST_READONLY_ROOT 未设置)',
batches: [],
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
}),
}
)
expect(html).toContain('只读盘点未接线')
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,
},
}),
}
)
expect(html).toContain('挂载可读,但没有批次目录')
expect(html).toContain('不能证明备份成功或失败')
})
it('非管理员只读:没有保存/下发/立即备份按钮,只给当前设置', () => {
@@ -288,12 +459,12 @@ describe('BackupScheduleView', () => {
})
describe('整盘占用与告警', () => {
it('没有磁盘接口时:不显示示例容量,四条告警一律无法判定', () => {
it('没有只读盘点时:不显示示例容量,四条告警只报未知原因', () => {
const html = view()
expect(html).toContain('未接线 · 不显示估算容量')
expect(html).toContain('后端目前没有「备份主机磁盘总量、空闲、备份目录占用」接口')
expect(html).toContain('容量来自只读挂载目录的 statfs 实测')
expect(html).toContain('无法判定')
expect(html).toContain('整盘总量 / 空闲 / 备份占用:未接线')
expect(html).toContain('整盘总量 / 空闲 / 备份实际占盘:未接线')
// 原型里的示例容量不能被当成产品事实带进来。
expect(html).not.toContain('总容量 240 GiB')
expect(html).not.toContain('总容量 500 GiB')
@@ -349,4 +520,54 @@ describe('整盘占用与告警', () => {
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('真实盘点:整盘色带取 statfs 容量与 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)
const html = view({}, { inventory })
for (const text of [
'只读挂载实测',
'系统其他占用',
'备份实际占盘',
'可用',
'配额内/外 —(无配额字段)',
'文件系统已用',
'挂载为只读',
'挂载设备 20 与容器根盘 10 不同',
])
expect(html).toContain(text)
})
it('挂载落在容器根盘:不把容器容量当主机磁盘,磁盘告警保持未知', () => {
const inventory = inventoryFixture({
mount: {
container_root: '/',
mount_verified: false,
lives_on_container_root: true,
read_only: true,
evidence: '挂载设备与容器根盘相同(7):容量不代表备份主机磁盘',
},
})
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('容器根盘')
const html = view({}, { inventory })
expect(html).toContain('容器根盘 · 不代表主机磁盘')
expect(html).toContain('不据此判定备份主机磁盘')
expect(html).not.toContain('备份实际占盘 1.40 GiB')
})
it('复制路径:空值与不可用按钮不谎报成功', async () => {
expect(await copyBackupPath('')).toBe(false)
})
})
+441 -82
View File
@@ -9,6 +9,8 @@ import {
saveBackupSchedule,
} from './backupSchedule'
import type { BackupSchedule } from './backupSchedule'
import { fetchBackupInventory } from './backupInventory'
import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
import './storageBackup.css'
export const formatBackupBytes = (bytes: number): string => {
@@ -190,11 +192,122 @@ const percent = (part: number, total: number): string => (total > 0 ? `${(100 *
export const storageAlertSummary = (alerts: StorageAlert[]): string => {
const unknown = alerts.filter((item) => !item.known)
if (unknown.length) return '无法判定(缺主机磁盘读数)'
if (unknown.length === alerts.length) return '无法判定(缺读数与配额字段)'
if (unknown.length) return `部分无法判定(${unknown.map((item) => item.label).join('、')})`
const active = alerts.filter((item) => item.active)
return active.length ? active.map((item) => item.label).join('、') : '四项均正常'
}
export interface InventoryUsage {
total: number
used: number
free: number
backup: number
system_other: number
}
// 只读挂载 + 实测容量 + 文件系统与容器根盘分离,三者同时成立才画整盘图。
// 备份实际占盘取所有批次的 st_blocks 合计,不是 MANIFEST 的表观字节。
export function inventoryUsage(inventory: BackupInventory | null): InventoryUsage | null {
if (
!inventory ||
!inventory.wired ||
!inventory.mount.mount_verified ||
!inventory.capacity.measured ||
inventory.capacity.total_bytes <= 0
) {
return null
}
const total = inventory.capacity.total_bytes
const used = Math.max(0, inventory.capacity.used_bytes)
const backup = Math.max(0, inventory.totals.actual_bytes)
return {
total,
used,
free: Math.max(0, inventory.capacity.available_bytes),
backup,
system_other: Math.max(0, used - backup),
}
}
// 配额与策略预留在后端仍是缺字段,不能因为容量读到了就假装能判定配额;
// 磁盘告警只拿"最近一批实际占盘"做参考,并注明不含预留。
export function inventoryAlerts(inventory: BackupInventory | null): StorageAlert[] {
const usage = inventoryUsage(inventory)
const latest = inventory?.batches[0]
const capacityKnown = Boolean(usage)
const latestBytes = latest?.actual_bytes ?? 0
const diskKnown = capacityKnown && latestBytes > 0
const diskActive = diskKnown && latestBytes > usage!.free
const diskDetail = !inventory
? '尚未读取备份目录'
: !inventory.wired
? '只读盘点未接线'
: !inventory.mount.mount_verified
? '目录位于容器根盘,读数不代表备份主机磁盘'
: !inventory.capacity.measured
? inventory.capacity.error || '未读到文件系统容量'
: latestBytes <= 0
? '没有可参考的批次实际占盘'
: `剩余可用 ${formatGib(usage!.free)} GiB,最近一批实际占盘 ${formatGib(latestBytes)} GiB(参考值,不含策略预留)`
return [
{
code: 'disk_low',
label: '磁盘不足',
active: diskActive,
known: diskKnown,
detail: diskDetail,
},
{
code: 'quota_low',
label: '配额不足',
active: false,
known: false,
detail: '后端没有备份总配额字段,无法判定',
},
{
code: 'both_low',
label: '磁盘与配额同时不足',
active: false,
known: false,
detail: '缺配额字段,无法判定',
},
{
code: 'quota_over_physical',
label: '配额超出物理空闲',
active: false,
known: false,
detail: '缺配额字段,无法判定',
},
]
}
export async function copyBackupPath(value: string, button?: HTMLButtonElement | null): Promise<boolean> {
if (!value) return false
try {
await navigator.clipboard.writeText(value)
if (button) button.textContent = '已复制'
return true
} catch {
// 内网 http 页面没有 clipboard API 权限时退回选中,不谎报“已复制”。
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()
if (button) button.textContent = copied ? '已复制' : '路径已选中,可复制'
return copied
}
}
const manifestLabel = (batch: BackupInventoryBatch): string =>
batch.manifest_state === 'ok' ? '清单完整' : batch.manifest_state === 'missing' ? '清单缺失' : '清单损坏'
// 备份执行主机上的整库逻辑备份(全部业务库一次 pg_dump)。
// 页面只展示接口真实给出的读数;目录、配额、预留、子库路径、历史批次与恢复
// 验证在后端契约里还没有字段,保留原型位置并写明"未接线"。
@@ -218,8 +331,12 @@ export interface BackupScheduleViewProps {
onApply: () => void
onRunNow: () => void
onReload: () => void
// 仅测试夹具提供;生产容器不传,磁盘区显示"未接线"。
// 仅测试夹具提供;生产容器不传,磁盘区改用真实盘点的容量。
disk?: StorageDiskObservation | null
inventory?: BackupInventory | null
inventoryLoading?: boolean
inventoryError?: string | null
onReloadInventory?: () => void
}
export function BackupScheduleView(props: BackupScheduleViewProps) {
@@ -244,6 +361,10 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
onRunNow,
onReload,
disk = null,
inventory = null,
inventoryLoading = false,
inventoryError = null,
onReloadInventory,
} = props
const days = Number(daysDraft)
const months = Number(monthsDraft)
@@ -283,7 +404,16 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
const hasLastRun = Boolean(schedule.last_run_stamp)
const runFailed = failedCount > 0 || Boolean(schedule.last_run_error)
const usage = disk ? storageUsage(disk) : null
const alerts = storageAlerts(disk)
const alerts = disk ? storageAlerts(disk) : inventoryAlerts(inventory)
const latestBatch: BackupInventoryBatch | null = inventory?.batches[0] ?? null
const inventoryFigure = inventoryUsage(inventory)
const inventoryReady = Boolean(inventory?.wired && !inventory.error)
const readyInventory = inventory && inventory.wired && !inventory.error ? inventory : null
const inventoryDatabases = latestBatch?.databases.map((item) => item.name) ?? []
const scopeDatabases = inventoryDatabases.length ? inventoryDatabases : schedule.last_run_databases
const scopeDatabaseCount = scopeDatabases.length
const scopeFailed = latestBatch ? latestBatch.databases.filter((item) => item.failed).length : failedCount
const hasScopeBatch = Boolean(latestBatch) || hasLastRun
return (
<section className="settings-panel wide storage-settings-panel" id="settings-storage">
@@ -311,22 +441,33 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
<span className={`storage-chip ${schedule.host_configured ? 'ok' : 'off'}`}>
{schedule.host_configured ? '平台已接主机凭据' : '平台未接主机凭据'}
</span>
<span className={`storage-chip ${inventoryReady ? 'ok' : 'off'}`}>
{inventoryLoading
? '文件盘点读取中'
: inventoryReady
? '文件盘点已接线'
: inventory?.error
? '文件盘点不可读'
: '文件盘点未接线'}
</span>
</div>
<dl className="storage-facts">
<dt>读取源</dt>
<dd>
{`备份执行主机 ${schedule.host_target || '(未配置)'} 本机直连 RDS`}
{databaseCount ? ` · 最近批次含 ${databaseCount} 个数据库` : ' · 数据库清单未从主机读到'}
{inventory?.source || `备份执行主机 ${schedule.host_target || '(未配置)'} 本机直连 RDS`}
{scopeDatabaseCount ? ` · 最近批次含 ${scopeDatabaseCount} 个数据库` : ' · 数据库清单未读到'}
</dd>
<dt>写入方向</dt>
<dd>
{`${schedule.host_target || '(未配置)'} 本地备份根目录`}
<span className="storage-inline-note">具体根目录未由接口返回,不在页面猜测</span>
{inventory?.host_root || `${schedule.host_target || '(未配置)'} 本地备份根目录`}
<span className="storage-inline-note">
{inventoryReady ? '只读挂载盘点;平台没有写路径' : '备份目录未接线或不可读,不在页面猜测'}
</span>
</dd>
<dt>执行范围</dt>
<dd>
{databaseCount
? `整批 · ${databaseCount} 个数据库(${schedule.last_run_databases.join('、')})`
{scopeDatabaseCount
? `整批 · ${scopeDatabaseCount} 个数据库(${scopeDatabases.join('、')})`
: '整批 · 数据库清单未读到,无法列出库名'}
</dd>
<dt>拨号地址</dt>
@@ -338,8 +479,8 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
</button>
<p className="hint">
<code>POST /api/v1/backup-schedule/run</code> 没有单库参数,一次就是该主机全部业务库的整批
pg_dump。用单库按钮触发会连整批一起跑,因此本页不开放单库动作;单库恢复只能用批次里该库的子目录,
但子目录路径当前接口没有返回。
pg_dump。用单库按钮触发会连整批一起跑,因此本页不开放单库动作;单库恢复请复制「备份记录」里该库的
完整子目录(来自只读盘点),不要自己拼路径。
</p>
</div>
</section>
@@ -347,19 +488,23 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
<section className="storage-block" aria-labelledby="storage-run-heading">
<div className="storage-block-heading">
<h3 id="storage-run-heading">立即备份</h3>
<span className={`storage-chip ${hasLastRun && !runFailed ? 'ok' : hasLastRun ? 'warn' : 'off'}`}>
{hasLastRun ? (runFailed ? '最近一批有失败' : '最近一批成功') : '尚无批次读数'}
<span
className={`storage-chip ${hasScopeBatch && scopeFailed === 0 ? 'ok' : hasScopeBatch ? 'warn' : 'off'}`}
>
{hasScopeBatch ? (scopeFailed > 0 ? '最近一批有失败' : '最近一批成功') : '尚无批次读数'}
</span>
</div>
<p>
{hasLastRun
? `最近一批 ${schedule.last_run_stamp}${runMoment(schedule) ? ` · ${runMoment(schedule)}` : ''} · ${databaseCount} 个数据库 · ${formatBackupBytes(schedule.last_run_total_bytes)} · ${schedule.last_run_duration_seconds} 秒`
: '还没有从主机读到任何批次。'}
{latestBatch
? `最近一批 ${latestBatch.stamp} · ${formatBackupMoment(latestBatch.created_at)} · ${scopeDatabaseCount} 个数据库 · 表观 ${formatBackupBytes(latestBatch.apparent_bytes)} · 实际占盘 ${formatBackupBytes(latestBatch.actual_bytes)} · ${latestBatch.duration_seconds} 秒`
: hasLastRun
? `SSH 读回最近一次 ${schedule.last_run_stamp} · ${databaseCount} 个数据库 · ${formatBackupBytes(schedule.last_run_total_bytes)}(文件盘点未接线,以下仅 SSH 结果)`
: '还没有从主机读到任何批次。'}
</p>
{schedule.running ? (
<div className="storage-progress" role="status">
<p className="storage-running">
正在备份({formatBackupMoment(schedule.running_started_at)} 开始,整批 {databaseCount || '未知'}{' '}
正在备份({formatBackupMoment(schedule.running_started_at)} 开始,整批 {scopeDatabaseCount || '未知'}{' '}
个数据库)。 没有真实百分比接口,这里只报在途状态,完成后自动刷新。
</p>
<progress className="storage-progress-bar" aria-label="备份进行中,无百分比" />
@@ -394,7 +539,17 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
>
<div className="storage-block-heading">
<h3 id="storage-disk-heading">整盘占用与告警</h3>
<span className="storage-chip off">{usage ? '已读到主机读数' : '未接线'}</span>
<span className="storage-chip off">
{usage
? '已读到主机读数'
: inventoryFigure
? inventory?.mount.read_only
? '只读挂载实测'
: '实测(挂载可写)'
: inventory?.capacity.measured
? '容器根盘(不可作主机容量)'
: '未接线'}
</span>
</div>
{usage && disk ? (
<>
@@ -446,29 +601,102 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
: ''}
</small>
</>
) : inventoryFigure && inventory ? (
<>
<div
className="storage-disk-track"
role="img"
aria-label={`挂载盘 ${formatGib(inventoryFigure.total)} GiB:系统其他占用 ${formatGib(inventoryFigure.system_other)} GiB、备份实际占盘 ${formatGib(inventoryFigure.backup)} GiB、可用 ${formatGib(inventoryFigure.free)} GiB`}
>
<div
className="storage-disk-other"
style={{ width: percent(inventoryFigure.system_other, inventoryFigure.total) }}
/>
<div
className="storage-disk-used"
style={{ width: percent(inventoryFigure.backup, inventoryFigure.total) }}
/>
<div
className="storage-disk-blank"
style={{
width: percent(
Math.max(0, inventoryFigure.total - inventoryFigure.used - inventoryFigure.free),
inventoryFigure.total
),
}}
/>
</div>
<div className="storage-disk-legend">
<span>
<i className="storage-dot other" />
系统其他占用 {formatGib(inventoryFigure.system_other)} GiB
</span>
<span>
<i className="storage-dot used" />
备份实际占盘 {formatGib(inventoryFigure.backup)} GiB
</span>
<span>
<i className="storage-dot blank" />
可用 {formatGib(inventoryFigure.free)} GiB
</span>
<span>
<i className="storage-dot zone" />
配额内/外 —(无配额字段)
</span>
</div>
<p className="storage-metric">
备份实际占盘 {formatGib(inventoryFigure.backup)} / 整盘 {formatGib(inventoryFigure.total)} GiB(
{inventoryFigure.total > 0
? `${((100 * inventoryFigure.backup) / inventoryFigure.total).toFixed(2)}%`
: '—'}
)· 文件系统已用 {formatGib(inventoryFigure.used)} GiB · 可用 {formatGib(inventoryFigure.free)} GiB
</p>
<small>
{inventory.mount.evidence} · 挂载点 {inventory.root} · 采集于 {formatBackupMoment(inventory.observed_at)}
{inventory.mount.read_only ? ' · 挂载为只读' : ' · 挂载不是只读(部署需改 :ro)'}
</small>
</>
) : inventory?.capacity.measured ? (
<>
<div
className="storage-disk-track storage-disk-track-unknown"
role="img"
aria-label="目录位于容器根盘,容量不代表备份主机磁盘"
>
<span>容器根盘 · 不代表主机磁盘</span>
</div>
<p className="storage-metric">
容器根盘实测 {formatGib(inventory.capacity.total_bytes)} GiB,可用{' '}
{formatGib(inventory.capacity.available_bytes)} GiB:仅作排障,不据此判定备份主机磁盘。
</p>
<small>{inventory.mount.evidence}</small>
</>
) : (
<>
<div
className="storage-disk-track storage-disk-track-unknown"
role="img"
aria-label="整盘占用未接线:后端未提供磁盘总量、空闲量与备份占用读数"
aria-label="整盘占用未接线:没有可读的只读挂载"
>
<span>未接线 · 不显示估算容量</span>
<span>{inventoryLoading ? '正在读取只读挂载…' : '未接线 · 不显示估算容量'}</span>
</div>
<div className="storage-disk-legend">
{['系统其他占用', '备份已用', '配额内空闲', '配额外空闲'].map((label, index) => (
{['系统其他占用', '备份实际占盘', '可用', '配额内/外'].map((label, index) => (
<span key={label}>
<i className={`storage-dot ${['other', 'used', 'zone', 'blank'][index]}`} />
<i className={`storage-dot ${['other', 'used', 'blank', 'zone'][index]}`} />
{label} —
</span>
))}
</div>
<p className="storage-metric">整盘总量 / 空闲 / 备份占用:未接线</p>
<p className="storage-metric">
整盘总量 / 空闲 / 备份实际占盘:{inventoryError || inventory?.error || '未接线'}
</p>
</>
)}
<p className="hint">
后端目前没有「备份主机磁盘总量、空闲、备份目录占用」接口:这里保留单条整盘图的位置,
不填示例容量、不用配额推算磁盘。以下四项告警按同一份真实读数判定。
容量来自只读挂载目录的 statfs 实测,并与容器根盘比较设备号;同一设备时不把容器容量当主机容量。 备份占盘按文件
st_blocks 统计(实际分配),不是 MANIFEST 的表观字节。配额与策略预留仍无后端字段,
四项告警中只有磁盘项能按实测判定。
</p>
<p className="storage-alert-summary">{storageAlertSummary(alerts)}</p>
<ul className="storage-alerts">
@@ -511,18 +739,22 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
备份主机上的目录
<input
type="text"
value=""
value={inventory?.host_root || ''}
readOnly
disabled
placeholder="接口未提供备份目录"
aria-label="备份主机上的目录(未接线)"
placeholder={inventoryReady ? '' : '只读盘点未接线'}
aria-label="备份主机上的目录(只读展示)"
/>
</label>
<div className="storage-block-actions">
<button type="button" disabled title="没有目录检查接口">
检查目录(不可用)
</button>
<span className="hint">目录检查接口未接线:无法证明目录可写、挂在哪块盘。</span>
<span className="hint">
{inventoryReady
? '目录来自只读挂载来源,只读展示;修改目录需部署变更,平台没有写接口。'
: '只读盘点未接线:目录不可证明,不能按设置推定。'}
</span>
</div>
<label className="storage-checkbox">
<input
@@ -624,57 +856,141 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
<section className="storage-block" aria-labelledby="storage-runs-heading">
<div className="storage-block-heading">
<h3 id="storage-runs-heading">备份记录</h3>
<span className="hint">接口只返回最近一批</span>
<span className="hint">
{readyInventory
? `${readyInventory.totals.batch_count} 批 · 只读盘点 · 实际占盘 ${formatBackupBytes(readyInventory.totals.actual_bytes)}`
: '只读盘点'}
</span>
<button type="button" onClick={onReloadInventory} disabled={inventoryLoading}>
{inventoryLoading ? '盘点中…' : '重新盘点'}
</button>
</div>
<p className="hint">
历史批次列表、每批的数据库明细与子库目录都没有接口:这里只能展示主机 MANIFEST 里的最近一批,
不补造历史记录,也不从时间戳推算目录。
</p>
{hasLastRun ? (
<details className="storage-batch" open>
<summary>
<span>{schedule.last_run_created_at || schedule.last_run_stamp}</span>
<span>{databaseCount} 个数据库 · 整批</span>
<strong className={runFailed ? 'off' : 'ok'}>
{runFailed ? '有失败/读取错误' : '成功 · 共 ' + formatBackupBytes(schedule.last_run_total_bytes)}
</strong>
</summary>
<p>
批次戳 {schedule.last_run_stamp} · 耗时 {schedule.last_run_duration_seconds} 秒 · 总占盘{' '}
{formatBackupBytes(schedule.last_run_total_bytes)} · 单库体积未由清单提供
</p>
<ul className="storage-sublibraries">
{schedule.last_run_databases.map((name) => {
const failed = schedule.last_run_failed_databases.includes(name)
return (
<li key={name}>
<code>{name}</code>
<span className={failed ? 'off' : 'ok'}>{failed ? '失败' : '已写入'}</span>
<small>子库目录与单库字节未由接口返回</small>
</li>
)
})}
</ul>
{schedule.last_run_failed_databases.length ? (
<p className="error-message">失败库:{schedule.last_run_failed_databases.join('、')}</p>
) : null}
<div className="storage-block-actions">
<button type="button" disabled title="接口未返回子库路径,无可复制内容">
复制目录(不可用)
</button>
<span className="hint">子库路径待接口返回后才能复制;当前不拼接猜测路径。</span>
</div>
<p className="storage-verify">
恢复验证:未接线(没有数据库备份恢复验证接口,不能把"备份成功"当成"可恢复")。
</p>
</details>
) : (
<p className="hint">
{schedule.last_run_error
? `最近一次结果读取失败:${schedule.last_run_error}`
: '还没有读到任何批次(平台未接主机凭据、主机连不上或尚未执行过);不能据此判断备份成功或失败。'}
{inventoryLoading && !inventory ? <p className="hint">正在读取只读挂载与 MANIFEST…</p> : null}
{inventoryError ? (
<p className="error-message" role="alert">
盘点请求失败:{inventoryError}。不能用 SSH 的“最近一次”代替历史;请检查 API 到只读挂载的接线。
</p>
)}
) : null}
{inventory && !inventory.wired ? (
<p className="hint">
只读盘点未接线:{inventory.error}。部署需把备份目录以 <code>:ro</code> 挂进 API (见
docs/STORAGE_BACKUP_READONLY_API.md);未读到批次不等于没有备份。
</p>
) : null}
{inventory && inventory.wired && inventory.error ? (
<p className="error-message" role="alert">
只读目录不可读:{inventory.error}
</p>
) : null}
{readyInventory ? (
<>
<p className="hint">
最近批次 {readyInventory.totals.latest_stamp || '—'} · 共 {readyInventory.totals.batch_count} 批 /{' '}
{readyInventory.totals.database_count} 个子库 · 表观{' '}
{formatBackupBytes(readyInventory.totals.apparent_bytes)} · 实际占盘{' '}
{formatBackupBytes(readyInventory.totals.actual_bytes)}。批次与路径来自只读目录,不依赖 SSH 计划读回。
</p>
{readyInventory.batches.length === 0 ? (
<p className="hint">
挂载可读,但没有批次目录(可能尚未执行,或挂载到了空目录);这不能证明备份成功或失败。
</p>
) : null}
{readyInventory.batches.map((batch, index) => {
const failedDatabases = batch.databases.filter((item) => item.failed)
const batchPath = batch.host_path || batch.path
return (
<details className="storage-batch" key={batch.stamp} open={index === 0}>
<summary>
<span>{batch.created_at || batch.stamp}</span>
<span>{batch.databases.length} 个数据库 · 整批</span>
<span className={`storage-manifest ${batch.manifest_state}`}>{manifestLabel(batch)}</span>
<strong className={failedDatabases.length || batch.manifest_state !== 'ok' ? 'off' : 'ok'}>
{failedDatabases.length
? `有失败 ${failedDatabases.length} 个`
: `实际占盘 ${formatBackupBytes(batch.actual_bytes)}`}
</strong>
</summary>
<p>
批次戳 {batch.stamp} · 表观 {formatBackupBytes(batch.apparent_bytes)} · 实际占盘{' '}
{formatBackupBytes(batch.actual_bytes)} · {batch.file_count} 个文件
{batch.duration_seconds ? ` · 耗时 ${batch.duration_seconds} 秒` : ''}
{batch.kind ? ` · ${batch.kind}` : ''}
</p>
{batch.manifest_state === 'ok' ? null : (
<p className="error-message">
{batch.manifest_state === 'missing'
? '此批次没有 MANIFEST.json:只能按目录统计占盘,无法确认完整性、耗时与库列表。'
: `此批次清单损坏:${batch.manifest_error || '无法解析'};只能按目录统计占盘。`}
</p>
)}
{!batch.sizes_complete ? (
<p className="error-message">
实际占盘未扫全:{batch.sizes_error || '文件数超过上限'};显示的是已扫描部分。
</p>
) : null}
<div className="storage-path-row">
<small>批次目录</small>
<code>{batchPath || '—'}</code>
<button
type="button"
disabled={!batch.host_path}
title={batch.host_path ? '复制完整主机路径' : '没有主机路径(只读盘点未配置主机根)'}
onClick={(event) => void copyBackupPath(batch.host_path, event.currentTarget)}
>
复制目录
</button>
</div>
<ul className="storage-sublibraries">
{batch.databases.map((database) => (
<li key={database.dir_name}>
<code>{database.name}</code>
<span className={database.failed || !database.present ? 'off' : 'ok'}>
{database.failed ? '失败' : database.present ? '已写入' : '目录缺失'}
</span>
<small>
实际 {formatBackupBytes(database.actual_bytes)} · 表观{' '}
{formatBackupBytes(database.apparent_bytes)} · {database.file_count} 个文件
{database.in_manifest ? '' : ' · 不在清单库列表'}
</small>
<div className="storage-path-row storage-sublibrary-path">
<code>{database.host_path || database.path || '—'}</code>
<button
type="button"
disabled={!database.host_path}
title={database.host_path ? '复制子库完整路径' : '没有主机路径'}
onClick={(event) => void copyBackupPath(database.host_path, event.currentTarget)}
>
复制子库目录
</button>
</div>
</li>
))}
</ul>
<p className="storage-verify">
恢复验证:未接线(没有数据库备份恢复验证接口,不能把“备份成功”当成“可恢复”)。
</p>
</details>
)
})}
{readyInventory.incomplete_count > 0 ? (
<p className="hint">
有 {readyInventory.incomplete_count} 个 <code>*.incomplete</code> 目录未计入批次(被中断的运行)。
</p>
) : null}
{readyInventory.skipped.length > 0 ? (
<p className="hint">
跳过 {readyInventory.skipped.length} 项:
{readyInventory.skipped.map((item) => `${item.name}(${item.reason})`).join(';')}
</p>
) : null}
{readyInventory.truncated ? <p className="hint">目录或文件数超过扫描上限,列表与占盘为部分结果。</p> : null}
<p className="hint">
盘点采集于 {formatBackupMoment(readyInventory.observed_at)} · 挂载点 {readyInventory.root || '—'} · 来源{' '}
{readyInventory.source || '—'}
</p>
</>
) : null}
{!inventory && !inventoryLoading && !inventoryError ? <p className="hint">尚未读取只读盘点。</p> : null}
</section>
<section className="storage-block" aria-labelledby="storage-host-heading">
@@ -712,14 +1028,14 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
</dd>
</dl>
<dl>
<dt>最近一次运行</dt>
<dt>SSH 最近一次结果(历史)</dt>
<dd>
{schedule.last_run_stamp || '—'}
{runMoment(schedule) ? ` · ${runMoment(schedule)}` : ''}
{schedule.last_run_stamp ? (runFailed ? ' · 有失败/读取错误' : ' · 成功') : ''}
</dd>
<dt>最近一次成功</dt>
<dd>未从主机读取(不能用最近一次运行代替成功;失败库/读取错误见上)</dd>
<dd>未从主机读取(不能用最近一次运行代替成功;历史批次以「备份记录」的只读盘点为准)</dd>
<dt>备份耗时 / 体积</dt>
<dd>
{schedule.last_run_stamp
@@ -738,6 +1054,9 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
</div>
{schedule.host_error ? <p className="hint">主机探测:{schedule.host_error}</p> : null}
{schedule.last_run_error ? <p className="hint">最近一次结果读取:{schedule.last_run_error}</p> : null}
{schedule.last_run_failed_databases.length ? (
<p className="hint">SSH 结果的失败库:{schedule.last_run_failed_databases.join('、')}</p>
) : null}
{schedule.host_cron_lines.length ? (
<p className="hint">
主机 cron 条目:<code>{schedule.host_cron_lines.join(' ; ')}</code>
@@ -767,6 +1086,9 @@ export function BackupScheduleSection() {
const [timeDraft, setTimeDraft] = useState('03:30')
const [daysDraft, setDaysDraft] = useState('7')
const [monthsDraft, setMonthsDraft] = useState('3')
const [inventory, setInventory] = useState<BackupInventory | null>(null)
const [inventoryLoading, setInventoryLoading] = useState(true)
const [inventoryError, setInventoryError] = useState<string | null>(null)
const polling = useRef<number | null>(null)
const adopt = useCallback((next: BackupSchedule) => {
@@ -797,10 +1119,40 @@ export function BackupScheduleSection() {
}
}, [adopt])
const loadInventory = useCallback(async () => {
setInventoryLoading(true)
setInventoryError(null)
try {
setInventory(await fetchBackupInventory())
} catch (cause) {
setInventoryError(cause instanceof Error ? cause.message : '读取只读备份盘点失败')
} finally {
setInventoryLoading(false)
}
}, [])
useEffect(() => {
void loadInventory()
}, [loadInventory])
useEffect(() => {
void load()
}, [load])
// 备份完成(running 转假)后再盘点一次,新批次才会出现在历史里;
// 运行中不反复扫目录,避免把主机 IO 当成轮询接口。
const wasRunning = useRef(false)
useEffect(() => {
if (schedule?.running) {
wasRunning.current = true
return
}
if (wasRunning.current) {
wasRunning.current = false
void loadInventory()
}
}, [schedule?.running, loadInventory])
// 立即备份约 30~60 秒:在途时轮询主机状态,直到 running 转假并出现新的最近一次结果。
useEffect(() => {
if (!schedule?.running) {
@@ -925,8 +1277,15 @@ export function BackupScheduleSection() {
onSave={() => void save()}
onApply={() => void apply()}
onRunNow={() => void runNow()}
onReload={() => void load()}
// disk 不传:后端还没有磁盘读数接口,磁盘区显示"未接线",绝不填示例容量。
onReload={() => {
void load()
void loadInventory()
}}
inventory={inventory}
inventoryLoading={inventoryLoading}
inventoryError={inventoryError}
onReloadInventory={() => void loadInventory()}
// disk 不传:生产只认只读挂载盘点;disk 仅测试夹具用于验证告警分支。
/>
)
}
+107
View File
@@ -0,0 +1,107 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { fetchBackupInventory } from './backupInventory'
const payload = {
data: {
wired: true,
root: '/var/lib/knowledge-governance/backup-host/rds-logical',
host_root: '/srv/kb-backups/rds-logical',
source: 'weknora-test:/srv/kb-backups/rds-logical',
observed_at: '2026-11-19T03:30:10Z',
mount: {
container_root: '/',
mount_verified: true,
lives_on_container_root: false,
read_only: true,
evidence: '挂载设备 20 与容器根盘 10 不同',
},
capacity: {
measured: true,
total_bytes: 257698037760,
free_bytes: 51539607552,
available_bytes: 48318382080,
used_bytes: 206158430208,
},
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',
duration_seconds: 53,
apparent_bytes: 1393646469,
actual_bytes: 1500000000,
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: 696320,
actual_bytes: 720896,
file_count: 12,
},
],
},
],
totals: {
batch_count: 1,
database_count: 1,
apparent_bytes: 1393646469,
actual_bytes: 1500000000,
latest_stamp: '20261118T193001Z',
latest_actual_bytes: 1500000000,
},
incomplete_count: 1,
skipped: [],
truncated: false,
},
}
afterEach(() => {
vi.unstubAllGlobals()
})
describe('fetchBackupInventory', () => {
it('保留真实批次、子库完整主机路径与实际占盘', async () => {
vi.stubGlobal(
'fetch',
vi.fn(() => Promise.resolve({ ok: true, json: () => Promise.resolve(payload) }))
)
const inventory = await fetchBackupInventory()
expect(inventory.wired).toBe(true)
expect(inventory.mount.mount_verified).toBe(true)
expect(inventory.capacity.measured).toBe(true)
expect(inventory.totals.actual_bytes).toBe(1500000000)
expect(inventory.batches[0].host_path).toBe('/srv/kb-backups/rds-logical/20261118T193001Z')
expect(inventory.batches[0].databases[0].host_path).toBe(
'/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir'
)
expect(inventory.batches[0].databases[0].actual_bytes).toBe(720896)
})
it('响应缺 wired 时整块报错,不默认成未接线', async () => {
vi.stubGlobal(
'fetch',
vi.fn(() => Promise.resolve({ ok: true, json: () => Promise.resolve({ data: {} }) }))
)
await expect(fetchBackupInventory()).rejects.toThrow('缺 wired')
})
it('HTTP 失败不返回空批次', async () => {
vi.stubGlobal(
'fetch',
vi.fn(() => Promise.resolve({ ok: false, status: 502 }))
)
await expect(fetchBackupInventory()).rejects.toThrow('HTTP 502')
})
})
+194
View File
@@ -0,0 +1,194 @@
// 「存储与备份 → 备份记录」只读盘点接口。真实字段来自备份主机目录的只读挂载:
// 批次目录、每个库的完整子目录、文件系统实测容量;不是 SSH 计划读回的副产物。
export interface BackupInventoryMount {
container_root: string
mount_verified: boolean
lives_on_container_root: boolean
read_only: boolean
evidence: string
error?: string
}
export interface BackupInventoryCapacity {
measured: boolean
total_bytes: number
free_bytes: number
available_bytes: number
used_bytes: number
error?: string
}
export interface BackupInventoryDatabase {
name: string
dir_name: string
path: string
host_path: string
present: boolean
failed: boolean
in_manifest: boolean
apparent_bytes: number
actual_bytes: number
file_count: number
}
export type BackupManifestState = 'ok' | 'missing' | 'invalid'
export interface BackupInventoryBatch {
stamp: string
path: string
host_path: string
manifest_state: BackupManifestState
manifest_path: string
manifest_error?: string
kind: string
created_at: string
started_at: string
duration_seconds: number
manifest_total_bytes: number
apparent_bytes: number
actual_bytes: number
file_count: number
sizes_complete: boolean
sizes_error?: string
databases: BackupInventoryDatabase[]
}
export interface BackupInventorySkipped {
name: string
reason: string
}
export interface BackupInventory {
wired: boolean
root: string
host_root: string
source: string
observed_at: string
error?: string
mount: BackupInventoryMount
capacity: BackupInventoryCapacity
batches: BackupInventoryBatch[]
totals: {
batch_count: number
database_count: number
apparent_bytes: number
actual_bytes: number
latest_stamp: string
latest_actual_bytes: number
}
incomplete_count: number
skipped: BackupInventorySkipped[]
truncated: 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 asBool = (value: unknown): boolean => value === true
const asList = (value: unknown): unknown[] => (Array.isArray(value) ? value : [])
const manifestState = (value: unknown): BackupManifestState =>
value === 'ok' || value === 'missing' || value === 'invalid' ? value : 'invalid'
function databaseProjection(item: unknown): BackupInventoryDatabase {
const value = record(item) ? item : {}
return {
name: asString(value.name),
dir_name: asString(value.dir_name),
path: asString(value.path),
host_path: asString(value.host_path),
present: asBool(value.present),
failed: asBool(value.failed),
in_manifest: asBool(value.in_manifest),
apparent_bytes: asNumber(value.apparent_bytes),
actual_bytes: asNumber(value.actual_bytes),
file_count: asNumber(value.file_count),
}
}
function batchProjection(item: unknown): BackupInventoryBatch {
const value = record(item) ? item : {}
return {
stamp: asString(value.stamp),
path: asString(value.path),
host_path: asString(value.host_path),
manifest_state: manifestState(value.manifest_state),
manifest_path: asString(value.manifest_path),
manifest_error: asString(value.manifest_error),
kind: asString(value.kind),
created_at: asString(value.created_at),
started_at: asString(value.started_at),
duration_seconds: asNumber(value.duration_seconds),
manifest_total_bytes: asNumber(value.manifest_total_bytes),
apparent_bytes: asNumber(value.apparent_bytes),
actual_bytes: asNumber(value.actual_bytes),
file_count: asNumber(value.file_count),
sizes_complete: asBool(value.sizes_complete),
sizes_error: asString(value.sizes_error),
databases: asList(value.databases).map(databaseProjection),
}
}
// 形状不对就整块报错:不能让缺 wired 的响应用默认 false 冒充"未接线"。
function inventoryProjection(value: unknown): BackupInventory {
if (!record(value) || typeof value.wired !== 'boolean') {
throw new Error('备份盘点响应无效(缺 wired)')
}
const mount = record(value.mount) ? value.mount : {}
const capacity = record(value.capacity) ? value.capacity : {}
const totals = record(value.totals) ? value.totals : {}
return {
wired: value.wired,
root: asString(value.root),
host_root: asString(value.host_root),
source: asString(value.source),
observed_at: asString(value.observed_at),
error: asString(value.error),
mount: {
container_root: asString(mount.container_root),
mount_verified: asBool(mount.mount_verified),
lives_on_container_root: asBool(mount.lives_on_container_root),
read_only: asBool(mount.read_only),
evidence: asString(mount.evidence),
error: asString(mount.error),
},
capacity: {
measured: asBool(capacity.measured),
total_bytes: asNumber(capacity.total_bytes),
free_bytes: asNumber(capacity.free_bytes),
available_bytes: asNumber(capacity.available_bytes),
used_bytes: asNumber(capacity.used_bytes),
error: asString(capacity.error),
},
batches: asList(value.batches).map(batchProjection),
totals: {
batch_count: asNumber(totals.batch_count),
database_count: asNumber(totals.database_count),
apparent_bytes: asNumber(totals.apparent_bytes),
actual_bytes: asNumber(totals.actual_bytes),
latest_stamp: asString(totals.latest_stamp),
latest_actual_bytes: asNumber(totals.latest_actual_bytes),
},
incomplete_count: asNumber(value.incomplete_count),
skipped: asList(value.skipped).map((item) => {
const entry = record(item) ? item : {}
return { name: asString(entry.name), reason: asString(entry.reason) }
}),
truncated: asBool(value.truncated),
}
}
export async function fetchBackupInventory(signal?: AbortSignal): Promise<BackupInventory> {
const response = await fetch('/api/v1/backup-schedule/inventory', {
headers: { Accept: 'application/json' },
signal,
})
if (!response.ok) {
throw new Error(`读取备份盘点失败(HTTP ${response.status})`)
}
const value = (await response.json().catch(() => null)) as unknown
if (!record(value) || !record(value.data)) throw new Error('备份盘点响应无效')
return inventoryProjection(value.data)
}
+71
View File
@@ -39,6 +39,20 @@
font-size: 13px;
color: var(--ink-base);
}
.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-block-heading button:disabled {
opacity: 0.55;
cursor: default;
}
.storage-chip {
border-radius: 999px;
padding: 2px 9px;
@@ -194,6 +208,60 @@
font-size: 11px;
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;
@@ -330,6 +398,9 @@
border-radius: 5px;
background: var(--bg-soft, #f6f8fa);
}
.storage-sublibrary-path {
grid-column: 1 / -1;
}
.storage-sublibraries .ok {
color: #17695a;
}