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 => ({ 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 => ({ 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 => ({ 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) }) })