diff --git a/compose.yaml b/compose.yaml index ef5a714..b5007cf 100644 --- a/compose.yaml +++ b/compose.yaml @@ -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}" diff --git a/web/src/BackupScheduleSection.test.tsx b/web/src/BackupScheduleSection.test.tsx deleted file mode 100644 index 765c7d9..0000000 --- a/web/src/BackupScheduleSection.test.tsx +++ /dev/null @@ -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 => ({ - 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 => { - 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 = {}, - extra: Record = {}, - disk: StorageDiskObservation | null = null -) => { - const schedule = { ...base, ...overrides } - return renderToStaticMarkup( - - ) -} - -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('>立即备份') - 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('
备份脚本
缺失
') - 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) - }) -}) diff --git a/web/src/BackupScheduleSection.tsx b/web/src/BackupScheduleSection.tsx deleted file mode 100644 index acc10bf..0000000 --- a/web/src/BackupScheduleSection.tsx +++ /dev/null @@ -1,1427 +0,0 @@ -import { useCallback, useEffect, useRef, useState } from 'react' - -import { useOptionalAuth } from './auth' -import { - applyBackupSchedule, - fetchBackupSchedule, - fetchBackupScheduleHost, - runBackupNow, - 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 | null | undefined): string => { - if (bytes === null || bytes === undefined || !Number.isFinite(bytes) || bytes < 0) return '—' - if (bytes === 0) return '0 B' - if (bytes < 1024) return `${bytes} B` - const mib = bytes / (1024 * 1024) - if (mib >= 1024) return `${(mib / 1024).toFixed(2)} GiB` - // 小文件不能舍成 0.0 MiB;不足 0.05 MiB 用 KiB,其余保留一位 MiB。 - if (mib < 0.05) return `${(bytes / 1024).toFixed(1)} KiB` - return `${mib.toFixed(1)} MiB` -} - -export const formatBackupMoment = (value: string): string => { - if (!value) return '—' - const parsed = new Date(value) - return Number.isNaN(parsed.getTime()) ? value : parsed.toLocaleString('zh-CN', { hour12: false }) -} - -// 清单里的 created_at 就是目录戳(如 20261009T060736Z),同值时不再重复显示一遍。 -export const runMoment = (schedule: { last_run_stamp: string; last_run_created_at: string }): string => { - const createdAt = schedule.last_run_created_at.trim() - if (!createdAt || createdAt === schedule.last_run_stamp.trim()) return '' - return formatBackupMoment(createdAt) -} - -export const backupTimeValid = (value: string): boolean => /^([01][0-9]|2[0-3]):[0-5][0-9]$/.test(value) -export const backupDaysValid = (value: number): boolean => Number.isInteger(value) && value >= 1 && value <= 365 -export const backupMonthsValid = (value: number): boolean => Number.isInteger(value) && value >= 0 && value <= 24 - -const GIB = 1024 * 1024 * 1024 - -// 整盘读数是"主机 + 卷 + 备份目录"三件事实的组合,当前后端没有对应接口: -// 页面只保留原型位置并写明原因,不在产品里填任何示例容量。测试夹具通过这个 -// 只读结构验证色带与告警的完整分支,生产容器恒传 null。 -export interface StorageDiskObservation { - total_bytes: number - free_bytes: number - // 与策略目录同一卷上的备份占用 - backup_bytes: number - // 其他磁盘上历史备份的占用(合计口径也要吃总配额) - other_volume_backup_bytes: number - quota_bytes: number - reserve_bytes: number - // 下次任务预计新增;未知时必须为空,不能拿上一次体积冒充 - estimate_bytes: number | null - sampled_at: string -} - -export type StorageAlertCode = 'disk_low' | 'quota_low' | 'both_low' | 'quota_over_physical' - -export interface StorageAlert { - code: StorageAlertCode - label: string - active: boolean - known: boolean - detail: string -} - -export interface StorageUsage { - total: number - free: number - system_other: number - backup: number - quota_free: number - beyond_quota_free: number - budget: number - used_total: number - allowance: number - writable: number -} - -export function storageUsage(observation: StorageDiskObservation): StorageUsage { - const total = Math.max(0, observation.total_bytes) - const free = Math.max(0, observation.free_bytes) - const backup = Math.max(0, observation.backup_bytes) - const otherBackups = Math.max(0, observation.other_volume_backup_bytes) - const reserve = Math.max(0, observation.reserve_bytes) - const budget = Math.max(0, observation.quota_bytes) - const usedTotal = backup + otherBackups - const allowance = Math.max(0, budget - usedTotal) - const writable = Math.max(0, free - reserve) - const systemOther = Math.max(0, total - free - backup) - const onOtherVolumes = Math.max(0, usedTotal - backup) - const localQuota = Math.max(0, budget - onOtherVolumes) - const inQuota = Math.min(backup, localQuota) - // 配额允许但盘上画不下的部分不进入色带,避免把配额当成物理空间。 - const quotaFree = Math.min(free, allowance) - return { - total, - free, - system_other: systemOther, - backup: inQuota, - quota_free: quotaFree, - beyond_quota_free: Math.max(0, free - quotaFree), - budget, - used_total: usedTotal, - allowance, - writable, - } -} - -// 四种告警与原型一致;读数缺失时每条都只能是"无法判定",不能默认正常。 -export function storageAlerts(observation: StorageDiskObservation | null): StorageAlert[] { - if (!observation) { - return [ - { code: 'disk_low', label: '磁盘不足', active: false, known: false, detail: '尚未读取宿主快照' }, - { 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: '尚未读取宿主快照', - }, - ] - } - const usage = storageUsage(observation) - const estimate = observation.estimate_bytes - if (estimate === null) { - return [ - { - code: 'disk_low', - label: '磁盘不足', - active: false, - known: false, - detail: '缺下次新增体积,不能判定是否装得下', - }, - { - code: 'quota_low', - label: '配额不足', - active: false, - known: false, - detail: '缺下次新增体积,不能判定配额是否够', - }, - { code: 'both_low', label: '磁盘与配额同时不足', active: false, known: false, detail: '缺下次新增体积' }, - { - code: 'quota_over_physical', - label: '配额超出物理空闲', - active: usage.allowance > usage.free, - known: true, - detail: `配额余量 ${formatGib(usage.allowance)} GiB,盘上实际空闲 ${formatGib(usage.free)} GiB`, - }, - ] - } - const diskLow = usage.writable < estimate - const quotaLow = usage.allowance < estimate - return [ - { - code: 'disk_low', - label: '磁盘不足', - active: diskLow, - known: true, - detail: diskLow - ? `扣除预留后可写 ${formatGib(usage.writable)} GiB,本次预计新增 ${formatGib(estimate)} GiB,差 ${formatGib(estimate - usage.writable)} GiB` - : `扣除预留后可写 ${formatGib(usage.writable)} GiB,够本次 ${formatGib(estimate)} GiB`, - }, - { - code: 'quota_low', - label: '配额不足', - active: quotaLow, - known: true, - detail: quotaLow - ? `配额余量 ${formatGib(usage.allowance)} GiB,本次预计新增 ${formatGib(estimate)} GiB,差 ${formatGib(estimate - usage.allowance)} GiB` - : `配额余量 ${formatGib(usage.allowance)} GiB,够本次 ${formatGib(estimate)} GiB`, - }, - { - code: 'both_low', - label: '磁盘与配额同时不足', - active: diskLow && quotaLow, - known: true, - detail: diskLow && quotaLow ? '两项都不够,本次备份会失败' : '未同时触发', - }, - { - code: 'quota_over_physical', - label: '配额超出物理空闲', - active: usage.allowance > usage.free, - known: true, - detail: - usage.allowance > usage.free - ? `配额还允许 ${formatGib(usage.allowance)} GiB,但盘上只剩 ${formatGib(usage.free)} GiB;超出部分画不进磁盘` - : '配额余量未超过物理空闲', - }, - ] -} - -const formatGib = (bytes: number): string => String(Number((bytes / GIB).toFixed(2))) -const percent = (part: number, total: number): string => (total > 0 ? `${(100 * part) / total}%` : '0%') - -export const storageAlertSummary = (alerts: StorageAlert[]): string => { - const unknown = alerts.filter((item) => !item.known) - const quotaOnly = ['quota_low', 'both_low', 'quota_over_physical'] - if (unknown.length === alerts.length) return '无法判定(缺读数与配额字段)' - if (unknown.length && unknown.every((item) => item.code === 'disk_low' || quotaOnly.includes(item.code))) { - const disk = alerts.find((item) => item.code === 'disk_low') - return disk?.known ? '磁盘项正常 · 配额字段未接线' : '磁盘项无法判定 · 配额字段未接线' - } - 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 -} - -// 完整新鲜的宿主快照 + 实测容量 + 采集器给出的文件系统,才画整盘图。 -// 备份实际占盘取快照的总实际分配,不是 MANIFEST 表观字节,也不接受部分字节。 -export function inventoryUsage(inventory: BackupInventory | null): InventoryUsage | null { - if ( - !inventory || - !inventory.wired || - !inventory.metadata.present || - !inventory.metadata.valid || - !inventory.metadata.fresh || - !inventory.metadata.complete || - !inventory.mount.mount_verified || - !inventory.capacity.measured || - inventory.capacity.total_bytes <= 0 || - inventory.totals.actual_bytes === null || - inventory.totals.actual_bytes === undefined - ) { - return null - } - if (inventory.batches.some((batch) => !batch.sizes_complete || batch.actual_bytes === null)) { - 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 ?? null - const diskKnown = - capacityKnown && latest !== undefined && latest.sizes_complete && latestBytes !== null && latestBytes !== undefined - const diskActive = diskKnown && latestBytes! > usage!.free - const diskDetail = !inventory - ? '尚未读取宿主元数据快照' - : !inventory.wired - ? '元数据快照未接线' - : !inventory.metadata.present - ? '元数据快照缺失' - : !inventory.metadata.valid - ? inventory.metadata.error || '元数据快照无效' - : !inventory.metadata.fresh - ? '元数据快照已陈旧' - : !inventory.metadata.complete - ? '元数据快照不完整:占盘与容量未知' - : !inventory.mount.mount_verified - ? '宿主采集器未给出可用文件系统' - : !inventory.capacity.measured - ? inventory.capacity.error || '未读到文件系统容量' - : latestBytes === null || latestBytes === undefined - ? '容量已读到,但缺最近批次实际占盘;不能判定是否装得下' - : `剩余可用 ${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 { - 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' ? '清单缺失' : '清单损坏' - -export type InventorySnapshotState = - 'loading' | 'unconfigured' | 'missing' | 'stale' | 'invalid' | 'incomplete' | 'ready' - -// 快照状态必须由接口字段判定,不能因为 fresh=false 就一律说“未接线”: -// 过期、缺失、无效、未配置是四种不同事实,目录/历史/容量都不能互相代替。 -export function inventorySnapshotState(inventory: BackupInventory | null): InventorySnapshotState { - if (!inventory) return 'loading' - if (!inventory.wired || !inventory.metadata.configured) return 'unconfigured' - if (!inventory.metadata.present) return 'missing' - const age = inventory.metadata.age_seconds - const maxAge = inventory.metadata.max_age_seconds - const staleByAge = maxAge > 0 && age > maxAge - if (!inventory.metadata.fresh && (staleByAge || inventory.metadata.error.includes('陈旧'))) return 'stale' - if (!inventory.metadata.valid) return 'invalid' - if (!inventory.metadata.fresh) return 'stale' - if (!inventory.metadata.complete) return 'incomplete' - return 'ready' -} - -const inventoryStateLabel = (state: InventorySnapshotState): string => { - switch (state) { - case 'unconfigured': - return '元数据快照未接线' - case 'missing': - return '元数据快照缺失' - case 'stale': - return '元数据快照已过期' - case 'invalid': - return '元数据快照无效' - case 'incomplete': - return '元数据快照不完整' - case 'ready': - return '元数据快照有效' - default: - return '元数据读取中' - } -} - -// 备份执行主机上的整库逻辑备份(全部业务库一次 pg_dump)。 -// 页面只展示接口真实给出的读数;目录、配额、预留、子库路径、历史批次与恢复 -// 验证在后端契约里还没有字段,保留原型位置并写明"未接线"。 -export interface BackupScheduleViewProps { - schedule: BackupSchedule - isAdmin: boolean - loading: boolean - probing: boolean - busy: 'save' | 'apply' | 'run' | null - error: string | null - message: string - enabledDraft: boolean - timeDraft: string - daysDraft: string - monthsDraft: string - onEnabledChange: (next: boolean) => void - onTimeChange: (next: string) => void - onDaysChange: (next: string) => void - onMonthsChange: (next: string) => void - onSave: () => void - onApply: () => void - onRunNow: () => void - onReload: () => void - // 仅测试夹具提供;生产容器不传,磁盘区改用真实盘点的容量。 - disk?: StorageDiskObservation | null - inventory?: BackupInventory | null - inventoryLoading?: boolean - inventoryError?: string | null - onReloadInventory?: () => void -} - -export function BackupScheduleView(props: BackupScheduleViewProps) { - const { - schedule, - isAdmin, - loading, - probing, - busy, - error, - message, - enabledDraft, - timeDraft, - daysDraft, - monthsDraft, - onEnabledChange, - onTimeChange, - onDaysChange, - onMonthsChange, - onSave, - onApply, - onRunNow, - onReload, - disk = null, - inventory = null, - inventoryLoading = false, - inventoryError = null, - onReloadInventory, - } = props - const days = Number(daysDraft) - const months = Number(monthsDraft) - const valid = backupTimeValid(timeDraft) && backupDaysValid(days) && backupMonthsValid(months) - const dirty = - enabledDraft !== schedule.enabled || - timeDraft !== schedule.schedule_time || - days !== schedule.retention_days || - months !== schedule.retention_months - const hostLine = !schedule.host_configured - ? '平台未挂载主机凭据(远端状态未知)' - : schedule.host_reachable - ? `${schedule.host_target} · 已连接` - : schedule.host_checked_at || schedule.host_error - ? `${schedule.host_target} · 连接失败` - : `${schedule.host_target} · 尚未探测` - // 未探测与探测失败必须分开:只读计划先返回时 reachable=false 不代表连不上。 - const hostProbePending = - schedule.host_configured && !schedule.host_reachable && !schedule.host_checked_at && !schedule.host_error - const syncLine = !schedule.host_configured - ? '无法比对(未读取主机计划)' - : hostProbePending - ? '尚未比对' - : !schedule.host_reachable - ? '无法比对(主机不可达)' - : schedule.in_sync - ? '已一致' - : '待下发' - // 只有真的连上并读回主机状态时,才能说脚本在不在;连不上是"未知"。 - const scriptLine = !schedule.host_reachable - ? '未知(未连上主机,未执行主机侧脚本)' - : schedule.host_script_present - ? '存在' - : '缺失' - const databaseCount = schedule.last_run_databases.length - const failedCount = schedule.last_run_failed_databases.length - const hasLastRun = Boolean(schedule.last_run_stamp) - const runFailed = failedCount > 0 || Boolean(schedule.last_run_error) - const usage = disk ? storageUsage(disk) : null - const alerts = disk ? storageAlerts(disk) : inventoryAlerts(inventory) - const snapshotState = inventorySnapshotState(inventory) - const snapshotLabel = inventory - ? inventoryStateLabel(snapshotState) - : inventoryError - ? '元数据快照读取失败' - : inventoryLoading - ? '元数据读取中' - : '元数据快照未读取' - const snapshotPathsTrusted = snapshotState === 'ready' || snapshotState === 'incomplete' - const sshFallbackReason = snapshotPathsTrusted ? '元数据快照无批次' : snapshotLabel - const latestBatch: BackupInventoryBatch | null = snapshotPathsTrusted ? (inventory?.batches[0] ?? null) : null - const inventoryFigure = inventoryUsage(inventory) - const inventoryReady = snapshotPathsTrusted - const readyInventory = snapshotPathsTrusted ? 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 ( -
-
-
-

存储与备份

-

- 本页管的是数据库整库逻辑备份(pg_dump 目录格式,在备份执行主机本地写盘); - 下方「归档占用」是版本快照的归档文件,两者不是同一种数据,体积不能相加。 -

-
- -
- {error ? ( -

- {error} -

- ) : null} - -
-
-

范围与读写方向

- - {schedule.host_configured ? '平台已接主机凭据' : '平台未接主机凭据'} - - - {inventoryLoading && !inventory - ? '元数据读取中' - : snapshotState === 'ready' - ? '元数据快照有效' - : snapshotState === 'incomplete' - ? '元数据快照不完整' - : snapshotLabel} - -
-
-
读取源
-
- {inventory?.source - ? `${inventory.source}${snapshotState === 'stale' ? '(快照已过期)' : ''}` - : `备份执行主机 ${schedule.host_target || '(未配置)'} 本机直连 RDS`} - {scopeDatabaseCount ? ` · 最近批次含 ${scopeDatabaseCount} 个数据库` : ' · 数据库清单未读到'} -
-
采集时间
-
- {inventory?.metadata.present - ? `${formatBackupMoment(inventory.metadata.collected_at)}(快照) · 年龄 ${inventory.metadata.age_seconds} 秒 / 上限 ${inventory.metadata.max_age_seconds} 秒 · ${ - snapshotState === 'stale' ? '已过期' : inventory.metadata.fresh ? '新鲜' : '不可用' - }` - : `—(${snapshotLabel})`} -
-
读回时间
-
{inventory?.observed_at ? `${formatBackupMoment(inventory.observed_at)}(API 读回)` : '—'}
-
写入方向
-
- {snapshotPathsTrusted && inventory?.host_root - ? inventory.host_root - : snapshotState === 'stale' - ? `—(${snapshotLabel}:不展示旧目录路径)` - : `—(${snapshotLabel})`} - - {snapshotPathsTrusted - ? '宿主采集器快照(只读);平台没有写路径' - : `${snapshotLabel}:目录不可验证,不按设置推定`} - -
-
执行范围
-
- {scopeDatabaseCount - ? `整批 · ${scopeDatabaseCount} 个数据库(${scopeDatabases.join('、')})` - : '整批 · 数据库清单未读到,无法列出库名'} -
-
拨号地址
-
{schedule.host_endpoint || '—'}
-
-
- -

- POST /api/v1/backup-schedule/run 没有单库参数,一次就是该主机全部业务库的整批 - pg_dump。用单库按钮触发会连整批一起跑,因此本页不开放单库动作;单库恢复请复制「备份记录」里该库的 - 完整子目录(来自宿主元数据快照),不要自己拼路径。 -

-
-
- -
-
-

立即备份

- - {hasScopeBatch ? (scopeFailed > 0 ? '最近一批有失败' : '最近一批成功') : '尚无批次读数'} - -
-

- {latestBatch - ? `最近一批 ${latestBatch.stamp} · ${formatBackupMoment(latestBatch.created_at)} · ${scopeDatabaseCount} 个数据库 · 表观 ${formatBackupBytes(latestBatch.apparent_bytes)} · ${ - latestBatch.actual_bytes === null - ? '实际占盘未知(采集不完整)' - : `实际占盘 ${formatBackupBytes(latestBatch.actual_bytes)}` - } · ${latestBatch.duration_seconds} 秒` - : hasLastRun - ? `SSH 读回最近一次 ${schedule.last_run_stamp} · ${databaseCount} 个数据库 · ${formatBackupBytes(schedule.last_run_total_bytes)}(${sshFallbackReason},以下仅 SSH 读回结果)` - : '还没有从主机读到任何批次。'} -

- {schedule.running ? ( -
-

- 正在备份({formatBackupMoment(schedule.running_started_at)} 开始,整批 {scopeDatabaseCount || '未知'}{' '} - 个数据库)。 没有真实百分比接口,这里只报在途状态,完成后自动刷新。 -

- -
- ) : null} - {schedule.run_last_error && !schedule.running ? ( -

上一次立即备份失败:{schedule.run_last_error}

- ) : null} - {isAdmin ? ( -
- - 触发的是该主机全部业务库的整批备份,不是 scope 快照,也不是单库。 -
- ) : ( -

立即备份仅管理员可触发;当前为只读。

- )} -
- -
item.known && item.active) ? 'storage-disk-low' : ''}`} - aria-labelledby="storage-disk-heading" - > -
-

整盘占用与告警

- - {usage ? '已读到主机读数' : inventoryFigure ? '宿主采集器实测' : '占盘未知'} - -
- {usage && disk ? ( - <> -
-
-
-
-
-
-
-
- - - 系统其他占用 {formatGib(usage.system_other)} GiB - - - - 备份已用 {formatGib(usage.backup)} GiB - - - - 配额内空闲 {formatGib(usage.quota_free)} GiB - - - - 配额外空闲 {formatGib(usage.beyond_quota_free)} GiB - -
-

- 备份已用 {formatGib(usage.used_total)} / {formatGib(usage.budget)} GiB( - {usage.budget > 0 ? `${((100 * usage.used_total) / usage.budget).toFixed(2)}%` : '—'})· 总配额占当前整盘{' '} - {usage.total > 0 ? `${((100 * usage.budget) / usage.total).toFixed(2)}%` : '—'} -

- - 读数采集于 {formatBackupMoment(disk.sampled_at)} · 本盘实际空闲 {formatGib(usage.free)} GiB,系统预留{' '} - {formatGib(disk.reserve_bytes)} GiB - {disk.other_volume_backup_bytes > 0 - ? ` · 其他磁盘的历史备份占用总配额 ${formatGib(disk.other_volume_backup_bytes)} GiB` - : ''} - - - ) : inventoryFigure && inventory ? ( - <> -
-
-
-
-
-
- - - 系统其他占用 {formatGib(inventoryFigure.system_other)} GiB - - - - 备份实际占盘 {formatGib(inventoryFigure.backup)} GiB - - - - 可用 {formatGib(inventoryFigure.free)} GiB - - - - 配额内/外 —(无配额字段) - -
-

- 备份实际占盘 {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 -

- - {inventory.mount.evidence} · 挂载点 {inventory.mount.mount_point || '—'} · 采集于{' '} - {formatBackupMoment(inventory.metadata.collected_at)} · 读回于 {formatBackupMoment(inventory.observed_at)} - -

- 备份文件系统必须由备份主机可写;API 只读挂载元数据快照,不向该盘写入。空间预测仅以上次整批实际占盘 - {latestBatch?.actual_bytes !== null && latestBatch?.actual_bytes !== undefined - ? ` ${formatBackupBytes(latestBatch.actual_bytes)}` - : '(未读到)'}{' '} - 作参考,不是接口预测,也不含策略预留。 -

- - ) : ( - <> -
- {inventoryLoading ? '正在读取宿主元数据快照…' : '占盘未知 · 不使用部分字节'} -
-
- {['系统其他占用', '备份实际占盘', '可用', '配额内/外'].map((label, index) => ( - - - {label} — - - ))} -
-

- 整盘总量 / 空闲 / 备份实际占盘: - {inventoryError || inventory?.metadata.error || inventory?.error || '未接线'} -

- - )} -

- 容量与实际占盘来自宿主单项元数据采集器(stat/du 元数据,不读数据库内容);API 不遍历备份目录。 - 快照陈旧、缺失或不完整时,容量图与任何可写预测都不使用部分字节。配额与策略预留仍无后端字段; - 容量可信时只对磁盘项判定,配额相关三项标注未接线。 -

-

{storageAlertSummary(alerts)}

-
    - {alerts.map((alert) => ( -
  • - {alert.label} - {alert.known ? (alert.active ? '触发' : '正常') : '无法判定'} - {alert.detail} -
  • - ))} -
-
- -
-
-

备份策略

- 北京时间 · 主机读回 -
-

- {!schedule.host_configured - ? '平台未挂载主机凭据:无法读取当前主机计划,远端 cron 是否仍在执行未知(历史下发不能代替实时状态)。' - : hostProbePending - ? '尚未探测当前主机计划:不能按设置或历史下发推定。' - : !schedule.host_reachable - ? '主机连不上:以下"主机生效"状态未知,不能按设置推定。' - : schedule.host_schedule_enabled - ? `主机生效:每天 ${schedule.host_schedule_time} · 保留 ${schedule.host_keep_days} 天 · 每月 ${schedule.host_keep_months} 份 · ${ - schedule.in_sync ? '与设置已一致' : '与设置不一致(待下发)' - }` - : '主机生效:定时备份已关闭(已有备份保留)'} - {schedule.host_next_run ? ` · 下次 ${schedule.host_next_run}` : ' · 下一次实际执行未由主机返回'} -

-

- 编辑草稿:{enabledDraft ? `每天 ${timeDraft || '—'} · 保留 ${daysDraft || '—'} 天` : '定时备份关闭'} · - 每月归档 {monthsDraft || '—'} 份{dirty ? ' · 有未保存修改,主机仍按生效计划执行' : ' · 与已保存设置一致'} -

- {isAdmin ? ( -
- -
- - - {snapshotPathsTrusted - ? '目录来自宿主元数据快照,只读展示;修改目录需部署变更,平台没有写接口。' - : snapshotState === 'stale' - ? '元数据快照已过期:目录不可验证,不沿用旧路径;等待宿主重新采集。' - : snapshotState === 'missing' - ? '元数据快照缺失:目录不可验证,需先在备份主机运行采集器。' - : snapshotState === 'invalid' - ? '元数据快照无效:目录不可验证,需检查快照内容。' - : snapshotState === 'loading' - ? inventoryError - ? '元数据快照读取失败:目录不可验证,请检查 API 到快照挂载的接线。' - : '尚未读取元数据快照:目录不可验证。' - : '元数据快照未接线:目录不可证明,不能按设置推定。'} - -
- -
- - - - - -
-

- 保存只提交后端契约里的四项:启用、每日时间、储存天数、每月归档份数。目录、总配额、磁盘预留没有对应字段, - 这里只占原型位置,不会被保存,也不会显示假的保存成功。 -

- {!valid ? ( -

定时时间需为 HH:MM(00:00~23:59),储存天数 1~365,每月归档 0~24。

- ) : null} -
- - - {message ? ( - - {message} - - ) : null} -
-

- 保存后从下次任务起使用新计划;历史文件保留在原路径。设置已保存但下发失败时,页面如实显示失败原因。 -

-
- ) : ( -

- 定时备份设置仅管理员可修改;当前设置: - {schedule.enabled ? `每天 ${schedule.schedule_time} · 保留 ${schedule.retention_days} 天` : '未启用'}。 -

- )} -
- -
-
-

备份记录

- - {readyInventory - ? `${readyInventory.totals.batch_count} 批 · 元数据快照 · 实际占盘 ${formatBackupBytes(readyInventory.totals.actual_bytes)}` - : `${snapshotLabel} · 不展示旧批次`} - - -
- {inventoryLoading && !inventory ?

正在读取宿主元数据快照…

: null} - {inventoryError ? ( -

- 快照请求失败:{inventoryError}。不能用 SSH 的“最近一次”代替历史;请检查 API 到快照挂载的接线。 -

- ) : null} - {inventory && snapshotState === 'unconfigured' ? ( -

- 元数据快照未接线:{inventory.metadata.error}。部署需在备份主机运行单次采集器并把输出目录只读挂进 API(见 - docs/STORAGE_BACKUP_READONLY_API.md);未读到批次不等于没有备份。 -

- ) : null} - {inventory && snapshotState === 'missing' ? ( -

- 元数据快照缺失:{inventory.metadata.error || inventory.error || '快照文件不存在'} - 。未读到批次不等于没有备份; 等待宿主采集器写出快照后重新盘点。 -

- ) : null} - {inventory && snapshotState === 'stale' ? ( -

- 元数据快照已过期:{inventory.metadata.error || '采集时间超过上限'}。旧批次、旧目录与旧容量都不再展示; - 等待宿主重新采集后重新盘点。 -

- ) : null} - {inventory && snapshotState === 'invalid' ? ( -

- 元数据快照无效:{inventory.metadata.error || inventory.error || '快照无法通过校验'} - 。不展示批次、路径或容量。 -

- ) : null} - {readyInventory ? ( - <> -

- 最近批次 {readyInventory.totals.latest_stamp || '—'} · 共 {readyInventory.totals.batch_count} 批 /{' '} - {readyInventory.totals.database_count} 个子库 ·{' '} - {readyInventory.metadata.complete && readyInventory.totals.actual_bytes !== null ? ( - <> - 表观 {formatBackupBytes(readyInventory.totals.apparent_bytes)} · 实际占盘{' '} - {formatBackupBytes(readyInventory.totals.actual_bytes)}。 - - ) : ( - <>采集快照不完整:所有批次占盘与容量未知。 - )}{' '} - 路径来自宿主快照,不依赖 SSH 计划读回。 -

-

- 采集时间 {formatBackupMoment(readyInventory.metadata.collected_at)}(宿主快照) · 读回时间{' '} - {formatBackupMoment(readyInventory.observed_at)}(API) · 快照年龄 {readyInventory.metadata.age_seconds}{' '} - 秒 / 上限 {readyInventory.metadata.max_age_seconds} 秒 · 新鲜度{' '} - {readyInventory.metadata.fresh ? '新鲜' : '已陈旧'} · 宿主 {readyInventory.metadata.host || '—'} · 快照{' '} - {readyInventory.metadata.generation || '—'} -

- {readyInventory.batches.length === 0 ? ( -

- 宿主快照可读,但没有批次目录(可能尚未执行,或采集到空目录);这不能证明备份成功或失败。 -

- ) : null} - {readyInventory.batches.map((batch, index) => { - const failedDatabases = batch.databases.filter((item) => item.failed) - const batchPath = batch.host_path || batch.path - return ( -
- - {batch.created_at || batch.stamp} - {batch.databases.length} 个数据库 · 整批 - {manifestLabel(batch)} - - {failedDatabases.length - ? `有失败 ${failedDatabases.length} 个` - : batch.actual_bytes === null - ? '占盘未知(采集不完整)' - : `实际占盘 ${formatBackupBytes(batch.actual_bytes)}`} - - -

- 批次戳 {batch.stamp} · 表观 {formatBackupBytes(batch.apparent_bytes)} · 实际占盘{' '} - {batch.actual_bytes === null ? '未知' : formatBackupBytes(batch.actual_bytes)} ·{' '} - {batch.file_count ?? '—'} 个文件 - {batch.duration_seconds ? ` · 耗时 ${batch.duration_seconds} 秒` : ''} - {batch.kind ? ` · ${batch.kind}` : ''} -

- {batch.manifest_state === 'ok' ? null : ( -

- {batch.manifest_state === 'missing' - ? '此批次没有 MANIFEST.json:完整性、耗时与库列表无法确认;占盘仅在快照完整时可信。' - : `此批次清单损坏:${batch.manifest_error || '无法解析'};库列表来自目录名,占盘仅在快照完整时可信。`} -

- )} - {!batch.sizes_complete ? ( -

- 采集不完整:占盘未知({batch.sizes_error || '宿主采集器未给出完整统计'});不使用部分字节。 -

- ) : null} -
- 批次目录 - {batchPath || '—'} - -
-
    - {batch.databases.map((database) => ( -
  • - {database.name} - - {database.failed ? '失败' : database.present ? '已写入' : '目录缺失'} - - - 实际 {formatBackupBytes(database.actual_bytes)} · 表观{' '} - {formatBackupBytes(database.apparent_bytes)} · {database.file_count ?? '—'} 个文件 - {database.in_manifest ? '' : ' · 不在清单库列表'} - -
    - {database.host_path || database.path || '—'} - -
    -
  • - ))} -
-

- 恢复验证:未接线(没有数据库备份恢复验证接口,不能把“备份成功”当成“可恢复”)。 -

-
- ) - })} - {readyInventory.incomplete_count > 0 ? ( -

- 有 {readyInventory.incomplete_count} 个 *.incomplete 目录未计入批次(被中断的运行)。 -

- ) : null} - {readyInventory.skipped.length > 0 ? ( -

- 跳过 {readyInventory.skipped.length} 项: - {readyInventory.skipped.map((item) => `${item.name}(${item.reason})`).join(';')} -

- ) : null} - {readyInventory.truncated ? ( -

快照被截断:批次或文件超过采集上限,占盘未知(不使用部分结果)。

- ) : null} -

- 快照采集于 {formatBackupMoment(readyInventory.metadata.collected_at)} · 快照文件{' '} - {readyInventory.metadata.path || '—'} · 来源 {readyInventory.source || '—'} -

- - ) : null} - {!inventory && !inventoryLoading && !inventoryError ?

尚未读取宿主元数据快照。

: null} -
- -
-
-

主机状态(读回)

- - {!schedule.host_configured - ? '未探测(平台未挂载主机凭据)' - : schedule.host_checked_at - ? `读取于 ${formatBackupMoment(schedule.host_checked_at)}` - : '尚未探测'} - -
-
-
-
目标主机
-
{hostLine}
-
拨号地址
-
{schedule.host_endpoint || '—'}
-
备份脚本
-
{scriptLine}
-
主机 cron
-
{schedule.host_cron_service ? `服务 ${schedule.host_cron_service}` : '—'}
-
下次计划(主机读回)
-
- {schedule.host_next_run - ? schedule.host_next_run - : !schedule.host_configured - ? '无法确认当前主机计划:平台未挂载主机凭据,远端 cron 可能仍在执行(历史下发不能代替实时状态)' - : hostProbePending - ? '尚未探测主机,无法确认下一次执行' - : schedule.host_schedule_enabled - ? `已配置每日 ${schedule.host_schedule_time};尚未核验下一次实际执行(不以历史下发时间推算)` - : '未启用定时或未从主机读到计划'} -
-
-
-
SSH 最近一次结果(历史)
-
- {schedule.last_run_stamp || '—'} - {runMoment(schedule) ? ` · ${runMoment(schedule)}` : ''} - {schedule.last_run_stamp ? (runFailed ? ' · 有失败/读取错误' : ' · 成功') : ''} -
-
最近一次成功
-
未从主机读取(不能用最近一次运行代替成功;历史批次以「备份记录」的元数据快照为准)
-
备份耗时 / 体积
-
- {schedule.last_run_stamp - ? `${schedule.last_run_duration_seconds} 秒 · ${formatBackupBytes(schedule.last_run_total_bytes)}` - : '—'} -
-
与设置是否一致
-
{syncLine}
-
最后下发(历史)
-
- {schedule.last_applied_at - ? `${formatBackupMoment(schedule.last_applied_at)}${schedule.last_applied_summary ? ` · ${schedule.last_applied_summary}` : ''} · 只记录当时下发结果,不能代表当前主机计划或执行状态` - : '—(没有历史下发记录;不能据设置推定主机计划)'} -
-
-
- {schedule.host_error ?

主机探测:{schedule.host_error}

: null} - {schedule.last_run_error ?

最近一次结果读取:{schedule.last_run_error}

: null} - {schedule.last_run_failed_databases.length ? ( -

SSH 结果的失败库:{schedule.last_run_failed_databases.join('、')}

- ) : null} - {schedule.host_cron_lines.length ? ( -

- 主机 cron 条目:{schedule.host_cron_lines.join(' ; ')} -

- ) : null} -
- -

- 留档分层:PG 行级留档(发布前,含 ES 文档)+ ES 快照仓 + OSS 版本控制 + 本节的整库逻辑备份 + RDS - 托管备份(控制台配置)。详见 docs/PRODUCTION_BACKUP_RECOVERY.md。 -

-
- ) -} - -// 容器:读取 + 下发 + 在途轮询。真正执行备份的是备份执行主机(同 VPC 直连 RDS)。 -export function BackupScheduleSection() { - const auth = useOptionalAuth() - const isAdmin = auth?.identity?.role === 'admin' - const [schedule, setSchedule] = useState(null) - const [loading, setLoading] = useState(true) - const [probing, setProbing] = useState(false) - const [busy, setBusy] = useState<'save' | 'apply' | 'run' | null>(null) - const [error, setError] = useState(null) - const [message, setMessage] = useState('') - const [enabledDraft, setEnabledDraft] = useState(false) - const [timeDraft, setTimeDraft] = useState('03:30') - const [daysDraft, setDaysDraft] = useState('7') - const [monthsDraft, setMonthsDraft] = useState('3') - const [inventory, setInventory] = useState(null) - const [inventoryLoading, setInventoryLoading] = useState(true) - const [inventoryError, setInventoryError] = useState(null) - const polling = useRef(null) - - const adopt = useCallback((next: BackupSchedule) => { - setSchedule(next) - setEnabledDraft(next.enabled) - setTimeDraft(next.schedule_time || '03:30') - setDaysDraft(String(next.retention_days ?? 7)) - setMonthsDraft(String(next.retention_months ?? 3)) - }, []) - - const load = useCallback(async () => { - setLoading(true) - setError(null) - try { - adopt(await fetchBackupSchedule()) - setProbing(true) - try { - adopt(await fetchBackupScheduleHost()) - } catch (cause) { - setError(cause instanceof Error ? cause.message : '读取目标主机上的备份状态失败') - } finally { - setProbing(false) - } - } catch (cause) { - setError(cause instanceof Error ? cause.message : '读取备份计划失败') - } finally { - setLoading(false) - } - }, [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) { - if (polling.current !== null) { - window.clearInterval(polling.current) - polling.current = null - } - return - } - if (polling.current !== null) return - polling.current = window.setInterval(() => { - void fetchBackupScheduleHost() - .then(adopt) - .catch(() => undefined) - }, 5000) - return () => { - if (polling.current !== null) { - window.clearInterval(polling.current) - polling.current = null - } - } - }, [schedule?.running, adopt]) - - const save = async () => { - setBusy('save') - setError(null) - setMessage('') - try { - const next = await saveBackupSchedule({ - enabled: enabledDraft, - schedule_time: timeDraft, - retention_days: Number(daysDraft), - retention_months: Number(monthsDraft), - apply: true, - }) - adopt(next) - if (!next.host_configured) { - setMessage('计划已保存。目标主机凭据未挂载,因此还不能下发到主机上的 cron。') - } else if (next.applied) { - setMessage( - `计划已保存并下发:每天 ${next.schedule_time} 执行,保留 ${next.retention_days} 天(每月另留 ${next.retention_months} 份)。` - ) - } else { - setMessage(`计划已保存,但下发失败:${next.apply_error}`) - } - } catch (cause) { - setError(cause instanceof Error ? cause.message : '保存备份计划失败') - } finally { - setBusy(null) - } - } - - const apply = async () => { - setBusy('apply') - setError(null) - setMessage('') - try { - const next = await applyBackupSchedule() - adopt(next) - setMessage(next.applied ? '已按当前设置重新下发到目标主机。' : `下发失败:${next.apply_error}`) - } catch (cause) { - setError(cause instanceof Error ? cause.message : '下发备份计划失败') - } finally { - setBusy(null) - } - } - - const runNow = async () => { - setBusy('run') - setError(null) - setMessage('') - try { - const start = await runBackupNow() - setMessage( - start.started - ? '已在目标主机上开始整批备份(全部业务库 pg_dump,约 30~60 秒),下方会自动刷新结果。' - : '已有一个备份任务在执行中。' - ) - adopt(await fetchBackupScheduleHost()) - } catch (cause) { - setError(cause instanceof Error ? cause.message : '触发备份失败') - } finally { - setBusy(null) - } - } - - if (!schedule) { - return ( -
-
-
-

存储与备份

-
-
- {error ? ( -

- {error} -

- ) : null} -

{loading ? '正在读取备份计划…' : '备份计划暂不可用。'}

-
- ) - } - - return ( - void save()} - onApply={() => void apply()} - onRunNow={() => void runNow()} - onReload={() => { - void load() - void loadInventory() - }} - inventory={inventory} - inventoryLoading={inventoryLoading} - inventoryError={inventoryError} - onReloadInventory={() => void loadInventory()} - // disk 不传:生产只认宿主元数据快照;disk 仅测试夹具用于验证告警分支。 - /> - ) -} diff --git a/web/src/LibraryStorageSection.tsx b/web/src/LibraryStorageSection.tsx deleted file mode 100644 index ab4d59f..0000000 --- a/web/src/LibraryStorageSection.tsx +++ /dev/null @@ -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(null) - const [error, setError] = useState(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 ( -
-
-

归档占用(版本快照,不是数据库备份)

-

- 只读口径:被版本引用的去重内容、blob 文件表观/实际分配字节、未被引用对象、清单文件。 - 这些归档文件与上面的整库数据库备份分开计量,不能相加。 -

-
- {loading ?

读取中…

: null} - {error ? ( -
- 读取失败 -

{error}

-
- ) : null} - {data && !data.available ?

{data.reason || '归档未接线'}

: null} - - {data?.available ? ( - <> -
-
-
版本数
-
{data.versions.length}
-
-
-
被版本引用的去重内容
-
{formatBytes(data.content_bytes)}
-
-
-
blob 文件(表观)
-
{formatBytes(data.blob_file_bytes)}
-
-
-
blob 实际分配
-
{formatBytes(data.blob_allocated_bytes)}
-
-
-
未被任何版本引用
-
- {data.unreferenced_blobs} 个 / {formatBytes(data.unreferenced_bytes)} -
-
-
-
清单文件
-
{formatBytes(data.manifest_file_bytes)}
-
-
- -
-

容量门禁

- {data.capacity.configured ? ( -

- 预算 {formatBytes(data.capacity.budget_bytes)} · 当前 {formatBytes(data.capacity.current_bytes)} · - 目标版本约 {formatBytes(data.capacity.required_bytes)} →{' '} - {data.capacity.ok ? '可写入' : `阻断:${data.capacity.reason}`} -

- ) : ( -

- 容量预算未设置(LIBRARY_CAPACITY_BUDGET_BYTES):无法证明装得下,生产写入按阻断处理。 -

- )} -
- -
- 保留策略与清理预览(未设置时按“全部保留”处理) -
-

保留与依赖保护

-

- {policyConfigured - ? `策略:${[ - plan && plan.policy.keep_versions > 0 ? `保留最近 ${plan.policy.keep_versions} 个版本` : '', - plan && plan.policy.keep_days > 0 ? `保留 ${plan.policy.keep_days} 天` : '', - ] - .filter(Boolean) - .join(' + ')}` - : '策略:未设置(不生成清理候选)'} -

-

- 受保护版本 {plan?.protected.length ?? 0} 个:生产生效、每库最近封存、每次生产预备份、运行中作业引用, - 不论多久都不会进入候选。 -

- {data.versions.filter((item) => item.protected).length > 0 ? ( -
    - {data.versions - .filter((item) => item.protected) - .map((item) => ( -
  • - {item.id.slice(0, 12)} {item.kind} · {(item.protected_by ?? []).join('、')} -
  • - ))} -
- ) : null} -
- -
-

清理预览

- {policyConfigured ? ( - plan && plan.candidates.length > 0 ? ( - <> -

- 按策略可考虑清理 {plan.candidates.length} 个版本,独占字节上限{' '} - {formatBytes(plan.reclaim_preview_bytes)}(共享归档文件不会因此释放,这不是可回收空间)。 -

-
    - {plan.candidates.map((item) => ( -
  • - {item.id.slice(0, 12)} {item.kind} · {item.reason.join(';')} ·{' '} - {formatBytes(item.exclusive_bytes)} -
  • - ))} -
- - ) : ( -

按当前策略没有可清理的候选版本。

- ) - ) : ( -

- 保留数量与天数都未设置,按「全部保留」处理:不生成候选,也不提供默认值。 -

- )} - {plan?.blocked.length ? ( -
    - {plan.blocked.map((item) => ( -
  • {item}
  • - ))} -
- ) : null} -
- -
    -
  • 自动清理:{data.automatic_cleanup ? '开启' : '保持关闭'}(页面不提供删除动作)
  • -
  • 实际删除需要单独授权,本页只给预览
  • -
  • 以上数字都不是「可回收空间」,不能用来估算清理收益
  • - {data.notes.map((note) => ( - // 服务端注记里的 blob 指归档文件:页面统一术语,不把实现细节甩给操作者。 -
  • {note.replace(/blob/gi, '归档文件')}
  • - ))} -
-
- - ) : null} -
- ) -} diff --git a/web/src/StorageBackupSummary.test.tsx b/web/src/StorageBackupSummary.test.tsx new file mode 100644 index 0000000..68c86ad --- /dev/null +++ b/web/src/StorageBackupSummary.test.tsx @@ -0,0 +1,277 @@ +// @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 => { + 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 => ({ + 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 Promise>> + +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()) + 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()) + 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()) + 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()) + await flush() + const button = container.querySelector('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()) + await flush() + expect(container.querySelectorAll('tbody tr')).toHaveLength(20) + const more = container.querySelector('.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() + }) +}) \ No newline at end of file diff --git a/web/src/StorageBackupSummary.tsx b/web/src/StorageBackupSummary.tsx new file mode 100644 index 0000000..0df521d --- /dev/null +++ b/web/src/StorageBackupSummary.tsx @@ -0,0 +1,270 @@ +// 「系统设置 → 存储与备份」只读摘要页:目录、最近成功/失败、归档占用、磁盘剩余、 +// 四条容量告警和批次列表。数据只来自宿主每 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 { + 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(null) + const [archive, setArchive] = useState(null) + const [archiveFailed, setArchiveFailed] = useState(false) + const [errors, setErrors] = useState([]) + const [loading, setLoading] = useState(true) + const [visible, setVisible] = useState(BATCH_PAGE) + const [copied, setCopied] = useState('') + const inFlight = useRef(false) + const copiedTimer = useRef | 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 ( +
+
+
+

存储与备份

+ {stateNote ?

{stateNote}

: null} +
+
+ 上次上报 {lastReport || UNKNOWN} + +
+
+ + {errors.length > 0 ? ( +

+ {errors.join(';')} +

+ ) : null} + + {loading ? ( +

正在读取存储与备份…

+ ) : ( + <> +
+ {cards.map((card) => ( +
+ {card.label} + + {card.value} + + + {card.note} + {card.copy ? ( + + ) : null} + +
+ ))} +
+ +
+
+

容量告警

+ 0 ? 'storage-alert-count is-pending' : 'storage-alert-count'}> + {pendingAlertCount(alerts)} 项需处理 + +
+
    + {alerts.map((alert) => ( +
  • + {alert.label} + {alert.value} + + {alert.conclusion} + +
  • + ))} +
+
+ +
+
+

备份批次

+ {batches.length > 0 ? `共 ${batches.length} 个` : ''} +
+ {batches.length === 0 ? ( +

+ {state === 'ready' || state === 'incomplete' + ? '暂无批次' + : `${hostValueLabel(state)}(上次上报 ${lastReport || UNKNOWN})`} +

+ ) : ( + + + + + + + + + + + + {shown.map((batch) => { + const outcome = batchOutcome(batch) + return ( + + + + + + + + + ) + })} + +
时间结果大小批次路径 +
{batchWhen(batch)} + + {outcome.failed ? '失败' : '成功'} + + {outcome.reasons.length > 0 ? ( +

{outcome.reasons.join(';')}

+ ) : null} +
{formatSize(batch.actual_bytes)}{batch.stamp} + {batch.path} + + +
+ )} + {visible < batches.length ? ( + + ) : null} +
+ + )} +
+ ) +} \ No newline at end of file diff --git a/web/src/SystemSettings.test.tsx b/web/src/SystemSettings.test.tsx index 253baab..236e403 100644 --- a/web/src/SystemSettings.test.tsx +++ b/web/src/SystemSettings.test.tsx @@ -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( ) : null} - {section === 'storage' ? ( - <> - - - - ) : null} + {section === 'storage' ? : null} {section === 'members' && identity?.role === 'admin' ? : null} {section === 'refresh' && settings ? (
diff --git a/web/src/backupSchedule.test.ts b/web/src/backupSchedule.test.ts deleted file mode 100644 index a6f1e4f..0000000 --- a/web/src/backupSchedule.test.ts +++ /dev/null @@ -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 - 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 }) - }) -}) diff --git a/web/src/backupSchedule.ts b/web/src/backupSchedule.ts deleted file mode 100644 index 24d38e4..0000000 --- a/web/src/backupSchedule.ts +++ /dev/null @@ -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 => - 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): 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 { - 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 { - return readSchedule('/api/v1/backup-schedule', '读取备份计划失败', signal) -} - -// host 端点会 SSH 探测目标主机(计划 + 最近一次结果),单独调用以免拖慢首屏。 -export function fetchBackupScheduleHost(signal?: AbortSignal): Promise { - return readSchedule('/api/v1/backup-schedule/host', '读取目标主机上的备份状态失败', signal) -} - -async function writeSchedule( - path: string, - method: string, - body: unknown, - failure: string, - signal?: AbortSignal -): Promise { - 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 { - return writeSchedule('/api/v1/backup-schedule', 'PUT', input, '保存备份计划失败', signal) -} - -export function applyBackupSchedule(signal?: AbortSignal): Promise { - return writeSchedule('/api/v1/backup-schedule/apply', 'POST', undefined, '下发备份计划失败', signal) -} - -export async function runBackupNow(signal?: AbortSignal): Promise { - 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 } -} diff --git a/web/src/libraryStorage.css b/web/src/libraryStorage.css deleted file mode 100644 index db2423f..0000000 --- a/web/src/libraryStorage.css +++ /dev/null @@ -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; -} diff --git a/web/src/storageBackup.css b/web/src/storageBackup.css index 4790780..37b3ae2 100644 --- a/web/src/storageBackup.css +++ b/web/src/storageBackup.css @@ -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; + } +} \ No newline at end of file diff --git a/web/src/storageSummary.test.ts b/web/src/storageSummary.test.ts new file mode 100644 index 0000000..dd49a2e --- /dev/null +++ b/web/src/storageSummary.test.ts @@ -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 => ({ + 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) + }) +}) \ No newline at end of file diff --git a/web/src/storageSummary.ts b/web/src/storageSummary.ts new file mode 100644 index 0000000..7c72f45 --- /dev/null +++ b/web/src/storageSummary.ts @@ -0,0 +1,359 @@ +// 「存储与备份」只读摘要的纯逻辑:数据源只有两个只读接口—— +// /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 \ No newline at end of file