feat(backup): 配额改按备份根占用并在超限时清理最旧批次
build / build (push) Successful in 3m22s

- 采集器上报 backup_root/usage/quota(加性字段),API 用 BACKUP_HOST_ROOT 校验并分别降级占用/配额
- 页面配额行改为备份占用 X / 配额 50 GB,4 条告警改用备份口径,解除本页归档依赖
- logical-backup.sh 预检按字节清理(保留最新、空间不足零删除),dump 后复查保护新批次
- backup_layout 写入 KB_BACKUP_QUOTA_BYTES;--show 输出根占用;新增 prune 工具与自检
This commit is contained in:
Zhero & Rin
2026-11-25 22:45:35 +08:00
committed by 姚章浩
parent 65476750b0
commit 144b49cb53
20 changed files with 1124 additions and 178 deletions
+24 -38
View File
@@ -5,7 +5,6 @@ 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
@@ -66,6 +65,7 @@ const inventory = (overrides: Partial<BackupInventory> = {}): BackupInventory =>
},
root: '/srv/kb-backups/rds-logical',
host_root: '/srv/kb-backups/rds-logical',
backup_root: '/srv/kb-backups',
source: 'host',
observed_at: '2026-11-24T10:18:00Z',
measurement: 'host-reported',
@@ -86,6 +86,18 @@ const inventory = (overrides: Partial<BackupInventory> = {}): BackupInventory =>
available_bytes: 1.2 * TB,
used_bytes: 0.8 * TB,
},
usage: {
root: '/srv/kb-backups',
measured: true,
complete: true,
actual_bytes: 40 * GIB,
apparent_bytes: 36 * GIB,
file_count: 400,
dir_count: 20,
error: '',
},
quota_bytes: 50 * GIB,
quota_error: '',
batches: [batch(0), batch(1, { manifest_state: 'invalid' })],
totals: {
batch_count: 2,
@@ -102,29 +114,6 @@ const inventory = (overrides: Partial<BackupInventory> = {}): BackupInventory =>
...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>>>
@@ -145,7 +134,7 @@ beforeEach(() => {
if (path.endsWith('/inventory')) {
return new Response(JSON.stringify({ data: inventory() }), { status: 200 })
}
return new Response(JSON.stringify(archive), { status: 200 })
return new Response('{}', { status: 404 })
})
vi.stubGlobal('fetch', fetcher)
})
@@ -158,7 +147,7 @@ afterEach(() => {
})
describe('StorageBackupSummary', () => {
it('renders directory, recent outcomes, archive usage, disk and the alert table', async () => {
it('renders directory, recent outcomes, backup occupancy, disk and the alert table', async () => {
act(() => root.render(<StorageBackupSummary />))
await flush()
const text = container.textContent || ''
@@ -166,9 +155,10 @@ describe('StorageBackupSummary', () => {
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('40 GB')
expect(text).toContain('配额 50 GB')
expect(text).not.toContain('归档占用')
expect(text).toContain('磁盘剩余')
expect(text).toContain('1.2 TB')
expect(text).toContain('上次上报')
@@ -180,12 +170,12 @@ describe('StorageBackupSummary', () => {
expect(text).not.toContain('示例')
})
it('asks for both read-only endpoints and refreshes once per 60 seconds while visible', async () => {
it('asks for the read-only inventory endpoint 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)
expect(paths().filter((path) => path.endsWith('/library/storage'))).toHaveLength(0)
await act(async () => {
await vi.advanceTimersByTimeAsync(60_000)
@@ -215,18 +205,14 @@ describe('StorageBackupSummary', () => {
host_root: '',
batches: [],
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
usage: { ...wired.usage, measured: false, complete: false, actual_bytes: null, error: '' },
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,
}
)
return new Response('{}', { status: 404 })
})
act(() => root.render(<StorageBackupSummary />))
await flush()
@@ -264,7 +250,7 @@ describe('StorageBackupSummary', () => {
{ status: 200 }
)
}
return new Response(JSON.stringify(archive), { status: 200 })
return new Response('{}', { status: 404 })
})
act(() => root.render(<StorageBackupSummary />))
await flush()
+13 -26
View File
@@ -1,12 +1,10 @@
// 「系统设置 → 存储与备份」只读摘要页:目录、最近成功/失败、归档占用、磁盘剩余、
// 四条容量告警和批次列表。数据只来自宿主每 5 分钟上报的快照与归档库接口,
// 本页没有任何写操作;读不到的量显示"主机未上报"或"—",不用 0 占位。
// 「系统设置 → 存储与备份」只读摘要页:目录、最近成功/失败、备份占用、磁盘剩余、
// 四条容量告警和批次列表。数据只来自宿主采集器上报的快照,本页没有任何写操作;
// 读不到的量显示"主机未上报"或"—",不用 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,
@@ -65,8 +63,6 @@ const hostStateLabel = (state: HostState): string => {
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)
@@ -77,24 +73,15 @@ export function StorageBackupSummary() {
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 : '读取备份元数据失败')
try {
setInventory(await fetchBackupInventory())
setErrors([])
} catch (error) {
setErrors([error instanceof Error ? error.message : '读取备份元数据失败'])
} finally {
setLoading(false)
inFlight.current = false
}
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(() => {
@@ -110,8 +97,8 @@ export function StorageBackupSummary() {
}, [load])
const state = hostState(inventory)
const alerts = storageAlerts(inventory, archive, archiveFailed)
const cards = summaryCards(inventory, archive, archiveFailed)
const alerts = storageAlerts(inventory)
const cards = summaryCards(inventory)
const batches = inventory?.batches ?? []
const shown = batches.slice(0, visible)
+55
View File
@@ -43,6 +43,19 @@ const payload = {
available_bytes: 48318382080,
used_bytes: 206158430208,
},
backup_root: '/srv/kb-backups',
usage: {
root: '/srv/kb-backups',
measured: true,
complete: true,
actual_bytes: 24318382080,
apparent_bytes: 23000000000,
file_count: 900,
dir_count: 30,
error: '',
},
quota_bytes: 53687091200,
quota_error: '',
batches: [
{
stamp: '20261118T193001Z',
@@ -108,6 +121,48 @@ describe('fetchBackupInventory', () => {
'/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir'
)
expect(inventory.batches[0].databases[0].actual_bytes).toBe(720896)
expect(inventory.backup_root).toBe('/srv/kb-backups')
expect(inventory.usage.measured).toBe(true)
expect(inventory.usage.actual_bytes).toBe(24318382080)
expect(inventory.quota_bytes).toBe(53687091200)
expect(inventory.quota_error).toBe('')
})
it('旧采集器缺 usage/quota 时显式未上报,不用批次和冒充占用', async () => {
const legacy = JSON.parse(JSON.stringify(payload))
delete legacy.data.backup_root
delete legacy.data.usage
delete legacy.data.quota_bytes
vi.stubGlobal(
'fetch',
vi.fn(() => Promise.resolve({ ok: true, json: () => Promise.resolve(legacy) }))
)
const inventory = await fetchBackupInventory()
expect(inventory.usage.measured).toBe(false)
expect(inventory.usage.actual_bytes).toBeNull()
expect(inventory.usage.error).toContain('未上报')
expect(inventory.quota_bytes).toBeNull()
expect(inventory.quota_error).toContain('未上报')
expect(inventory.totals.actual_bytes).toBe(1500000000)
})
it('不完整占用即使带部分字节也不展示', async () => {
const partial = JSON.parse(JSON.stringify(payload))
partial.data.usage = {
...partial.data.usage,
measured: true,
complete: false,
actual_bytes: 123,
error: '备份根占用未知:遍历失败',
}
vi.stubGlobal(
'fetch',
vi.fn(() => Promise.resolve({ ok: true, json: () => Promise.resolve(partial) }))
)
const inventory = await fetchBackupInventory()
expect(inventory.usage.measured).toBe(false)
expect(inventory.usage.actual_bytes).toBeNull()
expect(inventory.usage.error).toContain('遍历失败')
})
it('响应缺 wired 时整块报错,不默认成未接线', async () => {
+38
View File
@@ -39,6 +39,18 @@ export interface BackupInventoryCapacity {
error?: string
}
// 备份根累计占用:配额约束的对象。measured=false 时字节全为 null,页面不得用 0 冒充。
export interface BackupInventoryUsage {
root: string
measured: boolean
complete: boolean
actual_bytes: number | null
apparent_bytes: number | null
file_count: number | null
dir_count: number | null
error: string
}
export interface BackupInventoryDatabase {
name: string
dir_name: string
@@ -84,12 +96,16 @@ export interface BackupInventory {
metadata: BackupInventoryMetadata
root: string
host_root: string
backup_root: string
source: string
observed_at: string
error?: string
measurement: string
mount: BackupInventoryMount
capacity: BackupInventoryCapacity
usage: BackupInventoryUsage
quota_bytes: number | null
quota_error: string
batches: BackupInventoryBatch[]
totals: {
batch_count: number
@@ -115,6 +131,22 @@ const asNumberOrNull = (value: unknown): number | null =>
const asBool = (value: unknown): boolean => value === true
const asList = (value: unknown): unknown[] => (Array.isArray(value) ? value : [])
const usageProjection = (value: unknown): BackupInventoryUsage => {
const entry = record(value) ? value : {}
const complete = asBool(entry.complete)
const measured = asBool(entry.measured) && complete && asNumberOrNull(entry.actual_bytes) !== null
return {
root: asString(entry.root),
measured,
complete,
actual_bytes: measured ? asNumberOrNull(entry.actual_bytes) : null,
apparent_bytes: measured ? asNumberOrNull(entry.apparent_bytes) : null,
file_count: measured ? asNumberOrNull(entry.file_count) : null,
dir_count: measured ? asNumberOrNull(entry.dir_count) : null,
error: asString(entry.error) || (measured ? '' : '采集器未上报备份根占用(需要升级采集器)'),
}
}
const manifestState = (value: unknown): BackupManifestState =>
value === 'ok' || value === 'missing' || value === 'invalid' ? value : 'invalid'
@@ -186,10 +218,16 @@ function inventoryProjection(value: unknown): BackupInventory {
},
root: asString(value.root),
host_root: asString(value.host_root),
backup_root: asString(value.backup_root),
source: asString(value.source),
observed_at: asString(value.observed_at),
error: asString(value.error),
measurement: asString(value.measurement),
usage: usageProjection(value.usage),
quota_bytes: asNumberOrNull(value.quota_bytes),
quota_error:
asString(value.quota_error) ||
(asNumberOrNull(value.quota_bytes) === null ? '采集器未上报备份配额(需要升级采集器)' : ''),
mount: {
container_root: asString(mount.container_root),
mount_verified: asBool(mount.mount_verified),
+54 -44
View File
@@ -1,7 +1,6 @@
import { describe, expect, it } from 'vitest'
import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
import type { LibraryStorage } from './librarySnapshots'
import {
DISK_CRITICAL_AVAILABLE_PERCENT,
batchOutcome,
@@ -70,6 +69,7 @@ export const inventory = (overrides: Partial<BackupInventory> = {}): BackupInven
},
root: '/srv/kb-backups/rds-logical',
host_root: '/srv/kb-backups/rds-logical',
backup_root: '/srv/kb-backups',
source: 'host',
observed_at: '2026-11-24T10:18:00Z',
measurement: 'host-reported',
@@ -90,6 +90,18 @@ export const inventory = (overrides: Partial<BackupInventory> = {}): BackupInven
available_bytes: 1.2 * TB,
used_bytes: 0.8 * TB,
},
usage: {
root: '/srv/kb-backups',
measured: true,
complete: true,
actual_bytes: 22.65 * GIB,
apparent_bytes: 20 * GIB,
file_count: 1000,
dir_count: 40,
error: '',
},
quota_bytes: 50 * GIB,
quota_error: '',
batches: [batch()],
totals: {
batch_count: 1,
@@ -106,30 +118,6 @@ export const inventory = (overrides: Partial<BackupInventory> = {}): BackupInven
...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,
@@ -151,6 +139,19 @@ const unreported = (): BackupInventory =>
},
root: '',
host_root: '',
backup_root: '',
usage: {
root: '',
measured: false,
complete: false,
actual_bytes: null,
apparent_bytes: null,
file_count: null,
dir_count: null,
error: '采集器未上报备份根占用(需要升级采集器)',
},
quota_bytes: null,
quota_error: '采集器未上报备份配额(需要升级采集器)',
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
batches: [],
totals: {
@@ -230,48 +231,57 @@ describe('recentOutcome', () => {
})
describe('summaryCards', () => {
it('shows real values when the host reported and the archive is available', () => {
const cards = summaryCards(inventory(), archive(), false)
it('shows real values from the host snapshot for backup occupancy and quota', () => {
const cards = summaryCards(inventory())
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.backup).toBe(formatSize(22.65 * GIB))
expect(byKey.disk).toBe('1.2 TB')
expect(cards.find((card) => card.key === 'archive')?.note).toBe('配额 100 GB')
expect(cards.find((card) => card.key === 'backup')?.note).toBe('配额 50 GB')
expect(cards.some((card) => card.label === '归档占用')).toBe(false)
})
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 cards = summaryCards(unreported())
for (const key of ['root', 'success', 'failure', 'backup', '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)
const cards = summaryCards(
inventory({
metadata: { ...inventory().metadata, complete: false },
usage: {
...inventory().usage,
measured: false,
complete: false,
actual_bytes: null,
error: '备份根占用未知:遍历失败',
},
})
)
expect(cards.find((card) => card.key === 'root')?.value).toBe('/srv/kb-backups/rds-logical')
expect(cards.find((card) => card.key === 'backup')?.value).toBe('—')
expect(cards.find((card) => card.key === 'backup')?.note).toBe('备份根占用未知:遍历失败')
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)
it('judges disk and backup quota independently and counts pending rows', () => {
const healthy = storageAlerts(inventory())
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
inventory({ usage: { ...inventory().usage, actual_bytes: 45 * GIB }, quota_bytes: 50 * GIB })
)
expect(nearQuota.find((row) => row.key === 'quota_low')?.tone).toBe('warn')
expect(nearQuota.find((row) => row.key === 'both_low')?.conclusion).toBe('正常')
@@ -288,9 +298,9 @@ describe('storageAlerts', () => {
available_bytes: 0.01 * TB,
used_bytes: 1.99 * TB,
},
}),
archive({ capacity: { ...archive().capacity, current_bytes: 100 * GIB, budget_bytes: 100 * GIB } }),
false
usage: { ...inventory().usage, actual_bytes: 100 * GIB },
quota_bytes: 100 * GIB,
})
)
expect(tight.find((row) => row.key === 'disk_low')?.tone).toBe('bad')
expect(tight.find((row) => row.key === 'both_low')?.conclusion).toBe('需处理')
@@ -300,7 +310,7 @@ describe('storageAlerts', () => {
})
it('never claims a conclusion without numbers', () => {
const alerts = storageAlerts(unreported(), null, true)
const alerts = storageAlerts(unreported())
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)
+43 -50
View File
@@ -1,9 +1,7 @@
// 「存储与备份」只读摘要的纯逻辑:数据源只有两个只读接口——
// /api/v1/backup-schedule/inventory (宿主每 5 分钟上报的元数据快照)
// /api/v1/library/storage (归档库自身的占用与配额)
// 「存储与备份」只读摘要的纯逻辑:唯一数据源是宿主采集器快照
// /api/v1/backup-schedule/inventory (批次、备份根占用、配额与文件系统容量)
// 页面不提供任何写操作。读不到的量一律留空("主机未上报" / "—"),不用 0 冒充。
import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
import type { LibraryStorage } from './librarySnapshots'
// 阈值(与 docs/STORAGE_BACKUP_READONLY_API.md 的「页面口径」一致):
// 磁盘:可用空间 < 5% 红,< 10% 黄
@@ -159,11 +157,7 @@ export interface SummaryCard {
const lastReportNote = (inventory: BackupInventory): string =>
`上次上报 ${formatWhen(inventory.metadata.collected_at) || UNKNOWN}`
export function summaryCards(
inventory: BackupInventory | null,
archive: LibraryStorage | null,
archiveFailed: boolean
): SummaryCard[] {
export function summaryCards(inventory: BackupInventory | null): SummaryCard[] {
const state = hostState(inventory)
const facts = state === 'ready' || state === 'incomplete'
const sizes = state === 'ready'
@@ -181,7 +175,20 @@ export function summaryCards(
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
const usage = inventory?.usage
const usageKnown =
facts && Boolean(usage?.measured) && usage?.actual_bytes !== null && usage?.actual_bytes !== undefined
const quotaBytes = inventory?.quota_bytes
const quotaKnown = usageKnown && (quotaBytes ?? 0) > 0
const backupNote = !pending
? UNKNOWN
: !facts
? hostNote
: usageKnown
? quotaKnown
? `配额 ${formatSize(quotaBytes)}`
: inventory!.quota_error || '配额未上报'
: usage?.error || '本次上报不完整'
return [
{
@@ -207,17 +214,11 @@ export function summaryCards(
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: 'backup',
label: '备份占用',
value: usageKnown ? formatSize(usage!.actual_bytes) : facts ? UNKNOWN : hostValue,
note: backupNote,
unknown: !usageKnown,
},
{
key: 'disk',
@@ -244,23 +245,21 @@ export interface SummaryAlert {
export interface StorageFacts {
diskAvailableBytes: number | null
diskTotalBytes: number | null
archiveUsedBytes: number | null
archiveBudgetBytes: number | null
backupUsedBytes: number | null
backupQuotaBytes: number | null
}
export function storageFacts(
inventory: BackupInventory | null,
archive: LibraryStorage | null,
archiveFailed: boolean
): StorageFacts {
export function storageFacts(inventory: BackupInventory | null): 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
const usage = inventory?.usage
const used = usage?.measured && usage.actual_bytes !== null ? usage.actual_bytes : null
const quota = inventory?.quota_bytes ?? 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,
backupUsedBytes: used,
backupQuotaBytes: quota !== null && quota > 0 ? quota : null,
}
}
@@ -270,13 +269,9 @@ const tonePercent = (value: number, warn: number, critical: number): Tone =>
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[] {
export function storageAlerts(inventory: BackupInventory | null): SummaryAlert[] {
const state = hostState(inventory)
const facts = storageFacts(inventory, archive, archiveFailed)
const facts = storageFacts(inventory)
const diskKnown = facts.diskAvailableBytes !== null && (facts.diskTotalBytes ?? 0) > 0
const availablePercent = diskKnown ? Math.round((facts.diskAvailableBytes! / facts.diskTotalBytes!) * 100) : 0
const diskTone: Tone = diskKnown
@@ -287,16 +282,16 @@ export function storageAlerts(
: 'ok'
: 'none'
const quotaKnown = facts.archiveUsedBytes !== null && (facts.archiveBudgetBytes ?? 0) > 0
const usedPercent = quotaKnown ? Math.round((facts.archiveUsedBytes! / facts.archiveBudgetBytes!) * 100) : 0
const quotaKnown = facts.backupUsedBytes !== null && (facts.backupQuotaBytes ?? 0) > 0
const usedPercent = quotaKnown ? Math.round((facts.backupUsedBytes! / facts.backupQuotaBytes!) * 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!
diskKnown && facts.backupQuotaBytes !== null
? facts.backupQuotaBytes > facts.diskAvailableBytes!
? 'bad'
: 'ok'
: 'none'
@@ -315,12 +310,10 @@ export function storageAlerts(
key: 'quota_low',
label: '配额不足',
value: quotaKnown
? `${formatSize(facts.archiveUsedBytes)} / ${formatSize(facts.archiveBudgetBytes)}(${usedPercent}%)`
: archiveFailed
? UNKNOWN
: archive?.available
? '配额未设置'
: UNKNOWN,
? `${formatSize(facts.backupUsedBytes)} / ${formatSize(facts.backupQuotaBytes)}(${usedPercent}%)`
: inventory?.quota_error
? '配额未上报'
: UNKNOWN,
tone: quotaTone,
conclusion: quotaKnown ? conclusionText(quotaTone) : UNKNOWN_STATE,
},
@@ -335,11 +328,11 @@ export function storageAlerts(
key: 'quota_over_physical',
label: '配额超出物理空闲',
value:
diskKnown && facts.archiveBudgetBytes !== null
? `配额 ${formatSize(facts.archiveBudgetBytes)} · 可用 ${formatSize(facts.diskAvailableBytes)}`
diskKnown && facts.backupQuotaBytes !== null
? `配额 ${formatSize(facts.backupQuotaBytes)} · 可用 ${formatSize(facts.diskAvailableBytes)}`
: UNKNOWN,
tone: overPhysical,
conclusion: diskKnown && facts.archiveBudgetBytes !== null ? conclusionText(overPhysical) : UNKNOWN_STATE,
conclusion: diskKnown && facts.backupQuotaBytes !== null ? conclusionText(overPhysical) : UNKNOWN_STATE,
},
]
}