feat(settings): 存储与备份只读摘要页对齐验收
build / build (push) Successful in 2m12s

- 单一「存储与备份」页:目录、最近成功/失败、归档占用、磁盘剩余四张卡片 + 备份目录条
- 四条容量告警按磁盘可用/配额已用阈值给出 正常/注意/需处理,缺数显示 未知 而非正常
- 批次表默认 20 条 + 加载更多,展示失败原因与单条复制;60 秒自动刷新
- 未接入/未上报/过期/不完整/不可用分状态措辞,不用 0 冒充
- 移除计划编辑、下发、立即备份与库内诊断块(写端点保留)
- compose 接线 LIBRARY_CAPACITY_BUDGET_BYTES 与 BACKUP_HOST_* 只读元数据
This commit is contained in:
狐友 GXXP & LEN
2026-11-24 11:35:21 +08:00
committed by 姚章浩
parent 660320d646
commit b2248a9b64
14 changed files with 1539 additions and 3074 deletions
+348
View File
@@ -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