From df69b278ce8c96d2e7d529624f1a8cd8541ee79e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E5=A7=9A=E7=AB=A0=E6=B5=A9?=
Date: Thu, 19 Nov 2026 12:16:30 +0800
Subject: [PATCH 01/14] =?UTF-8?q?feat(settings):=20AI=20=E6=A8=A1=E5=9E=8B?=
=?UTF-8?q?=E8=BF=9E=E6=8E=A5=E6=94=B9=E4=B8=BA=E5=BD=93=E5=89=8D=E7=94=9F?=
=?UTF-8?q?=E6=95=88=E4=B8=8E=E7=8B=AC=E7=AB=8B=E8=8D=89=E7=A8=BF=E7=BC=96?=
=?UTF-8?q?=E8=BE=91?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
为什么:交互稿要求顶部只读已保存模型与真实核验态,下方编辑独立草稿;测试草稿
不得改写当前连接,保存一律回显服务端结果,草稿变动或配置被他人改动后旧测试失效。
原来只有一张表单和一个 busy 状态,测试与保存无法区分,清除密钥也与保存混在一起。
改了什么:QAModelSettings 拆成 saved / draft 两层;已配置密钥默认收起,仅更换或
首次录入展示输入框,换地址强制重新录入;清除并停用收进折叠区、二次确认且只提交
已保存连接;409 冲突重新拉取已保存配置并作废草稿测试。样式迁到 systemSettings.css,
删除 qaOps.css 里同名残留;合并分区与组件内重复说明。
怎么验的:npm test 119 文件 600 例全过(新增 mounted 交互回归 5 例);npm run build
通过;make verify 全量门禁 17 项 success(identity 本地 skipped)。未推送、未部署。
---
CHANGELOG.md | 18 ++
README.md | 2 +-
web/src/QAModelSettings.mounted.test.tsx | 197 +++++++++++++
web/src/QAModelSettings.test.tsx | 71 +++--
web/src/QAModelSettings.tsx | 352 ++++++++++++++++-------
web/src/SystemSettings.test.tsx | 9 +-
web/src/SystemSettings.tsx | 8 +-
web/src/qaOps.css | 7 -
web/src/systemSettings.css | 90 ++++++
9 files changed, 605 insertions(+), 149 deletions(-)
create mode 100644 web/src/QAModelSettings.mounted.test.tsx
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 39a7167..21892a8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,23 @@
# Changelog
+## 开发快照 0.1.401(AI 模型连接:当前生效 + 独立草稿)
+
+### Changed
+
+- 「系统设置 → AI 模型连接」按交互稿重排:顶部只读「当前生效」(模型 + 服务端真实核验态与地址),
+ 下方地址/模型是独立草稿;测试草稿只回显核验结果,不更新当前连接,「测试中」与「保存中」分开提示。
+- 保存成功一律用服务端响应回显当前信息;草稿改动或版本冲突(409)都会作废上一次草稿测试,
+ 冲突时载入最新已保存配置并要求按新版本重测。
+- 已配置密钥默认收起不回显,只有「更换密钥」或首次录入才出现输入框;更换基础地址强制重新录入密钥,
+ 取消更换无副作用。安全传输与独立密钥存储限制保持不变。
+- 「清除密钥并停用」收进单独折叠区,写明对问答分析与中文翻译的影响并二次确认;只提交已保存连接,
+ 未保存草稿不会被夹带,取消不产生任何请求。
+- 合并分区标题与组件内重复的说明文字,模型连接说明只保留一处。
+
+### Fixed
+
+- 模型连接的测试/保存不再共用同一个忙碌状态,避免把草稿测试结果误当成已生效配置。
+
## 开发快照 0.1.399(系统设置分区调整:AI 模型连接 / 知识库映射)
### Changed
diff --git a/README.md b/README.md
index 49b20ec..f61981c 100644
--- a/README.md
+++ b/README.md
@@ -127,7 +127,7 @@ make list # 查看检查清单与适用范围
## 问答运营模型配置
-管理员在「系统设置 → AI 模型连接」填写 OpenAI 兼容基础地址、模型和 API Key。测试连接发送最小非业务请求;保存不会启动历史全量任务,自动分析/翻译默认关闭。密钥不回显,保留、更换和清除分别选择;录入只允许有效 HTTPS 或本机回环连接,不允许跳过证书校验。
+管理员在「系统设置 → AI 模型连接」填写 OpenAI 兼容基础地址、模型和 API Key。页面顶部显示当前已保存的模型与服务端核验结果,下方编辑的是独立草稿:测试连接只核验草稿,保存才更新当前连接,保存成功后按服务端响应回显。测试连接发送最小非业务请求;保存不会启动历史全量任务,自动分析/翻译默认关闭。密钥不回显、默认收起,只有「更换密钥」或首次录入才显示输入框,更换基础地址须重新录入密钥;「清除密钥并停用」在单独折叠区里二次确认,只作用于已保存连接。录入只允许有效 HTTPS 或本机回环连接,不允许跳过证书校验。
API 和普通 worker 须只读挂载同一个独立的 **32 字节、0600 普通文件**,以 `QA_AI_MASTER_KEY_FILE` 指向容器内路径。文件属主应为实际运行 UID;不要复用 Agent 会话存储或把主密钥写进 Compose/Git。治理库只保存加密后的服务密钥;恢复时必须同时恢复治理库和这份独立主密钥。未配置主密钥时如实显示安全存储未就绪。
diff --git a/web/src/QAModelSettings.mounted.test.tsx b/web/src/QAModelSettings.mounted.test.tsx
new file mode 100644
index 0000000..78ef46a
--- /dev/null
+++ b/web/src/QAModelSettings.mounted.test.tsx
@@ -0,0 +1,197 @@
+// @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 { QAModelSettings } from './QAModelSettings'
+import type { AISettings } from './qaAITypes'
+let root: Root, host: HTMLDivElement
+type Call = { path: string; method: string; body: Record | null }
+let calls: Call[]
+let responder: (call: Call) => { status: number; data?: AISettings; error?: string }
+const saved: AISettings = {
+ revision: 1,
+ base_url: 'https://model.example.invalid/v1',
+ model: 'example-model',
+ key_configured: true,
+ verification: 'verified',
+ checked_at: '2026-11-18T10:00:00Z',
+ automatic_evaluation: true,
+ automatic_translation: false,
+ storage_ready: true,
+}
+const applied = (call: Call, extra: Partial = {}): AISettings => ({
+ ...saved,
+ revision: saved.revision + 1,
+ base_url: String(call.body?.base_url),
+ model: String(call.body?.model),
+ key_configured: call.body?.key_action !== 'clear',
+ verification: call.body?.key_action === 'clear' ? 'not_configured' : 'verified',
+ ...extra,
+})
+const ok = (data: AISettings) => ({ status: 200, data })
+beforeEach(() => {
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
+ host = document.createElement('div')
+ document.body.append(host)
+ root = createRoot(host)
+ calls = []
+ responder = (call) => ok(call.method === 'GET' ? saved : applied(call))
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (path: string, init?: RequestInit) => {
+ const call: Call = {
+ path,
+ method: init?.method ?? 'GET',
+ body: init?.body ? JSON.parse(String(init.body)) : null,
+ }
+ calls.push(call)
+ const result = responder(call)
+ return new Response(JSON.stringify(result.error ? { error: result.error } : { data: result.data }), {
+ status: result.status,
+ })
+ })
+ )
+})
+afterEach(async () => {
+ await act(async () => root.unmount())
+ host.remove()
+ vi.unstubAllGlobals()
+})
+const button = (label: string) => {
+ const found = [...host.querySelectorAll('button')].find((item) => item.textContent?.trim() === label)
+ expect(found, label).toBeTruthy()
+ return found!
+}
+const click = async (label: string) => {
+ const target = button(label)
+ await act(async () => target.click())
+ await act(async () => {})
+}
+const type = async (label: string, value: string) => {
+ const input = [...host.querySelectorAll('label')]
+ .find((item) => item.textContent?.startsWith(label))
+ ?.querySelector('input')
+ expect(input, label).toBeTruthy()
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, value)
+ input!.dispatchEvent(new Event('input', { bubbles: true }))
+ })
+}
+const current = () => host.querySelector('.qa-ai-model-current')?.textContent ?? ''
+const writes = () => calls.filter((call) => call.method === 'POST')
+const disable = async () => {
+ await click('清除密钥并停用…')
+ await click('确认清除并停用')
+}
+describe('AI 模型连接草稿编辑器', () => {
+ it('tests the draft without touching the saved connection and echoes the server after save', async () => {
+ await act(async () => root.render())
+ expect(current()).toContain('example-model · 已通过真实连接测试')
+ await type('模型名称', 'draft-model')
+ await click('测试连接')
+ const test = writes().at(-1)!
+ expect(test.path).toBe('/api/v1/qa-ops/ai/settings/test')
+ expect(test.body).toEqual({
+ base_revision: 1,
+ base_url: saved.base_url,
+ model: 'draft-model',
+ key_action: 'keep',
+ })
+ expect(host.textContent).toContain('草稿测试:已通过真实连接测试')
+ expect(host.textContent).toContain('草稿未保存,当前生效配置未改变')
+ // 测试不更新「当前生效」,也不产生保存。
+ expect(current()).toContain('example-model · 已通过真实连接测试')
+ expect(writes().filter((call) => call.path.endsWith('/settings'))).toHaveLength(0)
+ // 再改草稿 ⇒ 上一次测试结论失效。
+ await type('模型名称', 'saved-model')
+ expect(host.textContent).not.toContain('草稿测试:已通过真实连接测试')
+ await click('保存配置')
+ const save = writes().at(-1)!
+ expect(save.path).toBe('/api/v1/qa-ops/ai/settings')
+ expect(save.body).toEqual({ base_revision: 1, base_url: saved.base_url, model: 'saved-model', key_action: 'keep' })
+ // 保存后用服务端响应回显当前信息,而不是本地草稿转写。
+ expect(current()).toContain('saved-model · 已通过真实连接测试')
+ expect(host.textContent).toContain('已保存并更新当前连接:saved-model · 已通过真实连接测试')
+ expect(host.textContent).toContain('草稿与已保存配置一致')
+ })
+ it('keeps a configured key collapsed and sends a replacement only when asked', async () => {
+ await act(async () => root.render())
+ expect(host.querySelector('input[type=password]')).toBeNull()
+ await click('更换密钥')
+ await type('新 API 密钥', 'test-only-replacement-key')
+ await click('保存配置')
+ expect(writes().at(-1)!.body).toEqual({
+ base_revision: 1,
+ base_url: saved.base_url,
+ model: saved.model,
+ key_action: 'replace',
+ api_key: 'test-only-replacement-key',
+ })
+ expect(host.querySelector('input[type=password]')).toBeNull()
+ expect(host.textContent).not.toContain('test-only-replacement-key')
+ await click('更换密钥')
+ await click('取消更换')
+ expect(host.querySelector('input[type=password]')).toBeNull()
+ expect(host.textContent).toContain('草稿与已保存配置一致')
+ })
+ it('requires a fresh key when the address changes and hides cancelling', async () => {
+ await act(async () => root.render())
+ await type('API 基础地址', 'https://other.example.invalid/v1')
+ expect(host.querySelector('input[type=password]')).toBeTruthy()
+ expect(host.textContent).toContain('已更换基础地址:须重新录入密钥')
+ expect([...host.querySelectorAll('button')].some((item) => item.textContent?.trim() === '取消更换')).toBe(false)
+ expect(button('保存配置').disabled).toBe(true)
+ await type('新 API 密钥', 'second-secret')
+ await click('保存配置')
+ expect(writes().at(-1)!.body).toEqual({
+ base_revision: 1,
+ base_url: 'https://other.example.invalid/v1',
+ model: saved.model,
+ key_action: 'replace',
+ api_key: 'second-secret',
+ })
+ })
+ it('disables only the saved connection, and cancelling the confirmation has no effect', async () => {
+ await act(async () => root.render())
+ await type('模型名称', 'unsaved-draft')
+ await click('清除密钥并停用…')
+ await click('取消')
+ expect(writes()).toHaveLength(0)
+ expect(current()).toContain('example-model · 已通过真实连接测试')
+ expect([...host.querySelectorAll('input')].find((item) => item.value === 'unsaved-draft')).toBeTruthy()
+ await disable()
+ const clear = writes().at(-1)!
+ // 草稿里的 unsaved-draft 不会被夹带成停用提交。
+ expect(clear.body).toEqual({
+ base_revision: 1,
+ base_url: saved.base_url,
+ model: saved.model,
+ key_action: 'clear',
+ })
+ expect(current()).toContain('未配置可用密钥')
+ expect(host.textContent).toContain('已清除密钥并停用连接')
+ expect(host.querySelector('input[type=password]')).toBeTruthy()
+ })
+ it('drops a stale draft test when the saved revision changed elsewhere', async () => {
+ let gets = 0
+ responder = (call) => {
+ if (call.method === 'GET') {
+ gets += 1
+ return ok(gets === 1 ? saved : { ...saved, revision: 2, model: 'other-model' })
+ }
+ return call.path.endsWith('/settings/test')
+ ? { status: 409, error: '配置、输入、人工复核或预览已变化,请刷新;现有结论未被覆盖' }
+ : ok(applied(call))
+ }
+ await act(async () => root.render())
+ await type('模型名称', 'stale-draft')
+ await click('测试连接')
+ expect(host.textContent).toContain('已载入最新已保存配置(版本 2),草稿未保存,请重新测试')
+ expect(current()).toContain('other-model')
+ expect(host.textContent).not.toContain('草稿测试:')
+ // 之后的保存基于刷新后的版本号,不会拿旧 revision 覆盖别人的修改。
+ await type('模型名称', 'after-conflict')
+ await click('保存配置')
+ expect(writes().at(-1)!.body).toMatchObject({ base_revision: 2, model: 'after-conflict' })
+ })
+})
diff --git a/web/src/QAModelSettings.test.tsx b/web/src/QAModelSettings.test.tsx
index b116627..2a83571 100644
--- a/web/src/QAModelSettings.test.tsx
+++ b/web/src/QAModelSettings.test.tsx
@@ -1,37 +1,58 @@
import { it, expect } from 'vitest'
import { renderToStaticMarkup } from 'react-dom/server'
import { QAModelSettings, qaAIKeyEntryAllowed } from './QAModelSettings'
-it('provides independent write-only model settings and does not equate save with bulk execution', () => {
+import type { AISettings } from './qaAITypes'
+const saved: AISettings = {
+ revision: 3,
+ base_url: 'https://model.example.invalid/v1',
+ model: 'fixture-model',
+ key_configured: true,
+ verification: 'verified',
+ checked_at: '2026-10-19T00:00:00Z',
+ automatic_evaluation: false,
+ automatic_translation: false,
+ storage_ready: true,
+}
+it('shows the saved connection and keeps a configured key collapsed until replaced', () => {
+ const html = renderToStaticMarkup()
+ for (const text of [
+ '当前生效',
+ 'fixture-model · 已通过真实连接测试',
+ '已配置(不回显)',
+ '更换密钥',
+ 'API 基础地址',
+ '模型名称',
+ '测试连接',
+ '保存配置',
+ '清除密钥并停用连接',
+ '草稿与已保存配置一致',
+ ])
+ expect(html).toContain(text)
+ // 已配置的密钥默认收起:没有密码框,也没有把任何密钥值渲染出来。
+ expect(html).not.toContain('type="password"')
+ expect(html).not.toContain('保留现有密钥')
+ expect(html).not.toContain('fixture-only-api-key')
+})
+it('asks for a key on first entry and describes the disable impact', () => {
const html = renderToStaticMarkup(
)
- for (const text of [
- '问答评估模型',
- 'API 基础地址',
- '模型名称',
- 'API Key',
- 'type="password"',
- '测试连接',
- '保存配置',
- '保留现有密钥',
- '更换密钥',
- '清除密钥',
- '保存不会启动全量评估',
- ])
- expect(html).toContain(text)
- expect(html).not.toContain('value="fixture-only-api-key"')
+ expect(html).toContain('type="password"')
+ expect(html).toContain('API 密钥 未配置')
+ expect(html).toContain('未配置可用密钥')
+ expect(html).toContain('无法调用此模型')
+ expect(html).toContain('未保存的草稿不会被提交')
+ expect(html).toContain('当前没有已保存的密钥')
})
it('permits new-key entry only on HTTPS or browser-local loopback origins', () => {
expect(qaAIKeyEntryAllowed({ protocol: 'https:', hostname: 'kg.example.invalid' })).toBe(true)
diff --git a/web/src/QAModelSettings.tsx b/web/src/QAModelSettings.tsx
index ee9c4e3..2ca587c 100644
--- a/web/src/QAModelSettings.tsx
+++ b/web/src/QAModelSettings.tsx
@@ -2,6 +2,7 @@ import { useEffect, useState } from 'react'
import type { AISettings } from './qaAITypes'
import type { AISettingsInput } from './qaAI'
import { fetchAISettings, saveAISettings, testAISettings } from './qaAI'
+import { QARequestError } from './qaOps'
export function qaAIKeyEntryAllowed(location: { protocol: string; hostname: string }) {
return location.protocol === 'https:' || ['localhost', '127.0.0.1', '[::1]', '::1'].includes(location.hostname)
}
@@ -11,172 +12,303 @@ const verificationLabels: Record = {
unverified: '未完成核验,未启用调用',
rejected: '服务已拒绝,调用已阻断',
}
+const when = (value: string) => new Date(value).toLocaleString('zh-CN', { hour12: false })
+type Busy = '' | 'testing' | 'saving'
+type Notice = { tone: 'ok' | 'error'; text: string }
export function QAModelSettings({ initial }: { initial?: AISettings }) {
- const [settings, setSettings] = useState(initial ?? null),
- [base, setBase] = useState(initial?.base_url ?? ''),
- [model, setModel] = useState(initial?.model ?? '')
- const [keyAction, setKeyAction] = useState(
- initial?.key_configured ? 'keep' : 'replace'
- ),
- [key, setKey] = useState('')
- const [busy, setBusy] = useState(false),
- [error, setError] = useState(null),
- [message, setMessage] = useState(null)
- const secure = typeof window !== 'undefined' && qaAIKeyEntryAllowed(window.location)
+ // saved 始终是服务端已生效的那一份(顶部「当前生效」与停用操作的唯一依据);
+ // 下面的输入只是草稿,测试草稿不回写 saved,避免把未保存的值伪装成当前连接。
+ const [saved, setSaved] = useState(initial ?? null)
+ const [base, setBase] = useState(initial?.base_url ?? '')
+ const [model, setModel] = useState(initial?.model ?? '')
+ const [replace, setReplace] = useState(!initial?.key_configured)
+ const [key, setKey] = useState('')
+ const [busy, setBusy] = useState('')
+ const [tested, setTested] = useState(null)
+ const [confirmingDisable, setConfirmingDisable] = useState(false)
+ const [notice, setNotice] = useState(null)
+ const [loadError, setLoadError] = useState(null)
useEffect(() => {
if (initial) return
const controller = new AbortController()
void fetchAISettings(controller.signal)
.then((value) => {
- setSettings(value)
+ if (controller.signal.aborted) return
+ setSaved(value)
setBase(value.base_url)
setModel(value.model)
- setKeyAction(value.key_configured ? 'keep' : 'replace')
+ setReplace(!value.key_configured)
})
.catch((reason) => {
- if (!controller.signal.aborted) setError(reason instanceof Error ? reason.message : '模型配置读取失败')
+ if (!controller.signal.aborted) setLoadError(reason instanceof Error ? reason.message : '模型配置读取失败')
})
return () => controller.abort()
}, [initial])
- const dirty = () => {
- setMessage(null)
- setError(null)
+ const secure = typeof window !== 'undefined' && qaAIKeyEntryAllowed(window.location)
+ const configured = Boolean(saved?.key_configured)
+ // 服务端规则:保留旧密钥时地址不许变(旧密钥不会被发往新地址),所以换地址强制重新录入。
+ const baseChanged = Boolean(saved && base !== saved.base_url)
+ const keyRequired = !configured || baseChanged || replace
+ const keyAction: AISettingsInput['key_action'] = keyRequired ? 'replace' : 'keep'
+ const storageReady = Boolean(saved?.storage_ready)
+ const keyEntryBlocked = !secure || !storageReady
+ const dirty = Boolean(
+ saved && (base !== saved.base_url || model !== saved.model || key !== '' || (configured && replace))
+ )
+ const ready =
+ Boolean(saved) &&
+ busy === '' &&
+ base.trim() !== '' &&
+ model.trim() !== '' &&
+ (!keyRequired || (!keyEntryBlocked && key !== ''))
+ // 任何草稿改动都让上一次测试结果失效:旧草稿的核验结论不能贴在新草稿上。
+ const edit = (apply: () => void) => {
+ apply()
+ setTested(null)
+ setNotice(null)
}
- const run = async (test: boolean) => {
- if (!settings) return
- setBusy(true)
- setMessage(null)
- setError(null)
- const input: AISettingsInput = {
- base_revision: settings.revision,
- base_url: base,
- model,
- key_action: keyAction,
- ...(keyAction === 'replace' ? { api_key: key } : {}),
+ const input = (): AISettingsInput => ({
+ base_revision: saved!.revision,
+ base_url: base,
+ model,
+ key_action: keyAction,
+ ...(keyAction === 'replace' ? { api_key: key } : {}),
+ })
+ const apply = (result: AISettings, prefix: string) => {
+ setSaved(result)
+ setBase(result.base_url)
+ setModel(result.model)
+ setKey('')
+ setReplace(!result.key_configured)
+ setTested(null)
+ setConfirmingDisable(false)
+ setNotice({
+ tone: 'ok',
+ text: `${prefix}:${result.model || '未设置模型'} · ${verificationLabels[result.verification]}`,
+ })
+ }
+ const fail = async (reason: unknown) => {
+ const message = reason instanceof Error ? reason.message : '模型配置操作失败'
+ if (!(reason instanceof QARequestError) || reason.status !== 409) {
+ setNotice({ tone: 'error', text: message })
+ return
}
+ // 版本冲突:别人已经改过配置,这份草稿的测试结论作废;草稿本身保留,但必须按最新版本重测。
try {
- const result = await (test ? testAISettings(input) : saveAISettings(input))
- if (!test) {
- setSettings(result)
- setKey('')
- setKeyAction(result.key_configured ? 'keep' : 'replace')
- }
- setMessage(
- (test ? '连接测试:' : '配置已保存:') +
- verificationLabels[result.verification] +
- (test ? ';未保存、未启动任务' : ';保存不会启动全量评估')
+ const fresh = await fetchAISettings()
+ setSaved(fresh)
+ setReplace((current) => current || !fresh.key_configured)
+ setTested(null)
+ setNotice({
+ tone: 'error',
+ text: `${message};已载入最新已保存配置(版本 ${fresh.revision}),草稿未保存,请重新测试。`,
+ })
+ } catch {
+ setNotice({ tone: 'error', text: message })
+ }
+ }
+ const runTest = async () => {
+ if (!saved || !ready) return
+ setBusy('testing')
+ setNotice(null)
+ setTested(null)
+ try {
+ setTested(await testAISettings(input()))
+ } catch (reason) {
+ await fail(reason)
+ } finally {
+ setBusy('')
+ }
+ }
+ const runSave = async () => {
+ if (!saved || !ready) return
+ setBusy('saving')
+ setNotice(null)
+ try {
+ apply(await saveAISettings(input()), '已保存并更新当前连接')
+ } catch (reason) {
+ await fail(reason)
+ } finally {
+ setBusy('')
+ }
+ }
+ const runDisable = async () => {
+ if (!saved || busy !== '') return
+ setBusy('saving')
+ setNotice(null)
+ try {
+ // 只停用已保存连接:地址与模型取服务端当前值,未保存草稿不参与这次提交。
+ apply(
+ await saveAISettings({
+ base_revision: saved.revision,
+ base_url: saved.base_url,
+ model: saved.model,
+ key_action: 'clear',
+ }),
+ '已清除密钥并停用连接'
)
} catch (reason) {
- setError(reason instanceof Error ? reason.message : '模型配置操作失败')
+ await fail(reason)
} finally {
- setBusy(false)
+ setBusy('')
}
}
- const ready =
- Boolean(settings) &&
- !busy &&
- (keyAction !== 'replace' || (secure && Boolean(key) && Boolean(settings?.storage_ready)))
return (
-
- 问答评估模型
-
- 四字段分析和中文问题翻译共用此独立配置。保存不会启动全量评估,也不会自动开启新增处理。
-
- {settings ? (
+
+ {saved ? (
<>
-
- {verificationLabels[settings.verification]};密钥:{settings.key_configured ? '已配置(不回显)' : '未配置'}
- ;自动分析/翻译:{settings.automatic_evaluation ? '开' : '关'} /{' '}
- {settings.automatic_translation ? '开' : '关'}
-
-
+
+ 当前生效
+
+ {saved.model ? `${saved.model} · ` : ''}
+ {verificationLabels[saved.verification]}
+
+
+ {saved.base_url || '未设置地址'}
+ {saved.checked_at ? ` · 最近核验 ${when(saved.checked_at)}` : ''}
+
+
+
-
-
+
OpenAI 兼容基础地址,不含 /chat/completions。
+
+ API 密钥 {configured ? '已配置(不回显)' : '未配置'}
+ {configured && !keyRequired ? (
+
+ ) : null}
+
+ {keyRequired ? (
+
+
+ {configured && replace && !baseChanged ? (
+
+ ) : null}
+
+ ) : null}
+ {baseChanged && configured ? (
+
已更换基础地址:须重新录入密钥,原密钥不会发往新地址。
+ ) : null}
{!secure ? (
当前不是安全密钥录入连接。请使用有效HTTPS或本机 localhost
地址录入新密钥;不会通过失配证书或普通局域网HTTP发送新密钥。
) : null}
- {!settings.storage_ready ? (
+ {!storageReady ? (
独立安全存储未就绪,请配置服务器的 QA_AI_MASTER_KEY_FILE;不会读取 Hermes 密钥。
) : null}
-
-
Release Worker 默认关闭
diff --git a/web/src/KnowledgeBaseBinding.test.tsx b/web/src/KnowledgeBaseBinding.test.tsx
new file mode 100644
index 0000000..33dec3f
--- /dev/null
+++ b/web/src/KnowledgeBaseBinding.test.tsx
@@ -0,0 +1,213 @@
+// @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 { AuthContext } from './auth'
+import { KnowledgeBaseBinding } from './KnowledgeBaseBinding'
+import type { KBEnvironmentBinding } from './knowledgeBaseBindings'
+
+const binding = (environment: 'test' | 'production'): KBEnvironmentBinding => ({
+ environment,
+ revision: 1,
+ base_url: `https://${environment}.weknora.example`,
+ key_configured: true,
+ key_source: 'sealed',
+ internal_kb_id: `kb-${environment}-in-0001`,
+ internal_kb_name: `${environment} 内部资料`,
+ external_kb_id: `kb-${environment}-out-0001`,
+ external_kb_name: `${environment} 对外资料`,
+ verification: 'verified',
+ checked_at: null,
+ updated_by: 'admin',
+ updated_at: null,
+ source: 'web',
+ storage_ready: true,
+ replanned: 0,
+ retired_duplicates: 0,
+})
+
+const snapshot = {
+ data: { environments: [binding('test'), binding('production')], storage_ready: true },
+}
+const catalog = {
+ data: {
+ status: 'ok',
+ message: '已读取 2 个知识库',
+ page: 1,
+ page_size: 20,
+ total: 2,
+ options: [
+ { id: 'kb-new-in-0001', name: '新内部库', knowledge_count: 3 },
+ { id: 'kb-new-out-0001', name: '新对外库', knowledge_count: 4 },
+ ],
+ },
+}
+
+const json = (value: unknown, status = 200) => ({
+ ok: status >= 200 && status < 300,
+ status,
+ json: async () => value,
+})
+
+const auth = (role: 'admin' | 'viewer') => ({
+ identity: { id: `${role}-1`, username: role, display_name: role, role, must_change_password: false },
+ ready: true,
+ login: async () => null,
+ logout: async () => {},
+ changePassword: async () => null,
+ signedOut: 0,
+ notifySignedOut: () => {},
+})
+
+let root: Root
+let host: HTMLDivElement
+const flush = async () => {
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ })
+}
+const click = async (label: string) => {
+ const button = [...host.querySelectorAll('button')].find((item) => item.textContent?.trim() === label)
+ expect(button, label).toBeTruthy()
+ await act(async () => button!.click())
+ await flush()
+}
+const choose = async (label: string, value: string) => {
+ const select = [...host.querySelectorAll('label')]
+ .find((item) => item.textContent?.startsWith(label))
+ ?.querySelector('select')
+ expect(select, label).toBeTruthy()
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'value')!.set!.call(select, value)
+ select!.dispatchEvent(new Event('change', { bubbles: true }))
+ })
+}
+const type = async (label: string, value: string) => {
+ const input = [...host.querySelectorAll('label')]
+ .find((item) => item.textContent?.startsWith(label))
+ ?.querySelector('input')
+ expect(input, label).toBeTruthy()
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, value)
+ input!.dispatchEvent(new Event('input', { bubbles: true }))
+ })
+}
+
+beforeEach(() => {
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
+ host = document.createElement('div')
+ document.body.append(host)
+ root = createRoot(host)
+})
+afterEach(async () => {
+ await act(async () => root.unmount())
+ host.remove()
+ vi.unstubAllGlobals()
+})
+
+const render = async (role: 'admin' | 'viewer' = 'admin') => {
+ await act(async () => {
+ root.render(
+
+
+
+ )
+ })
+ await flush()
+}
+
+describe('KnowledgeBaseBinding', () => {
+ it('switches environments without letting a late catalog response cross over', async () => {
+ let resolveCatalog: ((value: unknown) => void) | null = null
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn((url: string) => {
+ if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshot))
+ if (String(url).includes('/catalog')) {
+ return new Promise((resolve) => {
+ resolveCatalog = resolve
+ })
+ }
+ return Promise.resolve(json({ data: binding('test') }))
+ })
+ )
+ await render()
+ expect(host.textContent).toContain('当前生效 · 测试 090')
+ expect(host.textContent).toContain('test 内部资料(kb-test-…)')
+
+ await click('验证并读取知识库')
+ await click('生产 090')
+ expect(host.textContent).toContain('当前生效 · 生产 090')
+ expect(host.textContent).toContain('production 内部资料')
+
+ await act(async () => {
+ resolveCatalog?.(json(catalog))
+ })
+ await flush()
+ // 迟到的测试环境列库结果不得出现在生产工作区。
+ expect(host.textContent).not.toContain('新内部库')
+ expect(host.textContent).toContain('production 内部资料')
+ })
+
+ it('keeps the old binding visible when a save fails and never applies an unsaved draft', async () => {
+ const fetchMock = vi.fn((url: string, init?: { method?: string }) => {
+ if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshot))
+ if (String(url).includes('/catalog')) return Promise.resolve(json(catalog))
+ if (init?.method === 'PUT') return Promise.resolve(json({ error: '候选实例拒绝保存' }, 400))
+ return Promise.resolve(json({ data: binding('test') }))
+ })
+ vi.stubGlobal('fetch', fetchMock)
+ await render()
+ await click('验证并读取知识库')
+ await choose('对内知识库', 'kb-new-in-0001')
+ await choose('对外知识库', 'kb-new-out-0001')
+ expect(host.textContent).toContain('有未保存的修改')
+ await click('保存测试绑定')
+
+ expect(host.textContent).toContain('候选实例拒绝保存')
+ // 顶部当前生效仍是旧值;草稿只存在于下方。
+ expect(host.textContent).toContain('test 内部资料(kb-test-…)')
+ expect(host.textContent).not.toContain('当前生效 · 测试 090新内部库')
+ const put = fetchMock.mock.calls.find((call) => call[1]?.method === 'PUT')
+ expect(put).toBeTruthy()
+ const body = JSON.parse(String((put![1] as { body: string }).body))
+ expect(body).toMatchObject({
+ base_revision: 1,
+ base_url: 'https://test.weknora.example',
+ key_action: 'keep',
+ internal_kb_id: 'kb-new-in-0001',
+ external_kb_id: 'kb-new-out-0001',
+ })
+ expect(body.api_key).toBeUndefined()
+ })
+
+ it('gives viewers a read-only summary with no editing inputs', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshot)))
+ await render('viewer')
+ expect(host.textContent).toContain('普通用户只读')
+ expect(host.textContent).toContain('当前生效 · 测试 090')
+ expect(host.querySelectorAll('input')).toHaveLength(0)
+ expect(
+ [...host.querySelectorAll('button')].every((button) =>
+ ['测试 090', '生产 090'].includes(button.textContent?.trim() ?? '')
+ )
+ ).toBe(true)
+ })
+
+ it('requires a new key after the address changes and clears the previous selection', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn((url: string) => {
+ if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshot))
+ return Promise.resolve(json(catalog))
+ })
+ )
+ await render()
+ await type('服务地址', 'https://new.weknora.example')
+ expect(host.textContent).toContain('已更换服务地址:必须为新地址重新录入 API Key')
+ const selects = [...host.querySelectorAll('select')]
+ expect(selects.every((select) => select.value === '')).toBe(true)
+ const save = [...host.querySelectorAll('button')].find((button) => button.textContent?.includes('保存测试绑定'))
+ expect(save?.hasAttribute('disabled')).toBe(true)
+ })
+})
diff --git a/web/src/KnowledgeBaseBinding.tsx b/web/src/KnowledgeBaseBinding.tsx
new file mode 100644
index 0000000..6e9ce9e
--- /dev/null
+++ b/web/src/KnowledgeBaseBinding.tsx
@@ -0,0 +1,570 @@
+import { useEffect, useMemo, useRef, useState } from 'react'
+
+import { useOptionalAuth } from './auth'
+import { secretEntryAllowed } from './secureEntry'
+import {
+ KBBindingError,
+ duplicateSelection,
+ fetchKBBindings,
+ fetchKBCatalog,
+ keyActionFor,
+ knowledgeBaseLabel,
+ saveKBBinding,
+ shortKnowledgeBaseID,
+} from './knowledgeBaseBindings'
+import type {
+ KBEnvironment,
+ KBEnvironmentBinding,
+ KBBindingSnapshot,
+ KBCatalog,
+ KBCatalogOption,
+} from './knowledgeBaseBindings'
+import { validServiceEndpoint } from './uiSettings'
+
+const environments: { key: KBEnvironment; label: string; short: string }[] = [
+ { key: 'test', label: '测试 090', short: '测试' },
+ { key: 'production', label: '生产 090', short: '生产' },
+]
+
+type Busy = '' | 'catalog' | 'saving'
+type Notice = { tone: 'ok' | 'error'; text: string }
+
+interface Draft {
+ baseURL: string
+ replaceKey: boolean
+ apiKey: string
+ internalID: string
+ internalName: string
+ externalID: string
+ externalName: string
+ catalog: KBCatalog | null
+ verifiedBaseURL: string
+}
+
+type Drafts = Record
+type BusyMap = Record
+type NoticeMap = Record
+
+function draftFrom(saved: KBEnvironmentBinding): Draft {
+ return {
+ baseURL: saved.base_url,
+ replaceKey: !saved.key_configured,
+ apiKey: '',
+ internalID: saved.internal_kb_id,
+ internalName: saved.internal_kb_name,
+ externalID: saved.external_kb_id,
+ externalName: saved.external_kb_name,
+ catalog: null,
+ verifiedBaseURL: '',
+ }
+}
+
+function emptyDrafts(snapshot: KBBindingSnapshot): Drafts {
+ return { test: draftFrom(snapshot.test), production: draftFrom(snapshot.production) }
+}
+
+const sameDraft = (draft: Draft, saved: KBEnvironmentBinding): boolean =>
+ draft.baseURL.trim() === saved.base_url &&
+ !draft.replaceKey &&
+ draft.apiKey === '' &&
+ draft.internalID === saved.internal_kb_id &&
+ draft.externalID === saved.external_kb_id
+
+const statusTone = (status: KBCatalog['status']): string =>
+ status === 'ok' ? 'ok' : status === 'empty' ? 'empty' : 'error'
+
+export function KnowledgeBaseBinding() {
+ const auth = useOptionalAuth()
+ const isAdmin = auth?.identity?.role === 'admin'
+ const [snapshot, setSnapshot] = useState(null)
+ const [env, setEnv] = useState('test')
+ const [drafts, setDrafts] = useState(null)
+ const [busy, setBusy] = useState({ test: '', production: '' })
+ const [notices, setNotices] = useState({ test: null, production: null })
+ const [loadError, setLoadError] = useState(null)
+ const [loading, setLoading] = useState(true)
+ const catalogSeq = useRef(0)
+ const saveSeq = useRef(0)
+ const envRef = useRef(env)
+ const loadAbort = useRef(null)
+ const catalogAbort = useRef(null)
+ const saveAbort = useRef(null)
+ envRef.current = env
+
+ const load = async () => {
+ const controller = new AbortController()
+ loadAbort.current?.abort()
+ loadAbort.current = controller
+ setLoading(true)
+ setLoadError(null)
+ try {
+ const next = await fetchKBBindings(controller.signal)
+ if (controller.signal.aborted) return
+ setSnapshot(next)
+ setDrafts((current) => current ?? emptyDrafts(next))
+ } catch (cause) {
+ if (!controller.signal.aborted) {
+ setLoadError(cause instanceof Error ? cause.message : '读取知识库绑定失败')
+ }
+ } finally {
+ if (!controller.signal.aborted) setLoading(false)
+ }
+ }
+
+ useEffect(() => {
+ void load()
+ return () => {
+ loadAbort.current?.abort()
+ catalogAbort.current?.abort()
+ saveAbort.current?.abort()
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [])
+
+ const saved = snapshot?.[env] ?? null
+ const draft = drafts?.[env] ?? null
+ const busyNow = busy[env]
+ const notice = notices[env]
+
+ const secure = typeof window !== 'undefined' && secretEntryAllowed(window.location)
+ const storageReady = Boolean(snapshot?.storage_ready)
+ const keyAction = saved && draft ? keyActionFor(saved, draft.baseURL, draft.replaceKey) : 'replace'
+ const keyReady = keyAction === 'keep' ? Boolean(saved?.key_configured) : draft?.apiKey.trim() !== ''
+ const keyEntryBlocked = !secure || !storageReady
+ const endpointValid = draft ? validServiceEndpoint(draft.baseURL) && draft.baseURL.trim() !== '' : false
+ const duplicate = draft ? duplicateSelection(draft.internalID, draft.externalID) : false
+ const catalogReady = Boolean(
+ draft?.catalog &&
+ draft.verifiedBaseURL === draft.baseURL &&
+ (draft.catalog.status === 'ok' || draft.catalog.status === 'empty')
+ )
+ const dirty = Boolean(saved && draft && !sameDraft(draft, saved))
+ const canSave = Boolean(
+ isAdmin &&
+ saved &&
+ draft &&
+ dirty &&
+ !busyNow &&
+ storageReady &&
+ endpointValid &&
+ keyReady &&
+ !duplicate &&
+ catalogReady
+ )
+
+ const patchDraft = (patch: Partial) => {
+ setDrafts((current) => (current ? { ...current, [env]: { ...current[env], ...patch } } : current))
+ setNotices((current) => ({ ...current, [env]: null }))
+ }
+
+ const switchEnvironment = (next: KBEnvironment) => {
+ if (next === env) return
+ // 切换只作废在途列库:迟到结果不得写进另一个环境的工作区。
+ // 保存按目标环境落库,响应也只更新该环境的状态,切回来仍是真实结果。
+ catalogSeq.current++
+ catalogAbort.current?.abort()
+ setEnv(next)
+ }
+
+ const onBaseURLChange = (value: string) => {
+ if (!saved) return
+ const changed = value.trim() !== saved.base_url
+ patchDraft({
+ baseURL: value,
+ replaceKey: changed ? true : !saved.key_configured,
+ internalID: '',
+ internalName: '',
+ externalID: '',
+ externalName: '',
+ catalog: null,
+ verifiedBaseURL: '',
+ })
+ }
+
+ const runCatalog = async (page: number) => {
+ if (!saved || !draft) return
+ if (!endpointValid) {
+ setNotices((current) => ({
+ ...current,
+ [env]: { tone: 'error', text: '请填写有效的 http(s) 服务地址(不能带用户名、? 查询串或 #)' },
+ }))
+ return
+ }
+ if (keyAction === 'replace' && draft.apiKey.trim() === '') {
+ setNotices((current) => ({ ...current, [env]: { tone: 'error', text: '请先填入这个地址的 API Key' } }))
+ return
+ }
+ if (keyAction === 'keep' && !saved.key_configured) {
+ setNotices((current) => ({ ...current, [env]: { tone: 'error', text: '当前连接还没有可用密钥,请先录入' } }))
+ return
+ }
+ const targetEnv = env
+ const seq = ++catalogSeq.current
+ const controller = new AbortController()
+ catalogAbort.current = controller
+ setBusy((current) => ({ ...current, [targetEnv]: 'catalog' }))
+ setNotices((current) => ({ ...current, [targetEnv]: null }))
+ try {
+ const catalog = await fetchKBCatalog(
+ targetEnv,
+ {
+ base_revision: saved.revision,
+ base_url: draft.baseURL.trim(),
+ key_action: keyAction,
+ ...(keyAction === 'replace' ? { api_key: draft.apiKey } : {}),
+ page,
+ page_size: 20,
+ },
+ controller.signal
+ )
+ if (controller.signal.aborted || seq !== catalogSeq.current || envRef.current !== targetEnv) return
+ setDrafts((current) => {
+ if (!current) return current
+ return {
+ ...current,
+ [targetEnv]: { ...current[targetEnv], catalog, verifiedBaseURL: draft.baseURL.trim() },
+ }
+ })
+ } catch (cause) {
+ if (controller.signal.aborted || seq !== catalogSeq.current || envRef.current !== targetEnv) return
+ setNotices((current) => ({
+ ...current,
+ [targetEnv]: { tone: 'error', text: cause instanceof Error ? cause.message : '读取知识库列表失败' },
+ }))
+ } finally {
+ setBusy((current) => ({ ...current, [targetEnv]: '' }))
+ }
+ }
+
+ const runSave = async () => {
+ if (!saved || !draft || !canSave) return
+ const targetEnv = env
+ const seq = ++saveSeq.current
+ const controller = new AbortController()
+ saveAbort.current = controller
+ setBusy((current) => ({ ...current, [targetEnv]: 'saving' }))
+ setNotices((current) => ({ ...current, [targetEnv]: null }))
+ try {
+ const view = await saveKBBinding(
+ targetEnv,
+ {
+ base_revision: saved.revision,
+ base_url: draft.baseURL.trim(),
+ key_action: keyAction,
+ ...(keyAction === 'replace' ? { api_key: draft.apiKey } : {}),
+ internal_kb_id: draft.internalID,
+ external_kb_id: draft.externalID,
+ },
+ controller.signal
+ )
+ if (controller.signal.aborted || seq !== saveSeq.current) return
+ setSnapshot((current) => (current ? { ...current, [targetEnv]: view } : current))
+ setDrafts((current) => (current ? { ...current, [targetEnv]: draftFrom(view) } : current))
+ const replan =
+ view.replanned || view.retired_duplicates
+ ? `;同时把 ${view.replanned} 项未上传的待入库重新指向新库${view.retired_duplicates ? `,${view.retired_duplicates} 项因新库已有同篇而退休` : ''}`
+ : ''
+ setNotices((current) => ({
+ ...current,
+ [targetEnv]: {
+ tone: 'ok',
+ text: `已保存${environments.find((item) => item.key === targetEnv)?.short}绑定:对内 ${
+ view.internal_kb_name || shortKnowledgeBaseID(view.internal_kb_id) || '未绑定'
+ } · 对外 ${view.external_kb_name || shortKnowledgeBaseID(view.external_kb_id) || '未绑定'}${replan}`,
+ },
+ }))
+ } catch (cause) {
+ if (controller.signal.aborted || seq !== saveSeq.current) return
+ const message = cause instanceof Error ? cause.message : '保存知识库绑定失败'
+ setNotices((current) => ({ ...current, [targetEnv]: { tone: 'error', text: message } }))
+ if (cause instanceof KBBindingError && cause.status === 409) {
+ // 冲突:重新读取服务器生效值,保留草稿但作废这次列库结论,必须按新版本重验。
+ try {
+ const fresh = await fetchKBBindings()
+ if (seq !== saveSeq.current) return
+ setSnapshot(fresh)
+ setDrafts((current) =>
+ current
+ ? { ...current, [targetEnv]: { ...current[targetEnv], catalog: null, verifiedBaseURL: '' } }
+ : current
+ )
+ } catch {
+ /* 读取失败时保留现有显示,错误信息已经可见 */
+ }
+ }
+ } finally {
+ setBusy((current) => ({ ...current, [targetEnv]: '' }))
+ }
+ }
+
+ const currentOptions = useMemo<{ internal: KBCatalogOption[]; external: KBCatalogOption[] }>(() => {
+ const base = draft?.catalog?.options ?? []
+ const withSelection = (id: string, name: string): KBCatalogOption[] => {
+ if (!id || base.some((option) => option.id === id)) return base
+ return [{ id, name: name || shortKnowledgeBaseID(id), knowledge_count: 0 }, ...base]
+ }
+ return {
+ internal: draft ? withSelection(draft.internalID, draft.internalName) : [],
+ external: draft ? withSelection(draft.externalID, draft.externalName) : [],
+ }
+ }, [draft])
+
+ const renderCurrent = (binding: KBEnvironmentBinding) => (
+
+
当前生效 · {environments.find((item) => item.key === binding.environment)?.label}
+
+
+ 对内 {knowledgeBaseLabel(binding.internal_kb_id, binding.internal_kb_name)}
+
+
+ 对外 {knowledgeBaseLabel(binding.external_kb_id, binding.external_kb_name)}
+
+
+
+ {binding.base_url || '未配置服务地址'} ·{' '}
+ {binding.key_configured
+ ? binding.key_source === 'file'
+ ? 'API Key 来自服务器文件'
+ : 'API Key 已配置(不回显)'
+ : 'API Key 未配置'}
+ {binding.source === 'legacy' ? ' · 旧部署配置' : ` · 版本 ${binding.revision}`}
+
+
+ )
+
+ if (!isAdmin) {
+ return (
+
+
+
+
知识库绑定
+
普通用户只读:这里显示当前生效的连接与内外库绑定。
+
+
+
+ {saved ? renderCurrent(saved) : loading ? 正在读取知识库绑定…
: null}
+ {loadError ? (
+
+ {loadError}
+
+ ) : null}
+
+ )
+ }
+
+ return (
+
+
+
+
知识库绑定
+
+ 一次保存当前环境的连接与对内/对外绑定。地址与密钥由服务器真实列库核验;顶部始终是已生效的值,
+ 下面的修改只是草稿。
+
+
+
+
+ {saved ? renderCurrent(saved) : loading ? 正在读取知识库绑定…
: null}
+ {loadError ? (
+
+ {loadError}
+
+ ) : null}
+ {!storageReady && snapshot ? (
+
+ 独立安全存储未就绪(服务器未配置 WEKNORA_BINDING_MASTER_KEY_FILE):可以查看旧绑定,但不能保存新连接。
+
+ ) : null}
+ {saved && draft ? (
+ <>
+
+ WeKnora 连接 · {environments.find((item) => item.key === env)?.label}
+ {env === 'production' ? (
+
+ 生产连接用于候选列库与探活;文档级/整库发布实际写入目标仍由部署配置决定(见下方诊断)。
+
+ ) : null}
+
+
+
+
API Key
+ {saved.key_configured && !draft.replaceKey ? (
+
+ 已配置(不回显){saved.key_source === 'file' ? ' · 服务器文件' : ''}
+ patchDraft({ replaceKey: true, apiKey: '' })}
+ disabled={busyNow !== ''}
+ >
+ 更换密钥
+
+
+ ) : (
+
+
+ patchDraft({ apiKey: event.target.value, catalog: null, verifiedBaseURL: '' })
+ }
+ autoComplete="new-password"
+ spellCheck={false}
+ placeholder={saved.key_configured ? '输入新密钥;保存后才生效' : '仅用于此治理平台'}
+ disabled={busyNow !== '' || keyEntryBlocked}
+ aria-invalid={keyEntryBlocked}
+ />
+ {saved.key_configured && draft.baseURL.trim() === saved.base_url ? (
+ patchDraft({ replaceKey: false, apiKey: '' })}
+ disabled={busyNow !== ''}
+ >
+ 取消更换
+
+ ) : null}
+
+ )}
+
+
+ {!secure ? (
+ 当前不是安全密钥录入连接:请用有效 HTTPS 或本机 localhost 录入新密钥。
+ ) : null}
+ {saved.base_url && draft.baseURL.trim() !== saved.base_url && saved.key_configured ? (
+ 已更换服务地址:必须为新地址重新录入 API Key,旧密钥不会发往新地址。
+ ) : null}
+
+ void runCatalog(draft.catalog?.page ?? 1)}
+ disabled={busyNow !== '' || !endpointValid || (keyAction === 'replace' && draft.apiKey.trim() === '')}
+ >
+ {busyNow === 'catalog' ? '正在验证并读取…' : '验证并读取知识库'}
+
+ 服务器会用这份地址与密钥真实列库,只读,不写入。
+
+ {draft.catalog ? (
+
+ {draft.catalog.message}
+ {draft.catalog.total > 0
+ ? ` · 第 ${draft.catalog.page} / ${Math.max(1, Math.ceil(draft.catalog.total / draft.catalog.page_size))} 页`
+ : ''}
+ {draft.catalog.total > draft.catalog.page_size ? (
+
+ void runCatalog(Math.max(1, draft.catalog!.page - 1))}
+ disabled={busyNow !== '' || draft.catalog.page <= 1}
+ >
+ 上一页
+
+ void runCatalog(draft.catalog!.page + 1)}
+ disabled={busyNow !== '' || draft.catalog.page * draft.catalog.page_size >= draft.catalog.total}
+ >
+ 下一页
+
+
+ ) : null}
+
+ ) : (
+ 验证并读取后,才能从这份连接可读的库里选择。
+ )}
+
+
+ 选择已有知识库
+
+
+
+
+ 名称相同很常见,括号里的短 ID 才是区分依据;对内与对外不能选同一个库。
+ {duplicate ? 对内和对外不能绑定同一个知识库。
: null}
+
+
+
+ {notice?.text || (dirty ? '有未保存的修改;当前生效值未改变' : '草稿与当前生效值一致')}
+
+ void runSave()} disabled={!canSave}>
+ {busyNow === 'saving'
+ ? '正在校验并保存…'
+ : `保存${environments.find((item) => item.key === env)?.short}绑定`}
+
+
+ >
+ ) : null}
+
+ )
+}
diff --git a/web/src/ProductionBindingsSection.tsx b/web/src/ProductionBindingsSection.tsx
index 251d841..bf3b889 100644
--- a/web/src/ProductionBindingsSection.tsx
+++ b/web/src/ProductionBindingsSection.tsx
@@ -22,6 +22,7 @@ export interface ProductionBindingsViewProps {
message: string
dirty: boolean
sameSelection: boolean
+ diagnosticsOnly?: boolean
onInternalChange: (next: string) => void
onExternalChange: (next: string) => void
onSave: () => void
@@ -41,6 +42,7 @@ export function ProductionBindingsView(props: ProductionBindingsViewProps) {
message,
dirty,
sameSelection,
+ diagnosticsOnly = false,
onInternalChange,
onExternalChange,
onSave,
@@ -161,7 +163,7 @@ export function ProductionBindingsView(props: ProductionBindingsViewProps) {
{bindings.updated_by ? ` · 最近修改:${bindings.updated_by}` : ''}
) : null}
- {isAdmin && bindings ? (
+ {!diagnosticsOnly && isAdmin && bindings ? (
@@ -178,13 +180,13 @@ export function ProductionBindingsView(props: ProductionBindingsViewProps) {
) : null}
) : null}
- {!isAdmin ? 仅管理员可修改文档级发布目标。
: null}
+ {!diagnosticsOnly && !isAdmin ? 仅管理员可修改文档级发布目标。
: null}
)
}
// 容器:读取 + 保存。整库目标只读展示,保存动作只写文档级绑定。
-export function ProductionBindingsSection() {
+export function ProductionBindingsSection({ diagnosticsOnly = false }: { diagnosticsOnly?: boolean } = {}) {
const auth = useOptionalAuth()
const isAdmin = auth?.identity?.role === 'admin'
const [bindings, setBindings] = useState(null)
@@ -256,6 +258,7 @@ export function ProductionBindingsSection() {
message={message}
dirty={dirty}
sameSelection={sameSelection}
+ diagnosticsOnly={diagnosticsOnly}
onInternalChange={setInternalDraft}
onExternalChange={setExternalDraft}
onSave={() => void save()}
diff --git a/web/src/QAModelSettings.tsx b/web/src/QAModelSettings.tsx
index 2ca587c..7dd47e6 100644
--- a/web/src/QAModelSettings.tsx
+++ b/web/src/QAModelSettings.tsx
@@ -3,9 +3,9 @@ import type { AISettings } from './qaAITypes'
import type { AISettingsInput } from './qaAI'
import { fetchAISettings, saveAISettings, testAISettings } from './qaAI'
import { QARequestError } from './qaOps'
-export function qaAIKeyEntryAllowed(location: { protocol: string; hostname: string }) {
- return location.protocol === 'https:' || ['localhost', '127.0.0.1', '[::1]', '::1'].includes(location.hostname)
-}
+import { secretEntryAllowed } from './secureEntry'
+// 兼容既有导入:密钥录入的安全判定只有一份,实现已移到 secureEntry。
+export const qaAIKeyEntryAllowed = secretEntryAllowed
const verificationLabels: Record = {
not_configured: '未配置可用密钥',
verified: '已通过真实连接测试',
diff --git a/web/src/RoutingBindingsSection.tsx b/web/src/RoutingBindingsSection.tsx
index 16c0400..a5c50df 100644
--- a/web/src/RoutingBindingsSection.tsx
+++ b/web/src/RoutingBindingsSection.tsx
@@ -4,7 +4,7 @@ import { useOptionalAuth } from './auth'
import { fetchRoutingBindingOptions, fetchRoutingBindings, saveRoutingBindings } from './routingBindings'
import type { KnowledgeBaseOption, RoutingBindings } from './routingBindings'
-export function RoutingBindingsSection() {
+export function RoutingBindingsSection({ diagnosticsOnly = false }: { diagnosticsOnly?: boolean } = {}) {
const auth = useOptionalAuth()
const isAdmin = auth?.identity?.role === 'admin'
const [bindings, setBindings] = useState(null)
@@ -168,7 +168,7 @@ export function RoutingBindingsSection() {
{bindings && !bindings.weknora_connected ? (
当前读不到 WeKnora 的库列表,只能按 ID 填写;连接恢复后可改为下拉选择。
) : null}
- {isAdmin && bindings ? (
+ {!diagnosticsOnly && isAdmin && bindings ? (
@@ -184,7 +184,7 @@ export function RoutingBindingsSection() {
) : null}
) : null}
- {!isAdmin ? 仅管理员可修改测试知识库绑定。
: null}
+ {!diagnosticsOnly && !isAdmin ? 仅管理员可修改测试知识库绑定。
: null}
)
}
diff --git a/web/src/SystemSettings.test.tsx b/web/src/SystemSettings.test.tsx
index aee2cf8..253baab 100644
--- a/web/src/SystemSettings.test.tsx
+++ b/web/src/SystemSettings.test.tsx
@@ -141,13 +141,13 @@ describe('SystemSettingsView AI 模型连接', () => {
/>
)
- it('keeps the model connection alone in AI 模型连接 and points WeKnora to 知识库映射', () => {
+ it('keeps the model connection alone in AI 模型连接 and points WeKnora to 知识库绑定', () => {
const adminHtml = view('admin')
for (const text of [
'AI 模型连接',
'正在读取已保存的模型连接',
'问答四字段分析与中文问题翻译共用此连接',
- 'WeKnora 的知识库连接已移到「知识库映射」',
+ 'WeKnora 的知识库连接已移到「知识库绑定」',
]) {
expect(adminHtml).toContain(text)
}
@@ -179,7 +179,7 @@ describe('SystemSettingsView', () => {
onRefresh={vi.fn()}
/>
)
- for (const text of ['系统设置', '数据源配置', 'AI 模型连接', '知识库映射', '存储与备份', '刷新策略'])
+ for (const text of ['系统设置', '数据源配置', 'AI 模型连接', '知识库绑定', '存储与备份', '刷新策略'])
expect(html).toContain(text)
// 主人 2026-10-26 要求去掉的噪声:页头副标题、刷新状态、权限条、活动版本横幅。
for (const removed of [
@@ -202,7 +202,7 @@ describe('SystemSettingsView', () => {
expect(html).not.toContain(removed)
// 需求(2026-10-10):新增入口只剩「可加入的来源」勾选,粘贴链接的按钮已下线。
for (const removed of ['+ 新增钉钉知识库', '新增钉钉知识库']) expect(html).not.toContain(removed)
- // WeKnora 连接已迁到「知识库映射」:地址与核验参数跟入库/封存/生产目标同屏。
+ // WeKnora 连接已迁到「知识库绑定」:主表单保存连接+绑定,诊断折叠保留。
const mapHtml = renderToStaticMarkup(
{
)
for (const text of [
- 'WeKnora 连接',
+ '知识库绑定',
+ '测试 090',
+ '生产 090',
+ '正在读取知识库绑定…',
+ '连接与绑定诊断',
'测试 WeKnora',
'生产 WeKnora',
- '测试地址',
- '生产地址',
- '生产租户 ID',
- '知识库 ID',
- '保存并校验连接',
- '生产核验参数',
+ '整库发布目标',
])
expect(mapHtml).toContain(text)
- // 凭据是服务器文件引用:连接卡只报状态,页面不提供 API Key 录入。
+ // 旧连接表单已被单一保存入口取代;SSR 尚未读到绑定时不渲染密钥输入。
+ for (const removed of ['保存并校验连接', '测试地址', '生产租户 ID', '生产核验参数'])
+ expect(mapHtml).not.toContain(removed)
expect(mapHtml).not.toContain('API Key')
const storageHtml = renderToStaticMarkup(
{
/>
)
- // 测试绑定与生产目标已合并为「知识库映射」:入库目标、封存源、生产目标同屏。
- expect(view('sources')).toContain('知识库映射')
+ // 旧入口(bindings / production-bindings)都落到「知识库绑定」:新主表单 + 折叠诊断。
+ expect(view('sources')).toContain('知识库绑定')
const bound = view('bindings')
+ expect(bound).toContain('id="settings-kb-bindings"')
+ expect(bound).toContain('知识库绑定')
+ expect(bound).toContain('正在读取知识库绑定…')
+ expect(bound).toContain('连接与绑定诊断')
+ // 诊断区保留原链路:测试入库绑定与生产目标入口仍在,但不再提供第二个保存路径。
expect(bound).toContain('id="settings-routing-bindings"')
expect(bound).toContain('分发到对应的测试 WeKnora 知识库')
- // 未读到绑定数据时(SSR 不跑 effect)面板也要如实存在,而不是空白。
- expect(bound).toContain('读取中…')
- // 发布目标(源库 → 目标库)是独立分区,与测试端收件库分开。
const target = view('production-bindings')
expect(target).toContain('id="settings-production-bindings"')
expect(target).toContain('整库发布目标')
@@ -437,7 +440,7 @@ describe('SystemSettingsView', () => {
expect(on).toContain('延迟 86ms')
expect(on).toContain('已启用 · 可提交生产请求')
expect(on).toContain('生产写入:开启')
- expect(on).toContain('凭据:服务器文件引用,页面不回读')
+ expect(on).toContain('凭据:服务器文件/加密存储,页面不回读')
const off = view(false, false)
expect(off).toContain('未启用')
expect(off).toContain('生产写入:关闭')
diff --git a/web/src/SystemSettings.tsx b/web/src/SystemSettings.tsx
index 26648a3..e61a57d 100644
--- a/web/src/SystemSettings.tsx
+++ b/web/src/SystemSettings.tsx
@@ -9,6 +9,8 @@ import { RoutingBindingsSection } from './RoutingBindingsSection'
import { ProductionBindingsSection } from './ProductionBindingsSection'
import { SourceWizard } from './SourceWizard'
import { PPConnection } from './PPConnection'
+import { KnowledgeBaseBinding } from './KnowledgeBaseBinding'
+import { WeKnoraConnectionDiagnostics } from './weKnoraDiagnostics'
import { useOptionalAuth } from './auth'
import { fetchMonitorOverview } from './monitor'
import type { MonitorOverview } from './monitor'
@@ -22,10 +24,9 @@ import type { SourceConnectionListItem } from './sourceConnections'
import { activateUISettings, createUISettingsCandidate, fetchActiveUISettings } from './uiSettings'
import type { UISettings, UISettingsCandidateInput } from './uiSettings'
import { refreshSettingsInput } from './settingsInputs'
-import { WeKnoraConnections } from './WeKnoraConnections'
import './systemSettings.css'
-// 连接配置已从「服务配置」迁到「知识库映射」。这两个纯函数仍从本模块导出,
+// 连接配置已从「服务配置」迁到「知识库绑定」。这两个纯函数仍从本模块导出,
// 既有调用与回归测试的导入路径不变。
export { refreshSettingsInput, serviceSettingsInput } from './settingsInputs'
export type { RefreshDrafts, ServiceDrafts } from './settingsInputs'
@@ -46,16 +47,16 @@ interface Props {
onSave: (input: UISettingsCandidateInput) => void
onSourcesChanged: () => void
onRefresh: () => void
- // 兼容旧入口:'bindings'/'production-bindings' 已合并为“知识库映射”。
- initialSection?: SectionKey | 'bindings' | 'production-bindings'
+ // 兼容旧入口:'bindings'/'production-bindings'/'knowledge-map' 都落到「知识库绑定」。
+ initialSection?: SectionKey | 'bindings' | 'production-bindings' | 'knowledge-map'
}
-type SectionKey = 'sources' | 'services' | 'knowledge-map' | 'storage' | 'refresh' | 'members'
+type SectionKey = 'sources' | 'services' | 'knowledge-bindings' | 'storage' | 'refresh' | 'members'
const sections: { key: SectionKey; label: string; adminOnly?: boolean }[] = [
{ key: 'sources', label: '数据源配置' },
{ key: 'services', label: 'AI 模型连接' },
- { key: 'knowledge-map', label: '知识库映射' },
+ { key: 'knowledge-bindings', label: '知识库绑定' },
{ key: 'storage', label: '存储与备份' },
{ key: 'refresh', label: '刷新策略' },
{ key: 'members', label: '成员与角色', adminOnly: true },
@@ -99,8 +100,8 @@ export function SystemSettingsView({
const auth = useOptionalAuth()
const identity = auth?.identity ?? null
const [section, setSection] = useState(
- initialSection === 'bindings' || initialSection === 'production-bindings'
- ? 'knowledge-map'
+ initialSection === 'bindings' || initialSection === 'production-bindings' || initialSection === 'knowledge-map'
+ ? 'knowledge-bindings'
: (initialSection as SectionKey)
)
const [documentRefresh, setDocumentRefresh] = useState<15 | 30 | 60>(settings?.document_refresh_seconds ?? 15)
@@ -133,7 +134,7 @@ export function SystemSettingsView({
finalizing !== settings.finalizing_after_seconds ||
concurrency !== settings.ingestion_concurrency)
)
- // 保存边界:刷新分区只带刷新草稿;WeKnora 连接草稿在 WeKnoraConnections 内独立保存,
+ // 保存边界:刷新分区只带刷新草稿;知识库绑定的连接/选库草稿在独立组件内一次保存,
// 互不夹带(未保存的地址不会因为保存刷新策略被写进去)。
const refreshInput = (): UISettingsCandidateInput =>
settings
@@ -210,36 +211,35 @@ export function SystemSettingsView({
AI 模型连接
问答四字段分析与中文问题翻译共用此连接;保存只更新这份连接,不会自动开启自动分析或自动翻译。
- WeKnora 的知识库连接已移到「知识库映射」。
+ WeKnora 的知识库连接已移到「知识库绑定」。
{isAdmin ? : 仅管理员可修改模型连接;密钥不回显。}
) : null}
- {section === 'knowledge-map' ? (
+ {section === 'knowledge-bindings' ? (
<>
- {settings ? (
-
- ) : null}
-
- 一张图看清三件事:入库目标(来源打标分发到此库)、
- 封存源(整库封存实际导出的库)、生产目标(同步写入的库)。
- 前两者不一致时,发布页显示的名字与封存出来的内容会对不上。
-
-
-
+
+
+ 连接与绑定诊断(探活、封存源、整库发布目标)
+ {settings ? (
+
+ ) : null}
+
+ 封存源是整库封存实际导出的库;整库发布目标由部署配置决定、只读。两者与上面的入库绑定不一致时,
+ 发布页显示的名字与封存出来的内容会对不上。
+
+
+
+
>
) : null}
{section === 'storage' ? (
@@ -254,7 +254,7 @@ export function SystemSettingsView({
刷新策略
-
保存只改这一组参数,不会带上「知识库映射」里未保存的连接地址。
+
保存只改这一组参数,不会带上「知识库绑定」里未保存的连接地址。
当前活动版本
diff --git a/web/src/WeKnoraConnections.mounted.test.tsx b/web/src/WeKnoraConnections.mounted.test.tsx
deleted file mode 100644
index f3cdeac..0000000
--- a/web/src/WeKnoraConnections.mounted.test.tsx
+++ /dev/null
@@ -1,130 +0,0 @@
-// @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 { WeKnoraConnections } from './WeKnoraConnections'
-import type { UISettings } from './uiSettings'
-
-const settings: UISettings = {
- id: 'settings-live',
- state: 'active',
- document_refresh_seconds: 30,
- resource_refresh_seconds: 60,
- stalled_after_seconds: 3600,
- finalizing_after_seconds: 14400,
- ingestion_concurrency: 4,
- test_weknora_base_url: 'https://server.test',
- production_weknora_base_url: 'https://server.prod',
- production_tenant_id: '10000',
- production_knowledge_base_id: 'kb-server',
- updated_by: 'admin-1',
- created_at: '2026-11-18T08:00:00Z',
- activated_at: '2026-11-18T08:00:00Z',
- retired_at: null,
- error_code: '',
-}
-let root: Root
-let host: HTMLDivElement
-const click = async (label: string) => {
- const button = [...host.querySelectorAll('button')].find((x) => x.textContent?.trim() === label)
- expect(button, label).toBeTruthy()
- await act(async () => button!.click())
-}
-const type = async (label: string, value: string) => {
- const input = [...host.querySelectorAll('label')]
- .find((x) => x.textContent?.startsWith(label))
- ?.querySelector('input')
- expect(input, label).toBeTruthy()
- await act(async () => {
- Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, value)
- input!.dispatchEvent(new Event('input', { bubbles: true }))
- })
-}
-beforeEach(() => {
- Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
- host = document.createElement('div')
- document.body.append(host)
- root = createRoot(host)
-})
-afterEach(async () => {
- await act(async () => root.unmount())
- host.remove()
-})
-
-describe('WeKnoraConnections', () => {
- it('保存只带连接草稿,刷新参数取服务器当前值', async () => {
- const onSave = vi.fn()
- await act(async () =>
- root.render(
-
- )
- )
- await type('测试地址', 'https://draft.test')
- await click('保存并校验连接')
- expect(onSave).toHaveBeenCalledTimes(1)
- expect(onSave.mock.calls[0][0]).toMatchObject({
- test_weknora_base_url: 'https://draft.test',
- production_weknora_base_url: 'https://server.prod',
- production_tenant_id: '10000',
- production_knowledge_base_id: 'kb-server',
- document_refresh_seconds: 30,
- ingestion_concurrency: 4,
- })
- })
-
- it('未修改时保存按钮不可点,非法地址也不允许提交', async () => {
- const onSave = vi.fn()
- await act(async () =>
- root.render(
-
- )
- )
- const saveButton = () =>
- [...host.querySelectorAll('button')].find((x) => x.textContent?.trim() === '保存并校验连接') as
- HTMLButtonElement | undefined
- expect(saveButton()?.disabled).toBe(true)
- await type('生产地址', 'https://draft.prod/?token=x')
- expect(saveButton()?.disabled).toBe(true)
- expect(host.textContent).toContain('格式不合法')
- await click('保存并校验连接')
- expect(onSave).not.toHaveBeenCalled()
- })
-
- it('工程师只看到只读摘要,没有保存入口', async () => {
- await act(async () =>
- root.render(
-
- )
- )
- expect(host.textContent).toContain('仅管理员可修改 WeKnora 连接')
- expect(host.textContent).toContain('https://server.test')
- expect([...host.querySelectorAll('button')]).toHaveLength(0)
- })
-})
diff --git a/web/src/WeKnoraConnections.tsx b/web/src/WeKnoraConnections.tsx
deleted file mode 100644
index 153cba5..0000000
--- a/web/src/WeKnoraConnections.tsx
+++ /dev/null
@@ -1,242 +0,0 @@
-import { useEffect, useState } from 'react'
-
-import type { MonitorOverview } from './monitor'
-import { serviceSettingsInput } from './settingsInputs'
-import type { CatalogRoutingCapabilities } from './sourceCatalog'
-import type { WorkerCapabilities } from './systemCapabilities'
-import { testUploadLabel } from './systemCapabilities'
-import { validKnowledgeBaseID, validProductionTenantID, validServiceEndpoint } from './uiSettings'
-import type { UISettings, UISettingsCandidateInput } from './uiSettings'
-
-type ServiceHealthView = MonitorOverview['health'][number]
-type ServiceView = MonitorOverview['services'][number]
-
-// 连接分区只保留四项可写值(测试地址、生产地址、生产 ID、知识库 ID),
-// 依赖与解析队列的状态仍按真实探测呈现,不写死。
-export const findHealth = (monitor: MonitorOverview | null, name: string): ServiceHealthView | undefined =>
- (monitor?.health || []).find((item) => item.name === name || item.name.startsWith(name))
-export const healthStateLabel = (health: ServiceHealthView | undefined, service: ServiceView | undefined): string => {
- if (!health) {
- if (!service) return '待配置'
- return service.state === 'healthy' ? '正常' : service.state === 'unknown' ? '未接入' : '需关注'
- }
- if (health.readiness === 'ready') return '可达 · 可接单'
- if (health.readiness === 'not_configured') return '状态未知 · 未配置'
- if (health.readiness === 'not_applicable') return '未部署'
- return health.liveness === 'up' ? '可达 · 不可接单' : '不可达 · 不可接单'
-}
-
-// 测试 WeKnora 卡片只证明“接口就绪”:readiness 不覆盖上传/解析执行器,
-// 所以不能沿用“可接单”这种承诺式措辞。
-export const testWeKnoraLabel = (health: ServiceHealthView | undefined, service: ServiceView | undefined): string => {
- const label = healthStateLabel(health, service)
- return label === '可达 · 可接单' ? '接口可达 · 执行器未验证' : label
-}
-
-export const healthStateDetail = (health: ServiceHealthView | undefined, service: ServiceView | undefined): string => {
- if (!health) return service?.detail || '真实 Provider 未接入'
- const success = health.last_success_at
- ? `最近成功 ${new Date(health.last_success_at).toLocaleTimeString('zh-CN', { hour12: false })}`
- : ''
- if (health.readiness === 'ready') return [`延迟 ${health.latency_ms}ms`, success].filter(Boolean).join(';')
- const failures = health.consecutive_failures ? `连续失败${health.consecutive_failures}次` : ''
- return [health.reason, success, failures].filter(Boolean).join(';')
-}
-
-// 生产 WeKnora 卡片:端点可达性来自真实探测,写入门禁来自生产开关,两者分开呈现。
-// 生产侧只做探活(/health),不做一次真实读写,所以接单能力永远是「未做接单验证」,
-// 不跟着别处的「可达 · 可接单」一起含糊过去。
-export const productionWeKnoraProbe = (monitor: MonitorOverview | null): string => {
- const health = findHealth(monitor, '生产 WeKnora')
- if (!health) return '端点探测:暂无真实探测结果'
- if (!health.configured) return '端点探测:未配置'
- const label =
- health.liveness === 'up'
- ? health.readiness === 'ready'
- ? '端点可达 · 未做接单验证'
- : '端点可达 · 不可接单'
- : '端点不可达'
- const detail = healthStateDetail(health, undefined)
- return `端点探测:${label}${detail ? `(${detail})` : ''}`
-}
-
-export interface WeKnoraConnectionsProps {
- settings: UISettings
- monitor: MonitorOverview | null
- routingCapabilities: CatalogRoutingCapabilities
- workerCapabilities?: WorkerCapabilities | null
- productionEnabled: boolean
- productionBackupRestoreVerified?: boolean
- isAdmin: boolean
- saving: boolean
- saveMessage: string | null
- onSave: (input: UISettingsCandidateInput) => void
-}
-
-// 「知识库映射 → WeKnora 连接」:地址由管理员在页面维护,保存前后端会真做一次
-// 探活与列库核验;凭据仍是服务器文件引用,页面只显示状态、不回读也不接受录入。
-export function WeKnoraConnections({
- settings,
- monitor,
- routingCapabilities,
- workerCapabilities = null,
- productionEnabled,
- productionBackupRestoreVerified = false,
- isAdmin,
- saving,
- saveMessage,
- onSave,
-}: WeKnoraConnectionsProps) {
- const [endpoint, setEndpoint] = useState(settings.production_weknora_base_url ?? '')
- const [testEndpoint, setTestEndpoint] = useState(settings.test_weknora_base_url ?? '')
- const [productionTenantID, setProductionTenantID] = useState(settings.production_tenant_id ?? '')
- const [productionKnowledgeBaseID, setProductionKnowledgeBaseID] = useState(
- settings.production_knowledge_base_id ?? ''
- )
-
- useEffect(() => {
- setEndpoint(settings.production_weknora_base_url)
- setTestEndpoint(settings.test_weknora_base_url)
- setProductionTenantID(settings.production_tenant_id)
- setProductionKnowledgeBaseID(settings.production_knowledge_base_id)
- }, [settings])
-
- const endpointValid = validServiceEndpoint(endpoint)
- const testEndpointValid = validServiceEndpoint(testEndpoint)
- const productionTenantIDValid = validProductionTenantID(productionTenantID)
- const productionKnowledgeBaseIDValid = validKnowledgeBaseID(productionKnowledgeBaseID)
- const valid = endpointValid && testEndpointValid && productionTenantIDValid && productionKnowledgeBaseIDValid
- const dirty =
- testEndpoint.trim() !== settings.test_weknora_base_url ||
- endpoint.trim() !== settings.production_weknora_base_url ||
- productionTenantID.trim() !== settings.production_tenant_id ||
- productionKnowledgeBaseID.trim() !== settings.production_knowledge_base_id
-
- return (
-
-
-
-
WeKnora 连接
-
- 测试与生产各自的地址在这里维护;保存前后端会真做一次探活与列库核验。凭据由服务器文件引用提供,
- 页面只显示是否已配置,不回读、也不能在这里录入。
-
-
-
-
-
- 测试 WeKnora
- {testWeKnoraLabel(findHealth(monitor, 'WeKnora API'), undefined)}
- {`${healthStateDetail(findHealth(monitor, 'WeKnora API'), undefined) || '端点探测:未配置'};解析队列 对内 ${routingCapabilities.internal_enabled ? '已配置' : '未配置'} · 对外 ${routingCapabilities.external_enabled ? '已配置' : '未配置'}`}
-
- {testUploadLabel(workerCapabilities)}
- {workerCapabilities ? `:${workerCapabilities.test_upload.detail}` : ''}
-
-
-
- 生产 WeKnora
-
- {!productionEnabled
- ? '未启用'
- : productionBackupRestoreVerified
- ? '已启用 · 可提交生产请求'
- : '已启用 · 被阻断'}
-
- {`${productionWeKnoraProbe(monitor)};生产写入:${productionEnabled ? '开启' : '关闭'};凭据:服务器文件引用,页面不回读`}
-
-
- {isAdmin ? (
- <>
-
-
-
-
-
- 生产核验参数(仅用于核验,不决定发布写入目标)
-
-
-
-
-
- 这两项用于确认生产端确实存在目标库、租户归属正确;整库发布的实际写入目标见下方「生产知识库绑定」,
- 由部署配置决定,不在本页修改。
-
-
-
- onSave(
- serviceSettingsInput(settings, {
- testEndpoint,
- endpoint,
- productionTenantID,
- productionKnowledgeBaseID,
- })
- )
- }
- disabled={saving || !valid || !dirty}
- >
- {saving ? '正在验证并启用…' : '保存并校验连接'}
-
-
- 保存规则与核验说明
-
- 四项留空即表示未配置。地址只接受 http(s) 源地址(不能带用户名密码、查询串或 # 片段,
- 凭据一律走文件引用);生产租户 ID 为十进制数字;知识库 ID 粘贴 URL 不会通过。
- 保存会生成修订、真实验证后原子启用;端点回答“没有这个知识库”或租户不符会拒收,
- 端点抖动、鉴权失败或未配置生产凭据只警告不拦。
-
-
- {valid ? null : (
-
- 格式不合法:地址需 http:// 或 https:// 开头的纯地址,不能带用户名密码、? 查询串或 # 片段;生产 ID
- 需为十进制数字;知识库 ID 不能含空格、/、?、# 或 \。
-
- )}
- {saveMessage ? (
-
- {saveMessage}
-
- ) : null}
- >
- ) : (
-
- 仅管理员可修改 WeKnora 连接;当前值:测试地址 {settings.test_weknora_base_url || '未配置'} · 生产地址{' '}
- {settings.production_weknora_base_url || '未配置'} · 生产 ID {settings.production_tenant_id || '未配置'} ·
- 知识库 ID {settings.production_knowledge_base_id || '未配置'}。
-
- )}
-
- )
-}
diff --git a/web/src/knowledgeBaseBindings.test.ts b/web/src/knowledgeBaseBindings.test.ts
new file mode 100644
index 0000000..3807e84
--- /dev/null
+++ b/web/src/knowledgeBaseBindings.test.ts
@@ -0,0 +1,70 @@
+import { describe, expect, it } from 'vitest'
+import {
+ duplicateSelection,
+ keyActionFor,
+ knowledgeBaseLabel,
+ parseKBBindingSnapshot,
+ shortKnowledgeBaseID,
+} from './knowledgeBaseBindings'
+import type { KBEnvironmentBinding } from './knowledgeBaseBindings'
+
+const binding = (environment: 'test' | 'production'): KBEnvironmentBinding => ({
+ environment,
+ revision: 1,
+ base_url: `https://${environment}.example`,
+ key_configured: true,
+ key_source: 'sealed',
+ internal_kb_id: `${environment}-in`,
+ internal_kb_name: '内部资料',
+ external_kb_id: `${environment}-out`,
+ external_kb_name: '对外资料',
+ verification: 'verified',
+ checked_at: null,
+ updated_by: 'admin',
+ updated_at: null,
+ source: 'web',
+ storage_ready: true,
+ replanned: 0,
+ retired_duplicates: 0,
+})
+
+describe('knowledgeBaseBindings', () => {
+ it('parses both environments and never projects a key field', () => {
+ const parsed = parseKBBindingSnapshot({
+ data: {
+ environments: [binding('test'), binding('production')],
+ storage_ready: true,
+ },
+ })
+ expect(parsed.test.base_url).toBe('https://test.example')
+ expect(parsed.production.internal_kb_name).toBe('内部资料')
+ expect(parsed.storage_ready).toBe(true)
+ const asRecord = parsed.test as unknown as Record
+ expect(asRecord.api_key).toBeUndefined()
+ expect(asRecord.key_ciphertext).toBeUndefined()
+ })
+
+ it('rejects a snapshot missing an environment instead of inventing one', () => {
+ expect(() => parseKBBindingSnapshot({ data: { environments: [binding('test')], storage_ready: true } })).toThrow()
+ })
+
+ it('shows a short id next to the name so same-name bases are distinguishable', () => {
+ expect(shortKnowledgeBaseID('0b217e8a-1234-5678')).toBe('0b217e8a…')
+ expect(knowledgeBaseLabel('0b217e8a-1234-5678', '客户帮助中心')).toBe('客户帮助中心(0b217e8a…)')
+ expect(knowledgeBaseLabel('', '')).toBe('未绑定')
+ })
+
+ it('rejects using one base for both sides', () => {
+ expect(duplicateSelection('kb-1', 'kb-1')).toBe(true)
+ expect(duplicateSelection('kb-1', 'kb-2')).toBe(false)
+ expect(duplicateSelection('', '')).toBe(false)
+ })
+
+ it('forces a new key for any address other than the saved one', () => {
+ const saved = binding('test')
+ expect(keyActionFor(saved, 'https://test.example', false)).toBe('keep')
+ expect(keyActionFor(saved, 'https://other.example', false)).toBe('replace')
+ expect(keyActionFor({ ...saved, key_configured: false }, 'https://test.example', false)).toBe('replace')
+ expect(keyActionFor(saved, 'https://test.example', true)).toBe('replace')
+ })
+})
diff --git a/web/src/knowledgeBaseBindings.ts b/web/src/knowledgeBaseBindings.ts
new file mode 100644
index 0000000..1911ff2
--- /dev/null
+++ b/web/src/knowledgeBaseBindings.ts
@@ -0,0 +1,225 @@
+import { newOperationID } from './operationKey'
+
+export type KBEnvironment = 'test' | 'production'
+
+export interface KBEnvironmentBinding {
+ environment: KBEnvironment
+ revision: number
+ base_url: string
+ key_configured: boolean
+ key_source: string
+ internal_kb_id: string
+ internal_kb_name: string
+ external_kb_id: string
+ external_kb_name: string
+ verification: string
+ checked_at: string | null
+ updated_by: string
+ updated_at: string | null
+ source: 'web' | 'legacy'
+ storage_ready: boolean
+ replanned: number
+ retired_duplicates: number
+}
+
+export interface KBBindingSnapshot {
+ test: KBEnvironmentBinding
+ production: KBEnvironmentBinding
+ storage_ready: boolean
+}
+
+export interface KBCatalogOption {
+ id: string
+ name: string
+ knowledge_count: number
+}
+
+export type KBCatalogStatus = 'ok' | 'empty' | 'unauthorized' | 'unreachable' | 'unsupported'
+
+export interface KBCatalog {
+ status: KBCatalogStatus
+ message: string
+ page: number
+ page_size: number
+ total: number
+ options: KBCatalogOption[]
+}
+
+export interface KBCatalogInput {
+ base_revision: number
+ base_url: string
+ key_action: 'keep' | 'replace'
+ api_key?: string
+ page: number
+ page_size: number
+}
+
+export interface KBBindingSaveInput {
+ base_revision: number
+ base_url: string
+ key_action: 'keep' | 'replace'
+ api_key?: string
+ internal_kb_id: string
+ external_kb_id: string
+}
+
+export class KBBindingError extends Error {
+ readonly status: number
+
+ constructor(message: string, status: number) {
+ super(message)
+ this.name = 'KBBindingError'
+ this.status = status
+ }
+}
+
+const record = (value: unknown): value is Record =>
+ Boolean(value) && typeof value === 'object' && !Array.isArray(value)
+
+const text = (value: unknown): string => (typeof value === 'string' ? value : '')
+const bool = (value: unknown): boolean => value === true
+const count = (value: unknown): number => (typeof value === 'number' && Number.isFinite(value) ? value : 0)
+
+function parseBinding(value: unknown): KBEnvironmentBinding {
+ if (!record(value) || (value.environment !== 'test' && value.environment !== 'production')) {
+ throw new Error('知识库绑定响应无效')
+ }
+ return {
+ environment: value.environment,
+ revision: count(value.revision),
+ base_url: text(value.base_url),
+ key_configured: bool(value.key_configured),
+ key_source: text(value.key_source),
+ internal_kb_id: text(value.internal_kb_id),
+ internal_kb_name: text(value.internal_kb_name),
+ external_kb_id: text(value.external_kb_id),
+ external_kb_name: text(value.external_kb_name),
+ verification: text(value.verification),
+ checked_at: typeof value.checked_at === 'string' ? value.checked_at : null,
+ updated_by: text(value.updated_by),
+ updated_at: typeof value.updated_at === 'string' ? value.updated_at : null,
+ source: value.source === 'web' ? 'web' : 'legacy',
+ storage_ready: bool(value.storage_ready),
+ replanned: count(value.replanned),
+ retired_duplicates: count(value.retired_duplicates),
+ }
+}
+
+export function parseKBBindingSnapshot(value: unknown): KBBindingSnapshot {
+ if (!record(value) || !record(value.data) || !Array.isArray(value.data.environments)) {
+ throw new Error('知识库绑定响应无效')
+ }
+ const byEnvironment = new Map()
+ for (const item of value.data.environments) {
+ const binding = parseBinding(item)
+ byEnvironment.set(binding.environment, binding)
+ }
+ const test = byEnvironment.get('test')
+ const production = byEnvironment.get('production')
+ if (!test || !production) throw new Error('知识库绑定响应缺少环境')
+ return { test, production, storage_ready: bool(value.data.storage_ready) }
+}
+
+// 名称相同是常见情况,短 ID 是唯一可辨的部分;两处都显示,不靠名称猜。
+export function shortKnowledgeBaseID(value: string): string {
+ return value.length > 8 ? `${value.slice(0, 8)}…` : value
+}
+
+export function knowledgeBaseLabel(id: string, name: string): string {
+ if (!id) return '未绑定'
+ return name ? `${name}(${shortKnowledgeBaseID(id)})` : shortKnowledgeBaseID(id)
+}
+
+export function duplicateSelection(internal: string, external: string): boolean {
+ return internal !== '' && internal === external
+}
+
+// Keep is only legal for exactly the saved address; any other draft address
+// needs a freshly typed key. This mirrors the server rule so the button state
+// cannot promise something the server will refuse.
+export function keyActionFor(saved: KBEnvironmentBinding, baseURL: string, replace: boolean): 'keep' | 'replace' {
+ if (replace || !saved.key_configured) return 'replace'
+ return baseURL.trim() === saved.base_url ? 'keep' : 'replace'
+}
+
+function failureMessage(value: unknown, fallback: string): string {
+ if (record(value) && typeof value.error === 'string' && value.error.trim() !== '') return value.error
+ return fallback
+}
+
+async function readResponse(response: Response): Promise> {
+ if (response.ok) {
+ const payload: unknown = await response.json()
+ return record(payload) ? payload : {}
+ }
+ const failure: unknown = await response.json().catch(() => null)
+ throw new KBBindingError(failureMessage(failure, `知识库绑定请求失败(HTTP ${response.status})`), response.status)
+}
+
+export async function fetchKBBindings(signal?: AbortSignal): Promise {
+ const response = await fetch('/api/v1/kb-bindings', { signal, headers: { Accept: 'application/json' } })
+ return parseKBBindingSnapshot(await readResponse(response))
+}
+
+export async function fetchKBCatalog(
+ environment: KBEnvironment,
+ input: KBCatalogInput,
+ signal?: AbortSignal
+): Promise {
+ const response = await fetch(`/api/v1/kb-bindings/${environment}/catalog`, {
+ method: 'POST',
+ signal,
+ headers: {
+ 'Content-Type': 'application/json',
+ Accept: 'application/json',
+ 'X-Governance-Action': 'kb-bindings',
+ 'Idempotency-Key': newOperationID(),
+ },
+ body: JSON.stringify(input),
+ })
+ const payload = await readResponse(response)
+ if (!record(payload.data)) throw new Error('知识库列表响应无效')
+ const item = payload.data
+ const status = text(item.status)
+ if (!['ok', 'empty', 'unauthorized', 'unreachable', 'unsupported'].includes(status)) {
+ throw new Error('知识库列表响应无效')
+ }
+ const options = Array.isArray(item.options)
+ ? item.options
+ .filter(record)
+ .map((option) => ({
+ id: text(option.id),
+ name: text(option.name),
+ knowledge_count: count(option.knowledge_count),
+ }))
+ .filter((option) => option.id)
+ : []
+ return {
+ status: status as KBCatalogStatus,
+ message: text(item.message),
+ page: count(item.page) || 1,
+ page_size: count(item.page_size) || 20,
+ total: count(item.total),
+ options,
+ }
+}
+
+export async function saveKBBinding(
+ environment: KBEnvironment,
+ input: KBBindingSaveInput,
+ signal?: AbortSignal
+): Promise {
+ const response = await fetch(`/api/v1/kb-bindings/${environment}`, {
+ method: 'PUT',
+ signal,
+ headers: {
+ 'Content-Type': 'application/json',
+ Accept: 'application/json',
+ 'X-Governance-Action': 'kb-bindings',
+ 'Idempotency-Key': newOperationID(),
+ },
+ body: JSON.stringify(input),
+ })
+ const payload = await readResponse(response)
+ return parseBinding(payload.data)
+}
diff --git a/web/src/secureEntry.ts b/web/src/secureEntry.ts
new file mode 100644
index 0000000..7d500d2
--- /dev/null
+++ b/web/src/secureEntry.ts
@@ -0,0 +1,5 @@
+// Secret entry is only allowed on a real HTTPS origin or loopback. Plain LAN
+// HTTP must not receive a key that would then cross the network in the clear.
+export function secretEntryAllowed(location: { protocol: string; hostname: string }): boolean {
+ return location.protocol === 'https:' || ['localhost', '127.0.0.1', '[::1]', '::1'].includes(location.hostname)
+}
diff --git a/web/src/systemSettings.css b/web/src/systemSettings.css
index 48662b5..fa0ae22 100644
--- a/web/src/systemSettings.css
+++ b/web/src/systemSettings.css
@@ -997,3 +997,173 @@ button.link {
grid-template-columns: 1fr;
}
}
+
+/* ── 知识库绑定(按环境一次保存连接 + 内外库)────────────────────────── */
+.kb-env-switch {
+ display: inline-flex;
+ gap: 4px;
+ margin: 0 0 14px;
+ padding: 3px;
+ border: 1px solid var(--border-base);
+ border-radius: 9px;
+ background: var(--bg-soft);
+}
+.kb-env-switch button {
+ border: 0;
+ background: transparent;
+ padding: 6px 14px;
+ border-radius: 6px;
+ color: var(--ink-mute);
+ cursor: pointer;
+ font: inherit;
+}
+.kb-env-switch button[aria-pressed='true'] {
+ background: var(--bg-panel);
+ color: var(--ink-base);
+ font-weight: 700;
+ box-shadow: 0 1px 2px rgb(0 0 0 / 8%);
+}
+.kb-current {
+ display: grid;
+ gap: 6px;
+ padding: 11px 14px;
+ margin-bottom: 14px;
+ border-inline-start: 3px solid var(--c-run, #318184);
+ border-radius: 8px;
+ background: var(--bg-soft);
+}
+.kb-current strong {
+ font-size: 12px;
+ color: var(--ink-mute);
+}
+.kb-current-targets {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px 24px;
+}
+.kb-current-targets span {
+ color: var(--ink-mute);
+ font-size: 12px;
+}
+.kb-current-targets b {
+ color: var(--ink-base);
+ font-weight: 700;
+}
+.kb-current small,
+.kb-block small,
+.kb-footer .muted {
+ color: var(--ink-mute);
+}
+.kb-block {
+ padding: 14px 0;
+ border-bottom: 1px solid var(--border-base);
+}
+.kb-block h3 {
+ margin: 0 0 10px;
+ color: var(--ink-base);
+ font-size: 13px;
+}
+.kb-fields,
+.kb-targets {
+ display: grid;
+ grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr);
+ gap: 14px;
+}
+.kb-targets {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+}
+.kb-fields label,
+.kb-targets label,
+.kb-key {
+ display: grid;
+ gap: 5px;
+ color: var(--ink-base);
+ font-size: 11px;
+ font-weight: 600;
+}
+.kb-key .label {
+ font-size: 11px;
+}
+.kb-key-line {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-height: 34px;
+}
+.kb-key-line input {
+ flex: 1;
+}
+.kb-key-line button.link {
+ border: 0;
+ background: transparent;
+ color: var(--c-run, #135e77);
+ cursor: pointer;
+ text-decoration: underline;
+ white-space: nowrap;
+}
+.kb-fields input,
+.kb-targets select,
+.kb-key-line input {
+ width: 100%;
+ min-height: 34px;
+ padding: 6px 9px;
+ border: 1px solid var(--border-base);
+ border-radius: 6px;
+ background: var(--bg-panel);
+ color: var(--ink-base);
+ font: inherit;
+}
+.kb-actions {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 10px;
+ margin-top: 10px;
+}
+.kb-catalog-status {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ margin-top: 10px;
+ padding: 8px 10px;
+ border-radius: 7px;
+ background: var(--bg-soft);
+ font-size: 11px;
+}
+.kb-catalog-status.ok {
+ color: var(--c-done, #1f7a4d);
+}
+.kb-catalog-status.empty {
+ color: var(--ink-mute);
+}
+.kb-catalog-status.error {
+ color: var(--c-fail, #a63b32);
+}
+.kb-pager {
+ display: inline-flex;
+ gap: 6px;
+}
+.kb-footer {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ padding-top: 14px;
+}
+.kb-binding-diagnostics {
+ margin-top: 14px;
+}
+.kb-binding-diagnostics > summary {
+ cursor: pointer;
+ color: var(--ink-mute);
+ font-size: 11px;
+}
+@media (max-width: 720px) {
+ .kb-fields,
+ .kb-targets {
+ grid-template-columns: 1fr;
+ }
+}
diff --git a/web/src/weKnoraDiagnostics.tsx b/web/src/weKnoraDiagnostics.tsx
new file mode 100644
index 0000000..4069eaf
--- /dev/null
+++ b/web/src/weKnoraDiagnostics.tsx
@@ -0,0 +1,101 @@
+import type { MonitorOverview } from './monitor'
+import type { CatalogRoutingCapabilities } from './sourceCatalog'
+import type { WorkerCapabilities } from './systemCapabilities'
+import { testUploadLabel } from './systemCapabilities'
+import type { UISettings } from './uiSettings'
+
+type ServiceHealthView = MonitorOverview['health'][number]
+type ServiceView = MonitorOverview['services'][number]
+
+// 连接卡只读诊断:知识库绑定的保存入口已收敛到「知识库绑定」主表单,
+// 这里保留原链路需要的探活/执行器状态,不再提供第二个保存路径。
+
+export const findHealth = (monitor: MonitorOverview | null, name: string): ServiceHealthView | undefined =>
+ (monitor?.health || []).find((item) => item.name === name || item.name.startsWith(name))
+
+export const healthStateLabel = (health: ServiceHealthView | undefined, service: ServiceView | undefined): string => {
+ if (!health) {
+ if (!service) return '待配置'
+ return service.state === 'healthy' ? '正常' : service.state === 'unknown' ? '未接入' : '需关注'
+ }
+ if (health.readiness === 'ready') return '可达 · 可接单'
+ if (health.readiness === 'not_configured') return '状态未知 · 未配置'
+ if (health.readiness === 'not_applicable') return '未部署'
+ return health.liveness === 'up' ? '可达 · 不可接单' : '不可达 · 不可接单'
+}
+
+export const testWeKnoraLabel = (health: ServiceHealthView | undefined, service: ServiceView | undefined): string => {
+ const label = healthStateLabel(health, service)
+ return label === '可达 · 可接单' ? '接口可达 · 执行器未验证' : label
+}
+
+export const healthStateDetail = (health: ServiceHealthView | undefined, service: ServiceView | undefined): string => {
+ if (!health) return service?.detail || '真实 Provider 未接入'
+ const success = health.last_success_at
+ ? `最近成功 ${new Date(health.last_success_at).toLocaleTimeString('zh-CN', { hour12: false })}`
+ : ''
+ if (health.readiness === 'ready') return [`延迟 ${health.latency_ms}ms`, success].filter(Boolean).join(';')
+ const failures = health.consecutive_failures ? `连续失败${health.consecutive_failures}次` : ''
+ return [health.reason, success, failures].filter(Boolean).join(';')
+}
+
+export const productionWeKnoraProbe = (monitor: MonitorOverview | null): string => {
+ const health = findHealth(monitor, '生产 WeKnora')
+ if (!health) return '端点探测:暂无真实探测结果'
+ if (!health.configured) return '端点探测:未配置'
+ const label =
+ health.liveness === 'up'
+ ? health.readiness === 'ready'
+ ? '端点可达 · 未做接单验证'
+ : '端点可达 · 不可接单'
+ : '端点不可达'
+ const detail = healthStateDetail(health, undefined)
+ return `端点探测:${label}${detail ? `(${detail})` : ''}`
+}
+
+export interface WeKnoraConnectionDiagnosticsProps {
+ settings: UISettings
+ monitor: MonitorOverview | null
+ routingCapabilities: CatalogRoutingCapabilities
+ workerCapabilities?: WorkerCapabilities | null
+ productionEnabled: boolean
+ productionBackupRestoreVerified?: boolean
+}
+
+export function WeKnoraConnectionDiagnostics({
+ settings,
+ monitor,
+ routingCapabilities,
+ workerCapabilities = null,
+ productionEnabled,
+ productionBackupRestoreVerified = false,
+}: WeKnoraConnectionDiagnosticsProps) {
+ return (
+
+
+ 测试 WeKnora
+ {testWeKnoraLabel(findHealth(monitor, 'WeKnora API'), undefined)}
+ {`${healthStateDetail(findHealth(monitor, 'WeKnora API'), undefined) || '端点探测:未配置'};解析队列 对内 ${
+ routingCapabilities.internal_enabled ? '已配置' : '未配置'
+ } · 对外 ${routingCapabilities.external_enabled ? '已配置' : '未配置'}`}
+
+ {testUploadLabel(workerCapabilities)}
+ {workerCapabilities ? `:${workerCapabilities.test_upload.detail}` : ''}
+
+ {settings.test_weknora_base_url || '未配置地址'} · 凭据:服务器文件/加密存储,页面不回读
+
+
+ 生产 WeKnora
+
+ {!productionEnabled
+ ? '未启用'
+ : productionBackupRestoreVerified
+ ? '已启用 · 可提交生产请求'
+ : '已启用 · 被阻断'}
+
+ {`${productionWeKnoraProbe(monitor)};生产写入:${productionEnabled ? '开启' : '关闭'}`}
+ {settings.production_weknora_base_url || '未配置地址'} · 凭据:服务器文件/加密存储,页面不回读
+
+
+ )
+}
From 1f5bf72aecd0dd7052cddc33599f92b5c2ef9809 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E5=A7=9A=E7=AB=A0=E6=B5=A9?=
Date: Thu, 19 Nov 2026 15:17:17 +0800
Subject: [PATCH 03/14] =?UTF-8?q?fix(release):=20=E4=BB=A5=E5=AE=9E?=
=?UTF-8?q?=E4=BE=8B=E8=BA=AB=E4=BB=BD=E9=98=BB=E6=96=AD=E7=BB=91=E5=AE=9A?=
=?UTF-8?q?=E4=B8=8E=E5=8F=91=E5=B8=83=E8=B7=A8=E5=AE=9E=E4=BE=8B?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
网页可能在实例 A 上列库并保存生产绑定,而文档发布执行器实际连实例 B。
克隆实例可以有相同知识库 ID、名称甚至租户,单靠 ID 无法证明写的是同一个
目标。现在绑定保存会冻结候选实例地址/租户,发布计划把身份冻结到每个项,
执行器在 Contract/Prepare/Activate/Restore/Compensate 前核对;不一致以
release_contract_mismatch 非重试失败关闭,不写目标。整库发布目标不变。
测试入库对象在上传前记录实际实例地址/租户;轮询、验收、移除先核对当前
连接,改绑实例或租户后旧对象不会被克隆实例接管。旧行没有身份时失败关闭。
「知识库绑定」保存要求对内/对外各选一个库,不再把显式未绑定回落到部署
默认 ID,避免换绑实例后带过去旧对象的默认库。
验证:隔离 PostgreSQL 覆盖绑定身份落库与发布计划冻结;v071 用同 ID/同租户
的 A/B 实例做正反例;四个测试 handler 的实例错配负例;前端 607 项通过。
---
CHANGELOG.md | 23 +++
cmd/api/main.go | 3 -
cmd/release-worker/runtime.go | 7 +-
cmd/worker/main.go | 3 -
docs/USER_FLOWS_ACCEPTANCE.md | 5 +-
internal/kbbinding/binding.go | 5 +-
internal/kbbinding/binding_test.go | 1 +
internal/kbbinding/save_integration_test.go | 20 ++-
internal/kbbinding/store.go | 43 ++---
...000082_instance_identity_contract.down.sql | 13 ++
.../000082_instance_identity_contract.up.sql | 20 +++
internal/platform/postgres/migrations_test.go | 12 +-
.../platform/postgres/production_bindings.go | 34 +++-
.../platform/postgres/publication_removal.go | 15 +-
.../release_execution_worker_store.go | 37 ++++-
.../release_execution_worker_store_test.go | 5 +-
.../release_identity_integration_test.go | 71 ++++++++
.../platform/postgres/routing_bindings.go | 2 +-
.../platform/postgres/test_publications.go | 53 +++---
.../test_publications_integration_test.go | 2 +-
.../postgres/test_publications_test.go | 20 ++-
internal/platform/weknora/types.go | 30 ++++
internal/releaseadapter/v071/archive_test.go | 2 +-
.../releaseadapter/v071/document_target.go | 40 +++++
.../v071/document_target_test.go | 46 +++++-
.../v071/three_lane_integration_test.go | 4 +-
.../releaseadapter/v071/wiki_channel_test.go | 1 +
internal/weknoraaccess/client.go | 31 ++++
internal/weknoraaccess/client_test.go | 23 +++
internal/workflows/release/handler.go | 11 +-
.../workflows/release/sidecar_publisher.go | 18 ++-
.../release/sidecar_publisher_test.go | 26 ++-
internal/workflows/testweknora/identity.go | 38 +++++
.../workflows/testweknora/identity_test.go | 152 ++++++++++++++++++
internal/workflows/testweknora/poll.go | 11 ++
internal/workflows/testweknora/poll_test.go | 4 +-
internal/workflows/testweknora/remove.go | 8 +
internal/workflows/testweknora/upload.go | 18 ++-
internal/workflows/testweknora/upload_test.go | 16 +-
internal/workflows/testweknora/validate.go | 27 +++-
scripts/test-scope.json | 5 +
web/src/KnowledgeBaseBinding.test.tsx | 20 +++
web/src/KnowledgeBaseBinding.tsx | 11 +-
43 files changed, 823 insertions(+), 113 deletions(-)
create mode 100644 internal/platform/postgres/migrations/000082_instance_identity_contract.down.sql
create mode 100644 internal/platform/postgres/migrations/000082_instance_identity_contract.up.sql
create mode 100644 internal/platform/postgres/release_identity_integration_test.go
create mode 100644 internal/workflows/testweknora/identity.go
create mode 100644 internal/workflows/testweknora/identity_test.go
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2102213..2d0c225 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,28 @@
# Changelog
+## 开发快照 0.1.403(实例身份约束:绑定、发布与测试对象不跨实例)
+
+### Added
+
+- 迁移 000082:`production_kb_bindings` 冻结每个方向核验时的实例地址与租户,
+ `release_item_executions` 冻结 `target_instance_url/target_tenant_id`,
+ `test_publications` 记录对象实际写入的测试实例地址/租户。
+- 文档发布执行器在 `Contract/Prepare/Activate/Restore/Compensate` 前统一核对实例身份:
+ 网页在实例 A 列库、执行器连实例 B 时,即使知识库 ID/租户相同也以
+ `release_contract_mismatch` 失败关闭,不写目标;整库发布目标不变。
+- 测试入库的上传/轮询/验收/移除按对象记录的身份核对当前连接;改绑实例或租户后,
+ 旧对象不会在克隆实例上继续轮询、验收或删除。
+- 回归:实例 A/B 同名同 ID 的隔离夹具、绑定身份写入计划、四个测试 handler 的正反例。
+
+### Changed
+
+- 「知识库绑定」保存必须为对内/对外各选一个库;显式“未绑定”不再回落部署默认 ID,
+ 避免换绑实例后把旧实例的默认库带到新实例。旧页面留下的既有绑定行保持原语义。
+
+### Security
+
+- 实例身份不匹配一律失败关闭;旧发布项缺少身份信息时也不再猜测,避免写错克隆实例。
+
## 开发快照 0.1.402(知识库绑定:按环境一次保存连接与内外库)
### Added
diff --git a/cmd/api/main.go b/cmd/api/main.go
index 35a9fe8..0c53269 100644
--- a/cmd/api/main.go
+++ b/cmd/api/main.go
@@ -147,9 +147,6 @@ func run(ctx context.Context, getenv func(string) string) error {
}
return internal, external, err
},
- RoutingDefaults: func() (string, string) {
- return config.InternalRoutingKnowledgeBaseID, config.ExternalRoutingKnowledgeBaseID
- },
})
productionEndpointResolver := func(resolveCtx context.Context) string {
return kbBindings.ResolveBaseURL(resolveCtx, kbbinding.EnvProduction)
diff --git a/cmd/release-worker/runtime.go b/cmd/release-worker/runtime.go
index fe6a905..b33a335 100644
--- a/cmd/release-worker/runtime.go
+++ b/cmd/release-worker/runtime.go
@@ -163,7 +163,12 @@ func buildReleaseRoute(ctx context.Context, archiveRoot string, snapshot release
if err != nil {
return cleanup(errors.New("create target WeKnora verifier"))
}
- documentTarget, err := v071.NewDocumentTarget(v071.DocumentTargetConfig{Archive: archive, Contract: targetContract, Postgres: postgresImporter, Search: targetSearch, Objects: objectImporter, Verifier: verifier})
+ documentTarget, err := v071.NewDocumentTarget(v071.DocumentTargetConfig{
+ Archive: archive, Contract: targetContract, Postgres: postgresImporter, Search: targetSearch,
+ Objects: objectImporter, Verifier: verifier,
+ TargetInstanceURL: route.Target.WeKnora.BaseURL,
+ TargetTenantID: route.TenantID,
+ })
if err != nil {
return cleanup(errors.New("create v0.7.1 document target"))
}
diff --git a/cmd/worker/main.go b/cmd/worker/main.go
index 69f4900..44888ef 100644
--- a/cmd/worker/main.go
+++ b/cmd/worker/main.go
@@ -221,9 +221,6 @@ func run(ctx context.Context, getenv func(string) string) error {
}
return internal, external, err
},
- RoutingDefaults: func() (string, string) {
- return config.InternalRoutingKnowledgeBaseID, config.ExternalRoutingKnowledgeBaseID
- },
})
log.Printf("library target evidence identity=%s", config.LibraryTargetIdentity())
// 启动先接管被中断的写作业(复用已持久化的预备份),再把剩下的孤儿判失败:
diff --git a/docs/USER_FLOWS_ACCEPTANCE.md b/docs/USER_FLOWS_ACCEPTANCE.md
index 9ad2fcd..6b94429 100644
--- a/docs/USER_FLOWS_ACCEPTANCE.md
+++ b/docs/USER_FLOWS_ACCEPTANCE.md
@@ -257,10 +257,11 @@
### D1 知识库绑定(测试 090 / 生产 090:连接 + 内外库)
- 入口:**系统设置 → 知识库绑定**(管理员;普通用户只读)
-- 步骤:选择环境 → 填写该环境服务地址与 API Key(已配置可保留,不回显)→ **验证并读取知识库**(服务器真实列库,分页;区分空库/无权限/不可达)→ 选对内、对外库(名称 + 短 ID,禁止同一个库)→ **保存该环境绑定**
+- 步骤:选择环境 → 填写该环境服务地址与 API Key(已配置可保留,不回显)→ **验证并读取知识库**(服务器真实列库,分页;区分空库/无权限/不可达)→ 选对内、对外库(名称 + 短 ID,禁止同一个库;**两个方向都必须选择**)→ **保存该环境绑定**
- 期望:一次保存同时生效连接与内外绑定;顶部「当前生效」回读服务器真实值;失败保留旧绑定,未保存草稿不影响当前值;切换环境时迟到的列库响应不串库
- 兼容:没有新配置行的旧部署继续使用文件凭据/默认绑定;保存新密钥需要独立主密钥文件 `WEKNORA_BINDING_MASTER_KEY_FILE`
-- 证据:`internal/kbbinding`(单元 + 隔离 PostgreSQL 集成)、`KnowledgeBaseBinding.test.tsx`
+- 实例约束:网页在实例 A 核验的绑定会冻结地址/租户;文档发布执行器连实例 B 时,即使知识库 ID/租户相同也拒绝写入(`release_contract_mismatch`)。测试对象改绑实例/租户后,旧对象不会被轮询/验收/移除。
+- 证据:`internal/kbbinding`(单元 + 隔离 PostgreSQL 集成)、`KnowledgeBaseBinding.test.tsx`、`TestStartReleaseExecutionFreezesTheBindingInstanceIdentity`、`TestDocumentTargetRejectsBindingVerifiedOnAnotherInstance`
- 状态:✅ 本地验证(未做业务验收)
### D2 测试知识库绑定(折叠诊断;主入口已并入 D1)
diff --git a/internal/kbbinding/binding.go b/internal/kbbinding/binding.go
index 1bd73bb..5e6e543 100644
--- a/internal/kbbinding/binding.go
+++ b/internal/kbbinding/binding.go
@@ -127,10 +127,7 @@ type Options struct {
LegacyKey func(string) (string, error)
// LegacyBinding resolves the pre-existing internal/external binding ids.
LegacyBinding func(context.Context, string) (string, string, error)
- // RoutingDefaults are the deployment bootstrap ids used to replan pending
- // publications when a saved side is empty.
- RoutingDefaults func() (string, string)
- Now func() time.Time
+ Now func() time.Time
}
type DB interface {
diff --git a/internal/kbbinding/binding_test.go b/internal/kbbinding/binding_test.go
index a35579c..2e412ee 100644
--- a/internal/kbbinding/binding_test.go
+++ b/internal/kbbinding/binding_test.go
@@ -119,6 +119,7 @@ func TestSaveInputValidationRejectsDuplicateAndBadIDs(t *testing.T) {
store := New(emptyDB{}, Options{Now: func() time.Time { return now }})
for _, input := range []SaveInput{
{BaseURL: "https://x.example", KeyAction: "replace", APIKey: "k", InternalKBID: "kb", ExternalKBID: "kb"},
+ {BaseURL: "https://x.example", KeyAction: "replace", APIKey: "k", InternalKBID: "kb-in"},
{BaseURL: "https://x.example", KeyAction: "replace", APIKey: "k", InternalKBID: "kb/1"},
{BaseURL: "https://x.example?token=1", KeyAction: "replace", APIKey: "k"},
} {
diff --git a/internal/kbbinding/save_integration_test.go b/internal/kbbinding/save_integration_test.go
index 172a2bb..6433777 100644
--- a/internal/kbbinding/save_integration_test.go
+++ b/internal/kbbinding/save_integration_test.go
@@ -32,9 +32,9 @@ func fakeCandidate(t *testing.T) *httptest.Server {
case r.URL.Path == "/api/v1/knowledge-bases":
_, _ = w.Write([]byte(`{"success":true,"total":2,"data":[{"id":"kb-in","name":"内部技术资料","knowledge_count":3},{"id":"kb-out","name":"客户使用手册","knowledge_count":4}]}`))
case r.URL.Path == "/api/v1/knowledge-bases/kb-in":
- _, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-in","name":"内部技术资料"}}`))
+ _, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-in","name":"内部技术资料","tenant_id":10000}}`))
case r.URL.Path == "/api/v1/knowledge-bases/kb-out":
- _, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-out","name":"客户使用手册"}}`))
+ _, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-out","name":"客户使用手册","tenant_id":10000}}`))
default:
w.WriteHeader(http.StatusNotFound)
}
@@ -82,9 +82,14 @@ INSERT INTO test_publications(id,source_item_version_id,test_kb_id,processing_st
MasterKeyFile: masterKey(t),
Timeout: 2 * time.Second,
AllowDockerHTTP: map[string]bool{kbbinding.EnvTest: true, kbbinding.EnvProduction: true},
- RoutingDefaults: func() (string, string) { return "env-in", "env-out" },
})
now := time.Date(2026, 11, 19, 8, 0, 0, 0, time.UTC)
+ if _, err := store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{
+ BaseRevision: 0, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(),
+ InternalKBID: "kb-in",
+ }, "admin", now); !errors.Is(err, kbbinding.ErrInvalid) {
+ t.Fatalf("save with an unbound side = %v, want ErrInvalid", err)
+ }
view, err := store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{
BaseRevision: 0, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(),
InternalKBID: "kb-in", ExternalKBID: "kb-out",
@@ -169,11 +174,12 @@ INSERT INTO test_publications(id,source_item_version_id,test_kb_id,processing_st
if prodView.Environment != kbbinding.EnvProduction || prodView.Revision != 1 {
t.Fatalf("production view = %#v", prodView)
}
- var productionInternal string
- if err := pool.QueryRow(ctx, `SELECT internal_kb_id FROM production_kb_bindings WHERE id='active'`).Scan(&productionInternal); err != nil {
+ var productionInternal, productionURL string
+ var productionTenant uint64
+ if err := pool.QueryRow(ctx, `SELECT internal_kb_id, internal_instance_url, internal_tenant_id FROM production_kb_bindings WHERE id='active'`).Scan(&productionInternal, &productionURL, &productionTenant); err != nil {
t.Fatal(err)
}
- if productionInternal != "kb-in" {
- t.Fatalf("production binding = %s", productionInternal)
+ if productionInternal != "kb-in" || productionURL != server.URL || productionTenant != 10000 {
+ t.Fatalf("production binding = %s / %s / %d", productionInternal, productionURL, productionTenant)
}
}
diff --git a/internal/kbbinding/store.go b/internal/kbbinding/store.go
index d3d8f42..82ff755 100644
--- a/internal/kbbinding/store.go
+++ b/internal/kbbinding/store.go
@@ -106,7 +106,12 @@ func (s *Store) Save(ctx context.Context, env string, input SaveInput, actor str
len(internal) > 128 || len(external) > 128 || !validBaseID(internal) || !validBaseID(external) {
return View{}, ErrInvalid
}
- if internal != "" && internal == external {
+ // 新页面必须给两个方向各选一个库:显式“未绑定”会回落到部署默认 ID,
+ // 而那个 ID 可能属于旧实例;在换绑实例后继续沿用就是错误目标。
+ if internal == "" || external == "" {
+ return View{}, ErrInvalid
+ }
+ if internal == external {
return View{}, ErrInvalid
}
saved, found, err := s.load(ctx, env)
@@ -121,7 +126,7 @@ func (s *Store) Save(ctx context.Context, env string, input SaveInput, actor str
if err != nil {
return View{}, ErrInvalid
}
- names, err := s.verifySelection(ctx, client, internal, external)
+ selected, err := s.verifySelection(ctx, client, internal, external)
if err != nil {
return View{}, err
}
@@ -169,7 +174,7 @@ ON CONFLICT(environment) DO UPDATE SET
internal_kb_name=EXCLUDED.internal_kb_name,external_kb_name=EXCLUDED.external_kb_name,
verification=EXCLUDED.verification,checked_at=EXCLUDED.checked_at,
updated_by=EXCLUDED.updated_by,updated_at=EXCLUDED.updated_at`,
- env, revision, baseURL, sealed, internal, external, names[internal], names[external], verification, now.UTC(), actor); err != nil {
+ env, revision, baseURL, sealed, internal, external, selected[internal].Name, selected[external].Name, verification, now.UTC(), actor); err != nil {
return View{}, ErrStorage
}
if _, err := tx.Exec(ctx, `
@@ -184,23 +189,16 @@ VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)`,
if err := postgresstore.SaveRoutingKBBindingsTx(ctx, tx, internal, external, actor, now.UTC()); err != nil {
return View{}, ErrStorage
}
- effectiveInternal, effectiveExternal := internal, external
- if s.options.RoutingDefaults != nil {
- defaultInternal, defaultExternal := s.options.RoutingDefaults()
- if effectiveInternal == "" {
- effectiveInternal = defaultInternal
- }
- if effectiveExternal == "" {
- effectiveExternal = defaultExternal
- }
- }
- replan, err = postgresstore.ReplanPendingPublicationsTx(ctx, tx, effectiveInternal, effectiveExternal, now.UTC())
+ replan, err = postgresstore.ReplanPendingPublicationsTx(ctx, tx, internal, external, now.UTC())
if err != nil {
return View{}, ErrStorage
}
} else {
// 生产页这里沿用「文档级发布」语义;整库发布目标由部署配置决定,本保存不写它。
- if err := postgresstore.SaveProductionKBBindingsTx(ctx, tx, internal, external, actor, now.UTC()); err != nil {
+ // 同时冻结候选实例地址与租户,执行器写入前必须与自己的目标一致。
+ if err := postgresstore.SaveProductionKBBindingsWithIdentityTx(ctx, tx,
+ internal, external, baseURL, baseURL,
+ selected[internal].TenantID, selected[external].TenantID, actor, now.UTC()); err != nil {
return View{}, ErrStorage
}
}
@@ -219,13 +217,18 @@ VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)`,
// verifySelection proves both chosen bases belong to THIS candidate instance by
// reading them with the draft credential. An empty selection still probes the
// list endpoint, so a save cannot store a connection nobody verified.
-func (s *Store) verifySelection(ctx context.Context, client *weknora.Client, internal, external string) (map[string]string, error) {
- names := map[string]string{}
+type selectedBase struct {
+ Name string
+ TenantID uint64
+}
+
+func (s *Store) verifySelection(ctx context.Context, client *weknora.Client, internal, external string) (map[string]selectedBase, error) {
+ selected := map[string]selectedBase{}
if internal == "" && external == "" {
if _, err := client.ListKnowledgeBasesPage(ctx, 1, 1); err != nil {
return nil, selectionError(err, "无法确认候选连接")
}
- return names, nil
+ return selected, nil
}
for _, id := range []string{internal, external} {
if id == "" {
@@ -238,9 +241,9 @@ func (s *Store) verifySelection(ctx context.Context, client *weknora.Client, int
if base.ID != id {
return nil, ErrInvalid
}
- names[id] = base.Name
+ selected[id] = selectedBase{Name: base.Name, TenantID: base.TenantID}
}
- return names, nil
+ return selected, nil
}
func selectionError(err error, message string) error {
diff --git a/internal/platform/postgres/migrations/000082_instance_identity_contract.down.sql b/internal/platform/postgres/migrations/000082_instance_identity_contract.down.sql
new file mode 100644
index 0000000..ec4e8eb
--- /dev/null
+++ b/internal/platform/postgres/migrations/000082_instance_identity_contract.down.sql
@@ -0,0 +1,13 @@
+ALTER TABLE test_publications
+ DROP COLUMN IF EXISTS test_instance_tenant,
+ DROP COLUMN IF EXISTS test_instance_url;
+
+ALTER TABLE release_item_executions
+ DROP COLUMN IF EXISTS target_tenant_id,
+ DROP COLUMN IF EXISTS target_instance_url;
+
+ALTER TABLE production_kb_bindings
+ DROP COLUMN IF EXISTS external_tenant_id,
+ DROP COLUMN IF EXISTS internal_tenant_id,
+ DROP COLUMN IF EXISTS external_instance_url,
+ DROP COLUMN IF EXISTS internal_instance_url;
\ No newline at end of file
diff --git a/internal/platform/postgres/migrations/000082_instance_identity_contract.up.sql b/internal/platform/postgres/migrations/000082_instance_identity_contract.up.sql
new file mode 100644
index 0000000..30f6668
--- /dev/null
+++ b/internal/platform/postgres/migrations/000082_instance_identity_contract.up.sql
@@ -0,0 +1,20 @@
+-- 实例身份约束:网页(kbbinding)在实例 A 上列库/选库,而文档发布执行器可能
+-- 连的是实例 B。同名/同 ID 的知识库在克隆实例里完全可能存在,所以 ID 本身
+-- 不能证明“写的是网页看到的那个实例”。这里把候选连接地址与租户随绑定冻结到
+-- 每个发布项,执行器在写入前用自己的目标地址/租户核对;不一致即失败关闭。
+--
+-- 同时给测试入库的发布项记录“对象实际写入的测试实例地址/租户”:
+-- 改绑实例或租户后,旧对象不能在克隆实例上继续轮询/验收/移除。
+ALTER TABLE production_kb_bindings
+ ADD COLUMN IF NOT EXISTS internal_instance_url TEXT NOT NULL DEFAULT '',
+ ADD COLUMN IF NOT EXISTS external_instance_url TEXT NOT NULL DEFAULT '',
+ ADD COLUMN IF NOT EXISTS internal_tenant_id BIGINT NOT NULL DEFAULT 0,
+ ADD COLUMN IF NOT EXISTS external_tenant_id BIGINT NOT NULL DEFAULT 0;
+
+ALTER TABLE release_item_executions
+ ADD COLUMN IF NOT EXISTS target_instance_url TEXT NOT NULL DEFAULT '',
+ ADD COLUMN IF NOT EXISTS target_tenant_id BIGINT NOT NULL DEFAULT 0;
+
+ALTER TABLE test_publications
+ ADD COLUMN IF NOT EXISTS test_instance_url TEXT NOT NULL DEFAULT '',
+ ADD COLUMN IF NOT EXISTS test_instance_tenant BIGINT NOT NULL DEFAULT 0;
\ No newline at end of file
diff --git a/internal/platform/postgres/migrations_test.go b/internal/platform/postgres/migrations_test.go
index 292bfb1..590235b 100644
--- a/internal/platform/postgres/migrations_test.go
+++ b/internal/platform/postgres/migrations_test.go
@@ -11,8 +11,16 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
if err != nil {
t.Fatalf("loadMigrations() error = %v", err)
}
- if len(migrations) != 81 {
- t.Fatalf("migration count = %d, want 81", len(migrations))
+ if len(migrations) != 82 {
+ t.Fatalf("migration count = %d, want 82", len(migrations))
+ }
+ // 82 是实例身份约束:绑定冻结候选实例地址/租户,发布项与测试对象都记录
+ // 实际实例身份;克隆实例同名/同 ID 不能冒充。
+ if identity := migrations[81]; identity.Version != 82 ||
+ !strings.Contains(identity.UpSQL, "target_instance_url") ||
+ !strings.Contains(identity.UpSQL, "test_instance_url") ||
+ !strings.Contains(identity.UpSQL, "internal_tenant_id") {
+ t.Fatalf("migration 82 = %#v", identity)
}
// 81 是环境级「知识库绑定」:连接密文与内外库同表同事务,历史只记是否配置密钥。
if binding := migrations[80]; binding.Version != 81 ||
diff --git a/internal/platform/postgres/production_bindings.go b/internal/platform/postgres/production_bindings.go
index f3a2a7a..ef526da 100644
--- a/internal/platform/postgres/production_bindings.go
+++ b/internal/platform/postgres/production_bindings.go
@@ -39,26 +39,48 @@ func (s *Store) SaveProductionKBBindings(ctx context.Context, internalID, extern
if now.IsZero() {
return errors.New("production binding save requires a timestamp")
}
- if _, err := s.db.Exec(ctx, productionBindingUpsertSQL, internalID, externalID, updatedBy, now); err != nil {
+ // 旧入口没有实例身份可写:显式清空身份列,执行器随后会失败关闭,
+ // 而不是沿用上一条(可能属于另一个实例的)地址/租户。
+ if _, err := s.db.Exec(ctx, productionBindingIdentityUpsertSQL,
+ internalID, externalID, updatedBy, now, "", "", 0, 0); err != nil {
return errors.New("save production kb bindings")
}
return nil
}
-const productionBindingUpsertSQL = `
-INSERT INTO production_kb_bindings(id,internal_kb_id,external_kb_id,updated_by,updated_at)
-VALUES('active',$1,$2,$3,$4)
+// productionBindingIdentityUpsertSQL freezes the instance identity the console
+// verified each side on. An empty URL keeps the legacy same-id behaviour for
+// old callers; the executor then cannot prove the instance and refuses a mapped
+// write instead of guessing.
+const productionBindingIdentityUpsertSQL = `
+INSERT INTO production_kb_bindings(
+ id,internal_kb_id,external_kb_id,updated_by,updated_at,
+ internal_instance_url,external_instance_url,internal_tenant_id,external_tenant_id)
+VALUES('active',$1,$2,$3,$4,$5,$6,$7,$8)
ON CONFLICT(id) DO UPDATE SET
internal_kb_id=EXCLUDED.internal_kb_id,
external_kb_id=EXCLUDED.external_kb_id,
updated_by=EXCLUDED.updated_by,
- updated_at=EXCLUDED.updated_at`
+ updated_at=EXCLUDED.updated_at,
+ internal_instance_url=EXCLUDED.internal_instance_url,
+ external_instance_url=EXCLUDED.external_instance_url,
+ internal_tenant_id=EXCLUDED.internal_tenant_id,
+ external_tenant_id=EXCLUDED.external_tenant_id`
// SaveProductionKBBindingsTx lets the environment-scoped 「知识库绑定」save
// update the same row inside its own transaction, so connection and bindings
// cannot be half-written.
func SaveProductionKBBindingsTx(ctx context.Context, tx pgx.Tx, internalID, externalID, updatedBy string, now time.Time) error {
- if _, err := tx.Exec(ctx, productionBindingUpsertSQL, internalID, externalID, updatedBy, now); err != nil {
+ return SaveProductionKBBindingsWithIdentityTx(ctx, tx, internalID, externalID, "", "", 0, 0, updatedBy, now)
+}
+
+// SaveProductionKBBindingsWithIdentityTx is used by the environment-scoped
+// 「知识库绑定」save: it stores which instance/tenant each side was verified on,
+// so the release executor can refuse a cloned instance with the same base id.
+func SaveProductionKBBindingsWithIdentityTx(ctx context.Context, tx pgx.Tx, internalID, externalID, internalURL, externalURL string, internalTenant, externalTenant uint64, updatedBy string, now time.Time) error {
+ if _, err := tx.Exec(ctx, productionBindingIdentityUpsertSQL,
+ internalID, externalID, updatedBy, now,
+ internalURL, externalURL, internalTenant, externalTenant); err != nil {
return errors.New("save production kb bindings")
}
return nil
diff --git a/internal/platform/postgres/publication_removal.go b/internal/platform/postgres/publication_removal.go
index 30159ab..2cba3ac 100644
--- a/internal/platform/postgres/publication_removal.go
+++ b/internal/platform/postgres/publication_removal.go
@@ -11,19 +11,22 @@ import (
)
type PublicationForRemoval struct {
- ID string
- TestKBID string
- KnowledgeID string
- RetrievalState governance.RetrievalState
+ ID string
+ TestKBID string
+ KnowledgeID string
+ TestInstanceURL string
+ TestInstanceTenant uint64
+ RetrievalState governance.RetrievalState
}
func (s *Store) LoadPublicationForRemoval(ctx context.Context, publicationID string) (PublicationForRemoval, error) {
var candidate PublicationForRemoval
var retrievalState string
- err := s.db.QueryRow(ctx, `SELECT id,test_kb_id,knowledge_id,retrieval_state
+ err := s.db.QueryRow(ctx, `SELECT id,test_kb_id,knowledge_id,test_instance_url,test_instance_tenant,retrieval_state
FROM test_publications
WHERE id=$1 AND knowledge_id<>'' AND retrieval_state='disabling'`, publicationID).Scan(
- &candidate.ID, &candidate.TestKBID, &candidate.KnowledgeID, &retrievalState,
+ &candidate.ID, &candidate.TestKBID, &candidate.KnowledgeID,
+ &candidate.TestInstanceURL, &candidate.TestInstanceTenant, &retrievalState,
)
if errors.Is(err, pgx.ErrNoRows) {
return PublicationForRemoval{}, ErrPublicationStateConflict
diff --git a/internal/platform/postgres/release_execution_worker_store.go b/internal/platform/postgres/release_execution_worker_store.go
index 5e131df..490fa4b 100644
--- a/internal/platform/postgres/release_execution_worker_store.go
+++ b/internal/platform/postgres/release_execution_worker_store.go
@@ -75,13 +75,32 @@ execution_gate AS (
WHEN 'internal' THEN binding.internal_kb_id
WHEN 'external' THEN binding.external_kb_id
END, ''),
- publication.test_kb_id) AS target_kb_id
+ publication.test_kb_id) AS target_kb_id,
+ -- 身份必须与 target_kb_id 来自同一来源:重试/回滚沿用的旧目标若
+ -- 没有身份(迁移前),不能拿当前绑定去补,否则会把旧项写到新实例;
+ -- 这种情况留空,由执行器失败关闭。
+ CASE
+ WHEN NULLIF(prior_item.target_knowledge_base_id, '') IS NOT NULL
+ THEN COALESCE(prior_item.target_instance_url, '')
+ ELSE COALESCE(NULLIF(CASE publication.target_scope
+ WHEN 'internal' THEN binding.internal_instance_url
+ WHEN 'external' THEN binding.external_instance_url
+ END, ''), '')
+ END AS target_instance_url,
+ CASE
+ WHEN NULLIF(prior_item.target_knowledge_base_id, '') IS NOT NULL
+ THEN COALESCE(prior_item.target_tenant_id, 0)
+ ELSE COALESCE(NULLIF(CASE publication.target_scope
+ WHEN 'internal' THEN binding.internal_tenant_id
+ WHEN 'external' THEN binding.external_tenant_id
+ END, 0), 0)
+ END AS target_tenant_id
FROM started
JOIN release_batch_items AS item ON item.release_batch_id = started.release_batch_id
JOIN test_publications AS publication ON publication.id = item.publication_id
LEFT JOIN production_kb_bindings AS binding ON binding.id = 'active'
LEFT JOIN LATERAL (
- SELECT candidate.target_knowledge_base_id
+ SELECT candidate.target_knowledge_base_id, candidate.target_instance_url, candidate.target_tenant_id
FROM release_item_executions AS candidate
JOIN release_executions AS candidate_execution ON candidate_execution.id = candidate.release_execution_id
WHERE candidate.publication_id = item.publication_id
@@ -94,11 +113,14 @@ execution_gate AS (
) AS prior_item ON TRUE
), seeded AS (
INSERT INTO release_item_executions (
- id, release_execution_id, publication_id, action, state, created_at, updated_at, target_knowledge_base_id
+ id, release_execution_id, publication_id, action, state, created_at, updated_at,
+ target_knowledge_base_id, target_instance_url, target_tenant_id
)
SELECT 'ri-' || SUBSTR(MD5(started.id || ':' || item.publication_id), 1, 32),
started.id, item.publication_id, item.action, 'pending', $4::TIMESTAMPTZ, $4::TIMESTAMPTZ,
- COALESCE(target_base.target_kb_id, '')
+ COALESCE(target_base.target_kb_id, ''),
+ COALESCE(target_base.target_instance_url, ''),
+ COALESCE(target_base.target_tenant_id, 0)
FROM started
JOIN release_batch_items AS item ON item.release_batch_id = started.release_batch_id
LEFT JOIN target_base ON target_base.publication_id = item.publication_id
@@ -129,6 +151,8 @@ execution_gate AS (
item.review_id AS release_revision,
publication.test_kb_id,
COALESCE(target_base.target_kb_id, '') AS target_kb_id,
+ COALESCE(target_base.target_instance_url, '') AS target_instance_url,
+ COALESCE(target_base.target_tenant_id, 0) AS target_tenant_id,
publication.knowledge_id,
item.decided_visibility,
COALESCE(previous.production_revision, '') AS previous_production_revision
@@ -180,6 +204,8 @@ SELECT COUNT(DISTINCT started.id)::INTEGER,
'release_revision', plan.release_revision,
'test_knowledge_base_id', plan.test_kb_id,
'target_knowledge_base_id', plan.target_kb_id,
+ 'target_instance_url', plan.target_instance_url,
+ 'target_tenant_id', plan.target_tenant_id,
'knowledge_id', plan.knowledge_id,
'decided_visibility', plan.decided_visibility,
'previous_production_revision', plan.previous_production_revision
@@ -307,7 +333,8 @@ func (s *Store) StartExecution(ctx context.Context, request releaseworkflow.Star
if !validShortID(item.PublicationID) || !validShortID(item.SourceItemVersionID) ||
!validRemoteIdentifier(item.TestKnowledgeBaseID) || !validRemoteIdentifier(item.TargetKnowledgeBaseID) || !validRemoteIdentifier(item.KnowledgeID) ||
(item.DecidedVisibility != governance.VisibilityInternal && item.DecidedVisibility != governance.VisibilityExternal) ||
- len(item.PreviousProductionRevision) > 128 {
+ len(item.PreviousProductionRevision) > 128 || len(item.TargetInstanceURL) > 300 ||
+ strings.ContainsAny(item.TargetInstanceURL, " \r\n\x00") {
return nil, errors.New("invalid release execution plan")
}
}
diff --git a/internal/platform/postgres/release_execution_worker_store_test.go b/internal/platform/postgres/release_execution_worker_store_test.go
index b61b212..a26c8df 100644
--- a/internal/platform/postgres/release_execution_worker_store_test.go
+++ b/internal/platform/postgres/release_execution_worker_store_test.go
@@ -13,7 +13,7 @@ import (
)
func TestStartReleaseExecutionSeedsItemsAndReturnsOnlyPendingPlan(t *testing.T) {
- payload := `[{"release_execution_id":"rx-safe","publication_id":"tp-safe","action":"delete","source_item_version_id":"sv-safe","source_revision":"source-v1","parse_revision":"parser-v1@index-v1","release_revision":"review-v1","test_knowledge_base_id":"kb-safe","target_knowledge_base_id":"prod-kb","knowledge_id":"knowledge-safe","decided_visibility":"internal","previous_production_revision":"prod-old"}]`
+ payload := `[{"release_execution_id":"rx-safe","publication_id":"tp-safe","action":"delete","source_item_version_id":"sv-safe","source_revision":"source-v1","parse_revision":"parser-v1@index-v1","release_revision":"review-v1","test_knowledge_base_id":"kb-safe","target_knowledge_base_id":"prod-kb","target_instance_url":"https://instance-a.weknora.example","target_tenant_id":10000,"knowledge_id":"knowledge-safe","decided_visibility":"internal","previous_production_revision":"prod-old"}]`
db := &recordingDB{row: startExecutionRow{executionCount: 1, payload: []byte(payload)}}
items, err := NewStore(db).StartExecution(context.Background(), releaseworkflow.StartExecutionRequest{
ExecutionID: "rx-safe", JobID: "job-safe", Operation: "publish", Now: time.Now(),
@@ -24,7 +24,7 @@ func TestStartReleaseExecutionSeedsItemsAndReturnsOnlyPendingPlan(t *testing.T)
if len(items) != 1 || items[0].PublicationID != "tp-safe" || items[0].Action != "delete" || items[0].KnowledgeID != "knowledge-safe" || items[0].PreviousProductionRevision != "prod-old" {
t.Fatalf("items=%#v", items)
}
- if items[0].TargetBase() != "prod-kb" {
+ if items[0].TargetBase() != "prod-kb" || items[0].TargetInstanceURL != "https://instance-a.weknora.example" || items[0].TargetTenantID != 10000 {
t.Fatalf("target base=%q, want the mapped 源库 → 目标库 target", items[0].TargetBase())
}
sql := strings.ToLower(db.queryRowSQL)
@@ -39,6 +39,7 @@ func TestStartReleaseExecutionSeedsItemsAndReturnsOnlyPendingPlan(t *testing.T)
"release_delete_ready", "item.action = 'delete'", "execution_gate.valid_items = execution_gate.item_count",
// the 源库 → 目标库 mapping is resolved into the plan and frozen per item
"production_kb_bindings", "target_knowledge_base_id", "target_base.target_kb_id",
+ "target_instance_url", "target_tenant_id", "internal_instance_url", "internal_tenant_id",
} {
if !strings.Contains(sql, required) {
t.Fatalf("start execution SQL missing %q", required)
diff --git a/internal/platform/postgres/release_identity_integration_test.go b/internal/platform/postgres/release_identity_integration_test.go
new file mode 100644
index 0000000..03ad5ed
--- /dev/null
+++ b/internal/platform/postgres/release_identity_integration_test.go
@@ -0,0 +1,71 @@
+package postgres
+
+import (
+ "context"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgxpool"
+
+ "knowledge-governance/internal/governance"
+ releaseworkflow "knowledge-governance/internal/workflows/release"
+)
+
+// The console verified the production binding on instance A. The release plan
+// must freeze that instance identity with each item; the executor later compares
+// it with its own route target before writing. Same knowledge-base id/tenant on
+// a cloned instance is not enough.
+func TestStartReleaseExecutionFreezesTheBindingInstanceIdentity(t *testing.T) {
+ databaseURL := isolatedIntegrationDatabaseURL(t, os.Getenv("TEST_DATABASE_URL"))
+ if databaseURL == "" {
+ t.Skip("TEST_DATABASE_URL is not set")
+ }
+ ctx := context.Background()
+ pool, err := pgxpool.New(ctx, databaseURL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer pool.Close()
+ if err := ApplyMigrations(ctx, pool); err != nil {
+ t.Fatal(err)
+ }
+ store := NewStore(pool)
+ now := time.Date(2026, 11, 19, 9, 0, 0, 0, time.UTC)
+ if _, err := pool.Exec(ctx, `INSERT INTO source_connections (id, source_type, name) VALUES ('conn-manual', 'manual', 'Manual')`); err != nil {
+ t.Fatal(err)
+ }
+ publicationID := "tp-identity-e2e"
+ insertReviewFixture(t, ctx, pool, 9, publicationID, now)
+ if _, err := store.ReviewPublication(ctx, governance.ReviewPublicationRequest{PublicationID: publicationID, Decision: governance.ReviewApproved, DecidedVisibility: governance.VisibilityInternal, ReviewerRef: "engineer-1", DecisionCode: "approved_for_release", Now: now.Add(time.Minute)}); err != nil {
+ t.Fatal(err)
+ }
+ batch, err := store.CreateReleaseBatch(ctx, governance.CreateReleaseBatchRequest{Name: "Identity publish", CreatedBy: "engineer-1", PublicationIDs: []string{publicationID}, Now: now.Add(2 * time.Minute)})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := store.SealReleaseBatch(ctx, governance.SealReleaseBatchRequest{BatchID: batch.ID, SealedBy: "engineer-2", Now: now.Add(3 * time.Minute)}); err != nil {
+ t.Fatal(err)
+ }
+ execution, err := store.AuthorizeReleaseBatch(ctx, governance.AuthorizeReleaseBatchRequest{BatchID: batch.ID, AuthorizedBy: "release-owner", AuthorizationCode: "production_release_authorized", Now: now.Add(4 * time.Minute)})
+ if err != nil {
+ t.Fatal(err)
+ }
+ tx, err := pool.Begin(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := SaveProductionKBBindingsWithIdentityTx(ctx, tx, "test-kb", "test-kb", "https://instance-a.weknora.example", "https://instance-a.weknora.example", 10000, 10000, "admin", now); err != nil {
+ t.Fatal(err)
+ }
+ if err := tx.Commit(ctx); err != nil {
+ t.Fatal(err)
+ }
+ plan, err := store.StartExecution(ctx, releaseworkflow.StartExecutionRequest{ExecutionID: execution.ID, JobID: execution.JobID, Operation: governance.ReleaseOperationPublish, Now: now.Add(5 * time.Minute)})
+ if err != nil || len(plan) != 1 {
+ t.Fatalf("plan=%#v error=%v", plan, err)
+ }
+ if plan[0].TargetKnowledgeBaseID != "test-kb" || plan[0].TargetInstanceURL != "https://instance-a.weknora.example" || plan[0].TargetTenantID != 10000 {
+ t.Fatalf("plan identity = %s / %s / %d", plan[0].TargetKnowledgeBaseID, plan[0].TargetInstanceURL, plan[0].TargetTenantID)
+ }
+}
diff --git a/internal/platform/postgres/routing_bindings.go b/internal/platform/postgres/routing_bindings.go
index 7a23e97..d47fdaa 100644
--- a/internal/platform/postgres/routing_bindings.go
+++ b/internal/platform/postgres/routing_bindings.go
@@ -86,7 +86,7 @@ WHERE stale.superseded_at IS NULL
// already in flight keeps its frozen target and stays visible in 待入库.
const replanMovePendingSQL = `
UPDATE test_publications pending
-SET test_kb_id = $1, updated_at = $3
+SET test_kb_id = $1, test_instance_url = '', test_instance_tenant = 0, updated_at = $3
WHERE pending.superseded_at IS NULL
AND pending.test_kb_id <> $1
AND pending.processing_state = 'planned'
diff --git a/internal/platform/postgres/test_publications.go b/internal/platform/postgres/test_publications.go
index 094ceed..9342115 100644
--- a/internal/platform/postgres/test_publications.go
+++ b/internal/platform/postgres/test_publications.go
@@ -29,22 +29,27 @@ type PublicationForUpload struct {
SourceItemVersionID string
TestKBID string
KnowledgeID string
- IngestState governance.IngestState
- ProcessingState governance.ProcessingState
- TargetScope governance.Visibility
- ContentObjectID string
- SHA256 string
- SizeBytes int64
- MIME string
- ValidatedFormat string
- LocalSpoolRef string
- Title string
+ // 对象实际写入的测试实例身份;空 = 迁移前的旧行,无法证明归属。
+ TestInstanceURL string
+ TestInstanceTenant uint64
+ IngestState governance.IngestState
+ ProcessingState governance.ProcessingState
+ TargetScope governance.Visibility
+ ContentObjectID string
+ SHA256 string
+ SizeBytes int64
+ MIME string
+ ValidatedFormat string
+ LocalSpoolRef string
+ Title string
}
type PublicationForPoll struct {
ID string
TestKBID string
KnowledgeID string
+ TestInstanceURL string
+ TestInstanceTenant uint64
ProcessingState governance.ProcessingState
PollSequence int
LastRemoteStatus string
@@ -55,9 +60,11 @@ type PublicationForPoll struct {
}
type PublicationForValidation struct {
- ID string
- TestKBID string
- KnowledgeID string
+ ID string
+ TestKBID string
+ KnowledgeID string
+ TestInstanceURL string
+ TestInstanceTenant uint64
// TargetScope 决定这条知识发到哪个生产库(对内/对外)。自动批准策略依赖它:
// 默认只自动批准"对内","对外"仍要人工。
TargetScope string
@@ -71,6 +78,7 @@ type LegacyVerificationCandidate struct {
const loadPublicationForUploadSQL = `
SELECT p.id, p.source_item_version_id, p.test_kb_id, p.knowledge_id,
+ p.test_instance_url, p.test_instance_tenant,
p.ingest_state, p.processing_state, p.target_scope,
co.id, co.sha256, co.size_bytes, co.mime, co.validated_format,
co.local_spool_ref, si.title
@@ -89,7 +97,8 @@ WHERE p.id = $1
`
const loadPublicationForPollSQL = `
-SELECT id, test_kb_id, knowledge_id, processing_state, poll_sequence,
+SELECT id, test_kb_id, knowledge_id, test_instance_url, test_instance_tenant,
+ processing_state, poll_sequence,
last_remote_status, last_remote_updated_at, processing_started_at,
last_observed_at, updated_at
FROM test_publications
@@ -97,7 +106,7 @@ WHERE id = $1
`
const loadPublicationForValidationSQL = `
-SELECT id, test_kb_id, knowledge_id, target_scope
+SELECT id, test_kb_id, knowledge_id, test_instance_url, test_instance_tenant, target_scope
FROM test_publications
WHERE id = $1
AND ingest_state = 'uploaded'
@@ -223,8 +232,10 @@ ON CONFLICT (idempotency_key) DO NOTHING
const markUploadingSQL = `
UPDATE test_publications
SET ingest_state = 'uploading',
+ test_instance_url = $2,
+ test_instance_tenant = $3,
last_error = '',
- updated_at = $2
+ updated_at = $4
WHERE id = $1
AND ingest_state IN ('pending', 'uploading')
AND processing_state = 'pending'
@@ -393,6 +404,8 @@ func (s *Store) LoadPublicationForUpload(ctx context.Context, publicationID stri
&candidate.SourceItemVersionID,
&candidate.TestKBID,
&candidate.KnowledgeID,
+ &candidate.TestInstanceURL,
+ &candidate.TestInstanceTenant,
&ingestState,
&processingState,
&candidate.TargetScope,
@@ -422,6 +435,8 @@ func (s *Store) LoadPublicationForPoll(ctx context.Context, publicationID string
&publication.ID,
&publication.TestKBID,
&publication.KnowledgeID,
+ &publication.TestInstanceURL,
+ &publication.TestInstanceTenant,
&processingState,
&publication.PollSequence,
&publication.LastRemoteStatus,
@@ -446,6 +461,8 @@ func (s *Store) LoadPublicationForValidation(ctx context.Context, publicationID
&publication.ID,
&publication.TestKBID,
&publication.KnowledgeID,
+ &publication.TestInstanceURL,
+ &publication.TestInstanceTenant,
&publication.TargetScope,
)
if errors.Is(err, pgx.ErrNoRows) {
@@ -594,8 +611,8 @@ func (s *Store) RetryPublication(ctx context.Context, publicationID string, now
return nil
}
-func (s *Store) MarkUploading(ctx context.Context, publicationID string, now time.Time) error {
- tag, err := s.db.Exec(ctx, markUploadingSQL, publicationID, now)
+func (s *Store) MarkUploading(ctx context.Context, publicationID, instanceURL string, instanceTenant uint64, now time.Time) error {
+ tag, err := s.db.Exec(ctx, markUploadingSQL, publicationID, instanceURL, instanceTenant, now)
if err != nil {
return fmt.Errorf("mark test publication uploading: %w", err)
}
diff --git a/internal/platform/postgres/test_publications_integration_test.go b/internal/platform/postgres/test_publications_integration_test.go
index 211bc09..4c68024 100644
--- a/internal/platform/postgres/test_publications_integration_test.go
+++ b/internal/platform/postgres/test_publications_integration_test.go
@@ -64,7 +64,7 @@ func TestPublicationOrchestrationIsAtomicAndRejectsStaleTransitions(t *testing.T
if _, err := store.LoadPublicationForUpload(ctx, "publication-1"); err != nil {
t.Fatal(err)
}
- if err := store.MarkUploading(ctx, "publication-1", now); err != nil {
+ if err := store.MarkUploading(ctx, "publication-1", "", 0, now); err != nil {
t.Fatal(err)
}
if sequence, err := store.RecordUploadAndSchedulePoll(ctx, "publication-1", "knowledge-1", now, now.Add(10*time.Second)); err != nil || sequence != 1 {
diff --git a/internal/platform/postgres/test_publications_test.go b/internal/platform/postgres/test_publications_test.go
index 255dfe7..6b9eb62 100644
--- a/internal/platform/postgres/test_publications_test.go
+++ b/internal/platform/postgres/test_publications_test.go
@@ -39,7 +39,7 @@ func TestLoadPublicationForUploadMapsVerifiedCandidate(t *testing.T) {
func TestMarkUploadingRejectsStalePublicationState(t *testing.T) {
db := &recordingDB{commandTag: pgconn.NewCommandTag("UPDATE 0")}
- err := NewStore(db).MarkUploading(context.Background(), "publication-1", time.Date(2026, time.September, 4, 2, 0, 0, 0, time.UTC))
+ err := NewStore(db).MarkUploading(context.Background(), "publication-1", "", 0, time.Date(2026, time.September, 4, 2, 0, 0, 0, time.UTC))
if !errors.Is(err, ErrPublicationStateConflict) {
t.Fatalf("MarkUploading() error = %v, want ErrPublicationStateConflict", err)
}
@@ -380,6 +380,8 @@ func (publicationValidationRow) Scan(dest ...any) error {
*(dest[0].(*string)) = "publication-1"
*(dest[1].(*string)) = "kb-1"
*(dest[2].(*string)) = "knowledge-1"
+ *(dest[3].(*string)) = ""
+ *(dest[4].(*uint64)) = 0
return nil
}
@@ -547,13 +549,15 @@ func (row publicationPollRow) Scan(dest ...any) error {
*(dest[0].(*string)) = "publication-1"
*(dest[1].(*string)) = "kb-1"
*(dest[2].(*string)) = "knowledge-1"
- *(dest[3].(*string)) = string(governance.ProcessingProcessing)
- *(dest[4].(*int)) = 2
- *(dest[5].(*string)) = "processing"
- *(dest[6].(**time.Time)) = &row.now
- *(dest[7].(**time.Time)) = &row.now
+ *(dest[3].(*string)) = ""
+ *(dest[4].(*uint64)) = 0
+ *(dest[5].(*string)) = string(governance.ProcessingProcessing)
+ *(dest[6].(*int)) = 2
+ *(dest[7].(*string)) = "processing"
*(dest[8].(**time.Time)) = &row.now
*(dest[9].(**time.Time)) = &row.now
+ *(dest[10].(**time.Time)) = &row.now
+ *(dest[11].(**time.Time)) = &row.now
return nil
}
@@ -572,6 +576,8 @@ func (publicationUploadRow) Scan(dest ...any) error {
"version-1",
"kb-1",
"",
+ "", // test_instance_url
+ uint64(0),
string(governance.IngestPending),
string(governance.ProcessingPending),
"internal",
@@ -589,6 +595,8 @@ func (publicationUploadRow) Scan(dest ...any) error {
*target = value.(string)
case *int64:
*target = value.(int64)
+ case *uint64:
+ *target = value.(uint64)
case *governance.Visibility:
*target = governance.Visibility(value.(string))
case nil:
diff --git a/internal/platform/weknora/types.go b/internal/platform/weknora/types.go
index 71e5374..b3ebe6f 100644
--- a/internal/platform/weknora/types.go
+++ b/internal/platform/weknora/types.go
@@ -2,6 +2,8 @@ package weknora
import (
"io"
+ "net/url"
+ "strings"
"time"
)
@@ -98,6 +100,34 @@ type knowledgeBaseResponse struct {
Data KnowledgeBase `json:"data"`
}
+// InstanceIdentity is the verifiable identity of the WeKnora instance a call
+// actually reached: the normalized service address plus the tenant that owns
+// the knowledge base. Knowledge base ids alone cannot distinguish a cloned
+// instance, so workflows that stored an object must compare this before using
+// the object again.
+type InstanceIdentity struct {
+ BaseURL string
+ TenantID uint64
+}
+
+// NormalizeInstanceURL is the single comparison form for service addresses:
+// scheme/host are case-insensitive and a trailing slash is not a different
+// instance. Userinfo/query/fragment never reach storage (endpoints are
+// validated as bare origins), so they are deliberately dropped here.
+func NormalizeInstanceURL(raw string) string {
+ parsed, err := url.Parse(strings.TrimSpace(raw))
+ if err != nil || parsed.Host == "" {
+ return strings.TrimSpace(raw)
+ }
+ parsed.Scheme = strings.ToLower(parsed.Scheme)
+ parsed.Host = strings.ToLower(parsed.Host)
+ parsed.Path = strings.TrimRight(parsed.Path, "/")
+ parsed.User = nil
+ parsed.RawQuery = ""
+ parsed.Fragment = ""
+ return parsed.String()
+}
+
type chunkListResponse struct {
Success bool `json:"success"`
Data []Chunk `json:"data"`
diff --git a/internal/releaseadapter/v071/archive_test.go b/internal/releaseadapter/v071/archive_test.go
index b73f0f9..b5e7ed6 100644
--- a/internal/releaseadapter/v071/archive_test.go
+++ b/internal/releaseadapter/v071/archive_test.go
@@ -151,5 +151,5 @@ func testDocumentBundle(t *testing.T) *DocumentBundle {
func fixedArchiveTime() time.Time { return time.Date(2026, 9, 6, 11, 0, 0, 0, time.UTC) }
func releasePlanForArchive() releaseworkflow.PlanItem {
- return releaseworkflow.PlanItem{ReleaseExecutionID: "rx-safe", PublicationID: "tp-safe", SourceItemVersionID: "sv-safe", SourceRevision: "source-v1", ParseRevision: "parser-v1@index-v1", ReleaseRevision: "review-v1", TestKnowledgeBaseID: "kb-safe", KnowledgeID: "knowledge-safe", DecidedVisibility: "internal"}
+ return releaseworkflow.PlanItem{ReleaseExecutionID: "rx-safe", PublicationID: "tp-safe", SourceItemVersionID: "sv-safe", SourceRevision: "source-v1", ParseRevision: "parser-v1@index-v1", ReleaseRevision: "review-v1", TestKnowledgeBaseID: "kb-safe", TargetInstanceURL: "https://executor.weknora.example", TargetTenantID: 10000, KnowledgeID: "knowledge-safe", DecidedVisibility: "internal"}
}
diff --git a/internal/releaseadapter/v071/document_target.go b/internal/releaseadapter/v071/document_target.go
index d08ad93..b2a5201 100644
--- a/internal/releaseadapter/v071/document_target.go
+++ b/internal/releaseadapter/v071/document_target.go
@@ -3,7 +3,9 @@ package v071
import (
"context"
"errors"
+ "fmt"
+ "knowledge-governance/internal/platform/weknora"
"knowledge-governance/internal/releasebundle"
releaseworkflow "knowledge-governance/internal/workflows/release"
)
@@ -49,6 +51,11 @@ type DocumentTargetConfig struct {
Search searchDocumentTarget
Objects objectDocumentTarget
Verifier ProductionVerifier
+ // TargetInstanceURL/TargetTenantID are the executor's own route target. The
+ // console freezes the instance it verified the binding on; this side must
+ // match before any document write/restore.
+ TargetInstanceURL string
+ TargetTenantID uint64
}
type DocumentTarget struct {
@@ -63,6 +70,9 @@ func NewDocumentTarget(config DocumentTargetConfig) (*DocumentTarget, error) {
}
func (target *DocumentTarget) Contract(ctx context.Context, item releaseworkflow.PlanItem) (releasebundle.TargetContract, error) {
+ if err := target.checkInstance(item); err != nil {
+ return releasebundle.TargetContract{}, err
+ }
contract, err := target.config.Contract.Contract(ctx, item)
if err != nil {
return releasebundle.TargetContract{}, errors.New("inspect target release contract")
@@ -75,6 +85,9 @@ func (target *DocumentTarget) Contract(ctx context.Context, item releaseworkflow
// same target base. The archive itself keeps the canonical source-form bundle:
// the remap is deterministic, so a rollback re-derives the same target form.
func (target *DocumentTarget) loadBundle(item releaseworkflow.PlanItem, revision string) (*DocumentBundle, error) {
+ if err := target.checkInstance(item); err != nil {
+ return nil, err
+ }
bundle, err := target.config.Archive.Load(revision)
if err != nil {
return nil, err
@@ -86,6 +99,9 @@ func (target *DocumentTarget) loadBundle(item releaseworkflow.PlanItem, revision
}
func (target *DocumentTarget) Prepare(ctx context.Context, item releaseworkflow.PlanItem, exported releaseworkflow.ExportedBundle) (releaseworkflow.PreparedChange, error) {
+ if err := target.checkInstance(item); err != nil {
+ return releaseworkflow.PreparedChange{}, err
+ }
bundle, ok := exported.(*DocumentBundle)
if !ok || validateDocumentBundle(bundle) != nil || bundle.Manifest.ReleaseRevision != item.ReleaseRevision {
return releaseworkflow.PreparedChange{}, errors.New("invalid v0.7.1 target bundle")
@@ -219,6 +235,30 @@ func (target *DocumentTarget) VerifyRestored(ctx context.Context, item releasewo
return nil
}
+// checkInstance is the single instance-identity boundary for the document
+// release path. Empty identity means a pre-identity binding: the executor
+// cannot prove which instance it is, so it fails closed instead of writing to a
+// cloned instance that happens to expose the same knowledge base id.
+func (target *DocumentTarget) checkInstance(item releaseworkflow.PlanItem) error {
+ if item.TargetInstanceURL == "" || item.TargetTenantID == 0 {
+ return fmt.Errorf("%w: binding has no verified instance identity", releaseworkflow.ErrTargetInstanceMismatch)
+ }
+ if target.config.TargetInstanceURL == "" || target.config.TargetTenantID == 0 {
+ return fmt.Errorf("%w: executor target identity is not configured", releaseworkflow.ErrTargetInstanceMismatch)
+ }
+ if weknora.NormalizeInstanceURL(item.TargetInstanceURL) != weknora.NormalizeInstanceURL(target.config.TargetInstanceURL) {
+ return fmt.Errorf("%w: binding verified on %s, executor writes %s",
+ releaseworkflow.ErrTargetInstanceMismatch,
+ weknora.NormalizeInstanceURL(item.TargetInstanceURL),
+ weknora.NormalizeInstanceURL(target.config.TargetInstanceURL))
+ }
+ if item.TargetTenantID != target.config.TargetTenantID {
+ return fmt.Errorf("%w: binding tenant %d, executor tenant %d",
+ releaseworkflow.ErrTargetInstanceMismatch, item.TargetTenantID, target.config.TargetTenantID)
+ }
+ return nil
+}
+
func (target *DocumentTarget) restoreBundle(ctx context.Context, item releaseworkflow.PlanItem, revision string) error {
bundle, err := target.loadBundle(item, revision)
if err != nil {
diff --git a/internal/releaseadapter/v071/document_target_test.go b/internal/releaseadapter/v071/document_target_test.go
index 2a972f8..4fd3ba8 100644
--- a/internal/releaseadapter/v071/document_target_test.go
+++ b/internal/releaseadapter/v071/document_target_test.go
@@ -2,6 +2,7 @@ package v071
import (
"context"
+ "errors"
"os"
"reflect"
"testing"
@@ -20,7 +21,7 @@ func TestDocumentTargetCoordinatesPrepareActivateVerifyAndRollback(t *testing.T)
t.Fatal(err)
}
calls := []string{}
- target, err := NewDocumentTarget(DocumentTargetConfig{Archive: archive, Contract: &stubContractInspector{contract: targetContractForBundle(current)}, Postgres: &stubPostgresTarget{calls: &calls}, Search: &stubSearchTarget{calls: &calls}, Objects: &stubObjectTarget{calls: &calls}, Verifier: &stubProductionVerifier{calls: &calls}})
+ target, err := NewDocumentTarget(DocumentTargetConfig{Archive: archive, Contract: &stubContractInspector{contract: targetContractForBundle(current)}, Postgres: &stubPostgresTarget{calls: &calls}, Search: &stubSearchTarget{calls: &calls}, Objects: &stubObjectTarget{calls: &calls}, Verifier: &stubProductionVerifier{calls: &calls}, TargetInstanceURL: "https://executor.weknora.example", TargetTenantID: 10000})
if err != nil {
t.Fatal(err)
}
@@ -60,7 +61,7 @@ func TestDocumentTargetCompensatesFirstReleaseByDisableWithoutDelete(t *testing.
archive, _ := NewBundleArchive(root, 16*1024*1024)
bundle := testDocumentBundle(t)
calls := []string{}
- target, _ := NewDocumentTarget(DocumentTargetConfig{Archive: archive, Contract: &stubContractInspector{contract: targetContractForBundle(bundle)}, Postgres: &stubPostgresTarget{calls: &calls}, Search: &stubSearchTarget{calls: &calls}, Objects: &stubObjectTarget{calls: &calls}, Verifier: &stubProductionVerifier{calls: &calls}})
+ target, _ := NewDocumentTarget(DocumentTargetConfig{Archive: archive, Contract: &stubContractInspector{contract: targetContractForBundle(bundle)}, Postgres: &stubPostgresTarget{calls: &calls}, Search: &stubSearchTarget{calls: &calls}, Objects: &stubObjectTarget{calls: &calls}, Verifier: &stubProductionVerifier{calls: &calls}, TargetInstanceURL: "https://executor.weknora.example", TargetTenantID: 10000})
item := releasePlanForArchive()
change, err := target.Prepare(context.Background(), item, bundle)
if err != nil {
@@ -179,3 +180,44 @@ func revisionFromSearch(snapshot SearchSnapshot) string {
}
return "unknown"
}
+
+// 网页在实例 A 上列库并保存了绑定,执行器实际连的是实例 B;即使两边知识库
+// ID 与租户完全相同,也不得写入 B。这里复用 DocumentTarget 的唯一实例身份
+// 检查,正例证明同一实例仍可通过。
+func TestDocumentTargetRejectsBindingVerifiedOnAnotherInstance(t *testing.T) {
+ root := t.TempDir()
+ _ = os.Chmod(root, 0o700)
+ archive, _ := NewBundleArchive(root, 16*1024*1024)
+ bundle := testDocumentBundle(t)
+ calls := []string{}
+ target, err := NewDocumentTarget(DocumentTargetConfig{
+ Archive: archive, Contract: &stubContractInspector{contract: targetContractForBundle(bundle)},
+ Postgres: &stubPostgresTarget{calls: &calls}, Search: &stubSearchTarget{calls: &calls},
+ Objects: &stubObjectTarget{calls: &calls}, Verifier: &stubProductionVerifier{calls: &calls},
+ TargetInstanceURL: "https://instance-b.weknora.example", TargetTenantID: 10000,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ item := releasePlanForArchive() // verified on instance A, same kb id, same tenant
+ item.TargetKnowledgeBaseID = "kb-safe"
+ if _, err := target.Contract(context.Background(), item); !errors.Is(err, releaseworkflow.ErrTargetInstanceMismatch) {
+ t.Fatalf("contract error = %v, want ErrTargetInstanceMismatch", err)
+ }
+ if _, err := target.Prepare(context.Background(), item, bundle); !errors.Is(err, releaseworkflow.ErrTargetInstanceMismatch) {
+ t.Fatalf("prepare error = %v, want ErrTargetInstanceMismatch", err)
+ }
+ if len(calls) != 0 {
+ t.Fatalf("no write/stage may happen before identity matches: %v", calls)
+ }
+
+ item.TargetInstanceURL = "https://instance-b.weknora.example"
+ item.TargetTenantID = 10000
+ if _, err := target.Contract(context.Background(), item); err != nil {
+ t.Fatalf("same instance must pass: %v", err)
+ }
+ item.TargetTenantID = 20000
+ if _, err := target.Contract(context.Background(), item); !errors.Is(err, releaseworkflow.ErrTargetInstanceMismatch) {
+ t.Fatalf("tenant mismatch error = %v, want ErrTargetInstanceMismatch", err)
+ }
+}
diff --git a/internal/releaseadapter/v071/three_lane_integration_test.go b/internal/releaseadapter/v071/three_lane_integration_test.go
index 29857bd..2478983 100644
--- a/internal/releaseadapter/v071/three_lane_integration_test.go
+++ b/internal/releaseadapter/v071/three_lane_integration_test.go
@@ -97,7 +97,7 @@ func TestLegacyThreeLanePublishRefusesUnplannedWritesIntegration(t *testing.T) {
}
verification := &verificationClient{knowledge: weknora.Knowledge{ID: "knowledge-release-safe", KnowledgeBaseID: "kb-release-safe", ParseStatus: "completed"}, chunkTotal: 1, search: []weknora.SearchResult{{ID: "chunk-release-safe", KnowledgeID: "knowledge-release-safe", Score: 0.8}}}
verifier, _ := NewWeKnoraVerifier(verification)
- target, err := NewDocumentTarget(DocumentTargetConfig{Archive: archive, Contract: &stubContractInspector{contract: contract}, Postgres: postgresImporter, Search: targetSearch, Objects: objectImporter, Verifier: verifier})
+ target, err := NewDocumentTarget(DocumentTargetConfig{Archive: archive, Contract: &stubContractInspector{contract: contract}, Postgres: postgresImporter, Search: targetSearch, Objects: objectImporter, Verifier: verifier, TargetInstanceURL: "https://executor.weknora.example", TargetTenantID: 10000})
if err != nil {
t.Fatal(err)
}
@@ -106,7 +106,7 @@ func TestLegacyThreeLanePublishRefusesUnplannedWritesIntegration(t *testing.T) {
t.Fatal(err)
}
- first := releaseworkflow.PlanItem{ReleaseExecutionID: "rx-release-1", PublicationID: "tp-release-1", SourceItemVersionID: "version-release-safe", SourceRevision: "source-v1", ParseRevision: "parser-v1@index-v1", ReleaseRevision: "review-release-1", TestKnowledgeBaseID: "kb-release-safe", KnowledgeID: "knowledge-release-safe", DecidedVisibility: "internal"}
+ first := releaseworkflow.PlanItem{ReleaseExecutionID: "rx-release-1", PublicationID: "tp-release-1", SourceItemVersionID: "version-release-safe", SourceRevision: "source-v1", ParseRevision: "parser-v1@index-v1", ReleaseRevision: "review-release-1", TestKnowledgeBaseID: "kb-release-safe", TargetInstanceURL: "https://executor.weknora.example", TargetTenantID: 10000, KnowledgeID: "knowledge-release-safe", DecidedVisibility: "internal"}
if _, err := exporter.Export(ctx, first); err != nil {
t.Fatalf("export preflight: %v", err)
}
diff --git a/internal/releaseadapter/v071/wiki_channel_test.go b/internal/releaseadapter/v071/wiki_channel_test.go
index c40a4cf..86aa5b8 100644
--- a/internal/releaseadapter/v071/wiki_channel_test.go
+++ b/internal/releaseadapter/v071/wiki_channel_test.go
@@ -182,6 +182,7 @@ func TestDocumentTargetAppliesWikiSnapshotWhenWithdrawing(t *testing.T) {
Archive: archive, Contract: &stubContractInspector{contract: targetContractForBundle(bundle)},
Postgres: &stubPostgresTarget{calls: &calls}, Search: &stubSearchTarget{calls: &calls},
Objects: &stubObjectTarget{calls: &calls}, Verifier: &stubProductionVerifier{calls: &calls},
+ TargetInstanceURL: "https://executor.weknora.example", TargetTenantID: 10000,
})
if err != nil {
t.Fatal(err)
diff --git a/internal/weknoraaccess/client.go b/internal/weknoraaccess/client.go
index 2ce9dab..dd12f31 100644
--- a/internal/weknoraaccess/client.go
+++ b/internal/weknoraaccess/client.go
@@ -47,6 +47,37 @@ func (client *Client) with(ctx context.Context, call func(*weknora.Client) error
return call(remote)
}
+func (client *Client) TargetIdentity(ctx context.Context, knowledgeBaseID string) (weknora.InstanceIdentity, error) {
+ target, err := client.Resolver.Resolve(ctx)
+ if err != nil {
+ return weknora.InstanceIdentity{}, err
+ }
+ if target.BaseURL == "" || target.APIKey == "" || knowledgeBaseID == "" {
+ return weknora.InstanceIdentity{}, ErrNotConfigured
+ }
+ timeout := client.Timeout
+ if timeout <= 0 {
+ timeout = defaultBusinessTimeout
+ }
+ remote, err := weknora.NewClient(weknora.ClientConfig{
+ BaseURL: target.BaseURL,
+ APIKey: target.APIKey,
+ Timeout: timeout,
+ AllowDockerHTTP: client.AllowDockerHTTP,
+ })
+ if err != nil {
+ return weknora.InstanceIdentity{}, err
+ }
+ base, err := remote.GetKnowledgeBase(ctx, knowledgeBaseID)
+ if err != nil {
+ return weknora.InstanceIdentity{}, err
+ }
+ return weknora.InstanceIdentity{
+ BaseURL: weknora.NormalizeInstanceURL(target.BaseURL),
+ TenantID: base.TenantID,
+ }, nil
+}
+
func (client *Client) UploadFile(ctx context.Context, request weknora.UploadRequest) (weknora.Knowledge, error) {
var knowledge weknora.Knowledge
err := client.with(ctx, func(remote *weknora.Client) error {
diff --git a/internal/weknoraaccess/client_test.go b/internal/weknoraaccess/client_test.go
index 6faedc2..e51db15 100644
--- a/internal/weknoraaccess/client_test.go
+++ b/internal/weknoraaccess/client_test.go
@@ -108,3 +108,26 @@ func TestExplicitShortBusinessTimeoutStillApplies(t *testing.T) {
t.Fatalf("explicit short timeout took %s", elapsed)
}
}
+
+func TestTargetIdentityReadsTheOwnedTenantFromTheCurrentBinding(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/api/v1/knowledge-bases/kb-current" {
+ w.WriteHeader(http.StatusNotFound)
+ return
+ }
+ _, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-current","name":"Current","tenant_id":10000}}`))
+ }))
+ defer server.Close()
+ client := &Client{Resolver: readiness.Resolver{
+ Endpoint: func(context.Context) string { return server.URL + "/" },
+ ReadKey: func() (string, error) { return "isolated-test-key", nil },
+ LoadBinding: func(context.Context) (string, error) { return "kb-current", nil },
+ }, Timeout: time.Second}
+ identity, err := client.TargetIdentity(context.Background(), "kb-current")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if identity.BaseURL != server.URL || identity.TenantID != 10000 {
+ t.Fatalf("identity = %#v", identity)
+ }
+}
diff --git a/internal/workflows/release/handler.go b/internal/workflows/release/handler.go
index bdf550b..f9b0a7c 100644
--- a/internal/workflows/release/handler.go
+++ b/internal/workflows/release/handler.go
@@ -37,6 +37,9 @@ var (
ErrInvalidReleaseJob = errors.New("invalid_release_job")
ErrReleaseRetryable = errors.New("release_retryable")
ErrReleaseState = errors.New("release_state_failed")
+ // ErrTargetInstanceMismatch: the binding was verified on instance A while
+ // the executor writes instance B (even with the same knowledge base id).
+ ErrTargetInstanceMismatch = errors.New("release_target_instance_mismatch")
)
type PlanItem struct {
@@ -51,7 +54,13 @@ type PlanItem struct {
// TargetKnowledgeBaseID is the 源库 → 目标库 mapping resolved when the
// execution started (see production_kb_bindings). It equals the tested base
// when the scope is unbound, which is the historical same-id semantics.
- TargetKnowledgeBaseID string `json:"target_knowledge_base_id"`
+ TargetKnowledgeBaseID string `json:"target_knowledge_base_id"`
+ // TargetInstanceURL/TargetTenantID freeze the instance identity the console
+ // verified the selected base on. The executor compares them with its own
+ // route target before any write; a cloned instance with the same base id is
+ // not the same target.
+ TargetInstanceURL string `json:"target_instance_url,omitempty"`
+ TargetTenantID uint64 `json:"target_tenant_id,omitempty"`
KnowledgeID string `json:"knowledge_id"`
DecidedVisibility governance.Visibility `json:"decided_visibility"`
PreviousProductionRevision string `json:"previous_production_revision"`
diff --git a/internal/workflows/release/sidecar_publisher.go b/internal/workflows/release/sidecar_publisher.go
index 9e4744e..8ec3dd4 100644
--- a/internal/workflows/release/sidecar_publisher.go
+++ b/internal/workflows/release/sidecar_publisher.go
@@ -132,7 +132,7 @@ func (publisher *SidecarPublisher) Publish(ctx context.Context, item PlanItem) (
}
targetContract, err := publisher.target.Contract(ctx, item)
if err != nil {
- return ItemResult{}, newSidecarError(ErrorCodeTargetUnavailable, true, err)
+ return ItemResult{}, targetError(err)
}
if err := releasebundle.Validate(manifest, targetContract, releaseItemMapping(item)); err != nil {
return ItemResult{}, newSidecarError(ErrorCodeContractMismatch, false, err)
@@ -166,7 +166,7 @@ func (publisher *SidecarPublisher) Rollback(ctx context.Context, item PlanItem)
}
restoredRevision, err := publisher.target.Restore(ctx, item, item.PreviousProductionRevision)
if err != nil {
- return ItemResult{}, newSidecarError(ErrorCodeTargetWriteFailed, true, err)
+ return ItemResult{}, targetError(err)
}
if restoredRevision != item.PreviousProductionRevision {
return ItemResult{}, newSidecarError(ErrorCodeContractMismatch, false, errors.New("restored revision mismatch"))
@@ -197,7 +197,7 @@ func (publisher *SidecarPublisher) Delete(ctx context.Context, item PlanItem) (I
}
targetContract, err := publisher.target.Contract(ctx, item)
if err != nil {
- return ItemResult{}, newSidecarError(ErrorCodeTargetUnavailable, true, err)
+ return ItemResult{}, targetError(err)
}
if err := releasebundle.Validate(manifest, targetContract, releaseItemMapping(item)); err != nil {
return ItemResult{}, newSidecarError(ErrorCodeContractMismatch, false, err)
@@ -224,6 +224,9 @@ func (publisher *SidecarPublisher) Delete(ctx context.Context, item PlanItem) (I
func (publisher *SidecarPublisher) compensateError(ctx context.Context, item PlanItem, change PreparedChange, code string, cause error) error {
if err := publisher.target.Compensate(ctx, item, change); err != nil {
+ if errors.Is(err, ErrTargetInstanceMismatch) {
+ return newSidecarError(ErrorCodeContractMismatch, false, err)
+ }
return newSidecarError(ErrorCodeRollbackFailed, false, err)
}
return newSidecarError(code, false, cause)
@@ -233,6 +236,15 @@ func newSidecarError(code string, retryable bool, cause error) error {
return &ItemError{Code: code, Retryable: retryable, Cause: cause}
}
+// targetError keeps an instance mismatch non-retryable: retrying the same item
+// on the same wrong instance will never become the verified target.
+func targetError(err error) error {
+ if errors.Is(err, ErrTargetInstanceMismatch) {
+ return newSidecarError(ErrorCodeContractMismatch, false, err)
+ }
+ return newSidecarError(ErrorCodeTargetUnavailable, true, err)
+}
+
func validRevision(value string) bool {
return value == strings.TrimSpace(value) && value != "" && len(value) <= 128 && !strings.ContainsAny(value, "\x00\r\n\t/?#\\")
}
diff --git a/internal/workflows/release/sidecar_publisher_test.go b/internal/workflows/release/sidecar_publisher_test.go
index efb334f..d375e04 100644
--- a/internal/workflows/release/sidecar_publisher_test.go
+++ b/internal/workflows/release/sidecar_publisher_test.go
@@ -163,6 +163,7 @@ func (bundle fakeExportedBundle) ReleaseManifest() releasebundle.Manifest { retu
type fakeSidecarTarget struct {
contract releasebundle.TargetContract
+ contractErr error
calls *[]string
prepared PreparedChange
prepareErr, activateErr, verifyErr, compensateErr, restoreErr, verifyRestoredErr error
@@ -172,7 +173,7 @@ type fakeSidecarTarget struct {
func (f *fakeSidecarTarget) Contract(context.Context, PlanItem) (releasebundle.TargetContract, error) {
*f.calls = append(*f.calls, "contract")
- return f.contract, nil
+ return f.contract, f.contractErr
}
func (f *fakeSidecarTarget) Prepare(context.Context, PlanItem, ExportedBundle) (PreparedChange, error) {
*f.calls = append(*f.calls, "prepare")
@@ -360,3 +361,26 @@ func TestSidecarPublisherGatesDeleteAndRollbackToo(t *testing.T) {
}
}
}
+
+// Instance identity mismatch is a contract failure, not a transient target
+// outage: retrying the same item on the same wrong instance can never succeed.
+func TestSidecarPublisherMapsInstanceMismatchToNonRetryableContractError(t *testing.T) {
+ calls := []string{}
+ manifest, err := releasebundle.Seal(testManifest())
+ if err != nil {
+ t.Fatal(err)
+ }
+ publisher, err := NewSidecarPublisher(&fakeExporter{manifest: manifest, calls: &calls},
+ &fakeSidecarTarget{contract: testTargetContract(), contractErr: ErrTargetInstanceMismatch, calls: &calls})
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, err = publisher.Publish(context.Background(), testPlanItem())
+ var itemErr *ItemError
+ if !errors.As(err, &itemErr) || itemErr.Code != ErrorCodeContractMismatch || itemErr.Retryable {
+ t.Fatalf("error=%#v", err)
+ }
+ if !reflect.DeepEqual(calls, []string{"export", "contract"}) {
+ t.Fatalf("calls=%v", calls)
+ }
+}
diff --git a/internal/workflows/testweknora/identity.go b/internal/workflows/testweknora/identity.go
new file mode 100644
index 0000000..53bd741
--- /dev/null
+++ b/internal/workflows/testweknora/identity.go
@@ -0,0 +1,38 @@
+package testweknora
+
+import (
+ "context"
+
+ "knowledge-governance/internal/platform/weknora"
+)
+
+// IdentityProvider is implemented by the production WeKnora access client. Unit
+// fakes may omit it; a handler must then treat stored identities as unverifiable
+// and never write/delete/adopt an object across instances.
+type IdentityProvider interface {
+ TargetIdentity(context.Context, string) (weknora.InstanceIdentity, error)
+}
+
+func resolveIdentity(ctx context.Context, client any, knowledgeBaseID string) (weknora.InstanceIdentity, bool, error) {
+ provider, ok := client.(IdentityProvider)
+ if !ok {
+ return weknora.InstanceIdentity{}, false, nil
+ }
+ identity, err := provider.TargetIdentity(ctx, knowledgeBaseID)
+ if err != nil {
+ return weknora.InstanceIdentity{}, true, err
+ }
+ identity.BaseURL = weknora.NormalizeInstanceURL(identity.BaseURL)
+ return identity, true, nil
+}
+
+// identityMatches requires BOTH the instance address and the owning tenant to
+// match. A cloned instance can expose the same knowledge base id and tenant id;
+// an empty stored identity is never treated as "matches anything".
+func identityMatches(storedURL string, storedTenant uint64, current weknora.InstanceIdentity) bool {
+ if storedURL == "" || storedTenant == 0 {
+ return false
+ }
+ return weknora.NormalizeInstanceURL(storedURL) == weknora.NormalizeInstanceURL(current.BaseURL) &&
+ storedTenant == current.TenantID
+}
diff --git a/internal/workflows/testweknora/identity_test.go b/internal/workflows/testweknora/identity_test.go
new file mode 100644
index 0000000..1fd9e97
--- /dev/null
+++ b/internal/workflows/testweknora/identity_test.go
@@ -0,0 +1,152 @@
+package testweknora
+
+import (
+ "context"
+ "errors"
+ "testing"
+ "time"
+
+ "knowledge-governance/internal/governance"
+ "knowledge-governance/internal/jobs"
+ postgresstore "knowledge-governance/internal/platform/postgres"
+ "knowledge-governance/internal/platform/weknora"
+)
+
+const (
+ instanceA = "https://instance-a.weknora.example"
+ instanceB = "https://instance-b.weknora.example"
+)
+
+type identityClient struct {
+ identity weknora.InstanceIdentity
+ identityErr error
+ knowledge weknora.Knowledge
+ chunkTotal int64
+ getCalls int
+ chunkCalls int
+ deleteCalls int
+ uploadCalls int
+}
+
+func (client *identityClient) TargetIdentity(context.Context, string) (weknora.InstanceIdentity, error) {
+ return client.identity, client.identityErr
+}
+func (client *identityClient) GetKnowledge(context.Context, string) (weknora.Knowledge, error) {
+ client.getCalls++
+ if client.knowledge.ID == "" {
+ return weknora.Knowledge{}, &weknora.HTTPError{StatusCode: 404}
+ }
+ return client.knowledge, nil
+}
+func (client *identityClient) ListChunks(context.Context, string, int, int, []string) ([]weknora.Chunk, int64, error) {
+ client.chunkCalls++
+ return []weknora.Chunk{{ID: "chunk-1"}}, client.chunkTotal, nil
+}
+func (client *identityClient) DeleteKnowledge(context.Context, string) error {
+ client.deleteCalls++
+ return nil
+}
+func (client *identityClient) UploadFile(context.Context, weknora.UploadRequest) (weknora.Knowledge, error) {
+ client.uploadCalls++
+ return weknora.Knowledge{}, errors.New("unexpected upload")
+}
+func (client *identityClient) ListKnowledge(context.Context, string, int, int) ([]weknora.Knowledge, int64, error) {
+ return nil, 0, nil
+}
+
+func TestPollRejectsObjectUploadedToAnotherInstance(t *testing.T) {
+ now := time.Date(2026, 11, 19, 9, 0, 0, 0, time.UTC)
+ store := &pollStoreStub{publication: postgresstore.PublicationForPoll{
+ ID: "publication-1", TestKBID: "kb-1", KnowledgeID: "knowledge-1",
+ TestInstanceURL: instanceA, TestInstanceTenant: 10000,
+ ProcessingState: governance.ProcessingProcessing, PollSequence: 2,
+ }}
+ client := &identityClient{
+ identity: weknora.InstanceIdentity{BaseURL: instanceB, TenantID: 10000},
+ knowledge: weknora.Knowledge{ID: "knowledge-1", KnowledgeBaseID: "kb-1", ParseStatus: "completed"},
+ }
+ handler, _ := NewPollHandler(PollHandlerConfig{Store: store, Client: client, PollDelay: time.Second, StallAfter: time.Hour, Now: func() time.Time { return now }})
+ if err := handler.Handle(context.Background(), jobs.Job{Payload: []byte(`{"publication_id":"publication-1","sequence":2}`)}); err != nil {
+ t.Fatalf("identity mismatch must be a visible terminal state, not a retry error: %v", err)
+ }
+ if client.getCalls != 0 || store.failureCode != "remote_instance_changed" {
+ t.Fatalf("getCalls=%d failureCode=%q", client.getCalls, store.failureCode)
+ }
+}
+
+func TestPollAcceptsObjectOnTheSameInstanceAndTenant(t *testing.T) {
+ now := time.Date(2026, 11, 19, 9, 0, 0, 0, time.UTC)
+ store := &pollStoreStub{publication: postgresstore.PublicationForPoll{
+ ID: "publication-1", TestKBID: "kb-1", KnowledgeID: "knowledge-1",
+ TestInstanceURL: instanceA, TestInstanceTenant: 10000,
+ ProcessingState: governance.ProcessingProcessing, PollSequence: 2,
+ }}
+ client := &identityClient{
+ identity: weknora.InstanceIdentity{BaseURL: instanceA, TenantID: 10000},
+ knowledge: weknora.Knowledge{ID: "knowledge-1", KnowledgeBaseID: "kb-1", ParseStatus: "finalizing"},
+ }
+ handler, _ := NewPollHandler(PollHandlerConfig{Store: store, Client: client, PollDelay: time.Second, StallAfter: time.Hour, Now: func() time.Time { return now }})
+ if err := handler.Handle(context.Background(), jobs.Job{Payload: []byte(`{"publication_id":"publication-1","sequence":2}`)}); err != nil {
+ t.Fatal(err)
+ }
+ if client.getCalls != 1 || store.recordedState != governance.ProcessingFinalizing {
+ t.Fatalf("getCalls=%d state=%v", client.getCalls, store.recordedState)
+ }
+}
+
+func TestRemoveRefusesToDeleteACloneObject(t *testing.T) {
+ store := &removalStoreStub{candidate: postgresstore.PublicationForRemoval{
+ ID: "publication-1", TestKBID: "kb-1", KnowledgeID: "knowledge-1",
+ TestInstanceURL: instanceA, TestInstanceTenant: 10000,
+ }}
+ client := &identityClient{identity: weknora.InstanceIdentity{BaseURL: instanceB, TenantID: 10000},
+ knowledge: weknora.Knowledge{ID: "knowledge-1", KnowledgeBaseID: "kb-1"}}
+ handler, _ := NewRemoveHandler(RemoveHandlerConfig{Store: store, Client: client})
+ if err := handler.Handle(context.Background(), jobs.Job{Payload: []byte(`{"publication_id":"publication-1"}`)}); err != nil {
+ t.Fatal(err)
+ }
+ if client.deleteCalls != 0 || client.getCalls != 0 || store.failed != "publication-1:removal_instance_changed" {
+ t.Fatalf("deleteCalls=%d getCalls=%d failed=%q", client.deleteCalls, client.getCalls, store.failed)
+ }
+}
+
+func TestValidateFailsClosedWithoutReadingTheClone(t *testing.T) {
+ store := &validateStoreStub{publication: postgresstore.PublicationForValidation{
+ ID: "publication-1", TestKBID: "kb-1", KnowledgeID: "knowledge-1",
+ TestInstanceURL: instanceA, TestInstanceTenant: 10000,
+ }}
+ client := &identityClient{identity: weknora.InstanceIdentity{BaseURL: instanceB, TenantID: 20000},
+ knowledge: weknora.Knowledge{ID: "knowledge-1", KnowledgeBaseID: "kb-1"}, chunkTotal: 3}
+ handler, _ := NewValidateHandler(ValidateHandlerConfig{Store: store, Client: client, PolicyVersion: "structural-v1"})
+ if err := handler.Handle(context.Background(), jobs.Job{Payload: []byte(`{"publication_id":"publication-1"}`)}); err != nil {
+ t.Fatal(err)
+ }
+ if client.getCalls != 0 || client.chunkCalls != 0 {
+ t.Fatalf("clone was read: get=%d chunks=%d", client.getCalls, client.chunkCalls)
+ }
+ states := map[string]governance.AcceptanceState{}
+ for _, result := range store.appended {
+ states[result.CheckType] = result.State
+ }
+ if states["knowledge_exists"] != governance.AcceptanceFailed || states["chunks_present"] != governance.AcceptanceFailed {
+ t.Fatalf("acceptance states = %#v", states)
+ }
+}
+
+func TestUploadRefusesToWriteAfterRebindingToAnotherInstance(t *testing.T) {
+ store := &uploadStoreStub{candidate: postgresstore.PublicationForUpload{
+ ID: "publication-1", TestKBID: "kb-1", TestInstanceURL: instanceA, TestInstanceTenant: 10000,
+ IngestState: governance.IngestPending, ProcessingState: governance.ProcessingPending,
+ TargetScope: governance.VisibilityInternal,
+ }}
+ client := &identityClient{identity: weknora.InstanceIdentity{BaseURL: instanceB, TenantID: 10000}}
+ handler, _ := NewUploadHandler(UploadHandlerConfig{
+ Store: store, Client: client, SpoolRoot: t.TempDir(), MaxUploadBytes: 1024, FirstPollDelay: time.Second,
+ })
+ if err := handler.Handle(context.Background(), jobs.Job{Payload: []byte(`{"publication_id":"publication-1","target_kb_id":"kb-1","target_scope":"internal"}`)}); err != nil {
+ t.Fatal(err)
+ }
+ if client.uploadCalls != 0 || store.uploadFailureCode != "upload_instance_changed" {
+ t.Fatalf("uploadCalls=%d failure=%q", client.uploadCalls, store.uploadFailureCode)
+ }
+}
diff --git a/internal/workflows/testweknora/poll.go b/internal/workflows/testweknora/poll.go
index 8af0a59..bc1ffcf 100644
--- a/internal/workflows/testweknora/poll.go
+++ b/internal/workflows/testweknora/poll.go
@@ -82,6 +82,17 @@ func (handler *PollHandler) Handle(ctx context.Context, job jobs.Job) error {
return ErrPollStateConflict
}
now := handler.now()
+ identity, hasProvider, identityErr := resolveIdentity(ctx, handler.client, publication.TestKBID)
+ if identityErr != nil {
+ return ErrPollRemoteFailed
+ }
+ if hasProvider && !identityMatches(publication.TestInstanceURL, publication.TestInstanceTenant, identity) {
+ // 旧对象属于另一个实例/租户:不能在新实例上按同名/同 ID 的对象继续推进。
+ if err := handler.store.RecordProcessingFailure(ctx, publication.ID, publication.PollSequence, "remote_instance_changed", now); err != nil {
+ return ErrPollStateConflict
+ }
+ return nil
+ }
knowledge, err := handler.client.GetKnowledge(ctx, publication.KnowledgeID)
if err != nil {
return ErrPollRemoteFailed
diff --git a/internal/workflows/testweknora/poll_test.go b/internal/workflows/testweknora/poll_test.go
index 4987fcc..890c4e5 100644
--- a/internal/workflows/testweknora/poll_test.go
+++ b/internal/workflows/testweknora/poll_test.go
@@ -158,6 +158,7 @@ type pollStoreStub struct {
completedValidated bool
stalledMarked bool
stalledCutoff time.Time
+ failureCode string
}
func (store *pollStoreStub) LoadPublicationForPoll(context.Context, string) (postgresstore.PublicationForPoll, error) {
@@ -177,7 +178,8 @@ func (store *pollStoreStub) RecordCompletedAndScheduleValidation(_ context.Conte
return nil
}
-func (store *pollStoreStub) RecordProcessingFailure(context.Context, string, int, string, time.Time) error {
+func (store *pollStoreStub) RecordProcessingFailure(_ context.Context, _ string, _ int, code string, _ time.Time) error {
+ store.failureCode = code
return nil
}
diff --git a/internal/workflows/testweknora/remove.go b/internal/workflows/testweknora/remove.go
index ebacadd..b76cba6 100644
--- a/internal/workflows/testweknora/remove.go
+++ b/internal/workflows/testweknora/remove.go
@@ -65,6 +65,14 @@ func (handler *RemoveHandler) Handle(ctx context.Context, job jobs.Job) error {
if err != nil {
return ErrRemoveStateConflict
}
+ identity, hasProvider, identityErr := resolveIdentity(ctx, handler.client, candidate.TestKBID)
+ if identityErr != nil {
+ return ErrRemoveRemoteFailed
+ }
+ if hasProvider && !identityMatches(candidate.TestInstanceURL, candidate.TestInstanceTenant, identity) {
+ // 不能拿旧实例的对象 ID 到新实例上删除同名对象。
+ return handler.failClosed(ctx, candidate.ID, "removal_instance_changed")
+ }
knowledge, err := handler.client.GetKnowledge(ctx, candidate.KnowledgeID)
if isNotFound(err) {
return handler.complete(ctx, candidate.ID)
diff --git a/internal/workflows/testweknora/upload.go b/internal/workflows/testweknora/upload.go
index d520238..0d794b7 100644
--- a/internal/workflows/testweknora/upload.go
+++ b/internal/workflows/testweknora/upload.go
@@ -27,7 +27,7 @@ var (
type UploadStore interface {
LoadPublicationForUpload(context.Context, string) (postgresstore.PublicationForUpload, error)
- MarkUploading(context.Context, string, time.Time) error
+ MarkUploading(context.Context, string, string, uint64, time.Time) error
RecordUploadAndSchedulePoll(context.Context, string, string, time.Time, time.Time) (int, error)
RecordUploadFailure(context.Context, string, string, time.Time) error
}
@@ -93,6 +93,20 @@ func (handler *UploadHandler) Handle(ctx context.Context, job jobs.Job) error {
if payload.TargetScope != "" && payload.TargetScope != string(candidate.TargetScope) {
return ErrUploadStateConflict
}
+ identity, hasProvider, identityErr := resolveIdentity(ctx, handler.client, candidate.TestKBID)
+ if identityErr != nil {
+ return ErrUploadRemoteFailed
+ }
+ if hasProvider {
+ if candidate.TestInstanceURL != "" || candidate.TestInstanceTenant != 0 {
+ if !identityMatches(candidate.TestInstanceURL, candidate.TestInstanceTenant, identity) {
+ return handler.recordTerminalUploadFailure(ctx, candidate.ID, "upload_instance_changed")
+ }
+ } else if candidate.IngestState == governance.IngestUploading {
+ // 旧行没有实例身份,又可能已经写到了旧实例:不能在克隆实例上恢复/接管。
+ return handler.recordTerminalUploadFailure(ctx, candidate.ID, "upload_instance_unknown")
+ }
+ }
if candidate.IngestState == governance.IngestUploading {
knowledge, err := handler.recoverAmbiguousUpload(ctx, candidate)
if err != nil {
@@ -117,7 +131,7 @@ func (handler *UploadHandler) Handle(ctx context.Context, job jobs.Job) error {
return handler.recordTerminalUploadFailure(ctx, candidate.ID, "upload_artifact_invalid")
}
defer artifact.Close()
- if err := handler.store.MarkUploading(ctx, candidate.ID, handler.now()); err != nil {
+ if err := handler.store.MarkUploading(ctx, candidate.ID, identity.BaseURL, identity.TenantID, handler.now()); err != nil {
return ErrUploadStateConflict
}
knowledge, uploadErr := handler.client.UploadFile(ctx, weknora.UploadRequest{
diff --git a/internal/workflows/testweknora/upload_test.go b/internal/workflows/testweknora/upload_test.go
index b60826d..257b857 100644
--- a/internal/workflows/testweknora/upload_test.go
+++ b/internal/workflows/testweknora/upload_test.go
@@ -312,19 +312,23 @@ func TestUploadHandlerRecordsInvalidArtifactForManualRetry(t *testing.T) {
}
type uploadStoreStub struct {
- candidate postgresstore.PublicationForUpload
- markedUploading bool
- recordedKnowledgeID string
- nextPollAt time.Time
- uploadFailureCode string
+ candidate postgresstore.PublicationForUpload
+ markedUploading bool
+ markedInstanceURL string
+ markedInstanceTenant uint64
+ recordedKnowledgeID string
+ nextPollAt time.Time
+ uploadFailureCode string
}
func (store *uploadStoreStub) LoadPublicationForUpload(context.Context, string) (postgresstore.PublicationForUpload, error) {
return store.candidate, nil
}
-func (store *uploadStoreStub) MarkUploading(context.Context, string, time.Time) error {
+func (store *uploadStoreStub) MarkUploading(_ context.Context, _ string, instanceURL string, tenantID uint64, _ time.Time) error {
store.markedUploading = true
+ store.markedInstanceURL = instanceURL
+ store.markedInstanceTenant = tenantID
return nil
}
diff --git a/internal/workflows/testweknora/validate.go b/internal/workflows/testweknora/validate.go
index 911bb52..17a5d51 100644
--- a/internal/workflows/testweknora/validate.go
+++ b/internal/workflows/testweknora/validate.go
@@ -101,10 +101,25 @@ func (handler *ValidateHandler) Handle(ctx context.Context, job jobs.Job) error
runID = job.ID
}
- knowledge, knowledgeErr := handler.client.GetKnowledge(ctx, publication.KnowledgeID)
+ identity, hasProvider, identityErr := resolveIdentity(ctx, handler.client, publication.TestKBID)
+ identityOK := !hasProvider || (identityErr == nil &&
+ identityMatches(publication.TestInstanceURL, publication.TestInstanceTenant, identity))
+ identityReason := ""
+ if hasProvider {
+ switch {
+ case identityErr != nil:
+ identityReason = "instance_identity_unreadable"
+ case !identityOK:
+ identityReason = "instance_changed"
+ }
+ }
knowledgeState := governance.AcceptancePassed
knowledgeEvidence := json.RawMessage(`{"matched":true}`)
- if knowledgeErr != nil || knowledge.ID != publication.KnowledgeID || knowledge.KnowledgeBaseID != publication.TestKBID {
+ if !identityOK {
+ knowledgeState = governance.AcceptanceFailed
+ knowledgeEvidence = mustJSON(map[string]any{"matched": false, "reason": identityReason})
+ } else if knowledge, knowledgeErr := handler.client.GetKnowledge(ctx, publication.KnowledgeID); knowledgeErr != nil ||
+ knowledge.ID != publication.KnowledgeID || knowledge.KnowledgeBaseID != publication.TestKBID {
knowledgeState = governance.AcceptanceFailed
knowledgeEvidence = json.RawMessage(`{"matched":false}`)
}
@@ -112,10 +127,14 @@ func (handler *ValidateHandler) Handle(ctx context.Context, job jobs.Job) error
return err
}
- _, chunkTotal, chunksErr := handler.client.ListChunks(ctx, publication.KnowledgeID, 1, 1, nil)
chunksState := governance.AcceptancePassed
- if chunksErr != nil || chunkTotal <= 0 {
+ chunkTotal := int64(0)
+ if !identityOK {
chunksState = governance.AcceptanceFailed
+ } else if _, total, chunksErr := handler.client.ListChunks(ctx, publication.KnowledgeID, 1, 1, nil); chunksErr != nil || total <= 0 {
+ chunksState = governance.AcceptanceFailed
+ } else {
+ chunkTotal = total
}
if err := handler.append(ctx, publication.ID, runID, "chunks_present", chunksState, mustJSON(map[string]any{"chunk_total": chunkTotal}), now); err != nil {
return err
diff --git a/scripts/test-scope.json b/scripts/test-scope.json
index 4b6884b..8995585 100644
--- a/scripts/test-scope.json
+++ b/scripts/test-scope.json
@@ -658,6 +658,11 @@
"test": "TestV090ProductionTargetPublishIsolated",
"reason": "需显式一次性本机PG(两份 0.9.0 真 schema 库)/ES/对象存储:真实导出→封存→ProductionLibraryTarget 写入 134 目标→逐表核对→写前镜像回滚,验证 0.9.0 无 wiki_log_entries、chunks 新增 NOT NULL 列走默认值、seq_id 由目标序列分配;普通CI没有这些服务,跳过不是通过"
},
+ {
+ "package": "knowledge-governance/internal/platform/postgres",
+ "test": "TestStartReleaseExecutionFreezesTheBindingInstanceIdentity",
+ "reason": "需显式一次性本机治理PG(TEST_DATABASE_URL):真实迁移、审核/封存/授权后 StartExecution 必须把绑定实例地址与租户冻结进发布项;普通CI没有该库,跳过不是通过"
+ },
{
"package": "knowledge-governance/internal/kbbinding",
"test": "TestSaveReadsBackResolvesTheKeyAndReplansPendingInOneTransaction",
diff --git a/web/src/KnowledgeBaseBinding.test.tsx b/web/src/KnowledgeBaseBinding.test.tsx
index 33dec3f..ff5132c 100644
--- a/web/src/KnowledgeBaseBinding.test.tsx
+++ b/web/src/KnowledgeBaseBinding.test.tsx
@@ -181,6 +181,26 @@ describe('KnowledgeBaseBinding', () => {
expect(body.api_key).toBeUndefined()
})
+ it('does not allow saving until both directions have an explicit base', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn((url: string) => {
+ if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshot))
+ if (String(url).includes('/catalog')) return Promise.resolve(json(catalog))
+ return Promise.resolve(json({ data: binding('test') }))
+ })
+ )
+ await render()
+ await click('验证并读取知识库')
+ await choose('对内知识库', 'kb-new-in-0001')
+ await choose('对外知识库', '')
+ const save = [...host.querySelectorAll('button')].find((button) => button.textContent?.includes('保存测试绑定'))
+ expect(save?.hasAttribute('disabled')).toBe(true)
+ expect(host.textContent).toContain('未选择不会回落到旧实例的默认库')
+ await choose('对外知识库', 'kb-new-out-0001')
+ expect(save?.hasAttribute('disabled')).toBe(false)
+ })
+
it('gives viewers a read-only summary with no editing inputs', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshot)))
await render('viewer')
diff --git a/web/src/KnowledgeBaseBinding.tsx b/web/src/KnowledgeBaseBinding.tsx
index 6e9ce9e..a11e1b6 100644
--- a/web/src/KnowledgeBaseBinding.tsx
+++ b/web/src/KnowledgeBaseBinding.tsx
@@ -148,6 +148,8 @@ export function KnowledgeBaseBinding() {
storageReady &&
endpointValid &&
keyReady &&
+ draft.internalID !== '' &&
+ draft.externalID !== '' &&
!duplicate &&
catalogReady
)
@@ -520,7 +522,7 @@ export function KnowledgeBaseBinding() {
}}
disabled={busyNow !== '' || !draft.catalog || draft.catalog.status !== 'ok'}
>
-
+
{currentOptions.internal.map((option) => (
+
{currentOptions.external.map((option) => (
From 6ae5150fdf73fbed6fb3ba4150a1f5ce9c4e14e0 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E5=A7=9A=E7=AB=A0=E6=B5=A9?=
Date: Thu, 19 Nov 2026 15:33:40 +0800
Subject: [PATCH 04/14] =?UTF-8?q?fix(worker):=20=E5=8D=95=E6=AC=A1?=
=?UTF-8?q?=E4=BB=BB=E5=8A=A1=E5=9B=BA=E5=AE=9A=E5=90=8C=E4=B8=80=20WeKnor?=
=?UTF-8?q?a=20=E8=BF=9E=E6=8E=A5?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
TargetIdentity 与业务调用原先各自 Resolve:身份核验通过后,上传/轮询/验收/
移除的后续调用仍可能在下一次解析时切到新实例。现在 BeginTask 只解析一次,
用同一连接读取对象租户并把该不可变连接钉进返回 context;后续上传、列库恢复、
查询、chunk 读取、删除与删除后重查全部复用它。
TaskConnector 优先于 IdentityProvider;仅实现 TargetIdentity 的窄假客户端仍可
工作,生产路径不会走双解析。新增假端点测试断言一次处理只解析一次、绑定后改
当前实例仍全部打到原实例;四个 handler 的 TaskConnector 假客户端断言所有业务
调用携带同一连接令牌,覆盖上传恢复和删除重查。
---
CHANGELOG.md | 10 +
docs/USER_FLOWS_ACCEPTANCE.md | 1 +
internal/weknoraaccess/client.go | 116 ++++++----
internal/weknoraaccess/client_test.go | 93 ++++++++
internal/workflows/testweknora/identity.go | 32 ++-
.../workflows/testweknora/identity_test.go | 214 ++++++++++++++++++
internal/workflows/testweknora/poll.go | 2 +-
internal/workflows/testweknora/remove.go | 2 +-
internal/workflows/testweknora/upload.go | 2 +-
internal/workflows/testweknora/validate.go | 2 +-
10 files changed, 424 insertions(+), 50 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2d0c225..800e5bb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,15 @@
# Changelog
+## 开发快照 0.1.404(单次任务固定同一 WeKnora 连接)
+
+### Fixed
+
+- 上传、轮询、验收、移除先 `BeginTask` 解析一次并核验对象租户,返回的 context 钉住同一
+ 不可变连接;后续上传、列库恢复、查询、chunk 读取、删除与删除后重查都复用它,不再
+ 各自 `Resolve`。任务开始后页面改绑实例,旧任务也不会中途切到新实例。
+- 回归:真实客户端假端点断言一次处理只解析一次且全部打到同一实例;四个 handler 用
+ TaskConnector 假客户端断言所有业务调用携带同一连接令牌,含上传恢复和删除重查。
+
## 开发快照 0.1.403(实例身份约束:绑定、发布与测试对象不跨实例)
### Added
diff --git a/docs/USER_FLOWS_ACCEPTANCE.md b/docs/USER_FLOWS_ACCEPTANCE.md
index 6b94429..db0c2df 100644
--- a/docs/USER_FLOWS_ACCEPTANCE.md
+++ b/docs/USER_FLOWS_ACCEPTANCE.md
@@ -262,6 +262,7 @@
- 兼容:没有新配置行的旧部署继续使用文件凭据/默认绑定;保存新密钥需要独立主密钥文件 `WEKNORA_BINDING_MASTER_KEY_FILE`
- 实例约束:网页在实例 A 核验的绑定会冻结地址/租户;文档发布执行器连实例 B 时,即使知识库 ID/租户相同也拒绝写入(`release_contract_mismatch`)。测试对象改绑实例/租户后,旧对象不会被轮询/验收/移除。
- 证据:`internal/kbbinding`(单元 + 隔离 PostgreSQL 集成)、`KnowledgeBaseBinding.test.tsx`、`TestStartReleaseExecutionFreezesTheBindingInstanceIdentity`、`TestDocumentTargetRejectsBindingVerifiedOnAnotherInstance`
+- 单次任务连接:`TestBeginTaskPinsOneResolvedConnectionForAllCalls`;`TestPollUsesOneVerifiedConnectionForAllCalls`、`TestValidateUsesOneVerifiedConnectionForAllCalls`、`TestRemoveUsesOneVerifiedConnectionForDeleteAndReadBack`、`TestUploadUsesOneVerifiedConnectionForWrite`、`TestUploadRecoveryUsesTheSameVerifiedConnection`
- 状态:✅ 本地验证(未做业务验收)
### D2 测试知识库绑定(折叠诊断;主入口已并入 D1)
diff --git a/internal/weknoraaccess/client.go b/internal/weknoraaccess/client.go
index dd12f31..b4ba2f2 100644
--- a/internal/weknoraaccess/client.go
+++ b/internal/weknoraaccess/client.go
@@ -15,15 +15,71 @@ var ErrNotConfigured = errors.New("WeKnora 有效端点/凭据未配置")
// The readiness probe has its own 10s cap; it must not bound upload/poll calls.
const defaultBusinessTimeout = 60 * time.Second
-// Client resolves the effective WeKnora target on every call. It deliberately
-// owns no cached *weknora.Client: endpoint, key and binding are console-managed.
+// Client resolves the effective WeKnora target on every call. Direct calls are
+// intentionally dynamic so console-managed endpoint/key/binding changes take
+// effect. A job that performs several calls must call BeginTask first: it
+// resolves once, verifies the owning tenant and pins that immutable connection
+// in the returned context, so no later call can silently switch instances.
type Client struct {
Resolver readiness.Resolver
Timeout time.Duration
AllowDockerHTTP bool
}
+type taskConnection struct {
+ remote *weknora.Client
+ baseURL string
+}
+
+type taskConnectionKey struct{}
+
+func taskConnectionFrom(ctx context.Context) *taskConnection {
+ connection, _ := ctx.Value(taskConnectionKey{}).(*taskConnection)
+ return connection
+}
+
+func (client *Client) newRemote(target readiness.Target) (*weknora.Client, error) {
+ timeout := client.Timeout
+ if timeout <= 0 {
+ timeout = defaultBusinessTimeout
+ }
+ return weknora.NewClient(weknora.ClientConfig{
+ BaseURL: target.BaseURL,
+ APIKey: target.APIKey,
+ Timeout: timeout,
+ AllowDockerHTTP: client.AllowDockerHTTP,
+ })
+}
+
+// BeginTask resolves the endpoint/key/binding exactly once, reads the owning
+// tenant through that same connection and returns a context that pins it.
+// Upload, poll, validate and remove must pass the returned context to every
+// follow-up call and re-read, including recovery and delete read-back.
+func (client *Client) BeginTask(ctx context.Context, knowledgeBaseID string) (context.Context, weknora.InstanceIdentity, error) {
+ target, err := client.Resolver.Resolve(ctx)
+ if err != nil {
+ return ctx, weknora.InstanceIdentity{}, err
+ }
+ if target.BaseURL == "" || target.APIKey == "" || knowledgeBaseID == "" {
+ return ctx, weknora.InstanceIdentity{}, ErrNotConfigured
+ }
+ remote, err := client.newRemote(target)
+ if err != nil {
+ return ctx, weknora.InstanceIdentity{}, err
+ }
+ base, err := remote.GetKnowledgeBase(ctx, knowledgeBaseID)
+ if err != nil {
+ return ctx, weknora.InstanceIdentity{}, err
+ }
+ connection := &taskConnection{remote: remote, baseURL: weknora.NormalizeInstanceURL(target.BaseURL)}
+ bound := context.WithValue(ctx, taskConnectionKey{}, connection)
+ return bound, weknora.InstanceIdentity{BaseURL: connection.baseURL, TenantID: base.TenantID}, nil
+}
+
func (client *Client) with(ctx context.Context, call func(*weknora.Client) error) error {
+ if connection := taskConnectionFrom(ctx); connection != nil && connection.remote != nil {
+ return call(connection.remote)
+ }
target, err := client.Resolver.Resolve(ctx)
if err != nil {
return err
@@ -31,16 +87,7 @@ func (client *Client) with(ctx context.Context, call func(*weknora.Client) error
if target.BaseURL == "" || target.APIKey == "" {
return ErrNotConfigured
}
- timeout := client.Timeout
- if timeout <= 0 {
- timeout = defaultBusinessTimeout
- }
- remote, err := weknora.NewClient(weknora.ClientConfig{
- BaseURL: target.BaseURL,
- APIKey: target.APIKey,
- Timeout: timeout,
- AllowDockerHTTP: client.AllowDockerHTTP,
- })
+ remote, err := client.newRemote(target)
if err != nil {
return err
}
@@ -48,34 +95,25 @@ func (client *Client) with(ctx context.Context, call func(*weknora.Client) error
}
func (client *Client) TargetIdentity(ctx context.Context, knowledgeBaseID string) (weknora.InstanceIdentity, error) {
- target, err := client.Resolver.Resolve(ctx)
- if err != nil {
- return weknora.InstanceIdentity{}, err
+ if connection := taskConnectionFrom(ctx); connection != nil && connection.remote != nil {
+ if knowledgeBaseID == "" {
+ return weknora.InstanceIdentity{}, ErrNotConfigured
+ }
+ base, err := connection.remote.GetKnowledgeBase(ctx, knowledgeBaseID)
+ if err != nil {
+ return weknora.InstanceIdentity{}, err
+ }
+ return weknora.InstanceIdentity{BaseURL: connection.baseURL, TenantID: base.TenantID}, nil
}
- if target.BaseURL == "" || target.APIKey == "" || knowledgeBaseID == "" {
- return weknora.InstanceIdentity{}, ErrNotConfigured
- }
- timeout := client.Timeout
- if timeout <= 0 {
- timeout = defaultBusinessTimeout
- }
- remote, err := weknora.NewClient(weknora.ClientConfig{
- BaseURL: target.BaseURL,
- APIKey: target.APIKey,
- Timeout: timeout,
- AllowDockerHTTP: client.AllowDockerHTTP,
- })
- if err != nil {
- return weknora.InstanceIdentity{}, err
- }
- base, err := remote.GetKnowledgeBase(ctx, knowledgeBaseID)
- if err != nil {
- return weknora.InstanceIdentity{}, err
- }
- return weknora.InstanceIdentity{
- BaseURL: weknora.NormalizeInstanceURL(target.BaseURL),
- TenantID: base.TenantID,
- }, nil
+ return client.identityOnce(ctx, knowledgeBaseID)
+}
+
+// identityOnce is the pre-task entry used by callers that only need identity.
+// Multi-call jobs use BeginTask so verification and every later call share the
+// same connection.
+func (client *Client) identityOnce(ctx context.Context, knowledgeBaseID string) (weknora.InstanceIdentity, error) {
+ _, identity, err := client.BeginTask(ctx, knowledgeBaseID)
+ return identity, err
}
func (client *Client) UploadFile(ctx context.Context, request weknora.UploadRequest) (weknora.Knowledge, error) {
diff --git a/internal/weknoraaccess/client_test.go b/internal/weknoraaccess/client_test.go
index e51db15..6e167c1 100644
--- a/internal/weknoraaccess/client_test.go
+++ b/internal/weknoraaccess/client_test.go
@@ -1,12 +1,17 @@
package weknoraaccess
import (
+ "bytes"
"context"
+ "io"
"net/http"
"net/http/httptest"
+ "sync"
"testing"
"time"
+ "knowledge-governance/internal/platform/weknora"
+
"knowledge-governance/internal/readiness"
)
@@ -131,3 +136,91 @@ func TestTargetIdentityReadsTheOwnedTenantFromTheCurrentBinding(t *testing.T) {
t.Fatalf("identity = %#v", identity)
}
}
+
+// 一次任务处理只能解析一次。BeginTask 在绑定时刻读取对象所属 tenant 并把同一个
+// 不可变连接钉进返回的 context;之后即使控制台已切到另一实例,上传、查询、
+// chunk 列表和删除(以及删除后的重查)仍必须走原实例。
+func TestBeginTaskPinsOneResolvedConnectionForAllCalls(t *testing.T) {
+ var mu sync.Mutex
+ hits := map[string]int{}
+ serve := func(name string) *httptest.Server {
+ return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ hits[name]++
+ mu.Unlock()
+ w.Header().Set("Content-Type", "application/json")
+ switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/api/v1/knowledge-bases/kb-1":
+ _, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-1","name":"KB","tenant_id":10000}}`))
+ case r.Method == http.MethodPost && r.URL.Path == "/api/v1/knowledge-bases/kb-1/knowledge/file":
+ _, _ = io.Copy(io.Discard, r.Body)
+ _, _ = w.Write([]byte(`{"success":true,"data":{"id":"kn-1","knowledge_base_id":"kb-1","parse_status":"pending"}}`))
+ case r.Method == http.MethodGet && r.URL.Path == "/api/v1/knowledge/kn-1":
+ _, _ = w.Write([]byte(`{"success":true,"data":{"id":"kn-1","knowledge_base_id":"kb-1"}}`))
+ case r.Method == http.MethodGet && r.URL.Path == "/api/v1/chunks/kn-1":
+ _, _ = w.Write([]byte(`{"success":true,"data":[],"total":1}`))
+ case r.Method == http.MethodDelete && r.URL.Path == "/api/v1/knowledge/kn-1":
+ _, _ = w.Write([]byte(`{"success":true}`))
+ default:
+ w.WriteHeader(http.StatusNotFound)
+ }
+ }))
+ }
+ first, second := serve("first"), serve("second")
+ defer first.Close()
+ defer second.Close()
+ current := first.URL
+ resolves := 0
+ client := &Client{Resolver: readiness.Resolver{
+ Endpoint: func(context.Context) string { resolves++; return current },
+ ReadKey: func() (string, error) { return "isolated-test-key", nil },
+ DefaultKB: "kb-1",
+ }, Timeout: time.Second}
+
+ taskCtx, identity, err := client.BeginTask(context.Background(), "kb-1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if identity.BaseURL != first.URL || identity.TenantID != 10000 || resolves != 1 {
+ t.Fatalf("identity=%#v resolves=%d", identity, resolves)
+ }
+ current = second.URL // 任务开始后控制台改绑到另一实例
+
+ if _, err := client.UploadFile(taskCtx, weknora.UploadRequest{KnowledgeBaseID: "kb-1", FileName: "a.md", Content: bytes.NewReader([]byte("x"))}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := client.GetKnowledge(taskCtx, "kn-1"); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := client.ListChunks(taskCtx, "kn-1", 1, 1, nil); err != nil {
+ t.Fatal(err)
+ }
+ if err := client.DeleteKnowledge(taskCtx, "kn-1"); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := client.GetKnowledge(taskCtx, "kn-1"); err != nil {
+ t.Fatal(err)
+ }
+ again, err := client.TargetIdentity(taskCtx, "kb-1")
+ if err != nil || again != identity {
+ t.Fatalf("identity on task connection=%#v err=%v", again, err)
+ }
+ mu.Lock()
+ firstHits, secondHits := hits["first"], hits["second"]
+ mu.Unlock()
+ if resolves != 1 || secondHits != 0 || firstHits != 7 {
+ t.Fatalf("resolves=%d first=%d second=%d", resolves, firstHits, secondHits)
+ }
+
+ // 反例:没有 BeginTask 的直接调用仍是动态解析,会走新当前实例。证明上面的
+ // 单次解析/同一连接不是测试假阳性。
+ if _, err := client.GetKnowledge(context.Background(), "kn-1"); err != nil {
+ t.Fatal(err)
+ }
+ mu.Lock()
+ secondHits = hits["second"]
+ mu.Unlock()
+ if resolves != 2 || secondHits != 1 {
+ t.Fatalf("direct call resolves=%d second=%d", resolves, secondHits)
+ }
+}
diff --git a/internal/workflows/testweknora/identity.go b/internal/workflows/testweknora/identity.go
index 53bd741..ab9274d 100644
--- a/internal/workflows/testweknora/identity.go
+++ b/internal/workflows/testweknora/identity.go
@@ -6,24 +6,42 @@ import (
"knowledge-governance/internal/platform/weknora"
)
-// IdentityProvider is implemented by the production WeKnora access client. Unit
-// fakes may omit it; a handler must then treat stored identities as unverifiable
-// and never write/delete/adopt an object across instances.
+// TaskConnector is implemented by the production client. BeginTask resolves the
+// endpoint/key/binding exactly once, verifies the object's owning tenant through
+// that connection and returns a context that pins the same immutable connection
+// for every later call of this job (including recovery and read-back).
+type TaskConnector interface {
+ BeginTask(context.Context, string) (context.Context, weknora.InstanceIdentity, error)
+}
+
+// IdentityProvider remains for narrow fakes/tests that only expose identity.
type IdentityProvider interface {
TargetIdentity(context.Context, string) (weknora.InstanceIdentity, error)
}
-func resolveIdentity(ctx context.Context, client any, knowledgeBaseID string) (weknora.InstanceIdentity, bool, error) {
+// resolveIdentity prefers BeginTask so upload/poll/validate/remove pass the
+// pinned context to every follow-up call. Returning the original ctx for
+// identity-only fakes keeps the unit seam simple; production never takes that
+// path.
+func resolveIdentity(ctx context.Context, client any, knowledgeBaseID string) (context.Context, weknora.InstanceIdentity, bool, error) {
+ if connector, ok := client.(TaskConnector); ok {
+ bound, identity, err := connector.BeginTask(ctx, knowledgeBaseID)
+ if err != nil {
+ return ctx, weknora.InstanceIdentity{}, true, err
+ }
+ identity.BaseURL = weknora.NormalizeInstanceURL(identity.BaseURL)
+ return bound, identity, true, nil
+ }
provider, ok := client.(IdentityProvider)
if !ok {
- return weknora.InstanceIdentity{}, false, nil
+ return ctx, weknora.InstanceIdentity{}, false, nil
}
identity, err := provider.TargetIdentity(ctx, knowledgeBaseID)
if err != nil {
- return weknora.InstanceIdentity{}, true, err
+ return ctx, weknora.InstanceIdentity{}, true, err
}
identity.BaseURL = weknora.NormalizeInstanceURL(identity.BaseURL)
- return identity, true, nil
+ return ctx, identity, true, nil
}
// identityMatches requires BOTH the instance address and the owning tenant to
diff --git a/internal/workflows/testweknora/identity_test.go b/internal/workflows/testweknora/identity_test.go
index 1fd9e97..9cc1feb 100644
--- a/internal/workflows/testweknora/identity_test.go
+++ b/internal/workflows/testweknora/identity_test.go
@@ -2,13 +2,19 @@ package testweknora
import (
"context"
+ "crypto/sha256"
+ "encoding/hex"
"errors"
+ "io"
+ "os"
+ "path/filepath"
"testing"
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
postgresstore "knowledge-governance/internal/platform/postgres"
+ "knowledge-governance/internal/platform/spool"
"knowledge-governance/internal/platform/weknora"
)
@@ -150,3 +156,211 @@ func TestUploadRefusesToWriteAfterRebindingToAnotherInstance(t *testing.T) {
t.Fatalf("uploadCalls=%d failure=%q", client.uploadCalls, store.uploadFailureCode)
}
}
+
+type taskTokenKey struct{}
+
+// taskClient is a normal fake TaskConnector. BeginTask pins a token in the
+// context; every business method records which token it received.
+type taskClient struct {
+ identity weknora.InstanceIdentity
+ identityErr error
+ beginCalls int
+ tokens []string
+
+ knowledge weknora.Knowledge
+ uploadResult weknora.Knowledge
+ listItems []weknora.Knowledge
+ chunkTotal int64
+ deleteGone bool
+ getCalls int
+ chunkCalls int
+ deleteCalls int
+ uploadCalls int
+ listCalls int
+}
+
+func (client *taskClient) BeginTask(ctx context.Context, _ string) (context.Context, weknora.InstanceIdentity, error) {
+ client.beginCalls++
+ if client.identityErr != nil {
+ return ctx, weknora.InstanceIdentity{}, client.identityErr
+ }
+ return context.WithValue(ctx, taskTokenKey{}, "connection-1"), client.identity, nil
+}
+
+func (client *taskClient) record(ctx context.Context) {
+ token, _ := ctx.Value(taskTokenKey{}).(string)
+ client.tokens = append(client.tokens, token)
+}
+
+func (client *taskClient) GetKnowledge(ctx context.Context, _ string) (weknora.Knowledge, error) {
+ client.record(ctx)
+ client.getCalls++
+ if client.deleteGone {
+ return weknora.Knowledge{}, &weknora.HTTPError{StatusCode: 404}
+ }
+ return client.knowledge, nil
+}
+
+func (client *taskClient) ListChunks(ctx context.Context, _ string, _, _ int, _ []string) ([]weknora.Chunk, int64, error) {
+ client.record(ctx)
+ client.chunkCalls++
+ return []weknora.Chunk{{ID: "chunk-1"}}, client.chunkTotal, nil
+}
+
+func (client *taskClient) DeleteKnowledge(ctx context.Context, _ string) error {
+ client.record(ctx)
+ client.deleteCalls++
+ client.deleteGone = true
+ return nil
+}
+
+func (client *taskClient) UploadFile(ctx context.Context, request weknora.UploadRequest) (weknora.Knowledge, error) {
+ client.record(ctx)
+ client.uploadCalls++
+ if request.Content != nil {
+ _, _ = io.Copy(io.Discard, request.Content)
+ }
+ return client.uploadResult, nil
+}
+
+func (client *taskClient) ListKnowledge(ctx context.Context, _ string, _, _ int) ([]weknora.Knowledge, int64, error) {
+ client.record(ctx)
+ client.listCalls++
+ return client.listItems, int64(len(client.listItems)), nil
+}
+
+func (client *taskClient) assertOneConnection(t *testing.T) {
+ t.Helper()
+ if client.beginCalls != 1 {
+ t.Fatalf("BeginTask calls=%d, want 1", client.beginCalls)
+ }
+ if len(client.tokens) == 0 {
+ t.Fatal("no business call recorded")
+ }
+ for index, token := range client.tokens {
+ if token != "connection-1" {
+ t.Fatalf("call %d used connection %q, want pinned connection-1", index, token)
+ }
+ }
+}
+
+func TestPollUsesOneVerifiedConnectionForAllCalls(t *testing.T) {
+ now := time.Date(2026, 11, 19, 9, 0, 0, 0, time.UTC)
+ store := &pollStoreStub{publication: postgresstore.PublicationForPoll{
+ ID: "publication-1", TestKBID: "kb-1", KnowledgeID: "knowledge-1",
+ TestInstanceURL: instanceA, TestInstanceTenant: 10000,
+ ProcessingState: governance.ProcessingProcessing, PollSequence: 2,
+ }}
+ client := &taskClient{identity: weknora.InstanceIdentity{BaseURL: instanceA, TenantID: 10000},
+ knowledge: weknora.Knowledge{ID: "knowledge-1", KnowledgeBaseID: "kb-1", ParseStatus: "finalizing"}}
+ handler, _ := NewPollHandler(PollHandlerConfig{Store: store, Client: client, PollDelay: time.Second, StallAfter: time.Hour, Now: func() time.Time { return now }})
+ if err := handler.Handle(context.Background(), jobs.Job{Payload: []byte(`{"publication_id":"publication-1","sequence":2}`)}); err != nil {
+ t.Fatal(err)
+ }
+ client.assertOneConnection(t)
+ if client.getCalls != 1 || store.recordedState != governance.ProcessingFinalizing {
+ t.Fatalf("getCalls=%d state=%v", client.getCalls, store.recordedState)
+ }
+}
+
+func TestValidateUsesOneVerifiedConnectionForAllCalls(t *testing.T) {
+ store := &validateStoreStub{publication: postgresstore.PublicationForValidation{
+ ID: "publication-1", TestKBID: "kb-1", KnowledgeID: "knowledge-1",
+ TestInstanceURL: instanceA, TestInstanceTenant: 10000,
+ }}
+ client := &taskClient{identity: weknora.InstanceIdentity{BaseURL: instanceA, TenantID: 10000},
+ knowledge: weknora.Knowledge{ID: "knowledge-1", KnowledgeBaseID: "kb-1"}, chunkTotal: 3}
+ handler, _ := NewValidateHandler(ValidateHandlerConfig{Store: store, Client: client, PolicyVersion: "structural-v1"})
+ if err := handler.Handle(context.Background(), jobs.Job{Payload: []byte(`{"publication_id":"publication-1"}`)}); err != nil {
+ t.Fatal(err)
+ }
+ client.assertOneConnection(t)
+ if client.getCalls != 1 || client.chunkCalls != 1 {
+ t.Fatalf("get=%d chunks=%d", client.getCalls, client.chunkCalls)
+ }
+}
+
+func TestRemoveUsesOneVerifiedConnectionForDeleteAndReadBack(t *testing.T) {
+ store := &removalStoreStub{candidate: postgresstore.PublicationForRemoval{
+ ID: "publication-1", TestKBID: "kb-1", KnowledgeID: "knowledge-1",
+ TestInstanceURL: instanceA, TestInstanceTenant: 10000,
+ }}
+ client := &taskClient{identity: weknora.InstanceIdentity{BaseURL: instanceA, TenantID: 10000},
+ knowledge: weknora.Knowledge{ID: "knowledge-1", KnowledgeBaseID: "kb-1"}}
+ handler, _ := NewRemoveHandler(RemoveHandlerConfig{Store: store, Client: client})
+ if err := handler.Handle(context.Background(), jobs.Job{Payload: []byte(`{"publication_id":"publication-1"}`)}); err != nil {
+ t.Fatal(err)
+ }
+ client.assertOneConnection(t)
+ if client.getCalls != 2 || client.deleteCalls != 1 || store.completed != "publication-1" {
+ t.Fatalf("get=%d delete=%d completed=%q", client.getCalls, client.deleteCalls, store.completed)
+ }
+}
+
+func TestUploadUsesOneVerifiedConnectionForWrite(t *testing.T) {
+ root := t.TempDir()
+ if err := os.Mkdir(filepath.Join(root, "objects"), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ body := []byte("one connection only\n")
+ if err := os.WriteFile(filepath.Join(root, "objects", "artifact.md"), body, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ digest := sha256.Sum256(body)
+ sha := hex.EncodeToString(digest[:])
+ if inspected, inspectErr := spool.InspectVerified(root, "objects/artifact.md", "md", 1024); inspectErr != nil {
+ t.Fatalf("inspect fixture: %v", inspectErr)
+ } else if inspected.SHA256 != sha || inspected.SizeBytes != int64(len(body)) {
+ t.Fatalf("inspect fixture = %#v", inspected)
+ }
+ store := &uploadStoreStub{candidate: postgresstore.PublicationForUpload{
+ ID: "publication-1", TestKBID: "kb-1", IngestState: governance.IngestPending,
+ ProcessingState: governance.ProcessingPending, TargetScope: governance.VisibilityInternal,
+ SHA256: sha, SizeBytes: int64(len(body)), ValidatedFormat: "md",
+ LocalSpoolRef: "objects/artifact.md", Title: "One connection",
+ }}
+ client := &taskClient{identity: weknora.InstanceIdentity{BaseURL: instanceA, TenantID: 10000},
+ uploadResult: weknora.Knowledge{ID: "knowledge-1", KnowledgeBaseID: "kb-1", ParseStatus: "pending"}}
+ handler, err := NewUploadHandler(UploadHandlerConfig{
+ Store: store, Client: client, SpoolRoot: root, MaxUploadBytes: 1024, FirstPollDelay: time.Second,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := handler.Handle(context.Background(), jobs.Job{Payload: []byte(`{"publication_id":"publication-1","target_kb_id":"kb-1","target_scope":"internal"}`)}); err != nil {
+ t.Fatal(err)
+ }
+ client.assertOneConnection(t)
+ if client.uploadCalls != 1 || store.markedInstanceURL != instanceA || store.markedInstanceTenant != 10000 {
+ t.Fatalf("uploads=%d marked=%s/%d", client.uploadCalls, store.markedInstanceURL, store.markedInstanceTenant)
+ }
+}
+
+func TestUploadRecoveryUsesTheSameVerifiedConnection(t *testing.T) {
+ store := &uploadStoreStub{candidate: postgresstore.PublicationForUpload{
+ ID: "publication-1", TestKBID: "kb-1", IngestState: governance.IngestUploading,
+ ProcessingState: governance.ProcessingPending, TargetScope: governance.VisibilityInternal,
+ TestInstanceURL: instanceA, TestInstanceTenant: 10000,
+ SHA256: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", SizeBytes: 10,
+ ValidatedFormat: "md", LocalSpoolRef: "objects/artifact.md", Title: "Recovery",
+ }}
+ recovered := weknora.Knowledge{
+ ID: "knowledge-1", KnowledgeBaseID: "kb-1",
+ Metadata: map[string]any{"publication_id": "publication-1", "content_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
+ }
+ client := &taskClient{identity: weknora.InstanceIdentity{BaseURL: instanceA, TenantID: 10000},
+ knowledge: recovered, listItems: []weknora.Knowledge{recovered}}
+ handler, err := NewUploadHandler(UploadHandlerConfig{
+ Store: store, Client: client, SpoolRoot: t.TempDir(), MaxUploadBytes: 1024, FirstPollDelay: time.Second,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := handler.Handle(context.Background(), jobs.Job{Payload: []byte(`{"publication_id":"publication-1","target_kb_id":"kb-1","target_scope":"internal"}`)}); err != nil {
+ t.Fatal(err)
+ }
+ client.assertOneConnection(t)
+ if client.listCalls != 1 || client.uploadCalls != 0 || store.recordedKnowledgeID != "knowledge-1" {
+ t.Fatalf("list=%d upload=%d recorded=%q", client.listCalls, client.uploadCalls, store.recordedKnowledgeID)
+ }
+}
diff --git a/internal/workflows/testweknora/poll.go b/internal/workflows/testweknora/poll.go
index bc1ffcf..ca5bebf 100644
--- a/internal/workflows/testweknora/poll.go
+++ b/internal/workflows/testweknora/poll.go
@@ -82,7 +82,7 @@ func (handler *PollHandler) Handle(ctx context.Context, job jobs.Job) error {
return ErrPollStateConflict
}
now := handler.now()
- identity, hasProvider, identityErr := resolveIdentity(ctx, handler.client, publication.TestKBID)
+ ctx, identity, hasProvider, identityErr := resolveIdentity(ctx, handler.client, publication.TestKBID)
if identityErr != nil {
return ErrPollRemoteFailed
}
diff --git a/internal/workflows/testweknora/remove.go b/internal/workflows/testweknora/remove.go
index b76cba6..b9228be 100644
--- a/internal/workflows/testweknora/remove.go
+++ b/internal/workflows/testweknora/remove.go
@@ -65,7 +65,7 @@ func (handler *RemoveHandler) Handle(ctx context.Context, job jobs.Job) error {
if err != nil {
return ErrRemoveStateConflict
}
- identity, hasProvider, identityErr := resolveIdentity(ctx, handler.client, candidate.TestKBID)
+ ctx, identity, hasProvider, identityErr := resolveIdentity(ctx, handler.client, candidate.TestKBID)
if identityErr != nil {
return ErrRemoveRemoteFailed
}
diff --git a/internal/workflows/testweknora/upload.go b/internal/workflows/testweknora/upload.go
index 0d794b7..84542e0 100644
--- a/internal/workflows/testweknora/upload.go
+++ b/internal/workflows/testweknora/upload.go
@@ -93,7 +93,7 @@ func (handler *UploadHandler) Handle(ctx context.Context, job jobs.Job) error {
if payload.TargetScope != "" && payload.TargetScope != string(candidate.TargetScope) {
return ErrUploadStateConflict
}
- identity, hasProvider, identityErr := resolveIdentity(ctx, handler.client, candidate.TestKBID)
+ ctx, identity, hasProvider, identityErr := resolveIdentity(ctx, handler.client, candidate.TestKBID)
if identityErr != nil {
return ErrUploadRemoteFailed
}
diff --git a/internal/workflows/testweknora/validate.go b/internal/workflows/testweknora/validate.go
index 17a5d51..04ec482 100644
--- a/internal/workflows/testweknora/validate.go
+++ b/internal/workflows/testweknora/validate.go
@@ -101,7 +101,7 @@ func (handler *ValidateHandler) Handle(ctx context.Context, job jobs.Job) error
runID = job.ID
}
- identity, hasProvider, identityErr := resolveIdentity(ctx, handler.client, publication.TestKBID)
+ ctx, identity, hasProvider, identityErr := resolveIdentity(ctx, handler.client, publication.TestKBID)
identityOK := !hasProvider || (identityErr == nil &&
identityMatches(publication.TestInstanceURL, publication.TestInstanceTenant, identity))
identityReason := ""
From 64448141231942ad4916e6aa8b78fc28a587c6ff Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E5=A7=9A=E7=AB=A0=E6=B5=A9?=
Date: Thu, 19 Nov 2026 23:31:16 +0800
Subject: [PATCH 05/14] =?UTF-8?q?feat(settings):=20=E5=AD=98=E5=82=A8?=
=?UTF-8?q?=E4=B8=8E=E5=A4=87=E4=BB=BD=E5=8D=95=E9=A1=B5=E5=AF=B9=E9=BD=90?=
=?UTF-8?q?=E7=9C=9F=E5=AE=9E=E6=8E=A5=E5=8F=A3?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
为什么:原型里的单库立备、示例容量、历史批次与目录检查在本仓接口中都不存在;
把整批 run 包装成单库按钮会误触发整批,填示例读数会把演示值当产品事实。
怎么改:按真实契约重排单页——范围/读写方向、四项告警、策略、最近批次、运行进度与
恢复验证。立即备份明确标注整批并禁用单库动作;目录/配额/预留、子库路径、历史批次、
恢复验证保留原型位置并注明未接线;归档与数据库备份分开计量。整盘色带与告警抽成
纯函数,用隔离夹具覆盖正常/不足/缺读数分支。
怎么验:tsc、vitest 618 项、vite build、prettier 通过;本地页面夹具在 1440/1024/768
无横向溢出,未接线与夹具读数两种形态均按预期渲染。
---
CHANGELOG.md | 18 +
web/src/BackupScheduleSection.test.tsx | 184 +++++-
web/src/BackupScheduleSection.tsx | 758 ++++++++++++++++++++-----
web/src/LibraryStorageSection.tsx | 7 +-
web/src/SystemSettings.tsx | 2 +-
web/src/storageBackup.css | 353 ++++++++++++
6 files changed, 1147 insertions(+), 175 deletions(-)
create mode 100644 web/src/storageBackup.css
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 800e5bb..c59402b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,23 @@
# Changelog
+## 开发快照 0.1.405(存储与备份:单页对齐真实接口)
+
+### Added
+
+- 「系统设置 → 存储与备份」按已批准交互稿落成单页:范围与读写方向、整盘占用与四项告警、
+ 备份策略、最近批次与子库清单、运行进度、恢复验证;立即备份按钮明确标注"整批全部业务库"。
+- 整盘色带与四项告警(磁盘不足/配额不足/两者同时/配额超出物理空闲)抽成纯函数,用隔离夹具
+ 覆盖正常、单项不足、同时不足与缺读数分支;生产页面在无磁盘接口时只显示"未接线"。
+- 策略区保留原型里的目录、总配额、磁盘预留位置,并逐项标注后端无对应字段、不会被保存。
+
+### Changed
+
+- 「立即备份一次」不再显示成单库动作:`POST /api/v1/backup-schedule/run` 没有单库参数,
+ 单库按钮会触发整批,因此页面禁用单库动作并说明"范围未经证实"。
+- 备份记录只展示主机 MANIFEST 的最近一批与库名;历史批次、子库路径、恢复验证没有接口,
+ 保留位置并注明原因,不拼造路径或假成功。
+- 「归档占用」改名为"版本快照,不是数据库备份",与数据库整库备份分开计量,避免把两者相加。
+
## 开发快照 0.1.404(单次任务固定同一 WeKnora 连接)
### Fixed
diff --git a/web/src/BackupScheduleSection.test.tsx b/web/src/BackupScheduleSection.test.tsx
index 7214cd0..75a8e60 100644
--- a/web/src/BackupScheduleSection.test.tsx
+++ b/web/src/BackupScheduleSection.test.tsx
@@ -8,7 +8,11 @@ import {
backupTimeValid,
formatBackupBytes,
runMoment,
+ storageAlerts,
+ storageAlertSummary,
+ storageUsage,
} from './BackupScheduleSection'
+import type { StorageDiskObservation } from './BackupScheduleSection'
import type { BackupSchedule } from './backupSchedule'
const base: BackupSchedule = {
@@ -49,7 +53,25 @@ const base: BackupSchedule = {
run_last_error: '',
}
-const view = (overrides: Partial = {}, extra: Record = {}) => {
+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 view = (
+ overrides: Partial = {},
+ extra: Record = {},
+ disk: StorageDiskObservation | null = null
+) => {
const schedule = { ...base, ...overrides }
return renderToStaticMarkup(
= {}, extra: Record
)
}
describe('BackupScheduleView', () => {
- it('管理员看到定时时间/储存天数与下发按钮,并显示主机上生效的计划与最近一次结果', () => {
+ it('按真实契约给出范围与读写方向,并把立即备份限定为整批', () => {
const html = view()
for (const text of [
'存储与备份',
- '备份执行主机',
- '定时时间',
- '储存天数',
- '每月归档保留',
- '保存并下发到主机',
- '重新下发当前设置',
- '立即备份一次',
- 'weknora-test · 已连接',
- '拨号地址',
+ '数据库整库逻辑备份',
+ '范围与读写方向',
+ '备份执行主机 weknora-test 本机直连 RDS',
+ '最近批次含 2 个数据库',
+ 'weknora-test 本地备份根目录',
+ '具体根目录未由接口返回',
+ '整批 · 2 个数据库(weknora_test、dobotai_prod)',
'100.85.111.121:22',
- '全库,不是 scope 快照',
- '每天 03:30 · 保留 7 天 · 每月 3 份',
- '已一致',
- '20261009T052909Z',
- '33 秒',
- '742.4 MiB',
- 'weknora_test、dobotai_prod',
+ '立即备份一次(整批 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('编辑草稿:每天 05:10 · 保留 14 天')
+ expect(html).toContain('有未保存修改,主机仍按生效计划执行')
expect(html).toContain('type="time"')
- expect(html).toContain('value="03:30"')
+ 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('最近批次只展示接口真实字段;子库路径/复制/恢复验证明确未接线', () => {
+ const html = view({ last_run_failed_databases: ['dobotai_prod'] })
+ expect(html).toContain('备份记录')
+ expect(html).toContain('接口只返回最近一批')
+ expect(html).toContain('批次戳 20261009T052909Z')
+ expect(html).toContain('耗时 33 秒')
+ expect(html).toContain('742.4 MiB')
+ expect(html).toContain('weknora_test')
+ expect(html).toContain('dobotai_prod')
+ expect(html).toContain('失败')
+ expect(html).toContain('子库目录与单库字节未由接口返回')
+ expect(html).toContain('复制目录(不可用)')
+ expect(html).toContain('恢复验证:未接线')
+ // 不拼造历史批次或示例子目录。
+ expect(html).not.toContain('/srv/kb-backups/rds-logical')
+ expect(html).not.toContain('11 月 19 日 03:30')
+ })
+
+ it('没有批次时说明不能据此判断成功/失败', () => {
+ const html = view({
+ last_run_stamp: '',
+ last_run_created_at: '',
+ last_run_databases: [],
+ last_run_total_bytes: 0,
+ host_reachable: false,
+ })
+ expect(html).toContain('还没有读到任何批次')
+ expect(html).toContain('不能据此判断备份成功或失败')
})
it('非管理员只读:没有保存/下发/立即备份按钮,只给当前设置', () => {
const html = view({}, { isAdmin: false })
expect(html).toContain('定时备份设置仅管理员可修改')
+ expect(html).toContain('立即备份仅管理员可触发')
expect(html).not.toContain('保存并下发到主机')
- expect(html).not.toContain('立即备份一次')
+ expect(html).not.toContain('立即备份一次(整批')
})
it('未接线:显式说明缺少主机凭据,下发与立即备份不可点', () => {
@@ -121,6 +196,7 @@ describe('BackupScheduleView', () => {
expect(html).toContain('未接线(缺少主机凭据)')
expect(html).toContain('待下发')
expect(html).toContain('目标主机凭据未挂载')
+ expect(html).toContain('主机未接线:定时计划不会执行')
expect(html).toContain('disabled')
})
@@ -137,6 +213,7 @@ describe('BackupScheduleView', () => {
expect(html).toContain('120.76.217.51:22')
expect(html).toContain('未知(未连上主机,未执行主机侧脚本)')
expect(html).not.toContain('缺失')
+ expect(html).toContain('主机连不上:以下"主机生效"状态未知')
})
it('已连上且脚本真的不在:这时才显示"缺失"', () => {
@@ -152,10 +229,11 @@ describe('BackupScheduleView', () => {
expect(html).toContain('每天 05:00')
})
- it('在途备份:按钮变"备份进行中…"并给出开始时间', () => {
+ it('在途备份:只报在途与开始时间,不造百分比', () => {
const html = view({ running: true, running_started_at: '2026-10-09T12:30:00Z' })
expect(html).toContain('备份进行中…')
expect(html).toContain('正在备份')
+ expect(html).toContain('没有真实百分比接口')
})
it('非法输入就地拦截,且保存按钮在未改动时不可点', () => {
@@ -188,3 +266,67 @@ describe('BackupScheduleView', () => {
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'])
+ })
+})
diff --git a/web/src/BackupScheduleSection.tsx b/web/src/BackupScheduleSection.tsx
index cbcdcb2..cfbc7ad 100644
--- a/web/src/BackupScheduleSection.tsx
+++ b/web/src/BackupScheduleSection.tsx
@@ -9,6 +9,7 @@ import {
saveBackupSchedule,
} from './backupSchedule'
import type { BackupSchedule } from './backupSchedule'
+import './storageBackup.css'
export const formatBackupBytes = (bytes: number): string => {
if (!bytes) return '—'
@@ -33,6 +34,170 @@ export const backupTimeValid = (value: string): boolean => /^([01][0-9]|2[0-3]):
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)
+ if (unknown.length) return '无法判定(缺主机磁盘读数)'
+ const active = alerts.filter((item) => item.active)
+ return active.length ? active.map((item) => item.label).join('、') : '四项均正常'
+}
+
+// 备份执行主机上的整库逻辑备份(全部业务库一次 pg_dump)。
+// 页面只展示接口真实给出的读数;目录、配额、预留、子库路径、历史批次与恢复
+// 验证在后端契约里还没有字段,保留原型位置并写明"未接线"。
export interface BackupScheduleViewProps {
schedule: BackupSchedule
isAdmin: boolean
@@ -53,9 +218,10 @@ export interface BackupScheduleViewProps {
onApply: () => void
onRunNow: () => void
onReload: () => void
+ // 仅测试夹具提供;生产容器不传,磁盘区显示"未接线"。
+ disk?: StorageDiskObservation | null
}
-// 纯视图:所有状态由 props 驱动,便于在测试里直接渲染各种状态(管理员/只读、已一致/待下发、在途)。
export function BackupScheduleView(props: BackupScheduleViewProps) {
const {
schedule,
@@ -77,6 +243,7 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
onApply,
onRunNow,
onReload,
+ disk = null,
} = props
const days = Number(daysDraft)
const months = Number(monthsDraft)
@@ -97,6 +264,12 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
: 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 = storageAlerts(disk)
return (
@@ -104,8 +277,8 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
存储与备份
- 整库逻辑备份(pg_dump 目录格式)在备份执行主机(同 VPC 直连 RDS)
- 上本地执行:这里设置定时时间与储存天数,保存即下发到主机 cron,并可读回主机上生效的计划与最近一次结果。
+ 本页管的是数据库整库逻辑备份(pg_dump 目录格式,在备份执行主机本地写盘);
+ 下方「归档占用」是版本快照的归档文件,两者不是同一种数据,体积不能相加。
@@ -117,161 +290,443 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
{error}
) : null}
-
-
- - 目标主机
- - {hostLine}
+
+
+
+
范围与读写方向
+
+ {schedule.host_configured ? '主机已接线' : '主机未接线'}
+
+
+
+ - 读取源
+ -
+ {`备份执行主机 ${schedule.host_target || '(未配置)'} 本机直连 RDS`}
+ {databaseCount ? ` · 最近批次含 ${databaseCount} 个数据库` : ' · 数据库清单未从主机读到'}
+
+ - 写入方向
+ -
+ {`${schedule.host_target || '(未配置)'} 本地备份根目录`}
+ 具体根目录未由接口返回,不在页面猜测
+
+ - 执行范围
+ -
+ {databaseCount
+ ? `整批 · ${databaseCount} 个数据库(${schedule.last_run_databases.join('、')})`
+ : '整批 · 数据库清单未读到,无法列出库名'}
+
- 拨号地址
- {schedule.host_endpoint || '—'}
- - 备份脚本
- - {scriptLine}
- - 主机 cron
- -
- {schedule.host_cron_service ? `服务 ${schedule.host_cron_service}` : '—'}
- {schedule.host_checked_at
- ? ` · 状态读取于 ${formatBackupMoment(schedule.host_checked_at)}`
- : ' · 状态读取时间未知'}
-
- - 下次计划(主机读回)
- -
- {schedule.host_next_run
- ? schedule.host_next_run
- : !schedule.host_configured
- ? '未接通备份执行主机:当前计划不会执行'
- : schedule.host_schedule_enabled
- ? `已配置每日 ${schedule.host_schedule_time};尚未核验下一次实际执行(不以历史下发时间推算)`
- : '未启用定时或未从主机读到计划'}
-
- - 最近一次运行
- -
- {schedule.last_run_stamp || '—'}
- {runMoment(schedule) ? ` · ${runMoment(schedule)}` : ''}
- {schedule.last_run_stamp
- ? schedule.last_run_failed_databases.length === 0 && !schedule.last_run_error
- ? ' · 成功'
- : ' · 有失败/读取错误'
- : ''}
-
- - 最近一次成功
- - 未从主机读取(不能用最近一次运行代替成功;失败库/读取错误见下方)
- - 备份耗时 / 体积
- -
- {schedule.last_run_stamp
- ? `${schedule.last_run_duration_seconds} 秒 · ${formatBackupBytes(schedule.last_run_total_bytes)}`
- : '—'}
-
-
- - 覆盖的库
- - {schedule.last_run_databases.length ? schedule.last_run_databases.join('、') : '—'}
- - 失败的库
- -
- {schedule.last_run_failed_databases.length
- ? schedule.last_run_failed_databases.join('、')
- : schedule.last_run_stamp
- ? '无'
- : '未知(还没有读到运行记录,不能据此判断没有失败)'}
-
- - 主机上生效的计划
- -
- {schedule.host_schedule_enabled
- ? `每天 ${schedule.host_schedule_time} · 保留 ${schedule.host_keep_days} 天 · 每月 ${schedule.host_keep_months} 份`
- : schedule.host_configured
- ? '未启用定时'
+
+
+ 仅备份该库(不可用)
+
+
+ POST /api/v1/backup-schedule/run 没有单库参数,一次就是该主机全部业务库的整批
+ pg_dump。用单库按钮触发会连整批一起跑,因此本页不开放单库动作;单库恢复只能用批次里该库的子目录,
+ 但子目录路径当前接口没有返回。
+
+
+
+
+
+
+
立即备份
+
+ {hasLastRun ? (runFailed ? '最近一批有失败' : '最近一批成功') : '尚无批次读数'}
+
+
+
+ {hasLastRun
+ ? `最近一批 ${schedule.last_run_stamp}${runMoment(schedule) ? ` · ${runMoment(schedule)}` : ''} · ${databaseCount} 个数据库 · ${formatBackupBytes(schedule.last_run_total_bytes)} · ${schedule.last_run_duration_seconds} 秒`
+ : '还没有从主机读到任何批次。'}
+
+ {schedule.running ? (
+
+
+ 正在备份({formatBackupMoment(schedule.running_started_at)} 开始,整批 {databaseCount || '未知'}{' '}
+ 个数据库)。 没有真实百分比接口,这里只报在途状态,完成后自动刷新。
+
+
+
+ ) : null}
+ {schedule.run_last_error && !schedule.running ? (
+ 上一次立即备份失败:{schedule.run_last_error}
+ ) : null}
+ {isAdmin ? (
+
+
+ {schedule.running
+ ? '备份进行中…'
+ : busy === 'run'
+ ? '正在触发…'
+ : `立即备份一次(整批${databaseCount ? ` ${databaseCount} 个数据库` : ''})`}
+
+ 触发的是该主机全部业务库的整批备份,不是 scope 快照,也不是单库。
+
+ ) : (
+ 立即备份仅管理员可触发;当前为只读。
+ )}
+
+
+ item.known && item.active) ? 'storage-disk-low' : ''}`}
+ aria-labelledby="storage-disk-heading"
+ >
+
+
整盘占用与告警
+ {usage ? '已读到主机读数' : '未接线'}
+
+ {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`
+ : ''}
+
+ >
+ ) : (
+ <>
+
+ 未接线 · 不显示估算容量
+
+
+ {['系统其他占用', '备份已用', '配额内空闲', '配额外空闲'].map((label, index) => (
+
+
+ {label} —
+
+ ))}
+
+ 整盘总量 / 空闲 / 备份占用:未接线
+ >
+ )}
+
+ 后端目前没有「备份主机磁盘总量、空闲、备份目录占用」接口:这里保留单条整盘图的位置,
+ 不填示例容量、不用配额推算磁盘。以下四项告警按同一份真实读数判定。
+
+ {storageAlertSummary(alerts)}
+
+ {alerts.map((alert) => (
+ -
+ {alert.label}
+ {alert.known ? (alert.active ? '触发' : '正常') : '无法判定'}
+ {alert.detail}
+
+ ))}
+
+
+
+
+
+
备份策略
+ 北京时间 · 主机读回
+
+
+ {!schedule.host_configured
+ ? '主机未接线:定时计划不会执行。'
+ : !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 ? (
+
+ ) : (
+
+ 定时备份设置仅管理员可修改;当前设置:
+ {schedule.enabled ? `每天 ${schedule.schedule_time} · 保留 ${schedule.retention_days} 天` : '未启用'}。
+
+ )}
+
+
+
+
+
备份记录
+ 接口只返回最近一批
+
+
+ 历史批次列表、每批的数据库明细与子库目录都没有接口:这里只能展示主机 MANIFEST 里的最近一批,
+ 不补造历史记录,也不从时间戳推算目录。
+
+ {hasLastRun ? (
+
+
+ {schedule.last_run_created_at || schedule.last_run_stamp}
+ {databaseCount} 个数据库 · 整批
+
+ {runFailed ? '有失败/读取错误' : '成功 · 共 ' + formatBackupBytes(schedule.last_run_total_bytes)}
+
+
+
+ 批次戳 {schedule.last_run_stamp} · 耗时 {schedule.last_run_duration_seconds} 秒 · 总占盘{' '}
+ {formatBackupBytes(schedule.last_run_total_bytes)} · 单库体积未由清单提供
+
+
+ {schedule.last_run_databases.map((name) => {
+ const failed = schedule.last_run_failed_databases.includes(name)
+ return (
+ -
+
{name}
+ {failed ? '失败' : '已写入'}
+ 子库目录与单库字节未由接口返回
+
+ )
+ })}
+
+ {schedule.last_run_failed_databases.length ? (
+ 失败库:{schedule.last_run_failed_databases.join('、')}
+ ) : null}
+
+
+ 复制目录(不可用)
+
+ 子库路径待接口返回后才能复制;当前不拼接猜测路径。
+
+
+ 恢复验证:未接线(没有数据库备份恢复验证接口,不能把"备份成功"当成"可恢复")。
+
+
+ ) : (
+
+ {schedule.last_run_error
+ ? `最近一次结果读取失败:${schedule.last_run_error}`
+ : '还没有读到任何批次(主机未接线、连不上或尚未执行过);不能据此判断备份成功或失败。'}
+
+ )}
+
+
+
+
+
主机状态(读回)
+
+ {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
+ ? '未接通备份执行主机:当前计划不会执行'
+ : schedule.host_schedule_enabled
+ ? `已配置每日 ${schedule.host_schedule_time};尚未核验下一次实际执行(不以历史下发时间推算)`
+ : '未启用定时或未从主机读到计划'}
+
+
+
+ - 最近一次运行
+ -
+ {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)}`
: '—'}
-
- - 与设置是否一致
- - {schedule.in_sync ? '已一致' : '待下发'}
-
-
- {schedule.host_error ? 主机探测:{schedule.host_error}
: null}
- {schedule.last_run_error ? 最近一次结果读取:{schedule.last_run_error}
: null}
- {schedule.host_cron_lines.length ? (
-
- 主机 cron 条目:{schedule.host_cron_lines.join(' ; ')}
-
- ) : null}
- {schedule.last_applied_at ? (
-
- 最后下发:{formatBackupMoment(schedule.last_applied_at)}
- {schedule.last_applied_summary ? ` · ${schedule.last_applied_summary}` : ''}
-
- ) : null}
+
+ - 与设置是否一致
+ - {schedule.in_sync ? '已一致' : '待下发'}
+ - 最后下发
+ -
+ {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.host_cron_lines.length ? (
+
+ 主机 cron 条目:{schedule.host_cron_lines.join(' ; ')}
+
+ ) : null}
+
+
留档分层:PG 行级留档(发布前,含 ES 文档)+ ES 快照仓 + OSS 版本控制 + 本节的整库逻辑备份 + RDS
托管备份(控制台配置)。详见 docs/PRODUCTION_BACKUP_RECOVERY.md。
- {isAdmin ? (
-
-
-
-
-
- {!valid ? (
-
定时时间需为 HH:MM(00:00~23:59),储存天数 1~365,每月归档 0~24。
- ) : null}
-
- {busy === 'save' ? '正在保存并下发…' : '保存并下发到主机'}
-
-
- {busy === 'apply' ? '正在下发…' : '重新下发当前设置'}
-
-
- {schedule.running ? '备份进行中…' : '立即备份一次(全库,不是 scope 快照)'}
-
-
- 「立即备份一次」执行的是主机上的整库逻辑备份(该主机上全部业务库的 pg_dump 目录),
- 不是本次对内/对外 scope 的整库快照;scope 快照在「发布管理 → 整库版本」里封存。
-
- {message ? (
-
- {message}
-
- ) : null}
- {schedule.running ? (
-
正在备份({formatBackupMoment(schedule.running_started_at)} 开始),完成后自动刷新。
- ) : null}
- {schedule.run_last_error && !schedule.running ? (
-
上一次立即备份失败:{schedule.run_last_error}
- ) : null}
-
- ) : (
-
- 定时备份设置仅管理员可修改;当前设置:
- {schedule.enabled ? `每天 ${schedule.schedule_time} · 保留 ${schedule.retention_days} 天` : '未启用'}。
-
- )}
)
}
@@ -399,7 +854,7 @@ export function BackupScheduleSection() {
const start = await runBackupNow()
setMessage(
start.started
- ? '已在目标主机上开始备份(整库 pg_dump,约 30~60 秒),下方会自动刷新结果。'
+ ? '已在目标主机上开始整批备份(全部业务库 pg_dump,约 30~60 秒),下方会自动刷新结果。'
: '已有一个备份任务在执行中。'
)
adopt(await fetchBackupScheduleHost())
@@ -449,6 +904,7 @@ export function BackupScheduleSection() {
onApply={() => void apply()}
onRunNow={() => void runNow()}
onReload={() => void load()}
+ // disk 不传:后端还没有磁盘读数接口,磁盘区显示"未接线",绝不填示例容量。
/>
)
}
diff --git a/web/src/LibraryStorageSection.tsx b/web/src/LibraryStorageSection.tsx
index ef340e2..ab4d59f 100644
--- a/web/src/LibraryStorageSection.tsx
+++ b/web/src/LibraryStorageSection.tsx
@@ -31,8 +31,11 @@ export function LibraryStorageSection() {
return (
- 版本快照与归档占用
- 只读口径:被版本引用的去重内容、blob 文件表观/实际分配字节、未被引用对象、清单文件。
+ 归档占用(版本快照,不是数据库备份)
+
+ 只读口径:被版本引用的去重内容、blob 文件表观/实际分配字节、未被引用对象、清单文件。
+ 这些归档文件与上面的整库数据库备份分开计量,不能相加。
+
{loading ? 读取中…
: null}
{error ? (
diff --git a/web/src/SystemSettings.tsx b/web/src/SystemSettings.tsx
index e61a57d..5773092 100644
--- a/web/src/SystemSettings.tsx
+++ b/web/src/SystemSettings.tsx
@@ -244,8 +244,8 @@ export function SystemSettingsView({
) : null}
{section === 'storage' ? (
<>
-
+
>
) : null}
{section === 'members' && identity?.role === 'admin' ? : null}
diff --git a/web/src/storageBackup.css b/web/src/storageBackup.css
new file mode 100644
index 0000000..354d3f2
--- /dev/null
+++ b/web/src/storageBackup.css
@@ -0,0 +1,353 @@
+/* 「系统设置 → 存储与备份」:数据库整库逻辑备份。
+ 原型里的单条整盘图与告警在这里保留位置;真实读数未接线时用虚底而不是假容量。 */
+.storage-settings-panel {
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+}
+.storage-settings-panel .settings-section-heading p {
+ margin: 0;
+ max-width: 78ch;
+ color: var(--ink-mute, #64748b);
+ font-size: 11px;
+ line-height: 1.7;
+}
+/* 主机读回用两栏事实表;窄列时自动落成一栏,避免 dd 把 dt 挤成竖排。 */
+.settings-panel .storage-settings-grid {
+ grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
+}
+.settings-panel .storage-settings-grid > dl {
+ grid-template-columns: minmax(104px, max-content) minmax(0, 1fr);
+}
+.storage-settings-panel code {
+ overflow-wrap: anywhere;
+}
+.storage-block {
+ border-top: 1px solid var(--border-base, #e2e8f0);
+ padding-top: 12px;
+}
+.storage-block-heading {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px 14px;
+ flex-wrap: wrap;
+ margin-bottom: 6px;
+}
+.storage-block-heading h3 {
+ margin: 0;
+ font-size: 13px;
+ color: var(--ink-base);
+}
+.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;
+ font-weight: 600;
+}
+.storage-alert-summary {
+ margin: 8px 0 0;
+ font-size: 11px;
+ font-weight: 600;
+ color: #3f5566;
+}
+.storage-alerts {
+ list-style: none;
+ margin: 8px 0 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);
+}
+.storage-alerts li strong {
+ font-size: 11px;
+}
+.storage-alerts li small {
+ color: var(--ink-mute, #64748b);
+ overflow-wrap: anywhere;
+}
+.storage-alerts .alert-on {
+ background: #fff1ec;
+ color: #a03a1e;
+}
+.storage-alerts .alert-ok {
+ background: #f0faf6;
+ color: #17695a;
+}
+.storage-alerts .alert-unknown {
+ background: #f8f5ee;
+ color: #715c2c;
+}
+.storage-plan {
+ margin: 4px 0;
+ font-size: 11px;
+ color: #3f5566;
+}
+.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'] {
+ 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;
+}
+.storage-policy-editor input:disabled {
+ background: var(--bg-soft, #f1f4f6);
+ color: var(--ink-mute, #64748b);
+}
+.storage-checkbox {
+ display: flex !important;
+ align-items: center;
+ gap: 6px;
+ font-size: 11px !important;
+ color: var(--ink-base) !important;
+}
+.storage-policy-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
+ gap: 8px 12px;
+}
+.storage-policy-grid label {
+ display: grid;
+ gap: 3px;
+ font-size: 10px;
+ color: var(--ink-mute, #64748b);
+}
+.storage-policy-grid input {
+ width: 100%;
+}
+.storage-batch {
+ border: 1px solid var(--border-base, #e2e8f0);
+ border-radius: 8px;
+ padding: 8px 10px;
+ font-size: 11px;
+}
+.storage-batch summary {
+ display: flex;
+ gap: 6px 14px;
+ flex-wrap: wrap;
+ align-items: baseline;
+ cursor: pointer;
+}
+.storage-batch summary strong.ok {
+ color: #17695a;
+}
+.storage-batch summary strong.off {
+ color: #a03a1e;
+}
+.storage-batch p {
+ margin: 6px 0;
+ color: #3f5566;
+}
+.storage-sublibraries {
+ list-style: none;
+ margin: 6px 0;
+ padding: 0;
+ display: grid;
+ gap: 4px;
+}
+.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-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,
+ .storage-alerts li {
+ grid-template-columns: minmax(0, 1fr);
+ }
+}
From 9eacf6473e65d83e614027c07134b5919ebeb791 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E5=A7=9A=E7=AB=A0=E6=B5=A9?=
Date: Thu, 19 Nov 2026 23:45:15 +0800
Subject: [PATCH 06/14] =?UTF-8?q?fix(settings):=20=E5=A4=87=E4=BB=BD?=
=?UTF-8?q?=E4=B8=BB=E6=9C=BA=E7=8A=B6=E6=80=81=E4=B8=8D=E5=BE=97=E7=94=B1?=
=?UTF-8?q?=E5=8E=86=E5=8F=B2=E4=B8=8B=E5=8F=91=E6=8E=A8=E6=96=AD?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
为什么:host_configured=false 时页面宣称"定时计划不会执行",但平台只是没挂载
主机凭据,远端既有 cron 可能仍在跑;最后下发是历史记录,也不能证明当前计划。
怎么改:无凭据时改为"无法确认当前主机计划/远端 cron 可能仍在执行";最后下发标为
历史并注明不能代表当前状态;未探测与探测失败分开;"与设置是否一致"只在真正读回
主机计划后判定。
怎么验:新增无凭据 + 有效历史下发、已接线未探测两例回归,断言不出现"不会执行";
vitest 619 项、tsc、prettier 通过;本地页面夹具 C 面板核对文案。
---
CHANGELOG.md | 11 +++++
web/src/BackupScheduleSection.test.tsx | 28 +++++++++--
web/src/BackupScheduleSection.tsx | 64 +++++++++++++++++---------
3 files changed, 78 insertions(+), 25 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c59402b..2d70b4a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,16 @@
# Changelog
+## 开发快照 0.1.406(备份主机状态不得由历史推断)
+
+### Fixed
+
+- 平台未挂载主机凭据时不再断言「定时计划不会执行」:改为无法确认当前主机计划,
+ 远端 cron 可能仍在执行;历史下发记录不能代替实时状态。
+- 「最后下发」明确标为历史记录,只证明当时下发过,不能代表当前主机计划或执行状态。
+- 未探测与探测失败分开:只读计划先返回时显示「尚未探测」,不误报「连接失败」;
+ 「与设置是否一致」只在真正读回主机计划后判定,未读到时显示无法比对。
+- 回归:无凭据但存在有效历史下发、已接线但尚未探测两例都不得出现执行断言。
+
## 开发快照 0.1.405(存储与备份:单页对齐真实接口)
### Added
diff --git a/web/src/BackupScheduleSection.test.tsx b/web/src/BackupScheduleSection.test.tsx
index 75a8e60..93dbc76 100644
--- a/web/src/BackupScheduleSection.test.tsx
+++ b/web/src/BackupScheduleSection.test.tsx
@@ -126,6 +126,8 @@ describe('BackupScheduleView', () => {
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"')
@@ -186,20 +188,37 @@ describe('BackupScheduleView', () => {
expect(html).not.toContain('立即备份一次(整批')
})
- it('未接线:显式说明缺少主机凭据,下发与立即备份不可点', () => {
+ 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('平台未挂载主机凭据(远端状态未知)')
+ 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).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,
@@ -214,6 +233,7 @@ describe('BackupScheduleView', () => {
expect(html).toContain('未知(未连上主机,未执行主机侧脚本)')
expect(html).not.toContain('缺失')
expect(html).toContain('主机连不上:以下"主机生效"状态未知')
+ expect(html).toContain('无法比对(主机不可达)')
})
it('已连上且脚本真的不在:这时才显示"缺失"', () => {
diff --git a/web/src/BackupScheduleSection.tsx b/web/src/BackupScheduleSection.tsx
index cfbc7ad..669037f 100644
--- a/web/src/BackupScheduleSection.tsx
+++ b/web/src/BackupScheduleSection.tsx
@@ -254,10 +254,24 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
days !== schedule.retention_days ||
months !== schedule.retention_months
const hostLine = !schedule.host_configured
- ? '未接线(缺少主机凭据)'
+ ? '平台未挂载主机凭据(远端状态未知)'
: schedule.host_reachable
? `${schedule.host_target} · 已连接`
- : `${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
? '未知(未连上主机,未执行主机侧脚本)'
@@ -295,7 +309,7 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
范围与读写方向
- {schedule.host_configured ? '主机已接线' : '主机未接线'}
+ {schedule.host_configured ? '平台已接主机凭据' : '平台未接主机凭据'}
@@ -475,14 +489,16 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
{!schedule.host_configured
- ? '主机未接线:定时计划不会执行。'
- : !schedule.host_reachable
- ? '主机连不上:以下"主机生效"状态未知,不能按设置推定。'
- : schedule.host_schedule_enabled
- ? `主机生效:每天 ${schedule.host_schedule_time} · 保留 ${schedule.host_keep_days} 天 · 每月 ${schedule.host_keep_months} 份 · ${
- schedule.in_sync ? '与设置已一致' : '与设置不一致(待下发)'
- }`
- : '主机生效:定时备份已关闭(已有备份保留)'}
+ ? '平台未挂载主机凭据:无法读取当前主机计划,远端 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}` : ' · 下一次实际执行未由主机返回'}
@@ -656,7 +672,7 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
{schedule.last_run_error
? `最近一次结果读取失败:${schedule.last_run_error}`
- : '还没有读到任何批次(主机未接线、连不上或尚未执行过);不能据此判断备份成功或失败。'}
+ : '还没有读到任何批次(平台未接主机凭据、主机连不上或尚未执行过);不能据此判断备份成功或失败。'}
)}
@@ -665,7 +681,11 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
主机状态(读回)
- {schedule.host_checked_at ? `读取于 ${formatBackupMoment(schedule.host_checked_at)}` : '尚未探测'}
+ {!schedule.host_configured
+ ? '未探测(平台未挂载主机凭据)'
+ : schedule.host_checked_at
+ ? `读取于 ${formatBackupMoment(schedule.host_checked_at)}`
+ : '尚未探测'}
@@ -683,10 +703,12 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
{schedule.host_next_run
? schedule.host_next_run
: !schedule.host_configured
- ? '未接通备份执行主机:当前计划不会执行'
- : schedule.host_schedule_enabled
- ? `已配置每日 ${schedule.host_schedule_time};尚未核验下一次实际执行(不以历史下发时间推算)`
- : '未启用定时或未从主机读到计划'}
+ ? '无法确认当前主机计划:平台未挂载主机凭据,远端 cron 可能仍在执行(历史下发不能代替实时状态)'
+ : hostProbePending
+ ? '尚未探测主机,无法确认下一次执行'
+ : schedule.host_schedule_enabled
+ ? `已配置每日 ${schedule.host_schedule_time};尚未核验下一次实际执行(不以历史下发时间推算)`
+ : '未启用定时或未从主机读到计划'}
@@ -705,12 +727,12 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
: '—'}
- 与设置是否一致
- - {schedule.in_sync ? '已一致' : '待下发'}
- - 最后下发
+ - {syncLine}
+ - 最后下发(历史)
-
{schedule.last_applied_at
- ? `${formatBackupMoment(schedule.last_applied_at)}${schedule.last_applied_summary ? ` · ${schedule.last_applied_summary}` : ''}`
- : '—'}
+ ? `${formatBackupMoment(schedule.last_applied_at)}${schedule.last_applied_summary ? ` · ${schedule.last_applied_summary}` : ''} · 只记录当时下发结果,不能代表当前主机计划或执行状态`
+ : '—(没有历史下发记录;不能据设置推定主机计划)'}
From 033f702d41bbc4fb9c70ed2114e6c64275389000 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E5=A7=9A=E7=AB=A0=E6=B5=A9?=
Date: Fri, 20 Nov 2026 00:58:18 +0800
Subject: [PATCH 07/14] =?UTF-8?q?feat(backup):=20=E5=8F=AA=E8=AF=BB?=
=?UTF-8?q?=E7=9B=98=E7=82=B9=E7=9C=9F=E5=AE=9E=E6=89=B9=E6=AC=A1=E3=80=81?=
=?UTF-8?q?=E5=AD=90=E5=BA=93=E8=B7=AF=E5=BE=84=E4=B8=8E=E5=AE=B9=E9=87=8F?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
为什么:28189 验收里历史批次/子库路径/容量都没有真实接口,页面只能占位;
用户要求修实际接口而不是继续改文案,同时不得写主机或触发备份。
怎么改:新增 GET /api/v1/backup-schedule/inventory,只读盘点 statfs 实测容量、
st_blocks 实际占盘、全部批次与 MANIFEST 状态、每个子库完整主机路径。目录必须
只读挂载;用设备号区分挂载文件系统与容器根盘,同设备时不给主机容量。清单
missing/invalid、未接线、不可读分别展示。SSH 计划读回与盘点独立加载。
前端消费该接口:整盘色带、批次列表、子库路径复制、清单失败与容器根盘提示。
怎么验:Go 单测覆盖清单/占盘/符号链接/容器根盘;handler 契约;appconfig 接线校验;
vitest 627 项、tsc、vite build、prettier 通过;本地页面夹具核对 8 批与路径复制,
1440/1024/768 无横向溢出。未连接真实主机、未执行备份、未改真实计划。
---
CHANGELOG.md | 22 +
api/openapi.yaml | 23 +
cmd/api/main.go | 26 +
compose.release-sim.yaml | 6 +
docs/PRODUCTION_BACKUP_RECOVERY.md | 5 +-
docs/STORAGE_BACKUP_READONLY_API.md | 187 +++++++
internal/appconfig/config.go | 27 +
internal/appconfig/config_test.go | 34 ++
internal/backupinventory/inventory.go | 592 +++++++++++++++++++++
internal/backupinventory/inventory_test.go | 205 +++++++
internal/httpapi/backup_inventory.go | 23 +
internal/httpapi/backup_inventory_test.go | 88 +++
internal/httpapi/server.go | 19 +-
web/src/BackupScheduleSection.test.tsx | 283 ++++++++--
web/src/BackupScheduleSection.tsx | 523 +++++++++++++++---
web/src/backupInventory.test.ts | 107 ++++
web/src/backupInventory.ts | 194 +++++++
web/src/storageBackup.css | 71 +++
18 files changed, 2317 insertions(+), 118 deletions(-)
create mode 100644 docs/STORAGE_BACKUP_READONLY_API.md
create mode 100644 internal/backupinventory/inventory.go
create mode 100644 internal/backupinventory/inventory_test.go
create mode 100644 internal/httpapi/backup_inventory.go
create mode 100644 internal/httpapi/backup_inventory_test.go
create mode 100644 web/src/backupInventory.test.ts
create mode 100644 web/src/backupInventory.ts
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2d70b4a..96db63f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,27 @@
# Changelog
+## 开发快照 0.1.407(备份盘点:只读挂载读真实批次与容量)
+
+### Added
+
+- `GET /api/v1/backup-schedule/inventory`:只读盘点 `rds-logical` 批次、MANIFEST 状态、每个
+ 子库完整主机路径、表观/实际占盘,以及只读挂载文件系统的实测容量。
+- 新包 `internal/backupinventory`:批次按目录戳倒序,`*.incomplete` 不计入;清单缺失/损坏
+ 逐批标注;实际占盘按 `st_blocks×512`;容量用 `statfs`,并与容器根盘比较设备号。
+- 系统设置 → 存储与备份接入盘点:整盘色带、批次列表、子库路径复制、清单失败与未接线分开;
+ SSH 计划读回与文件盘点独立加载,互不掩盖失败。
+- 文档 `docs/STORAGE_BACKUP_READONLY_API.md`:28189 候选接口契约、`:ro` 最小挂载与权限要求、
+ 可验证字段、现有写路径与尚未实现的后端写能力。
+
+### Changed
+
+- 备份策略目录改为只读展示盘点到的 `host_root`;配额/预留仍无后端字段,保留占位并标未知。
+- 磁盘告警只在“挂载与容器根盘分离 + 容量实测 + 有批次占盘参考”时判定;容器根盘读数只作排障。
+
+### Security
+
+- 盘点不执行远端文件命令、不写备份目录;只接受只读挂载,拒绝跟随符号链接批次,扫描有上限。
+
## 开发快照 0.1.406(备份主机状态不得由历史推断)
### Fixed
diff --git a/api/openapi.yaml b/api/openapi.yaml
index 8a0f990..021979a 100644
--- a/api/openapi.yaml
+++ b/api/openapi.yaml
@@ -1972,6 +1972,29 @@
}
}
},
+ "/api/v1/backup-schedule/inventory": {
+ "get": {
+ "tags": [
+ "Settings"
+ ],
+ "operationId": "getBackupScheduleInventory",
+ "summary": "只读盘点备份批次、子库完整路径与实际占盘、挂载文件系统实测容量",
+ "responses": {
+ "200": {
+ "$ref": "#/components/responses/Envelope"
+ },
+ "400": {
+ "$ref": "#/components/responses/BadRequest"
+ },
+ "500": {
+ "$ref": "#/components/responses/InternalError"
+ },
+ "503": {
+ "$ref": "#/components/responses/ServiceUnavailable"
+ }
+ }
+ }
+ },
"/api/v1/backup-schedule/apply": {
"post": {
"tags": [
diff --git a/cmd/api/main.go b/cmd/api/main.go
index 0c53269..70cdd02 100644
--- a/cmd/api/main.go
+++ b/cmd/api/main.go
@@ -8,6 +8,7 @@ import (
"net/http"
"os"
"os/signal"
+ "path"
"strings"
"syscall"
"time"
@@ -16,6 +17,7 @@ import (
"knowledge-governance/internal/appconfig"
"knowledge-governance/internal/backuphost"
+ "knowledge-governance/internal/backupinventory"
"knowledge-governance/internal/dingtalkdiscovery"
"knowledge-governance/internal/httpapi"
"knowledge-governance/internal/kbbinding"
@@ -55,6 +57,25 @@ func (dingtalkSourceLister) ValidateDingtalkDocument(ctx context.Context, node s
return dingtalkdiscovery.ValidateDocument(ctx, dingtalkdiscovery.ExecRunner{}, node)
}
+// 只读盘点的展示路径必须与挂载来源同一份:容器内挂载点不可给操作者复制,
+// 复制出去要在主机上能直接 cd/pg_restore。来源没配时用 target + 主机根拼。
+func backupInventoryHostRoot(config appconfig.Config) string {
+ if config.BackupHostReadonlyHostPath != "" {
+ return config.BackupHostReadonlyHostPath
+ }
+ return path.Join(config.BackupHostRoot, "rds-logical")
+}
+
+func backupInventorySource(config appconfig.Config) string {
+ if config.BackupHostReadonlySource != "" {
+ return config.BackupHostReadonlySource
+ }
+ if config.BackupHostTarget == "" {
+ return ""
+ }
+ return config.BackupHostTarget + ":" + backupInventoryHostRoot(config)
+}
+
func main() {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
@@ -318,6 +339,11 @@ func run(ctx context.Context, getenv func(string) string) error {
ScriptDir: config.BackupHostScriptDir,
Root: config.BackupHostRoot,
}),
+ BackupInventory: backupinventory.New(backupinventory.Config{
+ Root: config.BackupHostReadonlyRoot,
+ HostRoot: backupInventoryHostRoot(config),
+ Source: backupInventorySource(config),
+ }),
Auth: &httpapi.AuthConfig{Store: authStore, SessionTTL: 12 * time.Hour},
})
if err != nil {
diff --git a/compose.release-sim.yaml b/compose.release-sim.yaml
index f431d94..bf4728b 100644
--- a/compose.release-sim.yaml
+++ b/compose.release-sim.yaml
@@ -16,9 +16,15 @@ services:
BACKUP_HOST_TARGET: weknora-test
BACKUP_HOST_SCRIPT_DIR: /opt/weknora-test
BACKUP_HOST_ROOT: /srv/kb-backups
+ # 只读盘点(批次/子库路径/实测容量)与上面的 SSH 计划读回独立。
+ # 候选 28189 部署时按 docs/STORAGE_BACKUP_READONLY_API.md 打开,并要求宿主目录只读挂载:
+ # BACKUP_HOST_READONLY_ROOT: /var/lib/knowledge-governance/backup-host/rds-logical
+ # BACKUP_HOST_READONLY_HOST_PATH: /srv/kb-backups/rds-logical
+ # BACKUP_HOST_READONLY_SOURCE: weknora-test:/srv/kb-backups/rds-logical
volumes:
- ./secrets/release-sim:/run/release-secrets:ro
- ./secrets/backup-host:/run/backup-host:ro
+ # - /srv/kb-backups/rds-logical:/var/lib/knowledge-governance/backup-host/rds-logical:ro
release-worker:
environment:
diff --git a/docs/PRODUCTION_BACKUP_RECOVERY.md b/docs/PRODUCTION_BACKUP_RECOVERY.md
index 3f7038a..9915f4d 100644
--- a/docs/PRODUCTION_BACKUP_RECOVERY.md
+++ b/docs/PRODUCTION_BACKUP_RECOVERY.md
@@ -91,13 +91,16 @@ python3 scripts/restore_drill.py --snapshot-dir $KB_BACKUP_ROOT/target-kb-snapsh
- 页面:系统设置 → 存储与备份(管理员可改;保存 = 写入库并立刻下发;另有"重新下发当前设置"与"立即备份一次")。
- 接口:`GET /api/v1/backup-schedule`(不探测主机,首屏快)、`GET …/host`(SSH 读回主机 cron 与最近一次结果)、
+ `GET …/inventory`(只读挂载盘点全部批次/子库路径/实测容量,见 `docs/STORAGE_BACKUP_READONLY_API.md`)、
`PUT`(校验时间 `HH:MM` 与 1~365 天 / 0~24 月,非法值直接 400 且不落库不下发)、`POST …/apply`、`POST …/run`。
写操作按角色网关(`classifyRole`)限管理员——这份计划会落到数据面主机的 cron 上。
- 主机侧:`scripts/install_backup_schedule.sh`(幂等)写 `/etc/knowledge-governance/backup-schedule.env`
与 `/etc/cron.d/kb-logical-backup`;`logical-backup.sh` 从该文件读保留策略(显式传 `KEEP_DAILY/KEEP_MONTHS` 可覆盖)。
- 凭据:容器内只读挂载 `secrets/backup-host/{ssh_config,id_ed25519,known_hosts}`(0600),
环境变量 `BACKUP_HOST_SSH_CONFIG / BACKUP_HOST_TARGET / BACKUP_HOST_SCRIPT_DIR / BACKUP_HOST_ROOT`;
- **三项缺任一即"未接线"**,页面降级提示而不是报错。
+ **三项缺任一即"未接线"**,页面降级提示而不是报错。只读盘点另用
+ `BACKUP_HOST_READONLY_ROOT / BACKUP_HOST_READONLY_HOST_PATH / BACKUP_HOST_READONLY_SOURCE`,
+ 要求 `:ro` 挂载,见 `docs/STORAGE_BACKUP_READONLY_API.md`。
- 主机状态读取只认**有 `MANIFEST.json` 的完整目录**:被中断的运行会被脚本改名 `*.incomplete`,
所以"最近一次备份"永远不会显示一份半成品。
- 依赖两个运行前提:运行镜像里有 `openssh-client`,且容器用户的 uid 在 `/etc/passwd` 有名字
diff --git a/docs/STORAGE_BACKUP_READONLY_API.md b/docs/STORAGE_BACKUP_READONLY_API.md
new file mode 100644
index 0000000..f1c23a1
--- /dev/null
+++ b/docs/STORAGE_BACKUP_READONLY_API.md
@@ -0,0 +1,187 @@
+# 存储与备份:只读盘点接口与 28189 候选接线
+
+本页的「备份记录 / 整盘占用」只读**备份执行主机**上的 `rds-logical` 目录。接口不执行
+SSH 文件命令,也不写备份目录;它只读一个**只读挂载**进来的目录,并用 `statfs` 与
+`st_blocks` 给出实测容量和实际占盘。主机 cron 计划的读回仍是另一条 SSH 通道,两者独立。
+
+## 1. 接口契约
+
+`GET /api/v1/backup-schedule/inventory`(读者角色可看;不写任何东西)
+
+响应始终是 200 + `data`,未接线/目录不可读/清单损坏都写在字段里,页面据此区分原因。
+只有请求本身失败(如代理 502)才是非 200。
+
+```json
+{
+ "data": {
+ "wired": true,
+ "root": "/var/lib/knowledge-governance/backup-host/rds-logical",
+ "host_root": "/srv/kb-backups/rds-logical",
+ "source": "weknora-test:/srv/kb-backups/rds-logical",
+ "observed_at": "2026-11-19T03:30:10Z",
+ "error": "",
+ "mount": {
+ "container_root": "/",
+ "mount_verified": true,
+ "lives_on_container_root": false,
+ "read_only": true,
+ "evidence": "挂载设备 20 与容器根盘 10 不同:容量按挂载文件系统计量"
+ },
+ "capacity": {
+ "measured": true,
+ "total_bytes": 257698037760,
+ "free_bytes": 51539607552,
+ "available_bytes": 48318382080,
+ "used_bytes": 206158430208
+ },
+ "batches": [
+ {
+ "stamp": "20261118T193001Z",
+ "path": "/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z",
+ "host_path": "/srv/kb-backups/rds-logical/20261118T193001Z",
+ "manifest_state": "ok",
+ "manifest_path": "…/20261118T193001Z/MANIFEST.json",
+ "manifest_error": "",
+ "kind": "rds-logical-backup",
+ "created_at": "20261118T193001Z",
+ "duration_seconds": 53,
+ "manifest_total_bytes": 1393646469,
+ "apparent_bytes": 1393646469,
+ "actual_bytes": 1500000000,
+ "file_count": 214,
+ "sizes_complete": true,
+ "databases": [
+ {
+ "name": "weknora_v090prod",
+ "dir_name": "weknora_v090prod.dir",
+ "path": "…/20261118T193001Z/weknora_v090prod.dir",
+ "host_path": "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir",
+ "present": true,
+ "failed": false,
+ "in_manifest": true,
+ "apparent_bytes": 696320,
+ "actual_bytes": 720896,
+ "file_count": 12
+ }
+ ]
+ }
+ ],
+ "totals": {
+ "batch_count": 8,
+ "database_count": 0,
+ "apparent_bytes": 11141651752,
+ "actual_bytes": 12000000000,
+ "latest_stamp": "20261118T193001Z",
+ "latest_actual_bytes": 1500000000
+ },
+ "incomplete_count": 0,
+ "skipped": [],
+ "truncated": false
+ }
+}
+```
+
+> 示例中的容量、字节与库数只说明字段形状,**不是现场读数**;现场值必须由接口实测。
+> 候选现场已核实的事实只有:8 批、最近 `20261118T193001Z`、含 `weknora_v090prod.dir`。
+
+### 字段语义(页面可逐项核对)
+
+| 字段 | 含义 | 页面行为 |
+| --- | --- | --- |
+| `wired` | `BACKUP_HOST_READONLY_ROOT` 已配置 | false 显示“只读盘点未接线”,不显示空批次当“没有备份” |
+| `error` | 目录不存在/不可读 | 显示原因;批次区不伪造数据 |
+| `mount.mount_verified` | 挂载根与容器根盘设备号不同 | false 时容量只作排障,不当主机容量、不判磁盘告警 |
+| `mount.lives_on_container_root` | 与容器根盘同设备 | true 时页面明确“容器根盘·不代表主机磁盘” |
+| `mount.read_only` | `statfs` 标志含 `ST_RDONLY` | false 时提示部署需改 `:ro` |
+| `capacity.*` | 挂载文件系统的实测字节 | 只在 `mount_verified && measured` 时画色带 |
+| `batches[].manifest_state` | `ok` / `missing` / `invalid` | 逐批标注;损坏批仍按目录列子库与占盘 |
+| `batches[].actual_bytes` | 目录内文件 `st_blocks × 512` 合计 | 实际占盘(不是 MANIFEST 表观值) |
+| `databases[].host_path` | 主机上可复制的完整子库目录 | 复制按钮可用;不拼造路径 |
+| `databases[].present` | `.dir` 目录是否真的存在 | false 显示“目录缺失” |
+| `incomplete_count` | `*.incomplete` 目录数 | 仅提示,不计入批次 |
+| `skipped` | 符号链接/非法项/超限 | 显示跳过原因 |
+| `truncated` | 批次或文件数超扫描上限 | 明确“部分结果” |
+
+`apparent_bytes` 优先取 MANIFEST 的 `total_bytes`;没有/损坏清单时退回目录 `st_size` 合计。
+`actual_bytes` 永远是文件系统实际分配,不用表观字节冒充占盘。
+
+## 2. 28189 候选 API 的最小接线
+
+28189 是 `weknora-test` 上的候选 API(本机通过 SSH 隧道访问)。API 容器增加三项环境变量
+和一条**只读** bind mount;不新增 SSH 权限,也不把备份目录挂成可写:
+
+```yaml
+services:
+ api:
+ environment:
+ BACKUP_HOST_READONLY_ROOT: /var/lib/knowledge-governance/backup-host/rds-logical
+ BACKUP_HOST_READONLY_HOST_PATH: /srv/kb-backups/rds-logical
+ BACKUP_HOST_READONLY_SOURCE: weknora-test:/srv/kb-backups/rds-logical
+ volumes:
+ - /srv/kb-backups/rds-logical:/var/lib/knowledge-governance/backup-host/rds-logical:ro
+```
+
+要求:
+
+- 挂载必须带 `:ro`。宿主目录本身不要改成 777;用 ACL/附加组给 API 运行用户(镜像内
+ `uid 1000`)只读遍历权限,例如由有权限的运维执行 `setfacl -R -m u:1000:rX /srv/kb-backups/rds-logical`
+ (属主机变更,需单独批准;本次未执行)。
+- 只挂 `rds-logical`,不要挂整个 `/srv/kb-backups`,减少可读面。
+- `BACKUP_HOST_READONLY_ROOT` 与 `BACKUP_HOST_READONLY_HOST_PATH` 必填;`SOURCE` 可省略
+ (省略时用 `BACKUP_HOST_TARGET + 主机路径` 拼展示来源)。缺 `ROOT` 或 `HOST_PATH` 会拒绝启动,
+ 避免“看起来接线”或复制出猜的路径。
+- 主机 cron 计划仍走原有 `BACKUP_HOST_SSH_CONFIG/TARGET/SCRIPT_DIR`;本接口不依赖 SSH。
+
+### 部署后 30 秒核验(在 API 容器内)
+
+```sh
+ROOT=/var/lib/knowledge-governance/backup-host/rds-logical
+findmnt -T "$ROOT" -o TARGET,SOURCE,FSTYPE,OPTIONS
+stat -c '%d %n' "$ROOT" /
+df -B1 "$ROOT"
+ls -1 "$ROOT" | tail
+```
+
+期望:`findmnt` 的 SOURCE 是宿主备份盘、OPTIONS 含 `ro`;`stat` 的设备号与 `/` 不同
+(对应 `mount.mount_verified=true`);`df` 与 `capacity` 接近;`ls` 能看到
+`20261118T193001Z`。
+
+字段核对:`totals.batch_count=8`、`totals.latest_stamp=20261118T193001Z`、最近批的
+`databases` 含 `weknora_v090prod` 且 `present=true`、`host_path` 以
+`/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir` 结尾。
+
+若 `wired=false` 或 `error` 提示不可读:先查挂载与读权限,不要用 SSH 的“最近一次”补历史。
+
+## 3. 与主机计划读回的关系
+
+- `GET /api/v1/backup-schedule/host`:SSH 读 cron/脚本/计划 + MANIFEST 的最近一次摘要。
+- `GET /api/v1/backup-schedule/inventory`:只读挂载读全部批次、子库路径、实际占盘、容量。
+
+前端分别加载,互不掩盖失败:盘点不可读时计划区仍显示读回结果;SSH 连不上时历史区仍可
+展示文件事实。历史批次与子库路径以盘点为准,SSH 的“最近一次”只作历史参考。
+
+## 4. 现有写路径(本次未改)
+
+| 路径 | 写什么 | 权限 |
+| --- | --- | --- |
+| `PUT /api/v1/backup-schedule` | 计划写库;`apply=true` 时 SSH 下发 cron | 管理员 |
+| `POST /api/v1/backup-schedule/apply` | SSH 重写主机 cron/计划参数 | 管理员 |
+| `POST /api/v1/backup-schedule/run` | 在主机执行 `logical-backup.sh`(写备份目录/RDS dump) | 管理员 |
+| `BackupScheduleStore.SaveBackupSchedule` | 计划落库 | 服务内部 |
+| `MarkBackupScheduleApplied` | 下发摘要回写 | 服务内部 |
+| `backuphost.Apply / RunNow` | 远端脚本执行 | 服务内部 |
+
+本接口没有任何写备份目录、删批次、改 cron 的代码路径。
+
+## 5. 还需单独确认的后端写能力
+
+以下均**未实现**,需要单独评审与授权,不能在本次只读闭环里顺手打开:
+
+1. 配额 / 磁盘预留的持久化与执行(当前无字段;页面保留占位并标未知)。
+2. 旧批次保留/删除(按天/按月轮转)与删除前审计、可恢复窗口。
+3. 备份目录迁移/切换(涉及主机 cron 参数与历史文件位置)。
+4. 单库备份/单库恢复(现有 `run` 是整批;单库范围需先证明)。
+5. 恢复验证执行(`pg_restore` 演练、校验和、结果留档)。
+6. MANIFEST 修复/重建(当前只如实报 missing/invalid)。
+7. 远程挂载/权限变更的自动化(属部署与主机权限,必须人工批准)。
+8. 写操作的角色细分(目前写路径统一管理员;若要“备份操作员”需另立角色)。
\ No newline at end of file
diff --git a/internal/appconfig/config.go b/internal/appconfig/config.go
index 65e8337..91e8afb 100644
--- a/internal/appconfig/config.go
+++ b/internal/appconfig/config.go
@@ -68,6 +68,11 @@ type Config struct {
BackupHostTarget string
BackupHostScriptDir string
BackupHostRoot string
+ // BackupHostReadonlyRoot 是容器内只读挂载的 rds-logical 目录(批次/子库/实测容量)。
+ // 留空即"未接线";它与上面的 SSH 计划读回是两条独立通道。
+ BackupHostReadonlyRoot string
+ BackupHostReadonlyHostPath string
+ BackupHostReadonlySource string
// 版本记录(「版本记录」页):**匿名只读**远端仓库的提交与 tag。来源留空即"未接线"
// (页面降级展示,接口返回可用性=false)。只允许配置里批准的 origin 与仓库,
// 不接受任何调用方传入的 URL;本功能**不使用凭据**。
@@ -223,6 +228,9 @@ func Load(getenv func(string) string) (Config, error) {
BackupHostTarget: strings.TrimSpace(getenv("BACKUP_HOST_TARGET")),
BackupHostScriptDir: valueOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_SCRIPT_DIR")), "/opt/weknora-test"),
BackupHostRoot: valueOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_ROOT")), "/srv/kb-backups"),
+ BackupHostReadonlyRoot: strings.TrimSpace(getenv("BACKUP_HOST_READONLY_ROOT")),
+ BackupHostReadonlyHostPath: strings.TrimSpace(getenv("BACKUP_HOST_READONLY_HOST_PATH")),
+ BackupHostReadonlySource: strings.TrimSpace(getenv("BACKUP_HOST_READONLY_SOURCE")),
VersionHistoryGiteaBaseURL: strings.TrimSpace(getenv("VERSION_HISTORY_GITEA_BASE_URL")),
VersionHistoryRepo: valueOrDefault(strings.TrimSpace(getenv("VERSION_HISTORY_REPO")), "Weknora/knowledge-governance"),
VersionHistoryAllowedOrigins: splitOrigins(getenv("VERSION_HISTORY_ALLOWED_ORIGINS")),
@@ -518,6 +526,25 @@ func Load(getenv func(string) string) (Config, error) {
return Config{}, errors.New("TEST_AUTO_REVIEW_POLICY must be one of off, internal, all")
}
config.TestAutoReviewPolicy = string(normalizedPolicy)
+ // 只读盘点接线与生产发布开关无关:测试栈也可能要先读通历史批次。
+ if config.BackupHostReadonlyRoot != "" && !filepath.IsAbs(config.BackupHostReadonlyRoot) {
+ return Config{}, errors.New("BACKUP_HOST_READONLY_ROOT must be an absolute path")
+ }
+ if config.BackupHostReadonlyHostPath != "" && !filepath.IsAbs(config.BackupHostReadonlyHostPath) {
+ return Config{}, errors.New("BACKUP_HOST_READONLY_HOST_PATH must be an absolute path")
+ }
+ if config.BackupHostReadonlyRoot != "" && config.BackupHostReadonlyHostPath == "" {
+ return Config{}, errors.New("BACKUP_HOST_READONLY_HOST_PATH is required when read-only root is set")
+ }
+ if config.BackupHostReadonlyRoot == "" &&
+ (config.BackupHostReadonlyHostPath != "" || config.BackupHostReadonlySource != "") {
+ return Config{}, errors.New("BACKUP_HOST_READONLY_ROOT is required when host path/source is set")
+ }
+ for _, value := range []string{config.BackupHostReadonlyHostPath, config.BackupHostReadonlySource} {
+ if strings.ContainsAny(value, "\x00\r\n") {
+ return Config{}, errors.New("backup inventory display path/source contains control characters")
+ }
+ }
if config.ProductionReleaseRequestsEnabled {
// 目标主机凭据要么都给要么都不给:只给一半会把"未接线"伪装成"已接线"。
if (config.BackupHostSSHConfig == "") != (config.BackupHostTarget == "") {
diff --git a/internal/appconfig/config_test.go b/internal/appconfig/config_test.go
index 893bbe8..9eba702 100644
--- a/internal/appconfig/config_test.go
+++ b/internal/appconfig/config_test.go
@@ -53,6 +53,40 @@ func TestLoadUsesSafeDefaults(t *testing.T) {
}
}
+func TestLoadValidatesBackupInventoryMount(t *testing.T) {
+ base := map[string]string{"DATABASE_URL": "postgres://example"}
+ load := func(extra map[string]string) (Config, error) {
+ values := map[string]string{}
+ for key, value := range base {
+ values[key] = value
+ }
+ for key, value := range extra {
+ values[key] = value
+ }
+ return Load(func(key string) string { return values[key] })
+ }
+ if _, err := load(map[string]string{"BACKUP_HOST_READONLY_ROOT": "relative/path"}); err == nil {
+ t.Fatal("relative read-only root must be rejected")
+ }
+ if _, err := load(map[string]string{"BACKUP_HOST_READONLY_ROOT": "/var/lib/knowledge-governance/backup-host/rds-logical"}); err == nil {
+ t.Fatal("read-only root without host path must be rejected (copy paths must not be guessed)")
+ }
+ if _, err := load(map[string]string{"BACKUP_HOST_READONLY_HOST_PATH": "/srv/kb-backups/rds-logical"}); err == nil {
+ t.Fatal("host path without read-only root must be rejected")
+ }
+ config, err := load(map[string]string{
+ "BACKUP_HOST_READONLY_ROOT": "/var/lib/knowledge-governance/backup-host/rds-logical",
+ "BACKUP_HOST_READONLY_HOST_PATH": "/srv/kb-backups/rds-logical",
+ "BACKUP_HOST_READONLY_SOURCE": "weknora-test:/srv/kb-backups/rds-logical",
+ })
+ if err != nil {
+ t.Fatalf("valid inventory mount rejected: %v", err)
+ }
+ if config.BackupHostReadonlyRoot == "" || config.BackupHostReadonlyHostPath == "" || config.BackupHostReadonlySource == "" {
+ t.Fatalf("inventory mount fields lost: %#v", config)
+ }
+}
+
func TestLoadRequiresDatabaseURL(t *testing.T) {
if _, err := Load(func(string) string { return "" }); err == nil {
t.Fatal("Load() error = nil, want missing DATABASE_URL error")
diff --git a/internal/backupinventory/inventory.go b/internal/backupinventory/inventory.go
new file mode 100644
index 0000000..e3c0c99
--- /dev/null
+++ b/internal/backupinventory/inventory.go
@@ -0,0 +1,592 @@
+// Package backupinventory 只读盘点备份执行主机上的 rds-logical 备份目录。
+//
+// 为什么不是再开一条 SSH 命令:盘点要列全部历史批次、子库目录和实际占盘,
+// 在主机上跑 find/du/df 既扩大远端命令面,也无法证明"读的是这块盘"。这里
+// 只接受一个**只读挂载**进来的目录,平台侧没有写路径;容量用 statfs 量,
+// 并比较挂载根与容器根的文件系统设备号,避免把容器根盘冒充主机磁盘。
+package backupinventory
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "io/fs"
+ "os"
+ "path"
+ "path/filepath"
+ "sort"
+ "strings"
+ "syscall"
+ "time"
+)
+
+const (
+ defaultMaxBatches = 100
+ defaultMaxFiles = 200_000
+ defaultMaxManifestBytes = 8 << 20
+
+ // Linux statfs 的 ST_RDONLY;syscall 包没有导出这个名字。
+ statReadOnly = 0x1
+)
+
+type Config struct {
+ // Root 是容器内只读挂载点(如 /var/lib/knowledge-governance/backup-host/rds-logical)。
+ // 留空即未接线;页面显示原因,不返回空表冒充"没有备份"。
+ Root string
+ // HostRoot 是给操作者复制/在主机上执行的路径(如 /srv/kb-backups/rds-logical)。
+ HostRoot string
+ // Source 是展示用的来源,如 weknora-test:/srv/kb-backups/rds-logical。
+ Source string
+ // MaxBatches/MaxFiles/MaxManifestBytes 防止一个异常目录把 API 拖死。
+ MaxBatches int
+ MaxFiles int
+ MaxManifestBytes int64
+}
+
+type statFS struct {
+ Total uint64
+ Free uint64
+ Available uint64
+ ReadOnly bool
+}
+
+type ManifestState string
+
+const (
+ ManifestOK ManifestState = "ok"
+ ManifestMissing ManifestState = "missing"
+ ManifestInvalid ManifestState = "invalid"
+)
+
+type MountInfo struct {
+ ContainerRoot string `json:"container_root"`
+ MountVerified bool `json:"mount_verified"`
+ LivesOnContainerRoot bool `json:"lives_on_container_root"`
+ ReadOnly bool `json:"read_only"`
+ Evidence string `json:"evidence"`
+ Error string `json:"error,omitempty"`
+}
+
+type Capacity struct {
+ Measured bool `json:"measured"`
+ TotalBytes int64 `json:"total_bytes"`
+ FreeBytes int64 `json:"free_bytes"`
+ AvailableBytes int64 `json:"available_bytes"`
+ UsedBytes int64 `json:"used_bytes"`
+ Error string `json:"error,omitempty"`
+}
+
+type Database struct {
+ Name string `json:"name"`
+ DirName string `json:"dir_name"`
+ Path string `json:"path"`
+ HostPath string `json:"host_path"`
+ Present bool `json:"present"`
+ Failed bool `json:"failed"`
+ InManifest bool `json:"in_manifest"`
+ ApparentBytes int64 `json:"apparent_bytes"`
+ ActualBytes int64 `json:"actual_bytes"`
+ FileCount int `json:"file_count"`
+}
+
+type Batch struct {
+ Stamp string `json:"stamp"`
+ Path string `json:"path"`
+ HostPath string `json:"host_path"`
+ ManifestState ManifestState `json:"manifest_state"`
+ ManifestPath string `json:"manifest_path"`
+ ManifestError string `json:"manifest_error,omitempty"`
+ Kind string `json:"kind"`
+ CreatedAt string `json:"created_at"`
+ StartedAt string `json:"started_at"`
+ DurationSeconds int `json:"duration_seconds"`
+ ManifestBytes int64 `json:"manifest_total_bytes"`
+ ApparentBytes int64 `json:"apparent_bytes"`
+ ActualBytes int64 `json:"actual_bytes"`
+ FileCount int `json:"file_count"`
+ SizesComplete bool `json:"sizes_complete"`
+ SizesError string `json:"sizes_error,omitempty"`
+ Databases []Database `json:"databases"`
+}
+
+type Skipped struct {
+ Name string `json:"name"`
+ Reason string `json:"reason"`
+}
+
+type Totals struct {
+ BatchCount int `json:"batch_count"`
+ DatabaseCount int `json:"database_count"`
+ ApparentBytes int64 `json:"apparent_bytes"`
+ ActualBytes int64 `json:"actual_bytes"`
+ LatestStamp string `json:"latest_stamp"`
+ LatestActualBytes int64 `json:"latest_actual_bytes"`
+}
+
+type Snapshot struct {
+ Wired bool `json:"wired"`
+ Root string `json:"root"`
+ HostRoot string `json:"host_root"`
+ Source string `json:"source"`
+ ObservedAt string `json:"observed_at"`
+ Error string `json:"error,omitempty"`
+ Mount MountInfo `json:"mount"`
+ Capacity Capacity `json:"capacity"`
+ Batches []Batch `json:"batches"`
+ Totals Totals `json:"totals"`
+ IncompleteCount int `json:"incomplete_count"`
+ Skipped []Skipped `json:"skipped"`
+ Truncated bool `json:"truncated"`
+}
+
+type Reader struct {
+ config Config
+ now func() time.Time
+ statfs func(string) (statFS, error)
+ device func(string) (uint64, error)
+}
+
+func New(config Config) *Reader {
+ if config.MaxBatches <= 0 {
+ config.MaxBatches = defaultMaxBatches
+ }
+ if config.MaxFiles <= 0 {
+ config.MaxFiles = defaultMaxFiles
+ }
+ if config.MaxManifestBytes <= 0 {
+ config.MaxManifestBytes = defaultMaxManifestBytes
+ }
+ return &Reader{config: config, now: time.Now, statfs: defaultStatFS, device: defaultDevice}
+}
+
+func (r *Reader) Available() bool {
+ return r != nil && strings.TrimSpace(r.config.Root) != ""
+}
+
+// Snapshot 永远返回可投影的结构:未接线、目录不可读、清单损坏都写在字段里,
+// 由页面区分,不把任一种情况变成 500 或"没有备份"。
+func (r *Reader) Snapshot(ctx context.Context) Snapshot {
+ snapshot := Snapshot{
+ Wired: r.Available(),
+ HostRoot: r.config.HostRoot,
+ Source: r.config.Source,
+ Batches: []Batch{},
+ Skipped: []Skipped{},
+ }
+ if r == nil || !r.Available() {
+ snapshot.Error = "只读盘点未接线(BACKUP_HOST_READONLY_ROOT 未设置)"
+ snapshot.ObservedAt = r.observedAt()
+ return snapshot
+ }
+ snapshot.ObservedAt = r.observedAt()
+ snapshot.Root = filepath.Clean(r.config.Root)
+ resolved, err := filepath.EvalSymlinks(snapshot.Root)
+ if err != nil {
+ snapshot.Error = "只读挂载不可读:" + err.Error()
+ snapshot.Capacity.Error = snapshot.Error
+ return snapshot
+ }
+ info, err := os.Stat(resolved)
+ if err != nil {
+ snapshot.Error = "只读挂载不可读:" + err.Error()
+ snapshot.Capacity.Error = snapshot.Error
+ return snapshot
+ }
+ if !info.IsDir() {
+ snapshot.Error = "只读挂载不是目录:" + resolved
+ snapshot.Capacity.Error = snapshot.Error
+ return snapshot
+ }
+ snapshot.Root = resolved
+ snapshot.Mount = r.mountInfo(resolved)
+ if !snapshot.Mount.MountVerified {
+ reason := snapshot.Mount.Evidence
+ if snapshot.Mount.Error != "" {
+ reason = snapshot.Mount.Error
+ }
+ snapshot.Capacity = Capacity{Error: "无法证明只读目录位于独立挂载:" + reason}
+ } else {
+ snapshot.Capacity = r.capacity(resolved)
+ }
+
+ entries, err := os.ReadDir(resolved)
+ if err != nil {
+ snapshot.Error = "无法列出备份目录:" + err.Error()
+ return snapshot
+ }
+ dirs := make([]string, 0, len(entries))
+ for _, entry := range entries {
+ name := entry.Name()
+ if strings.HasSuffix(name, ".incomplete") {
+ snapshot.IncompleteCount++
+ continue
+ }
+ if name == "" || strings.ContainsAny(name, `/\`) {
+ snapshot.Skipped = append(snapshot.Skipped, Skipped{Name: name, Reason: "目录名不合法"})
+ continue
+ }
+ if entry.Type()&os.ModeSymlink != 0 {
+ snapshot.Skipped = append(snapshot.Skipped, Skipped{Name: name, Reason: "符号链接不跟随"})
+ continue
+ }
+ if !entry.IsDir() {
+ snapshot.Skipped = append(snapshot.Skipped, Skipped{Name: name, Reason: "不是批次目录"})
+ continue
+ }
+ dirs = append(dirs, name)
+ }
+ sort.Sort(sort.Reverse(sort.StringSlice(dirs)))
+ if len(dirs) > r.config.MaxBatches {
+ dirs = dirs[:r.config.MaxBatches]
+ snapshot.Truncated = true
+ }
+ for _, name := range dirs {
+ if ctx.Err() != nil {
+ snapshot.Error = "读取被取消:" + ctx.Err().Error()
+ break
+ }
+ batch, reason, walkTruncated := r.readBatch(ctx, resolved, name)
+ if reason != "" {
+ snapshot.Skipped = append(snapshot.Skipped, Skipped{Name: name, Reason: reason})
+ continue
+ }
+ if walkTruncated {
+ snapshot.Truncated = true
+ }
+ snapshot.Batches = append(snapshot.Batches, batch)
+ snapshot.Totals.ApparentBytes += batch.ApparentBytes
+ snapshot.Totals.ActualBytes += batch.ActualBytes
+ snapshot.Totals.DatabaseCount += len(batch.Databases)
+ }
+ snapshot.Totals.BatchCount = len(snapshot.Batches)
+ if len(snapshot.Batches) > 0 {
+ snapshot.Totals.LatestStamp = snapshot.Batches[0].Stamp
+ snapshot.Totals.LatestActualBytes = snapshot.Batches[0].ActualBytes
+ }
+ return snapshot
+}
+
+func (r *Reader) observedAt() string {
+ if r == nil || r.now == nil {
+ return ""
+ }
+ return r.now().UTC().Format(time.RFC3339)
+}
+
+func (r *Reader) mountInfo(root string) MountInfo {
+ info := MountInfo{ContainerRoot: "/"}
+ rootDevice, err := r.device(root)
+ if err != nil {
+ info.Error = "无法读取挂载设备号:" + err.Error()
+ info.Evidence = "无法证明挂载与容器根盘分离"
+ return info
+ }
+ containerDevice, err := r.device("/")
+ if err != nil {
+ info.Error = "无法读取容器根盘设备号:" + err.Error()
+ info.Evidence = "无法证明挂载与容器根盘分离"
+ return info
+ }
+ info.LivesOnContainerRoot = rootDevice == containerDevice
+ info.MountVerified = !info.LivesOnContainerRoot
+ if stats, statErr := r.statfs(root); statErr == nil {
+ info.ReadOnly = stats.ReadOnly
+ }
+ if info.MountVerified {
+ info.Evidence = fmt.Sprintf("挂载设备 %d 与容器根盘 %d 不同:容量按挂载文件系统计量", rootDevice, containerDevice)
+ } else {
+ info.Evidence = fmt.Sprintf("挂载设备与容器根盘相同(%d):容量不代表备份主机磁盘", rootDevice)
+ }
+ return info
+}
+
+func (r *Reader) capacity(root string) Capacity {
+ stats, err := r.statfs(root)
+ if err != nil {
+ return Capacity{Error: "无法读取文件系统容量:" + err.Error()}
+ }
+ used := uint64(0)
+ if stats.Total > stats.Free {
+ used = stats.Total - stats.Free
+ }
+ return Capacity{
+ Measured: true,
+ TotalBytes: int64(stats.Total),
+ FreeBytes: int64(stats.Free),
+ AvailableBytes: int64(stats.Available),
+ UsedBytes: int64(used),
+ }
+}
+
+type manifest struct {
+ Kind string `json:"kind"`
+ CreatedAt string `json:"created_at"`
+ StartedAt string `json:"started_at"`
+ DurationSeconds int `json:"duration_seconds"`
+ Databases []string `json:"databases"`
+ FailedDatabases []string `json:"failed_databases"`
+ TotalBytes int64 `json:"total_bytes"`
+ Files []struct {
+ File string `json:"file"`
+ Bytes int64 `json:"bytes"`
+ } `json:"files"`
+}
+
+type sizes struct {
+ apparent int64
+ actual int64
+ files int
+}
+
+func (value *sizes) add(other sizes) {
+ value.apparent += other.apparent
+ value.actual += other.actual
+ value.files += other.files
+}
+
+func (r *Reader) readBatch(ctx context.Context, root, name string) (Batch, string, bool) {
+ fullPath := filepath.Join(root, name)
+ resolved, err := filepath.EvalSymlinks(fullPath)
+ if err != nil {
+ return Batch{}, "无法解析批次目录:" + err.Error(), false
+ }
+ if !within(root, resolved) {
+ return Batch{}, "批次目录指向只读挂载之外", false
+ }
+ batch := Batch{
+ Stamp: name,
+ Path: resolved,
+ HostPath: joinHostPath(r.config.HostRoot, name),
+ ManifestPath: filepath.Join(resolved, "MANIFEST.json"),
+ ManifestState: ManifestMissing,
+ Databases: []Database{},
+ SizesComplete: true,
+ }
+
+ var parsed manifest
+ state, manifestErr := readManifest(batch.ManifestPath, r.config.MaxManifestBytes, &parsed)
+ batch.ManifestState = state
+ batch.ManifestError = manifestErr
+ if state == ManifestOK {
+ batch.Kind = parsed.Kind
+ batch.CreatedAt = parsed.CreatedAt
+ batch.StartedAt = parsed.StartedAt
+ batch.DurationSeconds = parsed.DurationSeconds
+ batch.ManifestBytes = parsed.TotalBytes
+ }
+
+ walked, byTop, walkErr, truncated := r.walkBatch(ctx, resolved)
+ batch.ApparentBytes = walked.apparent
+ batch.ActualBytes = walked.actual
+ batch.FileCount = walked.files
+ if walkErr != nil {
+ batch.SizesComplete = false
+ batch.SizesError = walkErr.Error()
+ }
+ if state == ManifestOK && parsed.TotalBytes > 0 {
+ batch.ApparentBytes = parsed.TotalBytes
+ }
+
+ manifestSizes := map[string]sizes{}
+ if state == ManifestOK {
+ for _, file := range parsed.Files {
+ clean := path.Clean(filepath.ToSlash(file.File))
+ if clean == "." || strings.HasPrefix(clean, "../") || path.IsAbs(clean) {
+ continue
+ }
+ top := strings.SplitN(clean, "/", 2)[0]
+ if !strings.HasSuffix(top, ".dir") {
+ continue
+ }
+ entry := manifestSizes[top]
+ entry.apparent += file.Bytes
+ entry.files++
+ manifestSizes[top] = entry
+ }
+ }
+
+ seen := map[string]bool{}
+ failed := map[string]bool{}
+ for _, db := range parsed.FailedDatabases {
+ failed[db] = true
+ }
+ appendDatabase := func(db string) {
+ if db == "" || seen[db] {
+ return
+ }
+ seen[db] = true
+ dirName := db + ".dir"
+ containerDir := filepath.Join(resolved, dirName)
+ info, statErr := os.Stat(containerDir)
+ present := statErr == nil && info.IsDir()
+ apparent := sizes{}
+ if entry, ok := manifestSizes[dirName]; ok {
+ apparent = entry
+ } else if walkedEntry, ok := byTop[dirName]; ok {
+ apparent = walkedEntry
+ }
+ batch.Databases = append(batch.Databases, Database{
+ Name: db,
+ DirName: dirName,
+ Path: containerDir,
+ HostPath: joinHostPath(batch.HostPath, dirName),
+ Present: present,
+ Failed: failed[db],
+ InManifest: contains(parsed.Databases, db),
+ ApparentBytes: apparent.apparent,
+ ActualBytes: byTop[dirName].actual,
+ FileCount: apparent.files,
+ })
+ }
+ for _, db := range parsed.Databases {
+ appendDatabase(db)
+ }
+ dirNames := make([]string, 0, len(byTop))
+ for top := range byTop {
+ if strings.HasSuffix(top, ".dir") {
+ dirNames = append(dirNames, top)
+ }
+ }
+ sort.Strings(dirNames)
+ for _, top := range dirNames {
+ appendDatabase(strings.TrimSuffix(top, ".dir"))
+ }
+ return batch, "", truncated
+}
+
+func (r *Reader) walkBatch(ctx context.Context, batchPath string) (sizes, map[string]sizes, error, bool) {
+ total := sizes{}
+ byTop := map[string]sizes{}
+ scanned := 0
+ truncated := false
+ err := filepath.WalkDir(batchPath, func(current string, entry fs.DirEntry, walkErr error) error {
+ if ctx.Err() != nil {
+ return ctx.Err()
+ }
+ if walkErr != nil {
+ return walkErr
+ }
+ if current == batchPath {
+ return nil
+ }
+ if entry.Type()&os.ModeSymlink != 0 {
+ if entry.IsDir() {
+ return filepath.SkipDir
+ }
+ return nil
+ }
+ if entry.IsDir() {
+ return nil
+ }
+ if scanned >= r.config.MaxFiles {
+ truncated = true
+ return errStopWalk
+ }
+ info, err := entry.Info()
+ if err != nil {
+ return nil
+ }
+ relative, err := filepath.Rel(batchPath, current)
+ if err != nil {
+ return nil
+ }
+ top := strings.SplitN(filepath.ToSlash(relative), "/", 2)[0]
+ fileSize := sizes{apparent: info.Size(), actual: actualBytes(info), files: 1}
+ total.add(fileSize)
+ entrySizes := byTop[top]
+ entrySizes.add(fileSize)
+ byTop[top] = entrySizes
+ scanned++
+ return nil
+ })
+ if errors.Is(err, errStopWalk) {
+ err = nil
+ }
+ if err != nil {
+ return total, byTop, err, truncated
+ }
+ return total, byTop, nil, truncated
+}
+
+var errStopWalk = errors.New("file scan limit reached")
+
+func readManifest(filename string, maxBytes int64, parsed *manifest) (ManifestState, string) {
+ file, err := os.Open(filename)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return ManifestMissing, ""
+ }
+ return ManifestInvalid, err.Error()
+ }
+ defer file.Close()
+ raw, err := io.ReadAll(io.LimitReader(file, maxBytes+1))
+ if err != nil {
+ return ManifestInvalid, err.Error()
+ }
+ if int64(len(raw)) > maxBytes {
+ return ManifestInvalid, fmt.Sprintf("清单超过 %d 字节读取上限", maxBytes)
+ }
+ if err := json.Unmarshal(raw, parsed); err != nil {
+ return ManifestInvalid, "清单无法解析:" + err.Error()
+ }
+ return ManifestOK, ""
+}
+
+func within(root, target string) bool {
+ relative, err := filepath.Rel(root, target)
+ if err != nil {
+ return false
+ }
+ return relative != ".." && !strings.HasPrefix(relative, ".."+string(os.PathSeparator))
+}
+
+func joinHostPath(root, name string) string {
+ if strings.TrimSpace(root) == "" {
+ return ""
+ }
+ return path.Join(filepath.ToSlash(root), name)
+}
+
+func contains(list []string, value string) bool {
+ for _, item := range list {
+ if item == value {
+ return true
+ }
+ }
+ return false
+}
+
+func actualBytes(info fs.FileInfo) int64 {
+ if stat, ok := info.Sys().(*syscall.Stat_t); ok {
+ return int64(stat.Blocks) * 512
+ }
+ return info.Size()
+}
+
+func defaultStatFS(root string) (statFS, error) {
+ var stats syscall.Statfs_t
+ if err := syscall.Statfs(root, &stats); err != nil {
+ return statFS{}, err
+ }
+ blockSize := uint64(stats.Bsize)
+ return statFS{
+ Total: stats.Blocks * blockSize,
+ Free: stats.Bfree * blockSize,
+ Available: stats.Bavail * blockSize,
+ ReadOnly: stats.Flags&statReadOnly != 0,
+ }, nil
+}
+
+func defaultDevice(root string) (uint64, error) {
+ info, err := os.Stat(root)
+ if err != nil {
+ return 0, err
+ }
+ stat, ok := info.Sys().(*syscall.Stat_t)
+ if !ok {
+ return 0, fmt.Errorf("无法读取 %s 的设备号", root)
+ }
+ return uint64(stat.Dev), nil
+}
diff --git a/internal/backupinventory/inventory_test.go b/internal/backupinventory/inventory_test.go
new file mode 100644
index 0000000..6fa3cc1
--- /dev/null
+++ b/internal/backupinventory/inventory_test.go
@@ -0,0 +1,205 @@
+package backupinventory
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "strings"
+ "syscall"
+ "testing"
+)
+
+func writeFile(t *testing.T, filename string, content string) {
+ t.Helper()
+ if err := os.MkdirAll(filepath.Dir(filename), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filename, []byte(content), 0o644); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func actualOf(t *testing.T, filename string) int64 {
+ t.Helper()
+ info, err := os.Stat(filename)
+ if err != nil {
+ t.Fatal(err)
+ }
+ stat, ok := info.Sys().(*syscall.Stat_t)
+ if !ok {
+ t.Fatal("no stat")
+ }
+ return int64(stat.Blocks) * 512
+}
+
+func fixtureRoot(t *testing.T) string {
+ t.Helper()
+ root := t.TempDir()
+ latest := filepath.Join(root, "20261118T193001Z")
+ writeFile(t, filepath.Join(latest, "MANIFEST.json"), `{
+ "kind": "rds-logical-backup",
+ "created_at": "20261118T193001Z",
+ "started_at": "20261118T192908Z",
+ "duration_seconds": 53,
+ "databases": ["weknora_v090prod", "weknora_test"],
+ "failed_databases": ["weknora_test"],
+ "total_bytes": 300,
+ "files": [
+ {"file": "weknora_v090prod.dir/toc.dat", "bytes": 100},
+ {"file": "weknora_v090prod.dir/0001.dat.gz", "bytes": 150},
+ {"file": "weknora_test.dir/toc.dat", "bytes": 50}
+ ]
+}`)
+ writeFile(t, filepath.Join(latest, "weknora_v090prod.dir", "toc.dat"), strings.Repeat("a", 100))
+ writeFile(t, filepath.Join(latest, "weknora_v090prod.dir", "0001.dat.gz"), strings.Repeat("b", 150))
+ writeFile(t, filepath.Join(latest, "weknora_test.dir", "toc.dat"), strings.Repeat("c", 50))
+
+ invalid := filepath.Join(root, "20261117T193001Z")
+ writeFile(t, filepath.Join(invalid, "MANIFEST.json"), "{not-json")
+ writeFile(t, filepath.Join(invalid, "weknora_prod.dir", "toc.dat"), strings.Repeat("d", 20))
+
+ missing := filepath.Join(root, "20261116T193001Z")
+ writeFile(t, filepath.Join(missing, "weknora_archive.dir", "toc.dat"), strings.Repeat("e", 30))
+
+ incomplete := filepath.Join(root, "20261115T193001Z.incomplete")
+ writeFile(t, filepath.Join(incomplete, "MANIFEST.json"), `{}`)
+
+ return root
+}
+
+func TestSnapshotReadsBatchesManifestsAndActualUsage(t *testing.T) {
+ root := fixtureRoot(t)
+ reader := New(Config{
+ Root: root,
+ HostRoot: "/srv/kb-backups/rds-logical",
+ Source: "weknora-test:/srv/kb-backups/rds-logical",
+ })
+ reader.device = func(path string) (uint64, error) {
+ if path == "/" {
+ return 10, nil
+ }
+ return 20, nil
+ }
+ reader.statfs = func(string) (statFS, error) {
+ return statFS{Total: 1000, Free: 400, Available: 350, ReadOnly: true}, nil
+ }
+
+ snapshot := reader.Snapshot(context.Background())
+ if !snapshot.Wired || snapshot.Error != "" {
+ t.Fatalf("应读到接线目录: %+v", snapshot)
+ }
+ if !snapshot.Mount.MountVerified || snapshot.Mount.LivesOnContainerRoot || !snapshot.Mount.ReadOnly {
+ t.Fatalf("挂载判定不对: %+v", snapshot.Mount)
+ }
+ if !snapshot.Capacity.Measured || snapshot.Capacity.TotalBytes != 1000 || snapshot.Capacity.AvailableBytes != 350 {
+ t.Fatalf("容量不对: %+v", snapshot.Capacity)
+ }
+ if len(snapshot.Batches) != 3 || snapshot.IncompleteCount != 1 {
+ t.Fatalf("批次数量不对: %d incomplete=%d", len(snapshot.Batches), snapshot.IncompleteCount)
+ }
+ latest := snapshot.Batches[0]
+ if latest.Stamp != "20261118T193001Z" || latest.ManifestState != ManifestOK {
+ t.Fatalf("最近批次不对: %+v", latest)
+ }
+ if latest.CreatedAt != "20261118T193001Z" || latest.DurationSeconds != 53 || latest.ManifestBytes != 300 {
+ t.Fatalf("清单字段不对: %+v", latest)
+ }
+ if latest.HostPath != "/srv/kb-backups/rds-logical/20261118T193001Z" {
+ t.Fatalf("批次主机路径不对: %q", latest.HostPath)
+ }
+ if len(latest.Databases) != 2 {
+ t.Fatalf("子库数量不对: %+v", latest.Databases)
+ }
+ prod := latest.Databases[0]
+ if prod.Name != "weknora_v090prod" || !prod.Present || prod.Failed || !prod.InManifest {
+ t.Fatalf("子库状态不对: %+v", prod)
+ }
+ if prod.Path != filepath.Join(root, "20261118T193001Z", "weknora_v090prod.dir") {
+ t.Fatalf("子库容器路径不对: %q", prod.Path)
+ }
+ if prod.HostPath != "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir" {
+ t.Fatalf("子库主机路径不对: %q", prod.HostPath)
+ }
+ expectedActual := actualOf(t, filepath.Join(root, "20261118T193001Z", "weknora_v090prod.dir", "toc.dat")) +
+ actualOf(t, filepath.Join(root, "20261118T193001Z", "weknora_v090prod.dir", "0001.dat.gz"))
+ if prod.ActualBytes != expectedActual {
+ t.Fatalf("子库实际占盘不对: got %d want %d", prod.ActualBytes, expectedActual)
+ }
+ if prod.ApparentBytes != 250 || prod.FileCount != 2 {
+ t.Fatalf("子库清单体积不对: %+v", prod)
+ }
+ if !latest.Databases[1].Failed {
+ t.Fatalf("失败库没有标记: %+v", latest.Databases[1])
+ }
+
+ broken := snapshot.Batches[1]
+ if broken.Stamp != "20261117T193001Z" || broken.ManifestState != ManifestInvalid || broken.ManifestError == "" {
+ t.Fatalf("损坏清单没有如实标记: %+v", broken)
+ }
+ if len(broken.Databases) != 1 || broken.Databases[0].Name != "weknora_prod" || !broken.Databases[0].Present {
+ t.Fatalf("清单损坏时仍应按目录列出子库: %+v", broken.Databases)
+ }
+ withoutManifest := snapshot.Batches[2]
+ if withoutManifest.ManifestState != ManifestMissing {
+ t.Fatalf("缺清单没有如实标记: %+v", withoutManifest)
+ }
+ if snapshot.Totals.BatchCount != 3 || snapshot.Totals.LatestStamp != "20261118T193001Z" {
+ t.Fatalf("汇总不对: %+v", snapshot.Totals)
+ }
+ if snapshot.ObservedAt == "" || snapshot.Source != "weknora-test:/srv/kb-backups/rds-logical" {
+ t.Fatalf("观测时间/来源不对: %+v", snapshot)
+ }
+}
+
+func TestSnapshotUnconfigured(t *testing.T) {
+ snapshot := New(Config{}).Snapshot(context.Background())
+ if snapshot.Wired || snapshot.Error == "" || len(snapshot.Batches) != 0 {
+ t.Fatalf("未接线必须给出原因且不伪造批次: %+v", snapshot)
+ }
+ if !strings.Contains(snapshot.Error, "未接线") {
+ t.Fatalf("未接线原因不清: %q", snapshot.Error)
+ }
+}
+
+func TestSnapshotMissingRoot(t *testing.T) {
+ reader := New(Config{Root: filepath.Join(t.TempDir(), "missing")})
+ snapshot := reader.Snapshot(context.Background())
+ if !snapshot.Wired || snapshot.Error == "" || snapshot.Capacity.Measured {
+ t.Fatalf("目录不存在应报错且不报容量: %+v", snapshot)
+ }
+}
+
+func TestSnapshotRefusesSymlinkBatches(t *testing.T) {
+ root := t.TempDir()
+ outside := t.TempDir()
+ writeFile(t, filepath.Join(outside, "MANIFEST.json"), `{"databases":["escaped"]}`)
+ if err := os.Symlink(outside, filepath.Join(root, "20261118T193001Z")); err != nil {
+ t.Fatal(err)
+ }
+ snapshot := New(Config{Root: root}).Snapshot(context.Background())
+ if len(snapshot.Batches) != 0 {
+ t.Fatalf("符号链接批次不能跟随: %+v", snapshot.Batches)
+ }
+ if len(snapshot.Skipped) != 1 || !strings.Contains(snapshot.Skipped[0].Reason, "符号链接") {
+ t.Fatalf("跳过原因不对: %+v", snapshot.Skipped)
+ }
+}
+
+func TestSnapshotDoesNotUseContainerRootCapacity(t *testing.T) {
+ root := fixtureRoot(t)
+ reader := New(Config{Root: root})
+ reader.device = func(string) (uint64, error) { return 7, nil }
+ reader.statfs = func(string) (statFS, error) {
+ return statFS{Total: 999, Free: 1, Available: 1}, nil
+ }
+ snapshot := reader.Snapshot(context.Background())
+ if snapshot.Mount.MountVerified || !snapshot.Mount.LivesOnContainerRoot {
+ t.Fatalf("同设备必须判定为容器根盘: %+v", snapshot.Mount)
+ }
+ if snapshot.Capacity.Measured || snapshot.Capacity.TotalBytes != 0 || snapshot.Capacity.Error == "" {
+ t.Fatalf("容器根盘不能冒充主机容量: %+v", snapshot.Capacity)
+ }
+ if len(snapshot.Batches) != 3 {
+ t.Fatalf("容量不可用不应影响批次读取: %+v", snapshot.Batches)
+ }
+}
diff --git a/internal/httpapi/backup_inventory.go b/internal/httpapi/backup_inventory.go
new file mode 100644
index 0000000..130cb71
--- /dev/null
+++ b/internal/httpapi/backup_inventory.go
@@ -0,0 +1,23 @@
+package httpapi
+
+import (
+ "context"
+ "net/http"
+
+ "knowledge-governance/internal/backupinventory"
+)
+
+// BackupInventoryReader 只读盘点备份主机目录。它与 SSH 主机计划读回完全独立:
+// 挂载没接线不应拖垮计划读回,计划读回失败也不应把历史批次说成"没有"。
+type BackupInventoryReader interface {
+ Available() bool
+ Snapshot(context.Context) backupinventory.Snapshot
+}
+
+// handleBackupInventory 返回真实批次、子库路径与实测容量。
+// 未接线/目录不可读/清单损坏都作为 200 的字段返回,由页面区分原因;
+// 只有投影本身失败才 500。
+func (config Config) handleBackupInventory(w http.ResponseWriter, r *http.Request) {
+ snapshot := config.BackupInventory.Snapshot(r.Context())
+ writeJSON(w, http.StatusOK, map[string]any{"data": snapshot})
+}
diff --git a/internal/httpapi/backup_inventory_test.go b/internal/httpapi/backup_inventory_test.go
new file mode 100644
index 0000000..197555c
--- /dev/null
+++ b/internal/httpapi/backup_inventory_test.go
@@ -0,0 +1,88 @@
+package httpapi
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "knowledge-governance/internal/backupinventory"
+)
+
+type fakeBackupInventory struct {
+ snapshot backupinventory.Snapshot
+}
+
+func (fake fakeBackupInventory) Available() bool { return fake.snapshot.Wired }
+
+func (fake fakeBackupInventory) Snapshot(context.Context) backupinventory.Snapshot {
+ return fake.snapshot
+}
+
+func TestBackupInventoryProjectionPassesRealFields(t *testing.T) {
+ config := Config{BackupInventory: fakeBackupInventory{snapshot: backupinventory.Snapshot{
+ Wired: true,
+ Root: "/var/lib/knowledge-governance/backup-host/rds-logical",
+ HostRoot: "/srv/kb-backups/rds-logical",
+ Source: "weknora-test:/srv/kb-backups/rds-logical",
+ Mount: backupinventory.MountInfo{
+ MountVerified: true,
+ ReadOnly: true,
+ Evidence: "挂载设备 20 与容器根盘 10 不同",
+ },
+ Capacity: backupinventory.Capacity{Measured: true, TotalBytes: 100, FreeBytes: 40, AvailableBytes: 35, UsedBytes: 60},
+ Batches: []backupinventory.Batch{{
+ Stamp: "20261118T193001Z",
+ HostPath: "/srv/kb-backups/rds-logical/20261118T193001Z",
+ ManifestState: backupinventory.ManifestOK,
+ ActualBytes: 1024,
+ Databases: []backupinventory.Database{{
+ Name: "weknora_v090prod",
+ HostPath: "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir",
+ Present: true,
+ ActualBytes: 512,
+ }},
+ }},
+ Totals: backupinventory.Totals{BatchCount: 1, LatestStamp: "20261118T193001Z"},
+ }}}
+ recorder := httptest.NewRecorder()
+ config.handleBackupInventory(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/backup-schedule/inventory", nil))
+ if recorder.Code != http.StatusOK {
+ t.Fatalf("status = %d", recorder.Code)
+ }
+ var payload struct {
+ Data backupinventory.Snapshot `json:"data"`
+ }
+ if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
+ t.Fatal(err)
+ }
+ if !payload.Data.Wired || !payload.Data.Mount.MountVerified || !payload.Data.Capacity.Measured {
+ t.Fatalf("接线/挂载/容量字段丢失: %+v", payload.Data)
+ }
+ if len(payload.Data.Batches) != 1 ||
+ payload.Data.Batches[0].Databases[0].HostPath != "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir" {
+ t.Fatalf("批次/子库真实路径丢失: %+v", payload.Data.Batches)
+ }
+ if payload.Data.Batches[0].ActualBytes != 1024 {
+ t.Fatalf("实际占盘字段丢失: %+v", payload.Data.Batches[0])
+ }
+}
+
+func TestBackupInventoryUnconfiguredIsNotAnError(t *testing.T) {
+ config := Config{BackupInventory: backupinventory.New(backupinventory.Config{})}
+ recorder := httptest.NewRecorder()
+ config.handleBackupInventory(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/backup-schedule/inventory", nil))
+ if recorder.Code != http.StatusOK {
+ t.Fatalf("未接线不应 500: %d", recorder.Code)
+ }
+ var payload struct {
+ Data backupinventory.Snapshot `json:"data"`
+ }
+ if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
+ t.Fatal(err)
+ }
+ if payload.Data.Wired || payload.Data.Error == "" || payload.Data.Batches == nil {
+ t.Fatalf("未接线必须给原因且批次为空数组: %+v", payload.Data)
+ }
+}
diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go
index 13443b6..d65ec88 100644
--- a/internal/httpapi/server.go
+++ b/internal/httpapi/server.go
@@ -15,6 +15,7 @@ import (
"time"
"knowledge-governance/internal/backuphost"
+ "knowledge-governance/internal/backupinventory"
"knowledge-governance/internal/dingtalkdiscovery"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
@@ -198,10 +199,13 @@ type Config struct {
// 它不是运行时开关:生产部署不设置它,那次探测仍然直连目标库逐表计数。
LibraryScopeProbe func(ctx context.Context, scope string) (bool, map[string]int64, error)
// LibraryRetentionVersions/Days 是保留策略;都为 0 = 未设置(不生成清理候选)。
- LibraryRetentionVersions int
- LibraryRetentionDays int
- BackupSchedule BackupScheduleStore
- BackupHost BackupHost
+ LibraryRetentionVersions int
+ LibraryRetentionDays int
+ BackupSchedule BackupScheduleStore
+ BackupHost BackupHost
+ // BackupInventory 读的是只读挂载的 rds-logical 目录(批次/子库/实测容量)。
+ // 与 BackupHost 的 SSH 计划读回分离,任一侧失败都不能影响另一侧。
+ BackupInventory BackupInventoryReader
BackupRuns *BackupRunTracker
ProductionBindings ProductionBindingStore
ProductionKnowledgeBases ProductionKnowledgeBaseLister
@@ -251,6 +255,10 @@ func NewHandler(config Config) (http.Handler, error) {
// 未挂载主机凭据:Available()=false,页面显示"未接线"而不是 500。
config.BackupHost = backuphost.New(backuphost.Config{})
}
+ if config.BackupInventory == nil {
+ // 未挂载只读备份目录:批次/容量显示"未接线",独立于 SSH 计划读回。
+ config.BackupInventory = backupinventory.New(backupinventory.Config{})
+ }
for _, knowledgeBaseID := range []string{config.InternalRoutingKnowledgeBaseID, config.ExternalRoutingKnowledgeBaseID} {
if knowledgeBaseID != "" && !validCatalogID(knowledgeBaseID) {
return nil, errors.New("routing knowledge base ID is invalid")
@@ -431,6 +439,9 @@ func NewHandler(config Config) (http.Handler, error) {
}
config.handleBackupScheduleHost(w, r)
})
+ mux.HandleFunc("GET /api/v1/backup-schedule/inventory", func(w http.ResponseWriter, r *http.Request) {
+ config.handleBackupInventory(w, r)
+ })
mux.HandleFunc("PUT /api/v1/backup-schedule", func(w http.ResponseWriter, r *http.Request) {
if config.BackupSchedule == nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "backup schedule storage unavailable"})
diff --git a/web/src/BackupScheduleSection.test.tsx b/web/src/BackupScheduleSection.test.tsx
index 93dbc76..ba5fdb4 100644
--- a/web/src/BackupScheduleSection.test.tsx
+++ b/web/src/BackupScheduleSection.test.tsx
@@ -6,13 +6,17 @@ import {
backupDaysValid,
backupMonthsValid,
backupTimeValid,
+ copyBackupPath,
formatBackupBytes,
+ inventoryAlerts,
+ inventoryUsage,
runMoment,
storageAlerts,
storageAlertSummary,
storageUsage,
} from './BackupScheduleSection'
import type { StorageDiskObservation } from './BackupScheduleSection'
+import type { BackupInventory } from './backupInventory'
import type { BackupSchedule } from './backupSchedule'
const base: BackupSchedule = {
@@ -67,6 +71,118 @@ const diskFixture = (overrides: Partial = {}): StorageDi
...overrides,
})
+const inventoryFixture = (overrides: Partial = {}): BackupInventory => {
+ const baseInventory: BackupInventory = {
+ wired: true,
+ root: '/var/lib/knowledge-governance/backup-host/rds-logical',
+ host_root: '/srv/kb-backups/rds-logical',
+ source: 'weknora-test:/srv/kb-backups/rds-logical',
+ observed_at: '2026-11-19T03:30:10Z',
+ error: '',
+ mount: {
+ container_root: '/',
+ mount_verified: true,
+ lives_on_container_root: false,
+ read_only: true,
+ evidence: '挂载设备 20 与容器根盘 10 不同:容量按挂载文件系统计量',
+ },
+ capacity: {
+ measured: true,
+ total_bytes: 240 * GiB,
+ free_bytes: 48 * GiB,
+ available_bytes: 45 * GiB,
+ used_bytes: 192 * GiB,
+ },
+ batches: [
+ {
+ stamp: '20261118T193001Z',
+ path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z',
+ host_path: '/srv/kb-backups/rds-logical/20261118T193001Z',
+ manifest_state: 'ok',
+ manifest_path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z/MANIFEST.json',
+ kind: 'rds-logical-backup',
+ created_at: '20261118T193001Z',
+ started_at: '20261118T192908Z',
+ duration_seconds: 53,
+ manifest_total_bytes: 1_393_646_469,
+ apparent_bytes: 1_393_646_469,
+ actual_bytes: 1_500_000_000,
+ file_count: 214,
+ sizes_complete: true,
+ databases: [
+ {
+ name: 'weknora_v090prod',
+ dir_name: 'weknora_v090prod.dir',
+ path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z/weknora_v090prod.dir',
+ host_path: '/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir',
+ present: true,
+ failed: false,
+ in_manifest: true,
+ apparent_bytes: 696_320,
+ actual_bytes: 720_896,
+ file_count: 12,
+ },
+ {
+ name: 'weknora_test',
+ dir_name: 'weknora_test.dir',
+ path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z/weknora_test.dir',
+ host_path: '/srv/kb-backups/rds-logical/20261118T193001Z/weknora_test.dir',
+ present: true,
+ failed: true,
+ in_manifest: true,
+ apparent_bytes: 10,
+ actual_bytes: 4096,
+ file_count: 1,
+ },
+ ],
+ },
+ {
+ stamp: '20261117T193001Z',
+ path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261117T193001Z',
+ host_path: '/srv/kb-backups/rds-logical/20261117T193001Z',
+ manifest_state: 'invalid',
+ manifest_path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261117T193001Z/MANIFEST.json',
+ manifest_error: '清单无法解析:unexpected end of JSON input',
+ kind: '',
+ created_at: '',
+ started_at: '',
+ duration_seconds: 0,
+ manifest_total_bytes: 0,
+ apparent_bytes: 2048,
+ actual_bytes: 4096,
+ file_count: 1,
+ sizes_complete: true,
+ databases: [
+ {
+ name: 'weknora_archive',
+ dir_name: 'weknora_archive.dir',
+ path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261117T193001Z/weknora_archive.dir',
+ host_path: '/srv/kb-backups/rds-logical/20261117T193001Z/weknora_archive.dir',
+ present: false,
+ failed: false,
+ in_manifest: false,
+ apparent_bytes: 0,
+ actual_bytes: 0,
+ file_count: 0,
+ },
+ ],
+ },
+ ],
+ totals: {
+ batch_count: 2,
+ database_count: 3,
+ apparent_bytes: 1_393_648_517,
+ actual_bytes: 1_500_004_096,
+ latest_stamp: '20261118T193001Z',
+ latest_actual_bytes: 1_500_000_000,
+ },
+ incomplete_count: 1,
+ skipped: [{ name: 'junk', reason: '不是批次目录' }],
+ truncated: false,
+ }
+ return { ...baseInventory, ...overrides }
+}
+
const view = (
overrides: Partial = {},
extra: Record = {},
@@ -95,6 +211,10 @@ const view = (
onRunNow={vi.fn()}
onReload={vi.fn()}
disk={disk}
+ inventory={(extra.inventory as BackupInventory) ?? null}
+ inventoryLoading={(extra.inventoryLoading as boolean) ?? false}
+ inventoryError={(extra.inventoryError as string | null) ?? null}
+ onReloadInventory={vi.fn()}
/>
)
}
@@ -109,7 +229,7 @@ describe('BackupScheduleView', () => {
'备份执行主机 weknora-test 本机直连 RDS',
'最近批次含 2 个数据库',
'weknora-test 本地备份根目录',
- '具体根目录未由接口返回',
+ '备份目录未接线或不可读,不在页面猜测',
'整批 · 2 个数据库(weknora_test、dobotai_prod)',
'100.85.111.121:22',
'立即备份一次(整批 2 个数据库)',
@@ -141,7 +261,7 @@ describe('BackupScheduleView', () => {
it('目录/配额/预留没有后端字段:控件禁用并写明原因,不会假装可保存', () => {
const html = view()
expect(html).toContain('备份主机上的目录')
- expect(html).toContain('接口未提供备份目录')
+ expect(html).toContain('只读盘点未接线')
expect(html).toContain('检查目录(不可用)')
expect(html).toContain('备份总配额(GiB)')
expect(html).toContain('磁盘预留(GiB)')
@@ -150,34 +270,85 @@ describe('BackupScheduleView', () => {
expect(html).toContain('disabled')
})
- it('最近批次只展示接口真实字段;子库路径/复制/恢复验证明确未接线', () => {
- const html = view({ last_run_failed_databases: ['dobotai_prod'] })
- expect(html).toContain('备份记录')
- expect(html).toContain('接口只返回最近一批')
- expect(html).toContain('批次戳 20261009T052909Z')
- expect(html).toContain('耗时 33 秒')
- expect(html).toContain('742.4 MiB')
- expect(html).toContain('weknora_test')
- expect(html).toContain('dobotai_prod')
- expect(html).toContain('失败')
- expect(html).toContain('子库目录与单库字节未由接口返回')
- expect(html).toContain('复制目录(不可用)')
- expect(html).toContain('恢复验证:未接线')
- // 不拼造历史批次或示例子目录。
- expect(html).not.toContain('/srv/kb-backups/rds-logical')
- expect(html).not.toContain('11 月 19 日 03:30')
+ it('只读盘点:展示全部批次、MANIFEST 状态、子库完整路径与实际占盘', () => {
+ const html = view({}, { inventory: inventoryFixture() })
+ for (const text of [
+ '备份记录',
+ '2 批 · 只读盘点',
+ '最近批次 20261118T193001Z',
+ '清单完整',
+ '清单损坏',
+ '批次戳 20261118T193001Z',
+ '实际占盘',
+ 'weknora_v090prod',
+ 'weknora_test',
+ '已写入',
+ '失败',
+ '目录缺失',
+ '/srv/kb-backups/rds-logical/20261118T193001Z',
+ '/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir',
+ '/srv/kb-backups/rds-logical/20261117T193001Z/weknora_archive.dir',
+ '复制子库目录',
+ '清单无法解析',
+ '有 1 个',
+ 'junk(不是批次目录)',
+ '恢复验证:未接线',
+ ])
+ expect(html).toContain(text)
+ expect(html).not.toContain('子库路径待接口返回')
+ expect(html).not.toContain('复制目录(不可用)')
})
- it('没有批次时说明不能据此判断成功/失败', () => {
- const html = view({
- last_run_stamp: '',
- last_run_created_at: '',
- last_run_databases: [],
- last_run_total_bytes: 0,
- host_reachable: false,
- })
- expect(html).toContain('还没有读到任何批次')
- expect(html).toContain('不能据此判断备份成功或失败')
+ it('没有只读盘点:不展示任何历史批次或伪造路径', () => {
+ const html = view()
+ expect(html).toContain('尚未读取只读盘点')
+ expect(html).not.toContain('批次戳')
+ expect(html).not.toContain('/srv/kb-backups/rds-logical')
+ })
+
+ it('盘点未接线:说明与 SSH 计划读回独立,未读到不等于没有备份', () => {
+ const html = view(
+ {},
+ {
+ inventory: inventoryFixture({
+ wired: false,
+ error: '只读盘点未接线(BACKUP_HOST_READONLY_ROOT 未设置)',
+ batches: [],
+ capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
+ }),
+ }
+ )
+ expect(html).toContain('只读盘点未接线')
+ expect(html).toContain('未读到批次不等于没有备份')
+ expect(html).toContain('文件盘点未接线')
+ expect(html).not.toContain('/srv/kb-backups/rds-logical/20261118T193001Z')
+ })
+
+ it('挂载可读但没有批次时说明不能据此判断成功/失败', () => {
+ const html = view(
+ {
+ last_run_stamp: '',
+ last_run_created_at: '',
+ last_run_databases: [],
+ last_run_total_bytes: 0,
+ host_reachable: false,
+ },
+ {
+ inventory: inventoryFixture({
+ batches: [],
+ totals: {
+ batch_count: 0,
+ database_count: 0,
+ apparent_bytes: 0,
+ actual_bytes: 0,
+ latest_stamp: '',
+ latest_actual_bytes: 0,
+ },
+ }),
+ }
+ )
+ expect(html).toContain('挂载可读,但没有批次目录')
+ expect(html).toContain('不能证明备份成功或失败')
})
it('非管理员只读:没有保存/下发/立即备份按钮,只给当前设置', () => {
@@ -288,12 +459,12 @@ describe('BackupScheduleView', () => {
})
describe('整盘占用与告警', () => {
- it('没有磁盘接口时:不显示示例容量,四条告警一律无法判定', () => {
+ it('没有只读盘点时:不显示示例容量,四条告警只报未知原因', () => {
const html = view()
expect(html).toContain('未接线 · 不显示估算容量')
- expect(html).toContain('后端目前没有「备份主机磁盘总量、空闲、备份目录占用」接口')
+ expect(html).toContain('容量来自只读挂载目录的 statfs 实测')
expect(html).toContain('无法判定')
- expect(html).toContain('整盘总量 / 空闲 / 备份占用:未接线')
+ expect(html).toContain('整盘总量 / 空闲 / 备份实际占盘:未接线')
// 原型里的示例容量不能被当成产品事实带进来。
expect(html).not.toContain('总容量 240 GiB')
expect(html).not.toContain('总容量 500 GiB')
@@ -349,4 +520,54 @@ describe('整盘占用与告警', () => {
const alerts = storageAlerts(diskFixture({ estimate_bytes: null }))
expect(alerts.filter((item) => !item.known).map((item) => item.code)).toEqual(['disk_low', 'quota_low', 'both_low'])
})
+
+ it('真实盘点:整盘色带取 statfs 容量与 st_blocks 实际占盘', () => {
+ const inventory = inventoryFixture()
+ const usage = inventoryUsage(inventory)
+ expect(usage).not.toBeNull()
+ expect(usage!.total).toBe(240 * GiB)
+ expect(usage!.free).toBe(45 * GiB)
+ expect(usage!.backup).toBe(1_500_004_096)
+ expect(usage!.system_other).toBe(192 * GiB - 1_500_004_096)
+ const alerts = inventoryAlerts(inventory)
+ expect(alerts.find((item) => item.code === 'disk_low')?.known).toBe(true)
+ expect(alerts.find((item) => item.code === 'disk_low')?.active).toBe(false)
+ expect(alerts.find((item) => item.code === 'quota_low')?.known).toBe(false)
+ const html = view({}, { inventory })
+ for (const text of [
+ '只读挂载实测',
+ '系统其他占用',
+ '备份实际占盘',
+ '可用',
+ '配额内/外 —(无配额字段)',
+ '文件系统已用',
+ '挂载为只读',
+ '挂载设备 20 与容器根盘 10 不同',
+ ])
+ expect(html).toContain(text)
+ })
+
+ it('挂载落在容器根盘:不把容器容量当主机磁盘,磁盘告警保持未知', () => {
+ const inventory = inventoryFixture({
+ mount: {
+ container_root: '/',
+ mount_verified: false,
+ lives_on_container_root: true,
+ read_only: true,
+ evidence: '挂载设备与容器根盘相同(7):容量不代表备份主机磁盘',
+ },
+ })
+ expect(inventoryUsage(inventory)).toBeNull()
+ const alerts = inventoryAlerts(inventory)
+ expect(alerts.find((item) => item.code === 'disk_low')?.known).toBe(false)
+ expect(alerts.find((item) => item.code === 'disk_low')?.detail).toContain('容器根盘')
+ const html = view({}, { inventory })
+ expect(html).toContain('容器根盘 · 不代表主机磁盘')
+ expect(html).toContain('不据此判定备份主机磁盘')
+ expect(html).not.toContain('备份实际占盘 1.40 GiB')
+ })
+
+ it('复制路径:空值与不可用按钮不谎报成功', async () => {
+ expect(await copyBackupPath('')).toBe(false)
+ })
})
diff --git a/web/src/BackupScheduleSection.tsx b/web/src/BackupScheduleSection.tsx
index 669037f..f06567a 100644
--- a/web/src/BackupScheduleSection.tsx
+++ b/web/src/BackupScheduleSection.tsx
@@ -9,6 +9,8 @@ import {
saveBackupSchedule,
} from './backupSchedule'
import type { BackupSchedule } from './backupSchedule'
+import { fetchBackupInventory } from './backupInventory'
+import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
import './storageBackup.css'
export const formatBackupBytes = (bytes: number): string => {
@@ -190,11 +192,122 @@ const percent = (part: number, total: number): string => (total > 0 ? `${(100 *
export const storageAlertSummary = (alerts: StorageAlert[]): string => {
const unknown = alerts.filter((item) => !item.known)
- if (unknown.length) return '无法判定(缺主机磁盘读数)'
+ if (unknown.length === alerts.length) return '无法判定(缺读数与配额字段)'
+ if (unknown.length) return `部分无法判定(${unknown.map((item) => item.label).join('、')})`
const active = alerts.filter((item) => item.active)
return active.length ? active.map((item) => item.label).join('、') : '四项均正常'
}
+export interface InventoryUsage {
+ total: number
+ used: number
+ free: number
+ backup: number
+ system_other: number
+}
+
+// 只读挂载 + 实测容量 + 文件系统与容器根盘分离,三者同时成立才画整盘图。
+// 备份实际占盘取所有批次的 st_blocks 合计,不是 MANIFEST 的表观字节。
+export function inventoryUsage(inventory: BackupInventory | null): InventoryUsage | null {
+ if (
+ !inventory ||
+ !inventory.wired ||
+ !inventory.mount.mount_verified ||
+ !inventory.capacity.measured ||
+ inventory.capacity.total_bytes <= 0
+ ) {
+ return null
+ }
+ const total = inventory.capacity.total_bytes
+ const used = Math.max(0, inventory.capacity.used_bytes)
+ const backup = Math.max(0, inventory.totals.actual_bytes)
+ return {
+ total,
+ used,
+ free: Math.max(0, inventory.capacity.available_bytes),
+ backup,
+ system_other: Math.max(0, used - backup),
+ }
+}
+
+// 配额与策略预留在后端仍是缺字段,不能因为容量读到了就假装能判定配额;
+// 磁盘告警只拿"最近一批实际占盘"做参考,并注明不含预留。
+export function inventoryAlerts(inventory: BackupInventory | null): StorageAlert[] {
+ const usage = inventoryUsage(inventory)
+ const latest = inventory?.batches[0]
+ const capacityKnown = Boolean(usage)
+ const latestBytes = latest?.actual_bytes ?? 0
+ const diskKnown = capacityKnown && latestBytes > 0
+ const diskActive = diskKnown && latestBytes > usage!.free
+ const diskDetail = !inventory
+ ? '尚未读取备份目录'
+ : !inventory.wired
+ ? '只读盘点未接线'
+ : !inventory.mount.mount_verified
+ ? '目录位于容器根盘,读数不代表备份主机磁盘'
+ : !inventory.capacity.measured
+ ? inventory.capacity.error || '未读到文件系统容量'
+ : latestBytes <= 0
+ ? '没有可参考的批次实际占盘'
+ : `剩余可用 ${formatGib(usage!.free)} GiB,最近一批实际占盘 ${formatGib(latestBytes)} GiB(参考值,不含策略预留)`
+ return [
+ {
+ code: 'disk_low',
+ label: '磁盘不足',
+ active: diskActive,
+ known: diskKnown,
+ detail: diskDetail,
+ },
+ {
+ code: 'quota_low',
+ label: '配额不足',
+ active: false,
+ known: false,
+ detail: '后端没有备份总配额字段,无法判定',
+ },
+ {
+ code: 'both_low',
+ label: '磁盘与配额同时不足',
+ active: false,
+ known: false,
+ detail: '缺配额字段,无法判定',
+ },
+ {
+ code: 'quota_over_physical',
+ label: '配额超出物理空闲',
+ active: false,
+ known: false,
+ detail: '缺配额字段,无法判定',
+ },
+ ]
+}
+
+export async function copyBackupPath(value: string, button?: HTMLButtonElement | null): Promise {
+ if (!value) return false
+ try {
+ await navigator.clipboard.writeText(value)
+ if (button) button.textContent = '已复制'
+ return true
+ } catch {
+ // 内网 http 页面没有 clipboard API 权限时退回选中,不谎报“已复制”。
+ const area = document.createElement('textarea')
+ area.value = value
+ area.setAttribute('readonly', '')
+ area.style.position = 'fixed'
+ area.style.opacity = '0'
+ document.body.append(area)
+ area.focus()
+ area.select()
+ const copied = document.execCommand('copy')
+ area.remove()
+ if (button) button.textContent = copied ? '已复制' : '路径已选中,可复制'
+ return copied
+ }
+}
+
+const manifestLabel = (batch: BackupInventoryBatch): string =>
+ batch.manifest_state === 'ok' ? '清单完整' : batch.manifest_state === 'missing' ? '清单缺失' : '清单损坏'
+
// 备份执行主机上的整库逻辑备份(全部业务库一次 pg_dump)。
// 页面只展示接口真实给出的读数;目录、配额、预留、子库路径、历史批次与恢复
// 验证在后端契约里还没有字段,保留原型位置并写明"未接线"。
@@ -218,8 +331,12 @@ export interface BackupScheduleViewProps {
onApply: () => void
onRunNow: () => void
onReload: () => void
- // 仅测试夹具提供;生产容器不传,磁盘区显示"未接线"。
+ // 仅测试夹具提供;生产容器不传,磁盘区改用真实盘点的容量。
disk?: StorageDiskObservation | null
+ inventory?: BackupInventory | null
+ inventoryLoading?: boolean
+ inventoryError?: string | null
+ onReloadInventory?: () => void
}
export function BackupScheduleView(props: BackupScheduleViewProps) {
@@ -244,6 +361,10 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
onRunNow,
onReload,
disk = null,
+ inventory = null,
+ inventoryLoading = false,
+ inventoryError = null,
+ onReloadInventory,
} = props
const days = Number(daysDraft)
const months = Number(monthsDraft)
@@ -283,7 +404,16 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
const hasLastRun = Boolean(schedule.last_run_stamp)
const runFailed = failedCount > 0 || Boolean(schedule.last_run_error)
const usage = disk ? storageUsage(disk) : null
- const alerts = storageAlerts(disk)
+ const alerts = disk ? storageAlerts(disk) : inventoryAlerts(inventory)
+ const latestBatch: BackupInventoryBatch | null = inventory?.batches[0] ?? null
+ const inventoryFigure = inventoryUsage(inventory)
+ const inventoryReady = Boolean(inventory?.wired && !inventory.error)
+ const readyInventory = inventory && inventory.wired && !inventory.error ? inventory : null
+ const inventoryDatabases = latestBatch?.databases.map((item) => item.name) ?? []
+ const scopeDatabases = inventoryDatabases.length ? inventoryDatabases : schedule.last_run_databases
+ const scopeDatabaseCount = scopeDatabases.length
+ const scopeFailed = latestBatch ? latestBatch.databases.filter((item) => item.failed).length : failedCount
+ const hasScopeBatch = Boolean(latestBatch) || hasLastRun
return (
@@ -311,22 +441,33 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
{schedule.host_configured ? '平台已接主机凭据' : '平台未接主机凭据'}
+
+ {inventoryLoading
+ ? '文件盘点读取中'
+ : inventoryReady
+ ? '文件盘点已接线'
+ : inventory?.error
+ ? '文件盘点不可读'
+ : '文件盘点未接线'}
+
- 读取源
-
- {`备份执行主机 ${schedule.host_target || '(未配置)'} 本机直连 RDS`}
- {databaseCount ? ` · 最近批次含 ${databaseCount} 个数据库` : ' · 数据库清单未从主机读到'}
+ {inventory?.source || `备份执行主机 ${schedule.host_target || '(未配置)'} 本机直连 RDS`}
+ {scopeDatabaseCount ? ` · 最近批次含 ${scopeDatabaseCount} 个数据库` : ' · 数据库清单未读到'}
- 写入方向
-
- {`${schedule.host_target || '(未配置)'} 本地备份根目录`}
- 具体根目录未由接口返回,不在页面猜测
+ {inventory?.host_root || `${schedule.host_target || '(未配置)'} 本地备份根目录`}
+
+ {inventoryReady ? '只读挂载盘点;平台没有写路径' : '备份目录未接线或不可读,不在页面猜测'}
+
- 执行范围
-
- {databaseCount
- ? `整批 · ${databaseCount} 个数据库(${schedule.last_run_databases.join('、')})`
+ {scopeDatabaseCount
+ ? `整批 · ${scopeDatabaseCount} 个数据库(${scopeDatabases.join('、')})`
: '整批 · 数据库清单未读到,无法列出库名'}
- 拨号地址
@@ -338,8 +479,8 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
POST /api/v1/backup-schedule/run 没有单库参数,一次就是该主机全部业务库的整批
- pg_dump。用单库按钮触发会连整批一起跑,因此本页不开放单库动作;单库恢复只能用批次里该库的子目录,
- 但子目录路径当前接口没有返回。
+ pg_dump。用单库按钮触发会连整批一起跑,因此本页不开放单库动作;单库恢复请复制「备份记录」里该库的
+ 完整子目录(来自只读盘点),不要自己拼路径。
@@ -347,19 +488,23 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
立即备份
-
- {hasLastRun ? (runFailed ? '最近一批有失败' : '最近一批成功') : '尚无批次读数'}
+
+ {hasScopeBatch ? (scopeFailed > 0 ? '最近一批有失败' : '最近一批成功') : '尚无批次读数'}
- {hasLastRun
- ? `最近一批 ${schedule.last_run_stamp}${runMoment(schedule) ? ` · ${runMoment(schedule)}` : ''} · ${databaseCount} 个数据库 · ${formatBackupBytes(schedule.last_run_total_bytes)} · ${schedule.last_run_duration_seconds} 秒`
- : '还没有从主机读到任何批次。'}
+ {latestBatch
+ ? `最近一批 ${latestBatch.stamp} · ${formatBackupMoment(latestBatch.created_at)} · ${scopeDatabaseCount} 个数据库 · 表观 ${formatBackupBytes(latestBatch.apparent_bytes)} · 实际占盘 ${formatBackupBytes(latestBatch.actual_bytes)} · ${latestBatch.duration_seconds} 秒`
+ : hasLastRun
+ ? `SSH 读回最近一次 ${schedule.last_run_stamp} · ${databaseCount} 个数据库 · ${formatBackupBytes(schedule.last_run_total_bytes)}(文件盘点未接线,以下仅 SSH 结果)`
+ : '还没有从主机读到任何批次。'}
{schedule.running ? (
- 正在备份({formatBackupMoment(schedule.running_started_at)} 开始,整批 {databaseCount || '未知'}{' '}
+ 正在备份({formatBackupMoment(schedule.running_started_at)} 开始,整批 {scopeDatabaseCount || '未知'}{' '}
个数据库)。 没有真实百分比接口,这里只报在途状态,完成后自动刷新。
@@ -394,7 +539,17 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
>
整盘占用与告警
- {usage ? '已读到主机读数' : '未接线'}
+
+ {usage
+ ? '已读到主机读数'
+ : inventoryFigure
+ ? inventory?.mount.read_only
+ ? '只读挂载实测'
+ : '实测(挂载可写)'
+ : inventory?.capacity.measured
+ ? '容器根盘(不可作主机容量)'
+ : '未接线'}
+
{usage && disk ? (
<>
@@ -446,29 +601,102 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
: ''}
>
+ ) : 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.root} · 采集于 {formatBackupMoment(inventory.observed_at)}
+ {inventory.mount.read_only ? ' · 挂载为只读' : ' · 挂载不是只读(部署需改 :ro)'}
+
+ >
+ ) : inventory?.capacity.measured ? (
+ <>
+
+ 容器根盘 · 不代表主机磁盘
+
+
+ 容器根盘实测 {formatGib(inventory.capacity.total_bytes)} GiB,可用{' '}
+ {formatGib(inventory.capacity.available_bytes)} GiB:仅作排障,不据此判定备份主机磁盘。
+
+
{inventory.mount.evidence}
+ >
) : (
<>
- 未接线 · 不显示估算容量
+ {inventoryLoading ? '正在读取只读挂载…' : '未接线 · 不显示估算容量'}
- {['系统其他占用', '备份已用', '配额内空闲', '配额外空闲'].map((label, index) => (
+ {['系统其他占用', '备份实际占盘', '可用', '配额内/外'].map((label, index) => (
-
+
{label} —
))}
-
整盘总量 / 空闲 / 备份占用:未接线
+
+ 整盘总量 / 空闲 / 备份实际占盘:{inventoryError || inventory?.error || '未接线'}
+
>
)}
- 后端目前没有「备份主机磁盘总量、空闲、备份目录占用」接口:这里保留单条整盘图的位置,
- 不填示例容量、不用配额推算磁盘。以下四项告警按同一份真实读数判定。
+ 容量来自只读挂载目录的 statfs 实测,并与容器根盘比较设备号;同一设备时不把容器容量当主机容量。 备份占盘按文件
+ st_blocks 统计(实际分配),不是 MANIFEST 的表观字节。配额与策略预留仍无后端字段,
+ 四项告警中只有磁盘项能按实测判定。
{storageAlertSummary(alerts)}
@@ -511,18 +739,22 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
备份主机上的目录
检查目录(不可用)
- 目录检查接口未接线:无法证明目录可写、挂在哪块盘。
+
+ {inventoryReady
+ ? '目录来自只读挂载来源,只读展示;修改目录需部署变更,平台没有写接口。'
+ : '只读盘点未接线:目录不可证明,不能按设置推定。'}
+
{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(' ; ')}
@@ -767,6 +1086,9 @@ export function BackupScheduleSection() {
const [timeDraft, setTimeDraft] = useState('03:30')
const [daysDraft, setDaysDraft] = useState('7')
const [monthsDraft, setMonthsDraft] = useState('3')
+ const [inventory, setInventory] = useState(null)
+ const [inventoryLoading, setInventoryLoading] = useState(true)
+ const [inventoryError, setInventoryError] = useState(null)
const polling = useRef(null)
const adopt = useCallback((next: BackupSchedule) => {
@@ -797,10 +1119,40 @@ export function BackupScheduleSection() {
}
}, [adopt])
+ const loadInventory = useCallback(async () => {
+ setInventoryLoading(true)
+ setInventoryError(null)
+ try {
+ setInventory(await fetchBackupInventory())
+ } catch (cause) {
+ setInventoryError(cause instanceof Error ? cause.message : '读取只读备份盘点失败')
+ } finally {
+ setInventoryLoading(false)
+ }
+ }, [])
+
+ useEffect(() => {
+ void loadInventory()
+ }, [loadInventory])
+
useEffect(() => {
void load()
}, [load])
+ // 备份完成(running 转假)后再盘点一次,新批次才会出现在历史里;
+ // 运行中不反复扫目录,避免把主机 IO 当成轮询接口。
+ const wasRunning = useRef(false)
+ useEffect(() => {
+ if (schedule?.running) {
+ wasRunning.current = true
+ return
+ }
+ if (wasRunning.current) {
+ wasRunning.current = false
+ void loadInventory()
+ }
+ }, [schedule?.running, loadInventory])
+
// 立即备份约 30~60 秒:在途时轮询主机状态,直到 running 转假并出现新的最近一次结果。
useEffect(() => {
if (!schedule?.running) {
@@ -925,8 +1277,15 @@ export function BackupScheduleSection() {
onSave={() => void save()}
onApply={() => void apply()}
onRunNow={() => void runNow()}
- onReload={() => void load()}
- // disk 不传:后端还没有磁盘读数接口,磁盘区显示"未接线",绝不填示例容量。
+ onReload={() => {
+ void load()
+ void loadInventory()
+ }}
+ inventory={inventory}
+ inventoryLoading={inventoryLoading}
+ inventoryError={inventoryError}
+ onReloadInventory={() => void loadInventory()}
+ // disk 不传:生产只认只读挂载盘点;disk 仅测试夹具用于验证告警分支。
/>
)
}
diff --git a/web/src/backupInventory.test.ts b/web/src/backupInventory.test.ts
new file mode 100644
index 0000000..358eb22
--- /dev/null
+++ b/web/src/backupInventory.test.ts
@@ -0,0 +1,107 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { fetchBackupInventory } from './backupInventory'
+
+const payload = {
+ data: {
+ wired: true,
+ root: '/var/lib/knowledge-governance/backup-host/rds-logical',
+ host_root: '/srv/kb-backups/rds-logical',
+ source: 'weknora-test:/srv/kb-backups/rds-logical',
+ observed_at: '2026-11-19T03:30:10Z',
+ mount: {
+ container_root: '/',
+ mount_verified: true,
+ lives_on_container_root: false,
+ read_only: true,
+ evidence: '挂载设备 20 与容器根盘 10 不同',
+ },
+ capacity: {
+ measured: true,
+ total_bytes: 257698037760,
+ free_bytes: 51539607552,
+ available_bytes: 48318382080,
+ used_bytes: 206158430208,
+ },
+ batches: [
+ {
+ stamp: '20261118T193001Z',
+ path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z',
+ host_path: '/srv/kb-backups/rds-logical/20261118T193001Z',
+ manifest_state: 'ok',
+ manifest_path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z/MANIFEST.json',
+ kind: 'rds-logical-backup',
+ created_at: '20261118T193001Z',
+ duration_seconds: 53,
+ apparent_bytes: 1393646469,
+ actual_bytes: 1500000000,
+ file_count: 214,
+ sizes_complete: true,
+ databases: [
+ {
+ name: 'weknora_v090prod',
+ dir_name: 'weknora_v090prod.dir',
+ path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z/weknora_v090prod.dir',
+ host_path: '/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir',
+ present: true,
+ failed: false,
+ in_manifest: true,
+ apparent_bytes: 696320,
+ actual_bytes: 720896,
+ file_count: 12,
+ },
+ ],
+ },
+ ],
+ totals: {
+ batch_count: 1,
+ database_count: 1,
+ apparent_bytes: 1393646469,
+ actual_bytes: 1500000000,
+ latest_stamp: '20261118T193001Z',
+ latest_actual_bytes: 1500000000,
+ },
+ incomplete_count: 1,
+ skipped: [],
+ truncated: false,
+ },
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals()
+})
+
+describe('fetchBackupInventory', () => {
+ it('保留真实批次、子库完整主机路径与实际占盘', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(() => Promise.resolve({ ok: true, json: () => Promise.resolve(payload) }))
+ )
+ const inventory = await fetchBackupInventory()
+ expect(inventory.wired).toBe(true)
+ expect(inventory.mount.mount_verified).toBe(true)
+ expect(inventory.capacity.measured).toBe(true)
+ expect(inventory.totals.actual_bytes).toBe(1500000000)
+ expect(inventory.batches[0].host_path).toBe('/srv/kb-backups/rds-logical/20261118T193001Z')
+ expect(inventory.batches[0].databases[0].host_path).toBe(
+ '/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir'
+ )
+ expect(inventory.batches[0].databases[0].actual_bytes).toBe(720896)
+ })
+
+ it('响应缺 wired 时整块报错,不默认成未接线', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(() => Promise.resolve({ ok: true, json: () => Promise.resolve({ data: {} }) }))
+ )
+ await expect(fetchBackupInventory()).rejects.toThrow('缺 wired')
+ })
+
+ it('HTTP 失败不返回空批次', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(() => Promise.resolve({ ok: false, status: 502 }))
+ )
+ await expect(fetchBackupInventory()).rejects.toThrow('HTTP 502')
+ })
+})
diff --git a/web/src/backupInventory.ts b/web/src/backupInventory.ts
new file mode 100644
index 0000000..ac6bd6d
--- /dev/null
+++ b/web/src/backupInventory.ts
@@ -0,0 +1,194 @@
+// 「存储与备份 → 备份记录」只读盘点接口。真实字段来自备份主机目录的只读挂载:
+// 批次目录、每个库的完整子目录、文件系统实测容量;不是 SSH 计划读回的副产物。
+export interface BackupInventoryMount {
+ container_root: string
+ mount_verified: boolean
+ lives_on_container_root: boolean
+ read_only: boolean
+ evidence: string
+ error?: string
+}
+
+export interface BackupInventoryCapacity {
+ measured: boolean
+ total_bytes: number
+ free_bytes: number
+ available_bytes: number
+ used_bytes: number
+ error?: string
+}
+
+export interface BackupInventoryDatabase {
+ name: string
+ dir_name: string
+ path: string
+ host_path: string
+ present: boolean
+ failed: boolean
+ in_manifest: boolean
+ apparent_bytes: number
+ actual_bytes: number
+ file_count: number
+}
+
+export type BackupManifestState = 'ok' | 'missing' | 'invalid'
+
+export interface BackupInventoryBatch {
+ stamp: string
+ path: string
+ host_path: string
+ manifest_state: BackupManifestState
+ manifest_path: string
+ manifest_error?: string
+ kind: string
+ created_at: string
+ started_at: string
+ duration_seconds: number
+ manifest_total_bytes: number
+ apparent_bytes: number
+ actual_bytes: number
+ file_count: number
+ sizes_complete: boolean
+ sizes_error?: string
+ databases: BackupInventoryDatabase[]
+}
+
+export interface BackupInventorySkipped {
+ name: string
+ reason: string
+}
+
+export interface BackupInventory {
+ wired: boolean
+ root: string
+ host_root: string
+ source: string
+ observed_at: string
+ error?: string
+ mount: BackupInventoryMount
+ capacity: BackupInventoryCapacity
+ batches: BackupInventoryBatch[]
+ totals: {
+ batch_count: number
+ database_count: number
+ apparent_bytes: number
+ actual_bytes: number
+ latest_stamp: string
+ latest_actual_bytes: number
+ }
+ incomplete_count: number
+ skipped: BackupInventorySkipped[]
+ truncated: boolean
+}
+
+const record = (value: unknown): value is Record =>
+ Boolean(value) && typeof value === 'object' && !Array.isArray(value)
+
+const asString = (value: unknown): string => (typeof value === 'string' ? value : '')
+const asNumber = (value: unknown): number => (typeof value === 'number' && Number.isFinite(value) ? value : 0)
+const asBool = (value: unknown): boolean => value === true
+const asList = (value: unknown): unknown[] => (Array.isArray(value) ? value : [])
+
+const manifestState = (value: unknown): BackupManifestState =>
+ value === 'ok' || value === 'missing' || value === 'invalid' ? value : 'invalid'
+
+function databaseProjection(item: unknown): BackupInventoryDatabase {
+ const value = record(item) ? item : {}
+ return {
+ name: asString(value.name),
+ dir_name: asString(value.dir_name),
+ path: asString(value.path),
+ host_path: asString(value.host_path),
+ present: asBool(value.present),
+ failed: asBool(value.failed),
+ in_manifest: asBool(value.in_manifest),
+ apparent_bytes: asNumber(value.apparent_bytes),
+ actual_bytes: asNumber(value.actual_bytes),
+ file_count: asNumber(value.file_count),
+ }
+}
+
+function batchProjection(item: unknown): BackupInventoryBatch {
+ const value = record(item) ? item : {}
+ return {
+ stamp: asString(value.stamp),
+ path: asString(value.path),
+ host_path: asString(value.host_path),
+ manifest_state: manifestState(value.manifest_state),
+ manifest_path: asString(value.manifest_path),
+ manifest_error: asString(value.manifest_error),
+ kind: asString(value.kind),
+ created_at: asString(value.created_at),
+ started_at: asString(value.started_at),
+ duration_seconds: asNumber(value.duration_seconds),
+ manifest_total_bytes: asNumber(value.manifest_total_bytes),
+ apparent_bytes: asNumber(value.apparent_bytes),
+ actual_bytes: asNumber(value.actual_bytes),
+ file_count: asNumber(value.file_count),
+ sizes_complete: asBool(value.sizes_complete),
+ sizes_error: asString(value.sizes_error),
+ databases: asList(value.databases).map(databaseProjection),
+ }
+}
+
+// 形状不对就整块报错:不能让缺 wired 的响应用默认 false 冒充"未接线"。
+function inventoryProjection(value: unknown): BackupInventory {
+ if (!record(value) || typeof value.wired !== 'boolean') {
+ throw new Error('备份盘点响应无效(缺 wired)')
+ }
+ const mount = record(value.mount) ? value.mount : {}
+ const capacity = record(value.capacity) ? value.capacity : {}
+ const totals = record(value.totals) ? value.totals : {}
+ return {
+ wired: value.wired,
+ root: asString(value.root),
+ host_root: asString(value.host_root),
+ source: asString(value.source),
+ observed_at: asString(value.observed_at),
+ error: asString(value.error),
+ mount: {
+ container_root: asString(mount.container_root),
+ mount_verified: asBool(mount.mount_verified),
+ lives_on_container_root: asBool(mount.lives_on_container_root),
+ read_only: asBool(mount.read_only),
+ evidence: asString(mount.evidence),
+ error: asString(mount.error),
+ },
+ capacity: {
+ measured: asBool(capacity.measured),
+ total_bytes: asNumber(capacity.total_bytes),
+ free_bytes: asNumber(capacity.free_bytes),
+ available_bytes: asNumber(capacity.available_bytes),
+ used_bytes: asNumber(capacity.used_bytes),
+ error: asString(capacity.error),
+ },
+ batches: asList(value.batches).map(batchProjection),
+ totals: {
+ batch_count: asNumber(totals.batch_count),
+ database_count: asNumber(totals.database_count),
+ apparent_bytes: asNumber(totals.apparent_bytes),
+ actual_bytes: asNumber(totals.actual_bytes),
+ latest_stamp: asString(totals.latest_stamp),
+ latest_actual_bytes: asNumber(totals.latest_actual_bytes),
+ },
+ incomplete_count: asNumber(value.incomplete_count),
+ skipped: asList(value.skipped).map((item) => {
+ const entry = record(item) ? item : {}
+ return { name: asString(entry.name), reason: asString(entry.reason) }
+ }),
+ truncated: asBool(value.truncated),
+ }
+}
+
+export async function fetchBackupInventory(signal?: AbortSignal): Promise {
+ const response = await fetch('/api/v1/backup-schedule/inventory', {
+ headers: { Accept: 'application/json' },
+ signal,
+ })
+ if (!response.ok) {
+ throw new Error(`读取备份盘点失败(HTTP ${response.status})`)
+ }
+ const value = (await response.json().catch(() => null)) as unknown
+ if (!record(value) || !record(value.data)) throw new Error('备份盘点响应无效')
+ return inventoryProjection(value.data)
+}
diff --git a/web/src/storageBackup.css b/web/src/storageBackup.css
index 354d3f2..4790780 100644
--- a/web/src/storageBackup.css
+++ b/web/src/storageBackup.css
@@ -39,6 +39,20 @@
font-size: 13px;
color: var(--ink-base);
}
+.storage-block-heading button {
+ font: inherit;
+ font-size: 10px;
+ padding: 3px 9px;
+ border-radius: 5px;
+ border: 1px solid var(--border-base, #cbd5e1);
+ background: var(--bg-panel, #fff);
+ color: inherit;
+ cursor: pointer;
+}
+.storage-block-heading button:disabled {
+ opacity: 0.55;
+ cursor: default;
+}
.storage-chip {
border-radius: 999px;
padding: 2px 9px;
@@ -194,6 +208,60 @@
font-size: 11px;
font-weight: 600;
}
+.storage-manifest {
+ font-size: 10px;
+ padding: 1px 7px;
+ border-radius: 999px;
+ border: 1px solid var(--border-base, #e2e8f0);
+}
+.storage-manifest.ok {
+ color: #17695a;
+ border-color: #a9d5c8;
+ background: #effaf5;
+}
+.storage-manifest.missing,
+.storage-manifest.invalid {
+ color: #a03a1e;
+ border-color: #f3c2b8;
+ background: #fff6f3;
+}
+.storage-path-row {
+ display: grid;
+ grid-template-columns: max-content minmax(0, 1fr) max-content;
+ gap: 4px 8px;
+ align-items: center;
+ margin: 5px 0;
+}
+.storage-path-row small {
+ color: var(--ink-mute, #64748b);
+}
+.storage-path-row code {
+ font-size: 10px;
+ padding: 3px 6px;
+ border-radius: 4px;
+ background: var(--bg-soft, #f6f8fa);
+ overflow-wrap: anywhere;
+}
+.storage-path-row button,
+.storage-sublibraries button {
+ font: inherit;
+ font-size: 10px;
+ padding: 3px 8px;
+ border-radius: 5px;
+ border: 1px solid var(--border-base, #cbd5e1);
+ background: var(--bg-panel, #fff);
+ color: inherit;
+ cursor: pointer;
+}
+.storage-path-row button:disabled,
+.storage-sublibraries button:disabled {
+ opacity: 0.55;
+ cursor: default;
+}
+.storage-sublibrary-path {
+ margin: 2px 0 0;
+ grid-template-columns: minmax(0, 1fr) max-content;
+}
.storage-alert-summary {
margin: 8px 0 0;
font-size: 11px;
@@ -330,6 +398,9 @@
border-radius: 5px;
background: var(--bg-soft, #f6f8fa);
}
+.storage-sublibrary-path {
+ grid-column: 1 / -1;
+}
.storage-sublibraries .ok {
color: #17695a;
}
From 63984dbfbeab77765bb098bf13e222764009be33 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E5=A7=9A=E7=AB=A0=E6=B5=A9?=
Date: Fri, 20 Nov 2026 01:41:28 +0800
Subject: [PATCH 08/14] =?UTF-8?q?fix(backup):=20=E5=AE=BF=E4=B8=BB?=
=?UTF-8?q?=E9=87=87=E9=9B=86=E5=99=A8=E6=8C=89=20du=20=E5=8F=A3=E5=BE=84?=
=?UTF-8?q?=E5=8E=BB=E9=87=8D=E7=A1=AC=E9=93=BE=E6=8E=A5=E5=B9=B6=E6=8B=92?=
=?UTF-8?q?=E7=BB=9D=E6=B8=85=E5=8D=95=E7=AC=A6=E5=8F=B7=E9=93=BE=E6=8E=A5?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
备份目录 root:root 0700,API 不再遍历;宿主采集器只读 stat/du,原子写快照。统计包含目录自身、树内 (dev,ino) 硬链接去重,单库与整批各自独立与 du -sB1 对齐;MANIFEST 仅接受目录内常规非符号链接文件并 O_NOFOLLOW 打开。快照缺失/陈旧/不完整时批次与子库字节为 null,页面不画容量图、不使用部分字节。
---
CHANGELOG.md | 22 +
api/openapi.yaml | 2 +-
cmd/api/main.go | 9 +-
compose.release-sim.yaml | 8 +-
docs/PRODUCTION_BACKUP_RECOVERY.md | 9 +-
docs/STORAGE_BACKUP_READONLY_API.md | 289 ++++---
internal/appconfig/config.go | 29 +-
internal/appconfig/config_test.go | 27 +-
internal/backupinventory/inventory.go | 914 ++++++++++-----------
internal/backupinventory/inventory_test.go | 373 +++++----
internal/httpapi/backup_inventory.go | 8 +-
internal/httpapi/backup_inventory_test.go | 15 +-
scripts/collect_backup_metadata.py | 581 +++++++++++++
web/src/BackupScheduleSection.test.tsx | 121 ++-
web/src/BackupScheduleSection.tsx | 205 +++--
web/src/backupInventory.test.ts | 29 +-
web/src/backupInventory.ts | 94 ++-
17 files changed, 1798 insertions(+), 937 deletions(-)
create mode 100755 scripts/collect_backup_metadata.py
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 96db63f..8968507 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,27 @@
# Changelog
+## 开发快照 0.1.408(备份盘点改宿主采集器:权限失败不再产出部分字节)
+
+### Fixed
+
+- 修复 API 以 uid 1000 遍历 root:root 0700 备份目录时 `sizes_complete=false` 但
+ `Database.ActualBytes` 仍保留部分计数的问题:API 不再遍历备份目录,只读宿主快照;
+ 快照不完整/陈旧/缺失时批次与子库字节全部为 `null`,页面不画容量图、不使用部分字节。
+- 容量图与任何可写预测只在“快照新鲜 + 完整 + 路径校验通过 + 容量实测”时出现;
+ 权限失败回归覆盖采集器注入 `PermissionError` 与 API 拒绝部分字段。
+- 单库 `696320` 只作现场核对值,代码与测试不写死。
+
+### Added
+
+- `scripts/collect_backup_metadata.py`:宿主单次只读采集器,stat/du + MANIFEST,
+ 原子写 `metadata.json`,不读数据库内容、不跟随符号链接、权限失败置空字节。
+ 统计口径与 `du -sB1` 对齐:目录自身计入、树内硬链接按 `(dev,ino)` 去重、
+ 单库与整批各自独立测量;MANIFEST 只接受批次目录内常规非符号链接文件,
+ 打开带 `O_NOFOLLOW`。
+- `GET /api/v1/backup-schedule/inventory` 读取并校验快照:schema、root、批次/子库路径、
+ 采集时效、完整性;批次/子库字节可空。
+- 文档改为 28189 快照挂载、采集器安装/定时、可验证字段与写能力清单。
+
## 开发快照 0.1.407(备份盘点:只读挂载读真实批次与容量)
### Added
diff --git a/api/openapi.yaml b/api/openapi.yaml
index 021979a..1891144 100644
--- a/api/openapi.yaml
+++ b/api/openapi.yaml
@@ -1978,7 +1978,7 @@
"Settings"
],
"operationId": "getBackupScheduleInventory",
- "summary": "只读盘点备份批次、子库完整路径与实际占盘、挂载文件系统实测容量",
+ "summary": "读取宿主元数据快照:批次、子库完整路径、实际占盘与文件系统容量(陈旧/不完整一律未知)",
"responses": {
"200": {
"$ref": "#/components/responses/Envelope"
diff --git a/cmd/api/main.go b/cmd/api/main.go
index 70cdd02..c072cb0 100644
--- a/cmd/api/main.go
+++ b/cmd/api/main.go
@@ -57,7 +57,7 @@ func (dingtalkSourceLister) ValidateDingtalkDocument(ctx context.Context, node s
return dingtalkdiscovery.ValidateDocument(ctx, dingtalkdiscovery.ExecRunner{}, node)
}
-// 只读盘点的展示路径必须与挂载来源同一份:容器内挂载点不可给操作者复制,
+// 宿主快照的展示路径必须与采集 root 同一份:容器内快照路径不可给操作者复制,
// 复制出去要在主机上能直接 cd/pg_restore。来源没配时用 target + 主机根拼。
func backupInventoryHostRoot(config appconfig.Config) string {
if config.BackupHostReadonlyHostPath != "" {
@@ -340,9 +340,10 @@ func run(ctx context.Context, getenv func(string) string) error {
Root: config.BackupHostRoot,
}),
BackupInventory: backupinventory.New(backupinventory.Config{
- Root: config.BackupHostReadonlyRoot,
- HostRoot: backupInventoryHostRoot(config),
- Source: backupInventorySource(config),
+ MetadataPath: config.BackupHostMetadataPath,
+ HostRoot: config.BackupHostReadonlyHostPath,
+ Source: backupInventorySource(config),
+ MaxAge: config.BackupHostMetadataMaxAge,
}),
Auth: &httpapi.AuthConfig{Store: authStore, SessionTTL: 12 * time.Hour},
})
diff --git a/compose.release-sim.yaml b/compose.release-sim.yaml
index bf4728b..f2a321d 100644
--- a/compose.release-sim.yaml
+++ b/compose.release-sim.yaml
@@ -17,14 +17,16 @@ services:
BACKUP_HOST_SCRIPT_DIR: /opt/weknora-test
BACKUP_HOST_ROOT: /srv/kb-backups
# 只读盘点(批次/子库路径/实测容量)与上面的 SSH 计划读回独立。
- # 候选 28189 部署时按 docs/STORAGE_BACKUP_READONLY_API.md 打开,并要求宿主目录只读挂载:
- # BACKUP_HOST_READONLY_ROOT: /var/lib/knowledge-governance/backup-host/rds-logical
+ # 候选 28189 部署时按 docs/STORAGE_BACKUP_READONLY_API.md 打开:
+ # 宿主采集器原子写 metadata.json,API 只读挂载输出目录(不挂备份目录):
+ # BACKUP_HOST_METADATA_PATH: /var/lib/knowledge-governance/backup-host/metadata.json
+ # BACKUP_HOST_METADATA_MAX_AGE: 15m
# BACKUP_HOST_READONLY_HOST_PATH: /srv/kb-backups/rds-logical
# BACKUP_HOST_READONLY_SOURCE: weknora-test:/srv/kb-backups/rds-logical
volumes:
- ./secrets/release-sim:/run/release-secrets:ro
- ./secrets/backup-host:/run/backup-host:ro
- # - /srv/kb-backups/rds-logical:/var/lib/knowledge-governance/backup-host/rds-logical:ro
+ # - /var/lib/knowledge-governance/backup-metadata:/var/lib/knowledge-governance/backup-host:ro
release-worker:
environment:
diff --git a/docs/PRODUCTION_BACKUP_RECOVERY.md b/docs/PRODUCTION_BACKUP_RECOVERY.md
index 9915f4d..d31425d 100644
--- a/docs/PRODUCTION_BACKUP_RECOVERY.md
+++ b/docs/PRODUCTION_BACKUP_RECOVERY.md
@@ -91,16 +91,17 @@ python3 scripts/restore_drill.py --snapshot-dir $KB_BACKUP_ROOT/target-kb-snapsh
- 页面:系统设置 → 存储与备份(管理员可改;保存 = 写入库并立刻下发;另有"重新下发当前设置"与"立即备份一次")。
- 接口:`GET /api/v1/backup-schedule`(不探测主机,首屏快)、`GET …/host`(SSH 读回主机 cron 与最近一次结果)、
- `GET …/inventory`(只读挂载盘点全部批次/子库路径/实测容量,见 `docs/STORAGE_BACKUP_READONLY_API.md`)、
+ `GET …/inventory`(宿主采集器快照读全部批次/子库路径/实测容量,见 `docs/STORAGE_BACKUP_READONLY_API.md`)、
`PUT`(校验时间 `HH:MM` 与 1~365 天 / 0~24 月,非法值直接 400 且不落库不下发)、`POST …/apply`、`POST …/run`。
写操作按角色网关(`classifyRole`)限管理员——这份计划会落到数据面主机的 cron 上。
- 主机侧:`scripts/install_backup_schedule.sh`(幂等)写 `/etc/knowledge-governance/backup-schedule.env`
与 `/etc/cron.d/kb-logical-backup`;`logical-backup.sh` 从该文件读保留策略(显式传 `KEEP_DAILY/KEEP_MONTHS` 可覆盖)。
- 凭据:容器内只读挂载 `secrets/backup-host/{ssh_config,id_ed25519,known_hosts}`(0600),
环境变量 `BACKUP_HOST_SSH_CONFIG / BACKUP_HOST_TARGET / BACKUP_HOST_SCRIPT_DIR / BACKUP_HOST_ROOT`;
- **三项缺任一即"未接线"**,页面降级提示而不是报错。只读盘点另用
- `BACKUP_HOST_READONLY_ROOT / BACKUP_HOST_READONLY_HOST_PATH / BACKUP_HOST_READONLY_SOURCE`,
- 要求 `:ro` 挂载,见 `docs/STORAGE_BACKUP_READONLY_API.md`。
+ **三项缺任一即"未接线"**,页面降级提示而不是报错。只读盘点另用宿主采集器
+ `scripts/collect_backup_metadata.py` 原子写 `metadata.json`,API 用
+ `BACKUP_HOST_METADATA_PATH / BACKUP_HOST_READONLY_HOST_PATH` 只读快照,见
+ `docs/STORAGE_BACKUP_READONLY_API.md`。
- 主机状态读取只认**有 `MANIFEST.json` 的完整目录**:被中断的运行会被脚本改名 `*.incomplete`,
所以"最近一次备份"永远不会显示一份半成品。
- 依赖两个运行前提:运行镜像里有 `openssh-client`,且容器用户的 uid 在 `/etc/passwd` 有名字
diff --git a/docs/STORAGE_BACKUP_READONLY_API.md b/docs/STORAGE_BACKUP_READONLY_API.md
index f1c23a1..577c694 100644
--- a/docs/STORAGE_BACKUP_READONLY_API.md
+++ b/docs/STORAGE_BACKUP_READONLY_API.md
@@ -1,166 +1,209 @@
-# 存储与备份:只读盘点接口与 28189 候选接线
+# 存储与备份:宿主元数据采集器、只读接口与 28189 接线
-本页的「备份记录 / 整盘占用」只读**备份执行主机**上的 `rds-logical` 目录。接口不执行
-SSH 文件命令,也不写备份目录;它只读一个**只读挂载**进来的目录,并用 `statfs` 与
-`st_blocks` 给出实测容量和实际占盘。主机 cron 计划的读回仍是另一条 SSH 通道,两者独立。
+「备份记录 / 整盘占用」不遍历备份目录。备份目录通常是 `root:root 0700`,API 容器
+用户 `uid 1000` 进不去;容器里遍历只会得到 permission denied 的部分字节。真实闭环是:
-## 1. 接口契约
+1. 备份主机上由**有读权限的宿主进程**运行 `scripts/collect_backup_metadata.py` 单次采集;
+ 只做 `stat`/`du` 元数据和读 `MANIFEST.json`,不读数据库内容文件。
+2. 采集器用同目录临时文件 + `fsync` + `os.replace` **原子写出** `metadata.json`。
+3. API 只读挂载这个 JSON,校验 schema、批次/子库路径、主机根、时效、完整性。
+4. 快照陈旧/缺失/不完整时,批次字节为 `null`,页面显示未知,不画容量图、不做可写预测。
+
+主机 cron 计划读回仍是原来的 SSH 通道(`/host`),与快照完全独立;API 不借用 SSH
+读文件,也不获得备份目录的容器权限。
+
+## 1. 采集器(宿主运行)
+
+脚本:`scripts/collect_backup_metadata.py`(Python 3 标准库,无第三方依赖)
+
+```sh
+python3 collect_backup_metadata.py \
+ --root /srv/kb-backups/rds-logical \
+ --output /var/lib/knowledge-governance/backup-metadata/metadata.json \
+ --source weknora-test:/srv/kb-backups/rds-logical
+```
+
+- 退出码:`0` 完整;`2` 已写快照但采集不完整/有错误;`1` 连快照都没写成。
+- 只读取:目录项 `lstat`、`statvfs`、`/proc/self/mountinfo`、`MANIFEST.json`;
+ **不打开任何 `.dat/.gz` 数据文件**。
+- 不跟随符号链接;`*.incomplete` 只计数不进入批次;单次最多 100 批(可调)。
+- 口径与 `du -sB1` 对齐:目录自身块计入;遍历整棵子树而非只求和文件;
+ 常规文件硬链接按 `(st_dev, st_ino)` 只算一次;**每个子库与整批各自独立测量**,
+ 所以单库字节与该子库自己的 `du` 一致、整批与整批 `du` 一致(不会把整批去重结果
+ 摊回单库)。
+- `MANIFEST.json` 只接受批次目录内的常规非符号链接文件;`lstat` + `O_NOFOLLOW`
+ 打开,符号链接/非普通文件一律 `invalid`,不会被跟随到别处。
+- 权限失败会写入 `batch.errors` 并把 `actual_bytes/apparent_bytes/file_count` 置 `null`;
+ 绝不把已数到的部分字节当占盘。
+
+建议由宿主定时器每 5 分钟跑一次(root 或备份目录所有者;不改任何备份权限):
+
+```cron
+*/5 * * * * /usr/bin/python3 /opt/knowledge-governance/collect_backup_metadata.py \
+ --root /srv/kb-backups/rds-logical \
+ --output /var/lib/knowledge-governance/backup-metadata/metadata.json \
+ --source weknora-test:/srv/kb-backups/rds-logical \
+ >> /var/log/knowledge-governance-backup-metadata.log 2>&1
+```
+
+目录 `0755`、文件 `0644`,只包含路径/清单摘要/计数,不含数据库内容。
+
+### 快照 schema(version 1)
+
+关键字段:
+
+| 字段 | 含义 |
+| --- | --- |
+| `schema_version` | `1`;API 不认识就整块拒绝 |
+| `collected_at` | UTC RFC3339;超过 `BACKUP_HOST_METADATA_MAX_AGE` 即陈旧 |
+| `generation` | 每次采集唯一 ID,便于核对读到的是哪一次原子快照 |
+| `root` | 宿主上的 `rds-logical` 绝对路径;API 要求与配置完全一致 |
+| `complete` | 全局完整;权限失败/截断/有错误时为 false |
+| `filesystem` | `mount_point/mount_source/fs_type/read_only/total/free/available` |
+| `batches[].complete` | 该批遍历完整;false 时字节必须为 null |
+| `batches[].actual_bytes` | `st_blocks×512` 实际分配,仅完整批有值 |
+| `batches[].databases[].path` | 子库完整宿主路径,必须等于 `/.dir` |
+| `batches[].manifest_state` | `ok` / `missing` / `invalid`(清单是元数据,不影响权限统计) |
+
+## 2. 接口契约
`GET /api/v1/backup-schedule/inventory`(读者角色可看;不写任何东西)
-响应始终是 200 + `data`,未接线/目录不可读/清单损坏都写在字段里,页面据此区分原因。
-只有请求本身失败(如代理 502)才是非 200。
+始终 200 + `data`;未接线/快照缺失/陈旧/不完整/路径不一致都写在字段里。
```json
{
"data": {
"wired": true,
- "root": "/var/lib/knowledge-governance/backup-host/rds-logical",
+ "metadata": {
+ "configured": true, "present": true, "valid": true,
+ "fresh": true, "complete": true,
+ "path": "/var/lib/knowledge-governance/backup-host/metadata.json",
+ "collected_at": "2026-11-20T01:00:00Z",
+ "age_seconds": 10, "max_age_seconds": 900,
+ "schema_version": 1, "generation": "20261120T010000Z-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": "挂载设备 20 与容器根盘 10 不同:容量按挂载文件系统计量"
+ "mount_verified": true, "read_only": false,
+ "mount_point": "/srv/kb-backups", "device": "/dev/sdb1", "fs_type": "ext4",
+ "evidence": "宿主采集器:/dev/sdb1 挂在 /srv/kb-backups(ext4),API 不遍历备份目录"
},
"capacity": {
- "measured": true,
- "total_bytes": 257698037760,
- "free_bytes": 51539607552,
- "available_bytes": 48318382080,
- "used_bytes": 206158430208
+ "measured": true, "total_bytes": 1000, "free_bytes": 400,
+ "available_bytes": 350, "used_bytes": 600
},
- "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": "…/20261118T193001Z/MANIFEST.json",
- "manifest_error": "",
- "kind": "rds-logical-backup",
- "created_at": "20261118T193001Z",
- "duration_seconds": 53,
- "manifest_total_bytes": 1393646469,
- "apparent_bytes": 1393646469,
- "actual_bytes": 1500000000,
- "file_count": 214,
- "sizes_complete": true,
- "databases": [
- {
- "name": "weknora_v090prod",
- "dir_name": "weknora_v090prod.dir",
- "path": "…/20261118T193001Z/weknora_v090prod.dir",
- "host_path": "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir",
- "present": true,
- "failed": false,
- "in_manifest": true,
- "apparent_bytes": 696320,
- "actual_bytes": 720896,
- "file_count": 12
- }
- ]
- }
- ],
+ "batches": [{
+ "stamp": "20261118T193001Z",
+ "path": "/srv/kb-backups/rds-logical/20261118T193001Z",
+ "host_path": "/srv/kb-backups/rds-logical/20261118T193001Z",
+ "manifest_state": "ok",
+ "actual_bytes": 4096, "apparent_bytes": 300, "file_count": 3,
+ "sizes_complete": true,
+ "databases": [{
+ "name": "weknora_v090prod",
+ "path": "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir",
+ "host_path": "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir",
+ "present": true, "failed": false, "in_manifest": true,
+ "actual_bytes": 4096, "apparent_bytes": 250, "file_count": 2
+ }]
+ }],
"totals": {
- "batch_count": 8,
- "database_count": 0,
- "apparent_bytes": 11141651752,
- "actual_bytes": 12000000000,
- "latest_stamp": "20261118T193001Z",
- "latest_actual_bytes": 1500000000
+ "batch_count": 8, "database_count": 0,
+ "actual_bytes": 12000000000, "apparent_bytes": 11141651752,
+ "latest_stamp": "20261118T193001Z", "latest_actual_bytes": 1500000000,
+ "complete": true
},
- "incomplete_count": 0,
- "skipped": [],
- "truncated": false
+ "incomplete_count": 0, "skipped": [], "truncated": false
}
}
```
-> 示例中的容量、字节与库数只说明字段形状,**不是现场读数**;现场值必须由接口实测。
-> 候选现场已核实的事实只有:8 批、最近 `20261118T193001Z`、含 `weknora_v090prod.dir`。
+> 示例中的容量/字节只说明字段形状,**不是现场读数**;候选现场已核实的事实只有:
+> 8 批、最近 `20261118T193001Z`、含 `weknora_v090prod.dir`。单库 `696320` 是现场核对值,
+> 代码与测试都不写死。
-### 字段语义(页面可逐项核对)
+### 语义与页面行为
-| 字段 | 含义 | 页面行为 |
+| 条件 | API | 页面 |
| --- | --- | --- |
-| `wired` | `BACKUP_HOST_READONLY_ROOT` 已配置 | false 显示“只读盘点未接线”,不显示空批次当“没有备份” |
-| `error` | 目录不存在/不可读 | 显示原因;批次区不伪造数据 |
-| `mount.mount_verified` | 挂载根与容器根盘设备号不同 | false 时容量只作排障,不当主机容量、不判磁盘告警 |
-| `mount.lives_on_container_root` | 与容器根盘同设备 | true 时页面明确“容器根盘·不代表主机磁盘” |
-| `mount.read_only` | `statfs` 标志含 `ST_RDONLY` | false 时提示部署需改 `:ro` |
-| `capacity.*` | 挂载文件系统的实测字节 | 只在 `mount_verified && measured` 时画色带 |
-| `batches[].manifest_state` | `ok` / `missing` / `invalid` | 逐批标注;损坏批仍按目录列子库与占盘 |
-| `batches[].actual_bytes` | 目录内文件 `st_blocks × 512` 合计 | 实际占盘(不是 MANIFEST 表观值) |
-| `databases[].host_path` | 主机上可复制的完整子库目录 | 复制按钮可用;不拼造路径 |
-| `databases[].present` | `.dir` 目录是否真的存在 | false 显示“目录缺失” |
-| `incomplete_count` | `*.incomplete` 目录数 | 仅提示,不计入批次 |
-| `skipped` | 符号链接/非法项/超限 | 显示跳过原因 |
-| `truncated` | 批次或文件数超扫描上限 | 明确“部分结果” |
+| `wired=false` | `metadata.error=未接线`,批次空 | 显示未接线与安装方式,不显示空表当“没备份” |
+| 快照文件缺失/不可读 | `present=false`、`valid=false` | 显示缺失;不使用 SSH 最近一次补历史 |
+| `collected_at` 超过 max age | `fresh=false`、`valid=false`、批次空、容量未测 | 显示陈旧;容量图/占盘未知 |
+| 任一批不完整/权限失败/截断 | `valid=true`、`complete=false`;所有 `*_bytes=null` | 列出路径与清单状态;占盘/容量“未知”,不画色带 |
+| 完整且新鲜 | 批次/子库字节与容量按快照 | 色带、批次、子库路径复制可用 |
+| 批次路径/子库路径与 root 不一致 | `valid=false`,整块拒绝 | 显示校验失败,不展示可疑路径 |
-`apparent_bytes` 优先取 MANIFEST 的 `total_bytes`;没有/损坏清单时退回目录 `st_size` 合计。
-`actual_bytes` 永远是文件系统实际分配,不用表观字节冒充占盘。
+API 的路径校验要求批次路径精确等于 `/`、子库精确等于
+`/.dir`;重复、分隔符、`..`、`.incomplete` 一律拒绝。
-## 2. 28189 候选 API 的最小接线
+## 3. 28189 候选 API 的最小接线
-28189 是 `weknora-test` 上的候选 API(本机通过 SSH 隧道访问)。API 容器增加三项环境变量
-和一条**只读** bind mount;不新增 SSH 权限,也不把备份目录挂成可写:
+API 只挂**采集器输出目录**,不挂备份目录:
```yaml
services:
api:
environment:
- BACKUP_HOST_READONLY_ROOT: /var/lib/knowledge-governance/backup-host/rds-logical
+ BACKUP_HOST_METADATA_PATH: /var/lib/knowledge-governance/backup-host/metadata.json
+ BACKUP_HOST_METADATA_MAX_AGE: 15m
BACKUP_HOST_READONLY_HOST_PATH: /srv/kb-backups/rds-logical
BACKUP_HOST_READONLY_SOURCE: weknora-test:/srv/kb-backups/rds-logical
volumes:
- - /srv/kb-backups/rds-logical:/var/lib/knowledge-governance/backup-host/rds-logical:ro
+ - /var/lib/knowledge-governance/backup-metadata:/var/lib/knowledge-governance/backup-host:ro
```
-要求:
+- `BACKUP_HOST_METADATA_PATH` 与 `BACKUP_HOST_READONLY_HOST_PATH` 必填;`SOURCE` 可省略
+ (用 target + host path 拼)。缺任一拒绝启动,避免“看起来接线”或复制猜的路径。
+- 只挂元数据目录,`uid 1000` 只需要读 `metadata.json`,**不需要**进入 root:root 0700 的备份目录。
+- 采集器由宿主 root/备份所有者运行;不新增 API SSH 权限,不改备份目录权限。
+- 主机 cron 计划仍走 `BACKUP_HOST_SSH_CONFIG/TARGET/SCRIPT_DIR`;与快照独立。
-- 挂载必须带 `:ro`。宿主目录本身不要改成 777;用 ACL/附加组给 API 运行用户(镜像内
- `uid 1000`)只读遍历权限,例如由有权限的运维执行 `setfacl -R -m u:1000:rX /srv/kb-backups/rds-logical`
- (属主机变更,需单独批准;本次未执行)。
-- 只挂 `rds-logical`,不要挂整个 `/srv/kb-backups`,减少可读面。
-- `BACKUP_HOST_READONLY_ROOT` 与 `BACKUP_HOST_READONLY_HOST_PATH` 必填;`SOURCE` 可省略
- (省略时用 `BACKUP_HOST_TARGET + 主机路径` 拼展示来源)。缺 `ROOT` 或 `HOST_PATH` 会拒绝启动,
- 避免“看起来接线”或复制出猜的路径。
-- 主机 cron 计划仍走原有 `BACKUP_HOST_SSH_CONFIG/TARGET/SCRIPT_DIR`;本接口不依赖 SSH。
+### 部署后核验
-### 部署后 30 秒核验(在 API 容器内)
+宿主:
```sh
-ROOT=/var/lib/knowledge-governance/backup-host/rds-logical
-findmnt -T "$ROOT" -o TARGET,SOURCE,FSTYPE,OPTIONS
-stat -c '%d %n' "$ROOT" /
-df -B1 "$ROOT"
-ls -1 "$ROOT" | tail
+ls -l /var/lib/knowledge-governance/backup-metadata/metadata.json
+python3 - <<'PY'
+import json
+d=json.load(open('/var/lib/knowledge-governance/backup-metadata/metadata.json'))
+print(d['schema_version'], d['collected_at'], d['complete'], d['root'], len(d['batches']))
+print(d['batches'][0]['stamp'], [x['name'] for x in d['batches'][0]['databases']][:5])
+PY
```
-期望:`findmnt` 的 SOURCE 是宿主备份盘、OPTIONS 含 `ro`;`stat` 的设备号与 `/` 不同
-(对应 `mount.mount_verified=true`);`df` 与 `capacity` 接近;`ls` 能看到
-`20261118T193001Z`。
+API 容器:
-字段核对:`totals.batch_count=8`、`totals.latest_stamp=20261118T193001Z`、最近批的
-`databases` 含 `weknora_v090prod` 且 `present=true`、`host_path` 以
-`/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir` 结尾。
+```sh
+cat /var/lib/knowledge-governance/backup-host/metadata.json >/dev/null && echo readable
+curl -s http://127.0.0.1:28189/api/v1/backup-schedule/inventory | head -c 400
+```
-若 `wired=false` 或 `error` 提示不可读:先查挂载与读权限,不要用 SSH 的“最近一次”补历史。
+字段核对(以现场为准,示例值不写死):
-## 3. 与主机计划读回的关系
+- `metadata.valid=true`、`fresh=true`;`complete=true` 才允许看占盘与容量。
+- `totals.batch_count=8`;`totals.latest_stamp=20261118T193001Z`。
+- 最近批 `databases` 含 `weknora_v090prod`、`present=true`,`host_path` 指向
+ `/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir`。
+- `capacity.measured=true` 且与宿主 `df -B1 /srv/kb-backups` 一致。
+- 若 `complete=false`:先看 `metadata.error` 里的 permission/遍历错误;**不要**用
+ `latest_actual_bytes` 或部分 `databases[].actual_bytes` 做容量判断(它们应为 null)。
-- `GET /api/v1/backup-schedule/host`:SSH 读 cron/脚本/计划 + MANIFEST 的最近一次摘要。
-- `GET /api/v1/backup-schedule/inventory`:只读挂载读全部批次、子库路径、实际占盘、容量。
+## 4. 与主机计划读回的关系
-前端分别加载,互不掩盖失败:盘点不可读时计划区仍显示读回结果;SSH 连不上时历史区仍可
-展示文件事实。历史批次与子库路径以盘点为准,SSH 的“最近一次”只作历史参考。
+- `/host`:SSH 读 cron/脚本/计划 + MANIFEST 最近一次摘要。
+- `/inventory`:宿主快照读全部批次、子库路径、实际占盘、容量。
-## 4. 现有写路径(本次未改)
+前端分别加载:快照不可用时计划区仍可显示;SSH 连不上时历史区仍可用快照。历史与子库
+路径以快照为准,SSH 的“最近一次”只作历史参考。
+
+## 5. 现有写路径(本次未改)
| 路径 | 写什么 | 权限 |
| --- | --- | --- |
@@ -171,17 +214,15 @@ ls -1 "$ROOT" | tail
| `MarkBackupScheduleApplied` | 下发摘要回写 | 服务内部 |
| `backuphost.Apply / RunNow` | 远端脚本执行 | 服务内部 |
-本接口没有任何写备份目录、删批次、改 cron 的代码路径。
+本接口与采集器没有写备份目录、删批次、改 cron 的代码路径。
-## 5. 还需单独确认的后端写能力
+## 6. 还需单独确认的后端写能力
-以下均**未实现**,需要单独评审与授权,不能在本次只读闭环里顺手打开:
-
-1. 配额 / 磁盘预留的持久化与执行(当前无字段;页面保留占位并标未知)。
-2. 旧批次保留/删除(按天/按月轮转)与删除前审计、可恢复窗口。
-3. 备份目录迁移/切换(涉及主机 cron 参数与历史文件位置)。
-4. 单库备份/单库恢复(现有 `run` 是整批;单库范围需先证明)。
+1. 配额 / 磁盘预留的持久化与执行(当前无字段)。
+2. 旧批次保留/删除与删除前审计、可恢复窗口。
+3. 备份目录迁移/切换。
+4. 单库备份/单库恢复(现有 run 是整批)。
5. 恢复验证执行(`pg_restore` 演练、校验和、结果留档)。
-6. MANIFEST 修复/重建(当前只如实报 missing/invalid)。
-7. 远程挂载/权限变更的自动化(属部署与主机权限,必须人工批准)。
-8. 写操作的角色细分(目前写路径统一管理员;若要“备份操作员”需另立角色)。
\ No newline at end of file
+6. MANIFEST 修复/重建。
+7. 采集器安装/权限变更自动化(属部署与主机权限,必须人工批准)。
+8. 写操作角色细分(目前统一管理员)。
\ No newline at end of file
diff --git a/internal/appconfig/config.go b/internal/appconfig/config.go
index 91e8afb..6bc09bb 100644
--- a/internal/appconfig/config.go
+++ b/internal/appconfig/config.go
@@ -68,9 +68,10 @@ type Config struct {
BackupHostTarget string
BackupHostScriptDir string
BackupHostRoot string
- // BackupHostReadonlyRoot 是容器内只读挂载的 rds-logical 目录(批次/子库/实测容量)。
+ // BackupHostMetadataPath 是容器内挂载的宿主 metadata.json(单次采集器的原子快照)。
// 留空即"未接线";它与上面的 SSH 计划读回是两条独立通道。
- BackupHostReadonlyRoot string
+ BackupHostMetadataPath string
+ BackupHostMetadataMaxAge time.Duration
BackupHostReadonlyHostPath string
BackupHostReadonlySource string
// 版本记录(「版本记录」页):**匿名只读**远端仓库的提交与 tag。来源留空即"未接线"
@@ -189,6 +190,10 @@ func Load(getenv func(string) string) (Config, error) {
return Config{}, errors.New("LIBRARY_EMBEDDING_DIMENSION must be a positive integer")
}
embeddingDimension := int(embeddingDimension64)
+ metadataMaxAge, err := durationOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_METADATA_MAX_AGE")), 15*time.Minute)
+ if err != nil {
+ return Config{}, errors.New("BACKUP_HOST_METADATA_MAX_AGE must be a positive duration")
+ }
config := Config{
DatabaseURL: getenv("DATABASE_URL"),
AppAddr: valueOrDefault(getenv("APP_ADDR"), ":8080"),
@@ -228,7 +233,8 @@ func Load(getenv func(string) string) (Config, error) {
BackupHostTarget: strings.TrimSpace(getenv("BACKUP_HOST_TARGET")),
BackupHostScriptDir: valueOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_SCRIPT_DIR")), "/opt/weknora-test"),
BackupHostRoot: valueOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_ROOT")), "/srv/kb-backups"),
- BackupHostReadonlyRoot: strings.TrimSpace(getenv("BACKUP_HOST_READONLY_ROOT")),
+ BackupHostMetadataPath: strings.TrimSpace(getenv("BACKUP_HOST_METADATA_PATH")),
+ BackupHostMetadataMaxAge: metadataMaxAge,
BackupHostReadonlyHostPath: strings.TrimSpace(getenv("BACKUP_HOST_READONLY_HOST_PATH")),
BackupHostReadonlySource: strings.TrimSpace(getenv("BACKUP_HOST_READONLY_SOURCE")),
VersionHistoryGiteaBaseURL: strings.TrimSpace(getenv("VERSION_HISTORY_GITEA_BASE_URL")),
@@ -526,19 +532,22 @@ func Load(getenv func(string) string) (Config, error) {
return Config{}, errors.New("TEST_AUTO_REVIEW_POLICY must be one of off, internal, all")
}
config.TestAutoReviewPolicy = string(normalizedPolicy)
- // 只读盘点接线与生产发布开关无关:测试栈也可能要先读通历史批次。
- if config.BackupHostReadonlyRoot != "" && !filepath.IsAbs(config.BackupHostReadonlyRoot) {
- return Config{}, errors.New("BACKUP_HOST_READONLY_ROOT must be an absolute path")
+ // 宿主采集器快照接线与生产发布开关无关:测试栈也要先读通历史批次。
+ if config.BackupHostMetadataPath != "" && !filepath.IsAbs(config.BackupHostMetadataPath) {
+ return Config{}, errors.New("BACKUP_HOST_METADATA_PATH must be an absolute path")
}
if config.BackupHostReadonlyHostPath != "" && !filepath.IsAbs(config.BackupHostReadonlyHostPath) {
return Config{}, errors.New("BACKUP_HOST_READONLY_HOST_PATH must be an absolute path")
}
- if config.BackupHostReadonlyRoot != "" && config.BackupHostReadonlyHostPath == "" {
- return Config{}, errors.New("BACKUP_HOST_READONLY_HOST_PATH is required when read-only root is set")
+ if config.BackupHostMetadataPath != "" && config.BackupHostReadonlyHostPath == "" {
+ return Config{}, errors.New("BACKUP_HOST_READONLY_HOST_PATH is required when metadata path is set")
}
- if config.BackupHostReadonlyRoot == "" &&
+ if config.BackupHostMetadataPath == "" &&
(config.BackupHostReadonlyHostPath != "" || config.BackupHostReadonlySource != "") {
- return Config{}, errors.New("BACKUP_HOST_READONLY_ROOT is required when host path/source is set")
+ return Config{}, errors.New("BACKUP_HOST_METADATA_PATH is required when host path/source is set")
+ }
+ if config.BackupHostMetadataMaxAge <= 0 || config.BackupHostMetadataMaxAge > 24*time.Hour {
+ return Config{}, errors.New("BACKUP_HOST_METADATA_MAX_AGE must be between 1s and 24h")
}
for _, value := range []string{config.BackupHostReadonlyHostPath, config.BackupHostReadonlySource} {
if strings.ContainsAny(value, "\x00\r\n") {
diff --git a/internal/appconfig/config_test.go b/internal/appconfig/config_test.go
index 9eba702..39ffbc6 100644
--- a/internal/appconfig/config_test.go
+++ b/internal/appconfig/config_test.go
@@ -65,25 +65,34 @@ func TestLoadValidatesBackupInventoryMount(t *testing.T) {
}
return Load(func(key string) string { return values[key] })
}
- if _, err := load(map[string]string{"BACKUP_HOST_READONLY_ROOT": "relative/path"}); err == nil {
- t.Fatal("relative read-only root must be rejected")
+ if _, err := load(map[string]string{"BACKUP_HOST_METADATA_PATH": "relative/path"}); err == nil {
+ t.Fatal("relative metadata path must be rejected")
}
- if _, err := load(map[string]string{"BACKUP_HOST_READONLY_ROOT": "/var/lib/knowledge-governance/backup-host/rds-logical"}); err == nil {
- t.Fatal("read-only root without host path must be rejected (copy paths must not be guessed)")
+ if _, err := load(map[string]string{"BACKUP_HOST_METADATA_PATH": "/var/lib/knowledge-governance/backup-host/metadata.json"}); err == nil {
+ t.Fatal("metadata path without host root must be rejected (paths must not be guessed)")
}
if _, err := load(map[string]string{"BACKUP_HOST_READONLY_HOST_PATH": "/srv/kb-backups/rds-logical"}); err == nil {
- t.Fatal("host path without read-only root must be rejected")
+ t.Fatal("host path without metadata path must be rejected")
+ }
+ if _, err := load(map[string]string{
+ "BACKUP_HOST_METADATA_PATH": "/var/lib/knowledge-governance/backup-host/metadata.json",
+ "BACKUP_HOST_READONLY_HOST_PATH": "/srv/kb-backups/rds-logical",
+ "BACKUP_HOST_METADATA_MAX_AGE": "nope",
+ }); err == nil {
+ t.Fatal("invalid metadata max age must be rejected")
}
config, err := load(map[string]string{
- "BACKUP_HOST_READONLY_ROOT": "/var/lib/knowledge-governance/backup-host/rds-logical",
+ "BACKUP_HOST_METADATA_PATH": "/var/lib/knowledge-governance/backup-host/metadata.json",
"BACKUP_HOST_READONLY_HOST_PATH": "/srv/kb-backups/rds-logical",
"BACKUP_HOST_READONLY_SOURCE": "weknora-test:/srv/kb-backups/rds-logical",
+ "BACKUP_HOST_METADATA_MAX_AGE": "5m",
})
if err != nil {
- t.Fatalf("valid inventory mount rejected: %v", err)
+ t.Fatalf("valid inventory snapshot config rejected: %v", err)
}
- if config.BackupHostReadonlyRoot == "" || config.BackupHostReadonlyHostPath == "" || config.BackupHostReadonlySource == "" {
- t.Fatalf("inventory mount fields lost: %#v", config)
+ if config.BackupHostMetadataPath == "" || config.BackupHostReadonlyHostPath == "" ||
+ config.BackupHostReadonlySource == "" || config.BackupHostMetadataMaxAge != 5*time.Minute {
+ t.Fatalf("inventory snapshot fields lost: %#v", config)
}
}
diff --git a/internal/backupinventory/inventory.go b/internal/backupinventory/inventory.go
index e3c0c99..75563a4 100644
--- a/internal/backupinventory/inventory.go
+++ b/internal/backupinventory/inventory.go
@@ -1,9 +1,9 @@
-// Package backupinventory 只读盘点备份执行主机上的 rds-logical 备份目录。
+// Package backupinventory 读取**宿主采集器**产出的备份元数据快照。
//
-// 为什么不是再开一条 SSH 命令:盘点要列全部历史批次、子库目录和实际占盘,
-// 在主机上跑 find/du/df 既扩大远端命令面,也无法证明"读的是这块盘"。这里
-// 只接受一个**只读挂载**进来的目录,平台侧没有写路径;容量用 statfs 量,
-// 并比较挂载根与容器根的文件系统设备号,避免把容器根盘冒充主机磁盘。
+// 为什么不在 API 里遍历备份目录:备份目录通常是 root:root 0700,API 容器用户
+// 没有进入权限;容器里遍历只能得到 permission denied 的部分字节,绝不能把部分
+// 计数当成实际占盘。这里只读宿主进程原子写出的 metadata.json,并校验 schema、
+// 批次路径、主机根、时效与完整性。API 不接触备份目录,也不借用 SSH/容器特权。
package backupinventory
import (
@@ -11,45 +11,32 @@ import (
"encoding/json"
"errors"
"fmt"
- "io"
- "io/fs"
"os"
"path"
- "path/filepath"
"sort"
"strings"
- "syscall"
"time"
)
const (
- defaultMaxBatches = 100
- defaultMaxFiles = 200_000
- defaultMaxManifestBytes = 8 << 20
-
- // Linux statfs 的 ST_RDONLY;syscall 包没有导出这个名字。
- statReadOnly = 0x1
+ SchemaVersion = 1
+ defaultMaxAge = 15 * time.Minute
+ defaultMaxBytes = 16 << 20
+ futureTolerance = 2 * time.Minute
+ measurementLabel = "host_collector"
)
type Config struct {
- // Root 是容器内只读挂载点(如 /var/lib/knowledge-governance/backup-host/rds-logical)。
- // 留空即未接线;页面显示原因,不返回空表冒充"没有备份"。
- Root string
- // HostRoot 是给操作者复制/在主机上执行的路径(如 /srv/kb-backups/rds-logical)。
+ // MetadataPath 是 API 容器内挂载的 metadata.json(宿主采集器原子写出)。
+ MetadataPath string
+ // HostRoot 是宿主上的 rds-logical 绝对路径,用于校验快照里的 root/批次路径。
HostRoot string
- // Source 是展示用的来源,如 weknora-test:/srv/kb-backups/rds-logical。
+ // Source 是展示来源;快照里的 source 非空时以快照为准。
Source string
- // MaxBatches/MaxFiles/MaxManifestBytes 防止一个异常目录把 API 拖死。
- MaxBatches int
- MaxFiles int
- MaxManifestBytes int64
-}
-
-type statFS struct {
- Total uint64
- Free uint64
- Available uint64
- ReadOnly bool
+ // MaxAge 超过即视为陈旧,旧快照的批次与容量一律不使用。
+ MaxAge time.Duration
+ // MaxBytes 防止异常大文件拖死 API。
+ MaxBytes int64
}
type ManifestState string
@@ -60,12 +47,32 @@ const (
ManifestInvalid ManifestState = "invalid"
)
+type MetadataInfo struct {
+ Configured bool `json:"configured"`
+ Present bool `json:"present"`
+ Valid bool `json:"valid"`
+ Fresh bool `json:"fresh"`
+ Complete bool `json:"complete"`
+ Path string `json:"path"`
+ CollectedAt string `json:"collected_at"`
+ AgeSeconds int64 `json:"age_seconds"`
+ MaxAgeSeconds int64 `json:"max_age_seconds"`
+ SchemaVersion int `json:"schema_version"`
+ Generation string `json:"generation"`
+ Host string `json:"host"`
+ CollectorVersion string `json:"collector_version"`
+ Error string `json:"error"`
+}
+
type MountInfo struct {
ContainerRoot string `json:"container_root"`
MountVerified bool `json:"mount_verified"`
LivesOnContainerRoot bool `json:"lives_on_container_root"`
ReadOnly bool `json:"read_only"`
Evidence string `json:"evidence"`
+ MountPoint string `json:"mount_point"`
+ Device string `json:"device"`
+ FSType string `json:"fs_type"`
Error string `json:"error,omitempty"`
}
@@ -86,29 +93,29 @@ type Database struct {
Present bool `json:"present"`
Failed bool `json:"failed"`
InManifest bool `json:"in_manifest"`
- ApparentBytes int64 `json:"apparent_bytes"`
- ActualBytes int64 `json:"actual_bytes"`
- FileCount int `json:"file_count"`
+ ApparentBytes *int64 `json:"apparent_bytes"`
+ ActualBytes *int64 `json:"actual_bytes"`
+ FileCount *int `json:"file_count"`
}
type Batch struct {
- Stamp string `json:"stamp"`
- Path string `json:"path"`
- HostPath string `json:"host_path"`
- ManifestState ManifestState `json:"manifest_state"`
- ManifestPath string `json:"manifest_path"`
- ManifestError string `json:"manifest_error,omitempty"`
- Kind string `json:"kind"`
- CreatedAt string `json:"created_at"`
- StartedAt string `json:"started_at"`
- DurationSeconds int `json:"duration_seconds"`
- ManifestBytes int64 `json:"manifest_total_bytes"`
- ApparentBytes int64 `json:"apparent_bytes"`
- ActualBytes int64 `json:"actual_bytes"`
- FileCount int `json:"file_count"`
- SizesComplete bool `json:"sizes_complete"`
- SizesError string `json:"sizes_error,omitempty"`
- Databases []Database `json:"databases"`
+ Stamp string `json:"stamp"`
+ Path string `json:"path"`
+ HostPath string `json:"host_path"`
+ ManifestState ManifestState `json:"manifest_state"`
+ ManifestPath string `json:"manifest_path"`
+ ManifestError string `json:"manifest_error,omitempty"`
+ Kind string `json:"kind"`
+ CreatedAt string `json:"created_at"`
+ StartedAt string `json:"started_at"`
+ DurationSeconds int `json:"duration_seconds"`
+ ManifestTotalBytes *int64 `json:"manifest_total_bytes"`
+ ApparentBytes *int64 `json:"apparent_bytes"`
+ ActualBytes *int64 `json:"actual_bytes"`
+ FileCount *int `json:"file_count"`
+ SizesComplete bool `json:"sizes_complete"`
+ SizesError string `json:"sizes_error,omitempty"`
+ Databases []Database `json:"databases"`
}
type Skipped struct {
@@ -119,152 +126,236 @@ type Skipped struct {
type Totals struct {
BatchCount int `json:"batch_count"`
DatabaseCount int `json:"database_count"`
- ApparentBytes int64 `json:"apparent_bytes"`
- ActualBytes int64 `json:"actual_bytes"`
+ ApparentBytes *int64 `json:"apparent_bytes"`
+ ActualBytes *int64 `json:"actual_bytes"`
LatestStamp string `json:"latest_stamp"`
- LatestActualBytes int64 `json:"latest_actual_bytes"`
+ LatestActualBytes *int64 `json:"latest_actual_bytes"`
+ Complete bool `json:"complete"`
}
type Snapshot struct {
- Wired bool `json:"wired"`
- Root string `json:"root"`
- HostRoot string `json:"host_root"`
- Source string `json:"source"`
- ObservedAt string `json:"observed_at"`
- Error string `json:"error,omitempty"`
- Mount MountInfo `json:"mount"`
- Capacity Capacity `json:"capacity"`
- Batches []Batch `json:"batches"`
- Totals Totals `json:"totals"`
- IncompleteCount int `json:"incomplete_count"`
- Skipped []Skipped `json:"skipped"`
- Truncated bool `json:"truncated"`
+ Wired bool `json:"wired"`
+ Metadata MetadataInfo `json:"metadata"`
+ Root string `json:"root"`
+ HostRoot string `json:"host_root"`
+ Source string `json:"source"`
+ ObservedAt string `json:"observed_at"`
+ Error string `json:"error,omitempty"`
+ Measurement string `json:"measurement"`
+ Mount MountInfo `json:"mount"`
+ Capacity Capacity `json:"capacity"`
+ Batches []Batch `json:"batches"`
+ Totals Totals `json:"totals"`
+ IncompleteCount int `json:"incomplete_count"`
+ Skipped []Skipped `json:"skipped"`
+ Truncated bool `json:"truncated"`
}
type Reader struct {
config Config
now func() time.Time
- statfs func(string) (statFS, error)
- device func(string) (uint64, error)
+ read func(string) ([]byte, error)
}
func New(config Config) *Reader {
- if config.MaxBatches <= 0 {
- config.MaxBatches = defaultMaxBatches
+ if config.MaxAge <= 0 {
+ config.MaxAge = defaultMaxAge
}
- if config.MaxFiles <= 0 {
- config.MaxFiles = defaultMaxFiles
+ if config.MaxBytes <= 0 {
+ config.MaxBytes = defaultMaxBytes
}
- if config.MaxManifestBytes <= 0 {
- config.MaxManifestBytes = defaultMaxManifestBytes
- }
- return &Reader{config: config, now: time.Now, statfs: defaultStatFS, device: defaultDevice}
+ return &Reader{config: config, now: time.Now, read: os.ReadFile}
}
func (r *Reader) Available() bool {
- return r != nil && strings.TrimSpace(r.config.Root) != ""
+ return r != nil && strings.TrimSpace(r.config.MetadataPath) != ""
}
-// Snapshot 永远返回可投影的结构:未接线、目录不可读、清单损坏都写在字段里,
-// 由页面区分,不把任一种情况变成 500 或"没有备份"。
+// ---- 宿主快照文件(collector 的输出;只读、字段可验证) ----
+
+type metadata struct {
+ SchemaVersion int `json:"schema_version"`
+ CollectorVersion string `json:"collector_version"`
+ Generation string `json:"generation"`
+ CollectedAt string `json:"collected_at"`
+ Host string `json:"host"`
+ Source string `json:"source"`
+ Root string `json:"root"`
+ Complete bool `json:"complete"`
+ Errors []string `json:"errors"`
+ Filesystem metadataFilesystem `json:"filesystem"`
+ IncompleteCount int `json:"incomplete_count"`
+ Skipped []Skipped `json:"skipped"`
+ Truncated bool `json:"truncated"`
+ Batches []metadataBatch `json:"batches"`
+}
+
+type metadataFilesystem struct {
+ MountPoint string `json:"mount_point"`
+ MountSource string `json:"mount_source"`
+ FSType string `json:"fs_type"`
+ ReadOnly bool `json:"read_only"`
+ TotalBytes int64 `json:"total_bytes"`
+ FreeBytes int64 `json:"free_bytes"`
+ AvailableBytes int64 `json:"available_bytes"`
+}
+
+type metadataBatch struct {
+ Stamp string `json:"stamp"`
+ Path string `json:"path"`
+ ManifestState string `json:"manifest_state"`
+ ManifestError string `json:"manifest_error"`
+ Kind string `json:"kind"`
+ CreatedAt string `json:"created_at"`
+ StartedAt string `json:"started_at"`
+ DurationSeconds int `json:"duration_seconds"`
+ ManifestTotalBytes *int64 `json:"manifest_total_bytes"`
+ Complete bool `json:"complete"`
+ Errors []string `json:"errors"`
+ ApparentBytes *int64 `json:"apparent_bytes"`
+ ActualBytes *int64 `json:"actual_bytes"`
+ FileCount *int `json:"file_count"`
+ Databases []metadataDatabase `json:"databases"`
+}
+
+type metadataDatabase struct {
+ Name string `json:"name"`
+ DirName string `json:"dir_name"`
+ Path string `json:"path"`
+ Present bool `json:"present"`
+ Failed bool `json:"failed"`
+ InManifest bool `json:"in_manifest"`
+ ApparentBytes *int64 `json:"apparent_bytes"`
+ ActualBytes *int64 `json:"actual_bytes"`
+ FileCount *int `json:"file_count"`
+}
+
+// Snapshot 只返回可验证的事实:陈旧/缺失/不完整一律不给批次字节与容量。
func (r *Reader) Snapshot(ctx context.Context) Snapshot {
snapshot := Snapshot{
- Wired: r.Available(),
- HostRoot: r.config.HostRoot,
- Source: r.config.Source,
- Batches: []Batch{},
- Skipped: []Skipped{},
+ Wired: r.Available(),
+ Measurement: measurementLabel,
+ Batches: []Batch{},
+ Skipped: []Skipped{},
+ ObservedAt: r.observedAt(),
+ Metadata: MetadataInfo{
+ Configured: r.Available(),
+ MaxAgeSeconds: int64(r.config.MaxAge / time.Second),
+ },
}
if r == nil || !r.Available() {
- snapshot.Error = "只读盘点未接线(BACKUP_HOST_READONLY_ROOT 未设置)"
- snapshot.ObservedAt = r.observedAt()
+ snapshot.Metadata.Error = "元数据快照未接线(BACKUP_HOST_METADATA_PATH 未设置)"
+ snapshot.Error = snapshot.Metadata.Error
return snapshot
}
- snapshot.ObservedAt = r.observedAt()
- snapshot.Root = filepath.Clean(r.config.Root)
- resolved, err := filepath.EvalSymlinks(snapshot.Root)
+ snapshot.Metadata.Path = r.config.MetadataPath
+ snapshot.HostRoot = r.config.HostRoot
+ snapshot.Source = r.config.Source
+ if ctx.Err() != nil {
+ snapshot.Metadata.Error = "读取被取消:" + ctx.Err().Error()
+ snapshot.Error = snapshot.Metadata.Error
+ return snapshot
+ }
+ raw, err := r.read(r.config.MetadataPath)
if err != nil {
- snapshot.Error = "只读挂载不可读:" + err.Error()
- snapshot.Capacity.Error = snapshot.Error
- return snapshot
- }
- info, err := os.Stat(resolved)
- if err != nil {
- snapshot.Error = "只读挂载不可读:" + err.Error()
- snapshot.Capacity.Error = snapshot.Error
- return snapshot
- }
- if !info.IsDir() {
- snapshot.Error = "只读挂载不是目录:" + resolved
- snapshot.Capacity.Error = snapshot.Error
- return snapshot
- }
- snapshot.Root = resolved
- snapshot.Mount = r.mountInfo(resolved)
- if !snapshot.Mount.MountVerified {
- reason := snapshot.Mount.Evidence
- if snapshot.Mount.Error != "" {
- reason = snapshot.Mount.Error
+ if errors.Is(err, os.ErrNotExist) {
+ snapshot.Metadata.Error = "宿主元数据快照不存在:需要先运行 collect_backup_metadata.py"
+ } else {
+ snapshot.Metadata.Error = "宿主元数据快照不可读:" + err.Error()
}
- snapshot.Capacity = Capacity{Error: "无法证明只读目录位于独立挂载:" + reason}
+ snapshot.Error = snapshot.Metadata.Error
+ return snapshot
+ }
+ snapshot.Metadata.Present = true
+ if int64(len(raw)) > r.config.MaxBytes {
+ return invalid(snapshot, fmt.Sprintf("元数据快照超过 %d 字节读取上限", r.config.MaxBytes))
+ }
+ var file metadata
+ if err := json.Unmarshal(raw, &file); err != nil {
+ return invalid(snapshot, "元数据快照无法解析:"+err.Error())
+ }
+ snapshot.Metadata.SchemaVersion = file.SchemaVersion
+ snapshot.Metadata.Generation = file.Generation
+ snapshot.Metadata.Host = file.Host
+ snapshot.Metadata.CollectorVersion = file.CollectorVersion
+ snapshot.Metadata.CollectedAt = file.CollectedAt
+ snapshot.Metadata.Complete = file.Complete
+ if file.Source != "" {
+ snapshot.Source = file.Source
+ }
+ if file.SchemaVersion != SchemaVersion {
+ return invalid(snapshot, fmt.Sprintf("元数据 schema_version=%d,API 只支持 %d", file.SchemaVersion, SchemaVersion))
+ }
+ collectedAt, err := time.Parse(time.RFC3339, file.CollectedAt)
+ if err != nil {
+ return invalid(snapshot, "元数据 collected_at 非法:"+file.CollectedAt)
+ }
+ age := r.now().UTC().Sub(collectedAt.UTC())
+ if age < -futureTolerance {
+ return invalid(snapshot, "元数据 collected_at 在未来,拒绝使用")
+ }
+ snapshot.Metadata.AgeSeconds = int64(age / time.Second)
+ if age > r.config.MaxAge {
+ snapshot.Metadata.Fresh = false
+ return invalid(snapshot, fmt.Sprintf("元数据已陈旧:采集于 %s,超过 %s", file.CollectedAt, r.config.MaxAge))
+ }
+ snapshot.Metadata.Fresh = true
+ if strings.TrimSpace(r.config.HostRoot) == "" {
+ return invalid(snapshot, "宿主根路径未配置:无法校验批次路径")
+ }
+ expectedRoot := path.Clean(strings.TrimSpace(r.config.HostRoot))
+ snapshot.HostRoot = expectedRoot
+ root := strings.TrimSpace(file.Root)
+ if !path.IsAbs(root) || path.Clean(root) != root {
+ return invalid(snapshot, "元数据 root 不是规范绝对路径:"+root)
+ }
+ if root != expectedRoot {
+ return invalid(snapshot, fmt.Sprintf("元数据 root=%s 与配置 %s 不一致", root, expectedRoot))
+ }
+ snapshot.Root = root
+ if err := validateBatches(root, file.Batches); err != nil {
+ return invalid(snapshot, err.Error())
+ }
+ snapshot.Metadata.Valid = true
+ snapshot.IncompleteCount = file.IncompleteCount
+ snapshot.Skipped = append(snapshot.Skipped, file.Skipped...)
+ snapshot.Truncated = file.Truncated
+ snapshot.Mount = MountInfo{
+ Evidence: "宿主采集器上报:" + file.Host,
+ MountPoint: file.Filesystem.MountPoint,
+ Device: file.Filesystem.MountSource,
+ FSType: file.Filesystem.FSType,
+ ReadOnly: file.Filesystem.ReadOnly,
+ }
+ if file.Filesystem.MountPoint == "" || !path.IsAbs(file.Filesystem.MountPoint) {
+ snapshot.Mount.Error = "宿主采集器没有给出文件系统挂载点"
+ } else if root != file.Filesystem.MountPoint && !strings.HasPrefix(root, strings.TrimSuffix(file.Filesystem.MountPoint, "/")+"/") {
+ snapshot.Mount.Error = "批次根不在采集器上报的挂载点下"
} else {
- snapshot.Capacity = r.capacity(resolved)
+ snapshot.Mount.MountVerified = true
+ snapshot.Mount.Evidence = fmt.Sprintf("宿主采集器:%s 挂在 %s(%s),API 不遍历备份目录",
+ file.Filesystem.MountSource, file.Filesystem.MountPoint, file.Filesystem.FSType)
}
- entries, err := os.ReadDir(resolved)
- if err != nil {
- snapshot.Error = "无法列出备份目录:" + err.Error()
+ // 快照不完整/截断:路径与清单状态可展示,但所有字节与容量一律未知,
+ // 绝不用部分 counts 或完整批次的局部字节拼总量。
+ complete := file.Complete && !file.Truncated && snapshot.Mount.MountVerified && allBatchesComplete(file.Batches)
+ if !complete {
+ snapshot.Metadata.Complete = false
+ snapshot.Metadata.Error = incompleteReason(file)
+ snapshot.Capacity = Capacity{Error: "采集快照不完整:容量与占盘未知"}
+ snapshot.Mount.MountVerified = false
+ snapshot.Mount.Error = "采集快照不完整,不能据此判定文件系统与占盘"
+ snapshot.Batches = projectBatches(root, file.Batches, false)
+ snapshot.Totals = totals(snapshot.Batches, false)
+ snapshot.Error = ""
return snapshot
}
- dirs := make([]string, 0, len(entries))
- for _, entry := range entries {
- name := entry.Name()
- if strings.HasSuffix(name, ".incomplete") {
- snapshot.IncompleteCount++
- continue
- }
- if name == "" || strings.ContainsAny(name, `/\`) {
- snapshot.Skipped = append(snapshot.Skipped, Skipped{Name: name, Reason: "目录名不合法"})
- continue
- }
- if entry.Type()&os.ModeSymlink != 0 {
- snapshot.Skipped = append(snapshot.Skipped, Skipped{Name: name, Reason: "符号链接不跟随"})
- continue
- }
- if !entry.IsDir() {
- snapshot.Skipped = append(snapshot.Skipped, Skipped{Name: name, Reason: "不是批次目录"})
- continue
- }
- dirs = append(dirs, name)
- }
- sort.Sort(sort.Reverse(sort.StringSlice(dirs)))
- if len(dirs) > r.config.MaxBatches {
- dirs = dirs[:r.config.MaxBatches]
- snapshot.Truncated = true
- }
- for _, name := range dirs {
- if ctx.Err() != nil {
- snapshot.Error = "读取被取消:" + ctx.Err().Error()
- break
- }
- batch, reason, walkTruncated := r.readBatch(ctx, resolved, name)
- if reason != "" {
- snapshot.Skipped = append(snapshot.Skipped, Skipped{Name: name, Reason: reason})
- continue
- }
- if walkTruncated {
- snapshot.Truncated = true
- }
- snapshot.Batches = append(snapshot.Batches, batch)
- snapshot.Totals.ApparentBytes += batch.ApparentBytes
- snapshot.Totals.ActualBytes += batch.ActualBytes
- snapshot.Totals.DatabaseCount += len(batch.Databases)
- }
- snapshot.Totals.BatchCount = len(snapshot.Batches)
- if len(snapshot.Batches) > 0 {
- snapshot.Totals.LatestStamp = snapshot.Batches[0].Stamp
- snapshot.Totals.LatestActualBytes = snapshot.Batches[0].ActualBytes
- }
+
+ snapshot.Metadata.Complete = true
+ snapshot.Capacity = projectCapacity(file.Filesystem)
+ snapshot.Batches = projectBatches(root, file.Batches, true)
+ snapshot.Totals = totals(snapshot.Batches, true)
return snapshot
}
@@ -275,318 +366,197 @@ func (r *Reader) observedAt() string {
return r.now().UTC().Format(time.RFC3339)
}
-func (r *Reader) mountInfo(root string) MountInfo {
- info := MountInfo{ContainerRoot: "/"}
- rootDevice, err := r.device(root)
- if err != nil {
- info.Error = "无法读取挂载设备号:" + err.Error()
- info.Evidence = "无法证明挂载与容器根盘分离"
- return info
- }
- containerDevice, err := r.device("/")
- if err != nil {
- info.Error = "无法读取容器根盘设备号:" + err.Error()
- info.Evidence = "无法证明挂载与容器根盘分离"
- return info
- }
- info.LivesOnContainerRoot = rootDevice == containerDevice
- info.MountVerified = !info.LivesOnContainerRoot
- if stats, statErr := r.statfs(root); statErr == nil {
- info.ReadOnly = stats.ReadOnly
- }
- if info.MountVerified {
- info.Evidence = fmt.Sprintf("挂载设备 %d 与容器根盘 %d 不同:容量按挂载文件系统计量", rootDevice, containerDevice)
- } else {
- info.Evidence = fmt.Sprintf("挂载设备与容器根盘相同(%d):容量不代表备份主机磁盘", rootDevice)
- }
- return info
+func invalid(snapshot Snapshot, reason string) Snapshot {
+ snapshot.Metadata.Valid = false
+ snapshot.Metadata.Complete = false
+ snapshot.Metadata.Error = reason
+ snapshot.Error = reason
+ snapshot.Batches = []Batch{}
+ snapshot.Capacity = Capacity{Error: reason}
+ snapshot.Totals = Totals{}
+ return snapshot
}
-func (r *Reader) capacity(root string) Capacity {
- stats, err := r.statfs(root)
- if err != nil {
- return Capacity{Error: "无法读取文件系统容量:" + err.Error()}
+func incompleteReason(file metadata) string {
+ if len(file.Errors) > 0 {
+ return "采集不完整:" + strings.Join(limit(file.Errors, 3), ";")
}
- used := uint64(0)
- if stats.Total > stats.Free {
- used = stats.Total - stats.Free
+ for _, batch := range file.Batches {
+ if len(batch.Errors) > 0 {
+ return "采集不完整:" + strings.Join(limit(batch.Errors, 3), ";")
+ }
+ }
+ return "采集不完整:存在无法遍历/统计的目录,占盘与容量未知"
+}
+
+func limit(items []string, n int) []string {
+ if len(items) <= n {
+ return items
+ }
+ return items[:n]
+}
+
+func allBatchesComplete(batches []metadataBatch) bool {
+ for _, batch := range batches {
+ if !batch.Complete || batch.ActualBytes == nil || batch.ApparentBytes == nil || batch.FileCount == nil {
+ return false
+ }
+ for _, database := range batch.Databases {
+ if database.ActualBytes == nil || database.ApparentBytes == nil || database.FileCount == nil {
+ return false
+ }
+ }
+ }
+ return true
+}
+
+// 校验的是"快照里的路径能否被安全地当成这台主机的批次/子库":
+// 根必须精确匹配配置,批次必须精确等于 root/,子库必须精确等于
+// batch/.dir,且不允许重复、分隔符、.incomplete。
+func validateBatches(root string, batches []metadataBatch) error {
+ seen := map[string]bool{}
+ for _, batch := range batches {
+ stamp := strings.TrimSpace(batch.Stamp)
+ if err := safeSegment(stamp); err != nil {
+ return fmt.Errorf("批次名不合法:%q(%v)", stamp, err)
+ }
+ if strings.HasSuffix(stamp, ".incomplete") {
+ return fmt.Errorf("批次 %q 是未完成目录,不应进入快照", stamp)
+ }
+ if seen[stamp] {
+ return fmt.Errorf("批次 %q 重复", stamp)
+ }
+ seen[stamp] = true
+ expected := path.Join(root, stamp)
+ if batch.Path != expected || !path.IsAbs(batch.Path) {
+ return fmt.Errorf("批次 %q 路径 %q 不等于 %q", stamp, batch.Path, expected)
+ }
+ switch ManifestState(batch.ManifestState) {
+ case ManifestOK, ManifestMissing, ManifestInvalid:
+ default:
+ return fmt.Errorf("批次 %q 的 manifest_state 不认识:%q", stamp, batch.ManifestState)
+ }
+ databaseSeen := map[string]bool{}
+ for _, database := range batch.Databases {
+ name := strings.TrimSpace(database.Name)
+ if err := safeSegment(name); err != nil {
+ return fmt.Errorf("批次 %q 子库名不合法:%q", stamp, name)
+ }
+ if databaseSeen[name] {
+ return fmt.Errorf("批次 %q 子库 %q 重复", stamp, name)
+ }
+ databaseSeen[name] = true
+ expectedDir := path.Join(expected, name+".dir")
+ if database.DirName != name+".dir" || database.Path != expectedDir || !path.IsAbs(database.Path) {
+ return fmt.Errorf("批次 %q 子库 %q 路径不合法:%q", stamp, name, database.Path)
+ }
+ }
+ }
+ return nil
+}
+
+func safeSegment(value string) error {
+ if value == "" || value == "." || value == ".." {
+ return errors.New("空值或相对路径")
+ }
+ for _, r := range value {
+ if r == '/' || r == '\\' || r == 0 || r == '\n' || r == '\r' {
+ return errors.New("包含路径分隔符或控制字符")
+ }
+ }
+ return nil
+}
+
+func projectBatches(root string, batches []metadataBatch, complete bool) []Batch {
+ result := make([]Batch, 0, len(batches))
+ for _, batch := range batches {
+ item := Batch{
+ Stamp: batch.Stamp,
+ Path: path.Join(root, batch.Stamp),
+ HostPath: path.Join(root, batch.Stamp),
+ ManifestState: ManifestState(batch.ManifestState),
+ ManifestPath: path.Join(root, batch.Stamp, "MANIFEST.json"),
+ ManifestError: batch.ManifestError,
+ Kind: batch.Kind,
+ CreatedAt: batch.CreatedAt,
+ StartedAt: batch.StartedAt,
+ DurationSeconds: batch.DurationSeconds,
+ SizesComplete: complete && batch.Complete,
+ Databases: []Database{},
+ }
+ if complete && batch.Complete {
+ item.ManifestTotalBytes = batch.ManifestTotalBytes
+ item.ApparentBytes = batch.ApparentBytes
+ item.ActualBytes = batch.ActualBytes
+ item.FileCount = batch.FileCount
+ }
+ for _, database := range batch.Databases {
+ entry := Database{
+ Name: database.Name,
+ DirName: database.DirName,
+ Path: path.Join(root, batch.Stamp, database.DirName),
+ HostPath: path.Join(root, batch.Stamp, database.DirName),
+ Present: database.Present,
+ Failed: database.Failed,
+ InManifest: database.InManifest,
+ }
+ if complete && batch.Complete {
+ entry.ApparentBytes = database.ApparentBytes
+ entry.ActualBytes = database.ActualBytes
+ entry.FileCount = database.FileCount
+ }
+ item.Databases = append(item.Databases, entry)
+ }
+ if !item.SizesComplete {
+ item.SizesError = "宿主采集器该项不完整,占盘未知"
+ }
+ result = append(result, item)
+ }
+ sort.Slice(result, func(i, j int) bool { return result[i].Stamp > result[j].Stamp })
+ return result
+}
+
+func totals(batches []Batch, complete bool) Totals {
+ result := Totals{BatchCount: len(batches), Complete: complete}
+ if len(batches) > 0 {
+ result.LatestStamp = batches[0].Stamp
+ }
+ for _, batch := range batches {
+ result.DatabaseCount += len(batch.Databases)
+ }
+ if !complete {
+ return result
+ }
+ var apparent, actual int64
+ for _, batch := range batches {
+ if batch.ApparentBytes != nil {
+ apparent += *batch.ApparentBytes
+ }
+ if batch.ActualBytes != nil {
+ actual += *batch.ActualBytes
+ }
+ }
+ result.ApparentBytes = &apparent
+ result.ActualBytes = &actual
+ if len(batches) > 0 {
+ result.LatestActualBytes = batches[0].ActualBytes
+ }
+ return result
+}
+
+func projectCapacity(filesystem metadataFilesystem) Capacity {
+ if filesystem.TotalBytes <= 0 {
+ return Capacity{Error: "宿主采集器没有给出文件系统容量"}
+ }
+ used := filesystem.TotalBytes - filesystem.FreeBytes
+ if used < 0 {
+ used = 0
}
return Capacity{
Measured: true,
- TotalBytes: int64(stats.Total),
- FreeBytes: int64(stats.Free),
- AvailableBytes: int64(stats.Available),
- UsedBytes: int64(used),
+ TotalBytes: filesystem.TotalBytes,
+ FreeBytes: filesystem.FreeBytes,
+ AvailableBytes: filesystem.AvailableBytes,
+ UsedBytes: used,
}
}
-
-type manifest struct {
- Kind string `json:"kind"`
- CreatedAt string `json:"created_at"`
- StartedAt string `json:"started_at"`
- DurationSeconds int `json:"duration_seconds"`
- Databases []string `json:"databases"`
- FailedDatabases []string `json:"failed_databases"`
- TotalBytes int64 `json:"total_bytes"`
- Files []struct {
- File string `json:"file"`
- Bytes int64 `json:"bytes"`
- } `json:"files"`
-}
-
-type sizes struct {
- apparent int64
- actual int64
- files int
-}
-
-func (value *sizes) add(other sizes) {
- value.apparent += other.apparent
- value.actual += other.actual
- value.files += other.files
-}
-
-func (r *Reader) readBatch(ctx context.Context, root, name string) (Batch, string, bool) {
- fullPath := filepath.Join(root, name)
- resolved, err := filepath.EvalSymlinks(fullPath)
- if err != nil {
- return Batch{}, "无法解析批次目录:" + err.Error(), false
- }
- if !within(root, resolved) {
- return Batch{}, "批次目录指向只读挂载之外", false
- }
- batch := Batch{
- Stamp: name,
- Path: resolved,
- HostPath: joinHostPath(r.config.HostRoot, name),
- ManifestPath: filepath.Join(resolved, "MANIFEST.json"),
- ManifestState: ManifestMissing,
- Databases: []Database{},
- SizesComplete: true,
- }
-
- var parsed manifest
- state, manifestErr := readManifest(batch.ManifestPath, r.config.MaxManifestBytes, &parsed)
- batch.ManifestState = state
- batch.ManifestError = manifestErr
- if state == ManifestOK {
- batch.Kind = parsed.Kind
- batch.CreatedAt = parsed.CreatedAt
- batch.StartedAt = parsed.StartedAt
- batch.DurationSeconds = parsed.DurationSeconds
- batch.ManifestBytes = parsed.TotalBytes
- }
-
- walked, byTop, walkErr, truncated := r.walkBatch(ctx, resolved)
- batch.ApparentBytes = walked.apparent
- batch.ActualBytes = walked.actual
- batch.FileCount = walked.files
- if walkErr != nil {
- batch.SizesComplete = false
- batch.SizesError = walkErr.Error()
- }
- if state == ManifestOK && parsed.TotalBytes > 0 {
- batch.ApparentBytes = parsed.TotalBytes
- }
-
- manifestSizes := map[string]sizes{}
- if state == ManifestOK {
- for _, file := range parsed.Files {
- clean := path.Clean(filepath.ToSlash(file.File))
- if clean == "." || strings.HasPrefix(clean, "../") || path.IsAbs(clean) {
- continue
- }
- top := strings.SplitN(clean, "/", 2)[0]
- if !strings.HasSuffix(top, ".dir") {
- continue
- }
- entry := manifestSizes[top]
- entry.apparent += file.Bytes
- entry.files++
- manifestSizes[top] = entry
- }
- }
-
- seen := map[string]bool{}
- failed := map[string]bool{}
- for _, db := range parsed.FailedDatabases {
- failed[db] = true
- }
- appendDatabase := func(db string) {
- if db == "" || seen[db] {
- return
- }
- seen[db] = true
- dirName := db + ".dir"
- containerDir := filepath.Join(resolved, dirName)
- info, statErr := os.Stat(containerDir)
- present := statErr == nil && info.IsDir()
- apparent := sizes{}
- if entry, ok := manifestSizes[dirName]; ok {
- apparent = entry
- } else if walkedEntry, ok := byTop[dirName]; ok {
- apparent = walkedEntry
- }
- batch.Databases = append(batch.Databases, Database{
- Name: db,
- DirName: dirName,
- Path: containerDir,
- HostPath: joinHostPath(batch.HostPath, dirName),
- Present: present,
- Failed: failed[db],
- InManifest: contains(parsed.Databases, db),
- ApparentBytes: apparent.apparent,
- ActualBytes: byTop[dirName].actual,
- FileCount: apparent.files,
- })
- }
- for _, db := range parsed.Databases {
- appendDatabase(db)
- }
- dirNames := make([]string, 0, len(byTop))
- for top := range byTop {
- if strings.HasSuffix(top, ".dir") {
- dirNames = append(dirNames, top)
- }
- }
- sort.Strings(dirNames)
- for _, top := range dirNames {
- appendDatabase(strings.TrimSuffix(top, ".dir"))
- }
- return batch, "", truncated
-}
-
-func (r *Reader) walkBatch(ctx context.Context, batchPath string) (sizes, map[string]sizes, error, bool) {
- total := sizes{}
- byTop := map[string]sizes{}
- scanned := 0
- truncated := false
- err := filepath.WalkDir(batchPath, func(current string, entry fs.DirEntry, walkErr error) error {
- if ctx.Err() != nil {
- return ctx.Err()
- }
- if walkErr != nil {
- return walkErr
- }
- if current == batchPath {
- return nil
- }
- if entry.Type()&os.ModeSymlink != 0 {
- if entry.IsDir() {
- return filepath.SkipDir
- }
- return nil
- }
- if entry.IsDir() {
- return nil
- }
- if scanned >= r.config.MaxFiles {
- truncated = true
- return errStopWalk
- }
- info, err := entry.Info()
- if err != nil {
- return nil
- }
- relative, err := filepath.Rel(batchPath, current)
- if err != nil {
- return nil
- }
- top := strings.SplitN(filepath.ToSlash(relative), "/", 2)[0]
- fileSize := sizes{apparent: info.Size(), actual: actualBytes(info), files: 1}
- total.add(fileSize)
- entrySizes := byTop[top]
- entrySizes.add(fileSize)
- byTop[top] = entrySizes
- scanned++
- return nil
- })
- if errors.Is(err, errStopWalk) {
- err = nil
- }
- if err != nil {
- return total, byTop, err, truncated
- }
- return total, byTop, nil, truncated
-}
-
-var errStopWalk = errors.New("file scan limit reached")
-
-func readManifest(filename string, maxBytes int64, parsed *manifest) (ManifestState, string) {
- file, err := os.Open(filename)
- if err != nil {
- if os.IsNotExist(err) {
- return ManifestMissing, ""
- }
- return ManifestInvalid, err.Error()
- }
- defer file.Close()
- raw, err := io.ReadAll(io.LimitReader(file, maxBytes+1))
- if err != nil {
- return ManifestInvalid, err.Error()
- }
- if int64(len(raw)) > maxBytes {
- return ManifestInvalid, fmt.Sprintf("清单超过 %d 字节读取上限", maxBytes)
- }
- if err := json.Unmarshal(raw, parsed); err != nil {
- return ManifestInvalid, "清单无法解析:" + err.Error()
- }
- return ManifestOK, ""
-}
-
-func within(root, target string) bool {
- relative, err := filepath.Rel(root, target)
- if err != nil {
- return false
- }
- return relative != ".." && !strings.HasPrefix(relative, ".."+string(os.PathSeparator))
-}
-
-func joinHostPath(root, name string) string {
- if strings.TrimSpace(root) == "" {
- return ""
- }
- return path.Join(filepath.ToSlash(root), name)
-}
-
-func contains(list []string, value string) bool {
- for _, item := range list {
- if item == value {
- return true
- }
- }
- return false
-}
-
-func actualBytes(info fs.FileInfo) int64 {
- if stat, ok := info.Sys().(*syscall.Stat_t); ok {
- return int64(stat.Blocks) * 512
- }
- return info.Size()
-}
-
-func defaultStatFS(root string) (statFS, error) {
- var stats syscall.Statfs_t
- if err := syscall.Statfs(root, &stats); err != nil {
- return statFS{}, err
- }
- blockSize := uint64(stats.Bsize)
- return statFS{
- Total: stats.Blocks * blockSize,
- Free: stats.Bfree * blockSize,
- Available: stats.Bavail * blockSize,
- ReadOnly: stats.Flags&statReadOnly != 0,
- }, nil
-}
-
-func defaultDevice(root string) (uint64, error) {
- info, err := os.Stat(root)
- if err != nil {
- return 0, err
- }
- stat, ok := info.Sys().(*syscall.Stat_t)
- if !ok {
- return 0, fmt.Errorf("无法读取 %s 的设备号", root)
- }
- return uint64(stat.Dev), nil
-}
diff --git a/internal/backupinventory/inventory_test.go b/internal/backupinventory/inventory_test.go
index 6fa3cc1..216f5d2 100644
--- a/internal/backupinventory/inventory_test.go
+++ b/internal/backupinventory/inventory_test.go
@@ -2,152 +2,253 @@ package backupinventory
import (
"context"
+ "encoding/json"
"os"
+ "os/exec"
"path/filepath"
"strings"
- "syscall"
"testing"
+ "time"
)
-func writeFile(t *testing.T, filename string, content string) {
- t.Helper()
- if err := os.MkdirAll(filepath.Dir(filename), 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filename, []byte(content), 0o644); err != nil {
- t.Fatal(err)
+const hostRoot = "/srv/kb-backups/rds-logical"
+
+func int64p(value int64) *int64 { return &value }
+func intp(value int) *int { return &value }
+
+func validMetadata() metadata {
+ latest := hostRoot + "/20261118T193001Z"
+ broken := hostRoot + "/20261117T193001Z"
+ without := hostRoot + "/20261116T193001Z"
+ return metadata{
+ SchemaVersion: SchemaVersion,
+ CollectorVersion: "backup-metadata/1",
+ Generation: "20261120T010000Z-abc123",
+ CollectedAt: "2026-11-20T01:00:00Z",
+ Host: "weknora-test",
+ Source: "weknora-test:" + hostRoot,
+ Root: hostRoot,
+ Complete: true,
+ Errors: []string{},
+ Filesystem: metadataFilesystem{
+ MountPoint: "/srv/kb-backups",
+ MountSource: "/dev/sdb1",
+ FSType: "ext4",
+ ReadOnly: false,
+ TotalBytes: 1000,
+ FreeBytes: 400,
+ AvailableBytes: 350,
+ },
+ IncompleteCount: 1,
+ Skipped: []Skipped{{Name: "notes.txt", Reason: "不是批次目录"}},
+ Batches: []metadataBatch{
+ {
+ Stamp: "20261118T193001Z",
+ Path: latest,
+ ManifestState: "ok",
+ Kind: "rds-logical-backup",
+ CreatedAt: "20261118T193001Z",
+ StartedAt: "20261118T192908Z",
+ DurationSeconds: 53,
+ ManifestTotalBytes: int64p(300),
+ Complete: true,
+ ApparentBytes: int64p(300),
+ ActualBytes: int64p(4096),
+ FileCount: intp(3),
+ Databases: []metadataDatabase{
+ {
+ Name: "weknora_v090prod", DirName: "weknora_v090prod.dir",
+ Path: latest + "/weknora_v090prod.dir", Present: true, InManifest: true,
+ ApparentBytes: int64p(250), ActualBytes: int64p(4096), FileCount: intp(2),
+ },
+ {
+ Name: "weknora_test", DirName: "weknora_test.dir",
+ Path: latest + "/weknora_test.dir", Present: true, InManifest: true, Failed: true,
+ ApparentBytes: int64p(50), ActualBytes: int64p(0), FileCount: intp(1),
+ },
+ },
+ },
+ {
+ Stamp: "20261117T193001Z",
+ Path: broken,
+ ManifestState: "invalid", ManifestError: "清单无法解析:unexpected end",
+ Complete: true, ApparentBytes: int64p(20), ActualBytes: int64p(2048), FileCount: intp(1),
+ Databases: []metadataDatabase{{
+ Name: "weknora_prod", DirName: "weknora_prod.dir",
+ Path: broken + "/weknora_prod.dir", Present: true,
+ ApparentBytes: int64p(20), ActualBytes: int64p(2048), FileCount: intp(1),
+ }},
+ },
+ {
+ Stamp: "20261116T193001Z",
+ Path: without,
+ ManifestState: "missing",
+ Complete: true, ApparentBytes: int64p(30), ActualBytes: int64p(1024), FileCount: intp(1),
+ Databases: []metadataDatabase{{
+ Name: "weknora_archive", DirName: "weknora_archive.dir",
+ Path: without + "/weknora_archive.dir", Present: true,
+ ApparentBytes: int64p(30), ActualBytes: int64p(1024), FileCount: intp(1),
+ }},
+ },
+ },
}
}
-func actualOf(t *testing.T, filename string) int64 {
+func writeMetadata(t *testing.T, value metadata) string {
t.Helper()
- info, err := os.Stat(filename)
+ raw, err := json.Marshal(value)
if err != nil {
t.Fatal(err)
}
- stat, ok := info.Sys().(*syscall.Stat_t)
- if !ok {
- t.Fatal("no stat")
+ filename := filepath.Join(t.TempDir(), "metadata.json")
+ if err := os.WriteFile(filename, raw, 0o644); err != nil {
+ t.Fatal(err)
}
- return int64(stat.Blocks) * 512
+ return filename
}
-func fixtureRoot(t *testing.T) string {
- t.Helper()
- root := t.TempDir()
- latest := filepath.Join(root, "20261118T193001Z")
- writeFile(t, filepath.Join(latest, "MANIFEST.json"), `{
- "kind": "rds-logical-backup",
- "created_at": "20261118T193001Z",
- "started_at": "20261118T192908Z",
- "duration_seconds": 53,
- "databases": ["weknora_v090prod", "weknora_test"],
- "failed_databases": ["weknora_test"],
- "total_bytes": 300,
- "files": [
- {"file": "weknora_v090prod.dir/toc.dat", "bytes": 100},
- {"file": "weknora_v090prod.dir/0001.dat.gz", "bytes": 150},
- {"file": "weknora_test.dir/toc.dat", "bytes": 50}
- ]
-}`)
- writeFile(t, filepath.Join(latest, "weknora_v090prod.dir", "toc.dat"), strings.Repeat("a", 100))
- writeFile(t, filepath.Join(latest, "weknora_v090prod.dir", "0001.dat.gz"), strings.Repeat("b", 150))
- writeFile(t, filepath.Join(latest, "weknora_test.dir", "toc.dat"), strings.Repeat("c", 50))
-
- invalid := filepath.Join(root, "20261117T193001Z")
- writeFile(t, filepath.Join(invalid, "MANIFEST.json"), "{not-json")
- writeFile(t, filepath.Join(invalid, "weknora_prod.dir", "toc.dat"), strings.Repeat("d", 20))
-
- missing := filepath.Join(root, "20261116T193001Z")
- writeFile(t, filepath.Join(missing, "weknora_archive.dir", "toc.dat"), strings.Repeat("e", 30))
-
- incomplete := filepath.Join(root, "20261115T193001Z.incomplete")
- writeFile(t, filepath.Join(incomplete, "MANIFEST.json"), `{}`)
-
- return root
+func readerAt(filename string, now time.Time) *Reader {
+ reader := New(Config{MetadataPath: filename, HostRoot: hostRoot, Source: "configured", MaxAge: 15 * time.Minute})
+ reader.now = func() time.Time { return now }
+ return reader
}
-func TestSnapshotReadsBatchesManifestsAndActualUsage(t *testing.T) {
- root := fixtureRoot(t)
- reader := New(Config{
- Root: root,
- HostRoot: "/srv/kb-backups/rds-logical",
- Source: "weknora-test:/srv/kb-backups/rds-logical",
- })
- reader.device = func(path string) (uint64, error) {
- if path == "/" {
- return 10, nil
- }
- return 20, nil
+func TestSnapshotReadsHostMetadataAndPaths(t *testing.T) {
+ filename := writeMetadata(t, validMetadata())
+ now := time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)
+ snapshot := readerAt(filename, now).Snapshot(context.Background())
+ if !snapshot.Wired || snapshot.Error != "" || !snapshot.Metadata.Valid || !snapshot.Metadata.Fresh || !snapshot.Metadata.Complete {
+ t.Fatalf("应接受新鲜的完整快照: %+v", snapshot.Metadata)
}
- reader.statfs = func(string) (statFS, error) {
- return statFS{Total: 1000, Free: 400, Available: 350, ReadOnly: true}, nil
- }
-
- snapshot := reader.Snapshot(context.Background())
- if !snapshot.Wired || snapshot.Error != "" {
- t.Fatalf("应读到接线目录: %+v", snapshot)
- }
- if !snapshot.Mount.MountVerified || snapshot.Mount.LivesOnContainerRoot || !snapshot.Mount.ReadOnly {
- t.Fatalf("挂载判定不对: %+v", snapshot.Mount)
+ if !snapshot.Mount.MountVerified || snapshot.Mount.LivesOnContainerRoot || snapshot.Mount.MountPoint != "/srv/kb-backups" {
+ t.Fatalf("宿主挂载判定不对: %+v", snapshot.Mount)
}
if !snapshot.Capacity.Measured || snapshot.Capacity.TotalBytes != 1000 || snapshot.Capacity.AvailableBytes != 350 {
t.Fatalf("容量不对: %+v", snapshot.Capacity)
}
- if len(snapshot.Batches) != 3 || snapshot.IncompleteCount != 1 {
- t.Fatalf("批次数量不对: %d incomplete=%d", len(snapshot.Batches), snapshot.IncompleteCount)
+ if snapshot.Metadata.AgeSeconds != 300 || snapshot.Metadata.Generation == "" || snapshot.Metadata.Host != "weknora-test" {
+ t.Fatalf("元数据字段不对: %+v", snapshot.Metadata)
+ }
+ if len(snapshot.Batches) != 3 || snapshot.IncompleteCount != 1 || len(snapshot.Skipped) != 1 {
+ t.Fatalf("批次计数不对: %+v", snapshot)
}
latest := snapshot.Batches[0]
- if latest.Stamp != "20261118T193001Z" || latest.ManifestState != ManifestOK {
+ if latest.Stamp != "20261118T193001Z" || latest.ManifestState != ManifestOK || latest.SizesComplete != true {
t.Fatalf("最近批次不对: %+v", latest)
}
- if latest.CreatedAt != "20261118T193001Z" || latest.DurationSeconds != 53 || latest.ManifestBytes != 300 {
- t.Fatalf("清单字段不对: %+v", latest)
- }
- if latest.HostPath != "/srv/kb-backups/rds-logical/20261118T193001Z" {
- t.Fatalf("批次主机路径不对: %q", latest.HostPath)
- }
- if len(latest.Databases) != 2 {
- t.Fatalf("子库数量不对: %+v", latest.Databases)
+ if latest.HostPath != hostRoot+"/20261118T193001Z" || latest.ManifestTotalBytes == nil || *latest.ManifestTotalBytes != 300 {
+ t.Fatalf("批次路径/清单不对: %+v", latest)
}
prod := latest.Databases[0]
- if prod.Name != "weknora_v090prod" || !prod.Present || prod.Failed || !prod.InManifest {
- t.Fatalf("子库状态不对: %+v", prod)
- }
- if prod.Path != filepath.Join(root, "20261118T193001Z", "weknora_v090prod.dir") {
- t.Fatalf("子库容器路径不对: %q", prod.Path)
- }
- if prod.HostPath != "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir" {
- t.Fatalf("子库主机路径不对: %q", prod.HostPath)
- }
- expectedActual := actualOf(t, filepath.Join(root, "20261118T193001Z", "weknora_v090prod.dir", "toc.dat")) +
- actualOf(t, filepath.Join(root, "20261118T193001Z", "weknora_v090prod.dir", "0001.dat.gz"))
- if prod.ActualBytes != expectedActual {
- t.Fatalf("子库实际占盘不对: got %d want %d", prod.ActualBytes, expectedActual)
- }
- if prod.ApparentBytes != 250 || prod.FileCount != 2 {
- t.Fatalf("子库清单体积不对: %+v", prod)
+ if prod.HostPath != hostRoot+"/20261118T193001Z/weknora_v090prod.dir" || prod.ActualBytes == nil || *prod.ActualBytes != 4096 {
+ t.Fatalf("子库完整路径/占盘不对: %+v", prod)
}
if !latest.Databases[1].Failed {
t.Fatalf("失败库没有标记: %+v", latest.Databases[1])
}
-
- broken := snapshot.Batches[1]
- if broken.Stamp != "20261117T193001Z" || broken.ManifestState != ManifestInvalid || broken.ManifestError == "" {
- t.Fatalf("损坏清单没有如实标记: %+v", broken)
+ if snapshot.Batches[1].ManifestState != ManifestInvalid || snapshot.Batches[1].ManifestError == "" {
+ t.Fatalf("损坏清单没有如实标记: %+v", snapshot.Batches[1])
}
- if len(broken.Databases) != 1 || broken.Databases[0].Name != "weknora_prod" || !broken.Databases[0].Present {
- t.Fatalf("清单损坏时仍应按目录列出子库: %+v", broken.Databases)
+ if snapshot.Batches[2].ManifestState != ManifestMissing {
+ t.Fatalf("缺清单没有如实标记: %+v", snapshot.Batches[2])
}
- withoutManifest := snapshot.Batches[2]
- if withoutManifest.ManifestState != ManifestMissing {
- t.Fatalf("缺清单没有如实标记: %+v", withoutManifest)
- }
- if snapshot.Totals.BatchCount != 3 || snapshot.Totals.LatestStamp != "20261118T193001Z" {
+ if snapshot.Totals.ActualBytes == nil || *snapshot.Totals.ActualBytes != 4096+2048+1024 || !snapshot.Totals.Complete {
t.Fatalf("汇总不对: %+v", snapshot.Totals)
}
- if snapshot.ObservedAt == "" || snapshot.Source != "weknora-test:/srv/kb-backups/rds-logical" {
- t.Fatalf("观测时间/来源不对: %+v", snapshot)
+ if snapshot.Source != "weknora-test:"+hostRoot || snapshot.Measurement != "host_collector" {
+ t.Fatalf("来源/测量方式不对: %+v", snapshot)
+ }
+}
+
+func TestSnapshotStaleIsUnknown(t *testing.T) {
+ value := validMetadata()
+ value.CollectedAt = "2026-11-20T00:00:00Z"
+ filename := writeMetadata(t, value)
+ snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
+ if snapshot.Metadata.Valid || snapshot.Metadata.Fresh || snapshot.Metadata.Complete {
+ t.Fatalf("陈旧快照不能算有效: %+v", snapshot.Metadata)
+ }
+ if len(snapshot.Batches) != 0 || snapshot.Capacity.Measured || snapshot.Totals.ActualBytes != nil {
+ t.Fatalf("陈旧快照不能给批次/容量/占盘: %+v", snapshot)
+ }
+ if !strings.Contains(snapshot.Error, "陈旧") {
+ t.Fatalf("陈旧原因不清: %q", snapshot.Error)
+ }
+}
+
+func TestSnapshotMissingMetadata(t *testing.T) {
+ reader := New(Config{MetadataPath: filepath.Join(t.TempDir(), "missing.json"), HostRoot: hostRoot})
+ snapshot := reader.Snapshot(context.Background())
+ if !snapshot.Wired || snapshot.Metadata.Present || snapshot.Metadata.Valid {
+ t.Fatalf("缺失快照不能算有效: %+v", snapshot.Metadata)
+ }
+ if !strings.Contains(snapshot.Error, "不存在") {
+ t.Fatalf("缺失原因不清: %q", snapshot.Error)
+ }
+}
+
+func TestSnapshotPermissionFailureNeverUsesPartialBytes(t *testing.T) {
+ value := validMetadata()
+ value.Complete = false
+ value.Errors = nil
+ value.Batches[0].Complete = false
+ value.Batches[0].Errors = []string{"遍历失败:PermissionError: Permission denied ('.../weknora_v090prod.dir')"}
+ // 模拟采集器在权限失败前已经数到的部分字节;API 绝不能把它们当占盘。
+ value.Batches[0].ActualBytes = int64p(100)
+ value.Batches[0].Databases[0].ActualBytes = int64p(100)
+ filename := writeMetadata(t, value)
+ snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
+ if !snapshot.Metadata.Valid || snapshot.Metadata.Complete {
+ t.Fatalf("不完整快照应 valid=true/complete=false: %+v", snapshot.Metadata)
+ }
+ if snapshot.Capacity.Measured || snapshot.Totals.ActualBytes != nil || snapshot.Totals.ApparentBytes != nil {
+ t.Fatalf("不完整快照不能给容量/总量: %+v", snapshot)
+ }
+ if len(snapshot.Batches) != 3 {
+ t.Fatalf("路径仍应列出: %+v", snapshot.Batches)
+ }
+ latest := snapshot.Batches[0]
+ if latest.ActualBytes != nil || latest.ApparentBytes != nil || latest.FileCount != nil || latest.SizesComplete {
+ t.Fatalf("不完整批次不能保留部分字节: %+v", latest)
+ }
+ if latest.Databases[0].ActualBytes != nil || latest.Databases[0].ApparentBytes != nil {
+ t.Fatalf("不完整子库不能保留部分字节: %+v", latest.Databases[0])
+ }
+ if !strings.Contains(snapshot.Metadata.Error, "Permission") {
+ t.Fatalf("权限失败原因丢失: %q", snapshot.Metadata.Error)
+ }
+}
+
+func TestSnapshotTruncatedIsUnknown(t *testing.T) {
+ value := validMetadata()
+ value.Truncated = true
+ filename := writeMetadata(t, value)
+ snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
+ if snapshot.Metadata.Complete || snapshot.Capacity.Measured || snapshot.Totals.ActualBytes != nil {
+ t.Fatalf("截断快照不能算完整/容量: %+v", snapshot)
+ }
+}
+
+func TestSnapshotRejectsPathMismatch(t *testing.T) {
+ value := validMetadata()
+ value.Batches[0].Path = "/srv/kb-backups/rds-logical/../evil"
+ filename := writeMetadata(t, value)
+ snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
+ if snapshot.Metadata.Valid || len(snapshot.Batches) != 0 {
+ t.Fatalf("路径不一致必须整块拒绝: %+v", snapshot.Metadata)
+ }
+ if !strings.Contains(snapshot.Error, "路径") {
+ t.Fatalf("路径错误原因不清: %q", snapshot.Error)
+ }
+}
+
+func TestSnapshotRejectsUnsupportedSchema(t *testing.T) {
+ value := validMetadata()
+ value.SchemaVersion = 99
+ filename := writeMetadata(t, value)
+ snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
+ if snapshot.Metadata.Valid || !strings.Contains(snapshot.Error, "schema_version") {
+ t.Fatalf("不支持的 schema 必须拒绝: %+v", snapshot)
}
}
@@ -161,45 +262,19 @@ func TestSnapshotUnconfigured(t *testing.T) {
}
}
-func TestSnapshotMissingRoot(t *testing.T) {
- reader := New(Config{Root: filepath.Join(t.TempDir(), "missing")})
- snapshot := reader.Snapshot(context.Background())
- if !snapshot.Wired || snapshot.Error == "" || snapshot.Capacity.Measured {
- t.Fatalf("目录不存在应报错且不报容量: %+v", snapshot)
- }
-}
-
-func TestSnapshotRefusesSymlinkBatches(t *testing.T) {
- root := t.TempDir()
- outside := t.TempDir()
- writeFile(t, filepath.Join(outside, "MANIFEST.json"), `{"databases":["escaped"]}`)
- if err := os.Symlink(outside, filepath.Join(root, "20261118T193001Z")); err != nil {
- t.Fatal(err)
- }
- snapshot := New(Config{Root: root}).Snapshot(context.Background())
- if len(snapshot.Batches) != 0 {
- t.Fatalf("符号链接批次不能跟随: %+v", snapshot.Batches)
- }
- if len(snapshot.Skipped) != 1 || !strings.Contains(snapshot.Skipped[0].Reason, "符号链接") {
- t.Fatalf("跳过原因不对: %+v", snapshot.Skipped)
- }
-}
-
-func TestSnapshotDoesNotUseContainerRootCapacity(t *testing.T) {
- root := fixtureRoot(t)
- reader := New(Config{Root: root})
- reader.device = func(string) (uint64, error) { return 7, nil }
- reader.statfs = func(string) (statFS, error) {
- return statFS{Total: 999, Free: 1, Available: 1}, nil
- }
- snapshot := reader.Snapshot(context.Background())
- if snapshot.Mount.MountVerified || !snapshot.Mount.LivesOnContainerRoot {
- t.Fatalf("同设备必须判定为容器根盘: %+v", snapshot.Mount)
- }
- if snapshot.Capacity.Measured || snapshot.Capacity.TotalBytes != 0 || snapshot.Capacity.Error == "" {
- t.Fatalf("容器根盘不能冒充主机容量: %+v", snapshot.Capacity)
- }
- if len(snapshot.Batches) != 3 {
- t.Fatalf("容量不可用不应影响批次读取: %+v", snapshot.Batches)
+// 宿主采集器的权限失败回归:self-test 用注入 walker 模拟 PermissionError,
+// 断言不完整时字节为 null 且不产生部分统计。
+func TestCollectorSelfTest(t *testing.T) {
+ python, err := exec.LookPath("python3")
+ if err != nil {
+ t.Skip("python3 not available")
+ }
+ command := exec.Command(python, "../../scripts/collect_backup_metadata.py", "--self-test")
+ output, err := command.CombinedOutput()
+ if err != nil {
+ t.Fatalf("collector self-test failed: %v\n%s", err, output)
+ }
+ if !strings.Contains(string(output), "self-test ok") {
+ t.Fatalf("collector self-test output unexpected: %s", output)
}
}
diff --git a/internal/httpapi/backup_inventory.go b/internal/httpapi/backup_inventory.go
index 130cb71..63033ef 100644
--- a/internal/httpapi/backup_inventory.go
+++ b/internal/httpapi/backup_inventory.go
@@ -7,15 +7,15 @@ import (
"knowledge-governance/internal/backupinventory"
)
-// BackupInventoryReader 只读盘点备份主机目录。它与 SSH 主机计划读回完全独立:
-// 挂载没接线不应拖垮计划读回,计划读回失败也不应把历史批次说成"没有"。
+// BackupInventoryReader 读取宿主采集器写出的元数据快照。它与 SSH 主机计划读回完全独立:
+// 快照缺失/陈旧不应拖垮计划读回,计划读回失败也不应把历史批次说成"没有"。
type BackupInventoryReader interface {
Available() bool
Snapshot(context.Context) backupinventory.Snapshot
}
-// handleBackupInventory 返回真实批次、子库路径与实测容量。
-// 未接线/目录不可读/清单损坏都作为 200 的字段返回,由页面区分原因;
+// handleBackupInventory 返回宿主采集器快照里的批次、子库路径与容量。
+// 未接线/快照缺失/陈旧/不完整/路径不一致都作为 200 的字段返回,由页面区分原因;
// 只有投影本身失败才 500。
func (config Config) handleBackupInventory(w http.ResponseWriter, r *http.Request) {
snapshot := config.BackupInventory.Snapshot(r.Context())
diff --git a/internal/httpapi/backup_inventory_test.go b/internal/httpapi/backup_inventory_test.go
index 197555c..879085b 100644
--- a/internal/httpapi/backup_inventory_test.go
+++ b/internal/httpapi/backup_inventory_test.go
@@ -21,30 +21,33 @@ func (fake fakeBackupInventory) Snapshot(context.Context) backupinventory.Snapsh
}
func TestBackupInventoryProjectionPassesRealFields(t *testing.T) {
+ actual := int64(1024)
+ databaseActual := int64(512)
config := Config{BackupInventory: fakeBackupInventory{snapshot: backupinventory.Snapshot{
Wired: true,
- Root: "/var/lib/knowledge-governance/backup-host/rds-logical",
+ Root: "/srv/kb-backups/rds-logical",
HostRoot: "/srv/kb-backups/rds-logical",
Source: "weknora-test:/srv/kb-backups/rds-logical",
+ Metadata: backupinventory.MetadataInfo{Configured: true, Present: true, Valid: true, Fresh: true, Complete: true},
Mount: backupinventory.MountInfo{
MountVerified: true,
ReadOnly: true,
- Evidence: "挂载设备 20 与容器根盘 10 不同",
+ Evidence: "宿主采集器:/dev/sdb1 挂在 /srv/kb-backups(ext4)",
},
Capacity: backupinventory.Capacity{Measured: true, TotalBytes: 100, FreeBytes: 40, AvailableBytes: 35, UsedBytes: 60},
Batches: []backupinventory.Batch{{
Stamp: "20261118T193001Z",
HostPath: "/srv/kb-backups/rds-logical/20261118T193001Z",
ManifestState: backupinventory.ManifestOK,
- ActualBytes: 1024,
+ ActualBytes: &actual,
Databases: []backupinventory.Database{{
Name: "weknora_v090prod",
HostPath: "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir",
Present: true,
- ActualBytes: 512,
+ ActualBytes: &databaseActual,
}},
}},
- Totals: backupinventory.Totals{BatchCount: 1, LatestStamp: "20261118T193001Z"},
+ Totals: backupinventory.Totals{BatchCount: 1, ActualBytes: &actual, LatestStamp: "20261118T193001Z", Complete: true},
}}}
recorder := httptest.NewRecorder()
config.handleBackupInventory(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/backup-schedule/inventory", nil))
@@ -64,7 +67,7 @@ func TestBackupInventoryProjectionPassesRealFields(t *testing.T) {
payload.Data.Batches[0].Databases[0].HostPath != "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir" {
t.Fatalf("批次/子库真实路径丢失: %+v", payload.Data.Batches)
}
- if payload.Data.Batches[0].ActualBytes != 1024 {
+ if payload.Data.Batches[0].ActualBytes == nil || *payload.Data.Batches[0].ActualBytes != 1024 {
t.Fatalf("实际占盘字段丢失: %+v", payload.Data.Batches[0])
}
}
diff --git a/scripts/collect_backup_metadata.py b/scripts/collect_backup_metadata.py
new file mode 100755
index 0000000..a1a32cf
--- /dev/null
+++ b/scripts/collect_backup_metadata.py
@@ -0,0 +1,581 @@
+#!/usr/bin/env python3
+"""备份目录的**单次宿主元数据采集器**(只读)。
+
+为什么不在 API 里遍历:备份目录通常是 root:root 0700,API 容器用户没有进入权限;
+容器里再 df/du 也证明不了宿主的盘。这个脚本在备份主机上由有读权限的宿主进程
+(root 或备份所有者)运行,只做 stat/du 和读 MANIFEST.json,产出原子快照 JSON;
+API 只读快照,不接触备份目录,也不借用 SSH 或容器特权。
+
+不读取任何数据库内容文件:只对目录项 lstat、统计 st_size/st_blocks,并读
+MANIFEST.json(元数据)。输出用同目录临时文件 + fsync + os.replace 原子替换。
+
+用法(宿主):
+ python3 collect_backup_metadata.py \
+ --root /srv/kb-backups/rds-logical \
+ --output /var/lib/knowledge-governance/backup-metadata/metadata.json \
+ --source weknora-test:/srv/kb-backups/rds-logical
+
+退出码:0 完整;2 已写快照但采集不完整/有错误;1 连快照都没写成。
+"""
+from __future__ import annotations
+
+import argparse
+import datetime as dt
+import errno
+import json
+import os
+import re
+import socket
+import stat
+import sys
+import tempfile
+import uuid
+from typing import Any, Callable, Iterable
+
+SCHEMA_VERSION = 1
+COLLECTOR_VERSION = "backup-metadata/1"
+MAX_MANIFEST_BYTES = 8 << 20
+MAX_ERRORS = 50
+STAMP_NAME = re.compile(r"^[A-Za-z0-9._-]+$")
+
+
+class CollectError(Exception):
+ pass
+
+
+def _error_text(error: BaseException) -> str:
+ if isinstance(error, OSError) and error.filename:
+ return f"{type(error).__name__}: {error.strerror or error} ({error.filename})"
+ return f"{type(error).__name__}: {error}"
+
+
+def _append_error(errors: list[str], text: str) -> None:
+ if len(errors) < MAX_ERRORS and text not in errors:
+ errors.append(text)
+
+
+def _unescape_mount(text: str) -> str:
+ return re.sub(r"\\([0-7]{3})", lambda m: chr(int(m.group(1), 8)), text)
+
+
+def mount_info(root: str) -> dict[str, Any]:
+ """从 /proc/self/mountinfo 找覆盖 root 的最长挂载点(只读文件,不碰备份内容)。"""
+ best: dict[str, Any] | None = None
+ try:
+ with open("/proc/self/mountinfo", "r", encoding="utf-8", errors="replace") as handle:
+ for line in handle:
+ before, sep, after = line.partition(" - ")
+ if not sep:
+ continue
+ fields = before.split()
+ tail = after.split()
+ if len(fields) < 6 or len(tail) < 3:
+ continue
+ mount_point = _unescape_mount(fields[4])
+ if root == mount_point or root.startswith(mount_point.rstrip("/") + "/"):
+ if best is None or len(mount_point) > len(best["mount_point"]):
+ best = {
+ "mount_point": mount_point,
+ "mount_source": _unescape_mount(tail[1]),
+ "fs_type": tail[0],
+ "read_only": "ro" in fields[5].split(","),
+ }
+ except OSError:
+ return {}
+ return best or {}
+
+
+def capacity(root: str) -> tuple[dict[str, Any], list[str]]:
+ errors: list[str] = []
+ info = mount_info(root)
+ try:
+ stats = os.statvfs(root)
+ block = stats.f_frsize or stats.f_bsize
+ info.update(
+ {
+ "total_bytes": stats.f_blocks * block,
+ "free_bytes": stats.f_bfree * block,
+ "available_bytes": stats.f_bavail * block,
+ }
+ )
+ if "read_only" not in info:
+ flags = getattr(stats, "f_flag", 0)
+ info["read_only"] = bool(flags & getattr(os, "ST_RDONLY", 1))
+ except OSError as error:
+ _append_error(errors, "statvfs: " + _error_text(error))
+ return info, errors
+
+
+def _read_manifest(path: str) -> tuple[str, str, dict[str, Any]]:
+ # MANIFEST 只接受目录内的常规文件:lstat 拒绝符号链接,open 再带 O_NOFOLLOW,
+ # 防止采集器被一个指向别处的清单带跑(只读,也不会跟随到归档内容)。
+ try:
+ info = os.lstat(path)
+ except FileNotFoundError:
+ return "missing", "", {}
+ except OSError as error:
+ return "invalid", "清单不可读:" + _error_text(error), {}
+ if stat.S_ISLNK(info.st_mode) or not stat.S_ISREG(info.st_mode):
+ return "invalid", "清单不是目录内的常规文件(拒绝符号链接)", {}
+ if info.st_size > MAX_MANIFEST_BYTES:
+ return "invalid", f"清单超过 {MAX_MANIFEST_BYTES} 字节读取上限", {}
+ flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
+ try:
+ descriptor = os.open(path, flags)
+ except OSError as error:
+ return "invalid", "清单不可读:" + _error_text(error), {}
+ try:
+ with os.fdopen(descriptor, "rb") as handle:
+ opened = os.fstat(handle.fileno())
+ if not stat.S_ISREG(opened.st_mode):
+ return "invalid", "清单在打开后不是常规文件", {}
+ raw = handle.read(MAX_MANIFEST_BYTES + 1)
+ except OSError as error:
+ return "invalid", "清单不可读:" + _error_text(error), {}
+ if len(raw) > MAX_MANIFEST_BYTES:
+ return "invalid", f"清单超过 {MAX_MANIFEST_BYTES} 字节读取上限", {}
+ try:
+ value = json.loads(raw.decode("utf-8"))
+ except (UnicodeDecodeError, json.JSONDecodeError) as error:
+ return "invalid", "清单无法解析:" + str(error), {}
+ if not isinstance(value, dict):
+ return "invalid", "清单不是对象", {}
+ return "ok", "", value
+
+
+def measure_tree(path: str, scan: Callable[[str], Iterable[Any]] = os.scandir, max_files: int = 500_000) -> dict[str, Any]:
+ """只 stat 目录项;口径与 `du -sB1` 一致。
+
+ - 目录自身也计入(st_size + st_blocks),不只求和文件;
+ - 子树完整遍历,任何 lstat/scandir 错误置 complete=false;
+ - 常规文件硬链接按 (dev, ino) 只算一次(单库/整批各自独立去重);
+ - 符号链接、设备等非目录/非普通文件不跟随、不计入(与参考 du 口径一致)。
+
+ scan 可注入,self-test 用它模拟 PermissionError;生产默认 os.scandir。
+ """
+ apparent = actual = files = dirs = 0
+ seen: set[tuple[int, int]] = set()
+ errors: list[str] = []
+ complete = True
+ stack = [path]
+ while stack:
+ current = stack.pop()
+ try:
+ info = os.lstat(current)
+ except OSError as error:
+ complete = False
+ _append_error(errors, "stat 失败:" + _error_text(error))
+ continue
+ if stat.S_ISDIR(info.st_mode):
+ dirs += 1
+ apparent += int(info.st_size)
+ actual += int(getattr(info, "st_blocks", 0)) * 512
+ try:
+ entries = list(scan(current))
+ except OSError as error:
+ complete = False
+ _append_error(errors, "遍历失败:" + _error_text(error))
+ continue
+ entries.sort(key=lambda entry: entry.name)
+ for entry in entries:
+ try:
+ child = entry.stat(follow_symlinks=False)
+ except OSError as error:
+ complete = False
+ _append_error(errors, "stat 失败:" + _error_text(error))
+ continue
+ if stat.S_ISDIR(child.st_mode):
+ stack.append(entry.path)
+ continue
+ if not stat.S_ISREG(child.st_mode):
+ continue # symlink/设备不跟随,du 默认也不计目标
+ if int(getattr(child, "st_nlink", 0)) > 1:
+ key = (int(child.st_dev), int(child.st_ino))
+ if key in seen:
+ continue # du 只算一次
+ seen.add(key)
+ if files >= max_files:
+ complete = False
+ _append_error(errors, f"文件数超过采集上限 {max_files}")
+ stack.clear()
+ break
+ apparent += int(child.st_size)
+ actual += int(getattr(child, "st_blocks", 0)) * 512
+ files += 1
+ return {
+ "apparent_bytes": apparent,
+ "actual_bytes": actual,
+ "file_count": files,
+ "dir_count": dirs,
+ "complete": complete,
+ "errors": errors,
+ }
+
+
+def collect(
+ root: str,
+ source: str = "",
+ host: str | None = None,
+ max_batches: int = 100,
+ scan: Callable[[str], Iterable[Any]] = os.scandir,
+ now: dt.datetime | None = None,
+) -> dict[str, Any]:
+ root = os.path.abspath(root)
+ collected_at = (now or dt.datetime.now(dt.timezone.utc)).astimezone(dt.timezone.utc)
+ snapshot: dict[str, Any] = {
+ "schema_version": SCHEMA_VERSION,
+ "collector_version": COLLECTOR_VERSION,
+ "generation": f"{collected_at.strftime('%Y%m%dT%H%M%SZ')}-{uuid.uuid4().hex[:12]}",
+ "collected_at": collected_at.isoformat().replace("+00:00", "Z"),
+ "host": host or socket.gethostname(),
+ "source": source,
+ "root": root,
+ "complete": True,
+ "errors": [],
+ "filesystem": {},
+ "incomplete_count": 0,
+ "skipped": [],
+ "truncated": False,
+ "batches": [],
+ }
+ errors: list[str] = snapshot["errors"]
+ try:
+ if not os.path.isdir(root):
+ raise CollectError(f"备份根不是目录:{root}")
+ entries = list(os.scandir(root))
+ except OSError as error:
+ _append_error(errors, "无法列出备份根:" + _error_text(error))
+ snapshot["complete"] = False
+ snapshot["filesystem"], capacity_errors = capacity(root)
+ for item in capacity_errors:
+ _append_error(errors, item)
+ return snapshot
+
+ fs_info, capacity_errors = capacity(root)
+ snapshot["filesystem"] = fs_info
+ for item in capacity_errors:
+ _append_error(errors, item)
+
+ dirs: list[str] = []
+ for entry in entries:
+ name = entry.name
+ if name.endswith(".incomplete"):
+ snapshot["incomplete_count"] += 1
+ continue
+ if not STAMP_NAME.match(name) or "/" in name or "\\" in name:
+ snapshot["skipped"].append({"name": name, "reason": "目录名不合法"})
+ continue
+ try:
+ if entry.is_symlink():
+ snapshot["skipped"].append({"name": name, "reason": "符号链接不跟随"})
+ continue
+ if not entry.is_dir(follow_symlinks=False):
+ snapshot["skipped"].append({"name": name, "reason": "不是批次目录"})
+ continue
+ except OSError as error:
+ _append_error(errors, "批次项不可读:" + _error_text(error))
+ continue
+ dirs.append(name)
+ dirs.sort(reverse=True)
+ if len(dirs) > max_batches:
+ dirs = dirs[:max_batches]
+ snapshot["truncated"] = True
+
+ for name in dirs:
+ snapshot["batches"].append(_collect_batch(root, name, scan))
+ snapshot["complete"] = (
+ not errors
+ and not snapshot["truncated"]
+ and all(batch["complete"] for batch in snapshot["batches"])
+ )
+ return snapshot
+
+
+def _collect_batch(root: str, name: str, scan: Callable[[str], Iterable[Any]]) -> dict[str, Any]:
+ batch_path = os.path.join(root, name)
+ state, manifest_error, manifest = _read_manifest(os.path.join(batch_path, "MANIFEST.json"))
+ tree = measure_tree(batch_path, scan)
+ errors = list(tree["errors"])
+ manifest_databases = [
+ item for item in (manifest.get("databases") or []) if isinstance(item, str)
+ ] if isinstance(manifest.get("databases"), list) else []
+ raw_failed = manifest.get("failed_databases")
+ failed_values: list[Any] = raw_failed if isinstance(raw_failed, list) else []
+ failed = {item for item in failed_values if isinstance(item, str)}
+ actual_dirs: set[str] = set()
+ try:
+ for entry in scan(batch_path):
+ db_name = entry.name[: -len(".dir")] if entry.name.endswith(".dir") else ""
+ if not db_name or not STAMP_NAME.match(db_name):
+ continue
+ try:
+ info = entry.stat(follow_symlinks=False)
+ except OSError as error:
+ _append_error(errors, "子库目录不可读:" + _error_text(error))
+ continue
+ if not stat.S_ISDIR(info.st_mode) or stat.S_ISLNK(info.st_mode):
+ continue
+ actual_dirs.add(db_name)
+ except OSError as error:
+ _append_error(errors, "批次目录不可读:" + _error_text(error))
+
+ names = sorted(set(manifest_databases) | actual_dirs)
+ databases: list[dict[str, Any]] = []
+ for db in names:
+ if not db or not STAMP_NAME.match(db):
+ continue
+ dir_name = db + ".dir"
+ path = os.path.join(batch_path, dir_name)
+ present = db in actual_dirs
+ if state == "ok" and db in manifest_databases and not present:
+ _append_error(errors, f"清单列出 {db} 但 {dir_name} 不存在")
+ measured = measure_tree(path, scan) if present else None
+ db_complete = bool(measured is not None and measured["complete"])
+ if measured is not None and not measured["complete"]:
+ _append_error(errors, f"子库 {db} 遍历不完整")
+ databases.append(
+ {
+ "name": db,
+ "dir_name": dir_name,
+ "path": path,
+ "present": present,
+ "failed": db in failed,
+ "in_manifest": db in manifest_databases,
+ "apparent_bytes": measured["apparent_bytes"] if measured is not None and db_complete else None,
+ "actual_bytes": measured["actual_bytes"] if measured is not None and db_complete else None,
+ "file_count": measured["file_count"] if measured is not None and db_complete else None,
+ "dir_count": measured["dir_count"] if measured is not None and db_complete else None,
+ "complete": db_complete,
+ "errors": measured["errors"] if measured is not None else [],
+ }
+ )
+
+ complete = tree["complete"] and all(database["complete"] for database in databases) and not errors
+ manifest_total = manifest.get("total_bytes") if state == "ok" else 0
+ if state == "ok" and not isinstance(manifest_total, int):
+ manifest_total = 0
+ duration = manifest.get("duration_seconds") if state == "ok" else 0
+ if not isinstance(duration, int):
+ duration = 0
+ batch = {
+ "stamp": name,
+ "path": batch_path,
+ "manifest_state": state,
+ "manifest_error": manifest_error,
+ "kind": manifest.get("kind", "") if state == "ok" else "",
+ "created_at": manifest.get("created_at", "") if state == "ok" else "",
+ "started_at": manifest.get("started_at", "") if state == "ok" else "",
+ "duration_seconds": duration,
+ "manifest_total_bytes": int(manifest_total) if state == "ok" else None,
+ "complete": complete,
+ "errors": errors,
+ "apparent_bytes": (int(manifest_total) if state == "ok" and manifest_total else tree["apparent_bytes"]) if complete else None,
+ "actual_bytes": tree["actual_bytes"] if complete else None,
+ "file_count": tree["file_count"] if complete else None,
+ "dir_count": tree["dir_count"] if complete else None,
+ "databases": databases if complete else [
+ {**database, "apparent_bytes": None, "actual_bytes": None, "file_count": None, "dir_count": None}
+ for database in databases
+ ],
+ }
+ return batch
+
+
+def write_snapshot(output: str, snapshot: dict[str, Any]) -> None:
+ directory = os.path.dirname(os.path.abspath(output))
+ os.makedirs(directory, mode=0o755, exist_ok=True)
+ fd, temporary = tempfile.mkstemp(prefix=".metadata-", dir=directory)
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ json.dump(snapshot, handle, ensure_ascii=False, sort_keys=True, indent=2)
+ handle.write("\n")
+ handle.flush()
+ os.fsync(handle.fileno())
+ os.chmod(temporary, 0o644)
+ os.replace(temporary, output)
+ dir_fd = os.open(directory, os.O_DIRECTORY)
+ try:
+ os.fsync(dir_fd)
+ finally:
+ os.close(dir_fd)
+ except BaseException:
+ try:
+ os.unlink(temporary)
+ except OSError:
+ pass
+ raise
+
+
+def _self_test() -> None:
+ import shutil
+ import sys as _sys
+
+ base = tempfile.mkdtemp(prefix="backup-metadata-test-")
+ try:
+ root = os.path.join(base, "rds-logical")
+ stamp = "20261118T193001Z"
+ batch = os.path.join(root, stamp)
+ os.makedirs(os.path.join(batch, "weknora_test.dir"), mode=0o700)
+ payload = "x" * 100
+ with open(os.path.join(batch, "weknora_test.dir", "toc.dat"), "w", encoding="utf-8") as handle:
+ handle.write(payload)
+ manifest = {
+ "kind": "rds-logical-backup",
+ "created_at": stamp,
+ "duration_seconds": 53,
+ "databases": ["weknora_test"],
+ "failed_databases": [],
+ "total_bytes": len(payload),
+ "files": [{"file": "weknora_test.dir/toc.dat", "bytes": len(payload)}],
+ }
+ with open(os.path.join(batch, "MANIFEST.json"), "w", encoding="utf-8") as handle:
+ json.dump(manifest, handle)
+ fixed = dt.datetime(2026, 11, 20, 1, 2, 3, tzinfo=dt.timezone.utc)
+ snapshot = collect(root, "weknora-test:" + root, "weknora-test", now=fixed)
+ assert snapshot["complete"] is True, snapshot
+ assert snapshot["schema_version"] == SCHEMA_VERSION
+ assert snapshot["batches"][0]["manifest_state"] == "ok"
+ assert snapshot["batches"][0]["databases"][0]["name"] == "weknora_test"
+ assert snapshot["batches"][0]["actual_bytes"] >= len(payload)
+ assert snapshot["filesystem"]["total_bytes"] > 0
+
+ def denied_scan(target: str):
+ if target.endswith(".dir"):
+ raise PermissionError(errno.EACCES, "Permission denied", target)
+ return os.scandir(target)
+
+ denied = collect(root, scan=denied_scan, now=fixed)
+ assert denied["complete"] is False
+ assert denied["batches"][0]["complete"] is False
+ assert denied["batches"][0]["actual_bytes"] is None
+ assert denied["batches"][0]["databases"][0]["actual_bytes"] is None
+ assert any("Permission denied" in item for item in denied["batches"][0]["errors"])
+
+ # 与参考 host-backup-inventory.sh 同口径:目录自身计入、树内硬链接去重、
+ # 单库与整批各自独立测量,各自与自身的 du -sB1 一致。
+ import subprocess
+
+ if shutil.which("du"):
+ def du_bytes(target: str) -> int:
+ result = subprocess.run(
+ ["du", "-sB1", target], capture_output=True, text=True, check=True
+ )
+ return int(result.stdout.split()[0])
+
+ link_root = os.path.join(base, "hardlink-root")
+ plain_root = os.path.join(base, "single-hardlink-root")
+ plain_batch = os.path.join(plain_root, "20261114T193001Z")
+ plain_db = os.path.join(plain_batch, "weknora_v090prod.dir")
+ os.makedirs(plain_db)
+ with open(os.path.join(plain_db, "base.tar"), "wb") as handle:
+ handle.write(b"x" * 5000)
+ os.link(os.path.join(plain_db, "base.tar"), os.path.join(plain_db, "base.tar.link"))
+ with open(os.path.join(plain_batch, "MANIFEST.json"), "w", encoding="utf-8") as handle:
+ json.dump({"databases": ["weknora_v090prod"]}, handle)
+ plain = collect(plain_root, now=fixed)
+ plain_db_info = plain["batches"][0]["databases"][0]
+ plain_batch_info = plain["batches"][0]
+ assert plain_db_info["actual_bytes"] == du_bytes(plain_db), plain_db_info
+ assert plain_batch_info["actual_bytes"] == du_bytes(plain_batch), plain_batch_info
+ assert plain_db_info["file_count"] == 1, plain_db_info
+
+ link_batch = os.path.join(link_root, "20261116T193001Z")
+ db_a = os.path.join(link_batch, "weknora_a.dir")
+ db_b = os.path.join(link_batch, "weknora_b.dir")
+ os.makedirs(db_a)
+ os.makedirs(db_b)
+ with open(os.path.join(db_a, "one.dat"), "wb") as handle:
+ handle.write(b"x" * 5000)
+ os.link(os.path.join(db_a, "one.dat"), os.path.join(db_a, "alias.dat"))
+ with open(os.path.join(db_b, "two.dat"), "wb") as handle:
+ handle.write(b"y" * 3000)
+ # 跨子库硬链接:整批 du 只算一次,单库 du 各自算一次。
+ os.link(os.path.join(db_a, "one.dat"), os.path.join(db_b, "shared.dat"))
+ with open(os.path.join(link_batch, "globals.sql"), "wb") as handle:
+ handle.write(b"z" * 1000)
+ with open(os.path.join(link_batch, "MANIFEST.json"), "w", encoding="utf-8") as handle:
+ json.dump({"kind": "rds-logical-backup", "databases": ["weknora_a", "weknora_b"]}, handle)
+
+ linked = collect(link_root, now=fixed)
+ linked_batch = linked["batches"][0]
+ assert linked["complete"] is True, linked
+ by_name = {item["name"]: item for item in linked_batch["databases"]}
+ assert by_name["weknora_a"]["actual_bytes"] == du_bytes(db_a), by_name["weknora_a"]
+ assert by_name["weknora_b"]["actual_bytes"] == du_bytes(db_b), by_name["weknora_b"]
+ assert linked_batch["actual_bytes"] == du_bytes(link_batch), linked_batch
+ # 逻辑文件数:one/alias/shared 同一 inode 只计一次,再加 two.dat、globals.sql、MANIFEST
+ assert by_name["weknora_a"]["file_count"] == 1, by_name["weknora_a"]
+ assert by_name["weknora_b"]["file_count"] == 2, by_name["weknora_b"]
+ assert linked_batch["file_count"] == 4, linked_batch
+ assert linked_batch["actual_bytes"] >= 5000 + 3000 + 1000
+
+ # MANIFEST 只接受批次目录内的常规文件:指向别处的符号链接必须 invalid,不能被跟随。
+ symlink_root = os.path.join(base, "symlink-root")
+ symlink_batch = os.path.join(symlink_root, "20261115T193001Z")
+ os.makedirs(os.path.join(symlink_batch, "weknora_x.dir"))
+ outside = os.path.join(base, "outside-manifest.json")
+ with open(outside, "w", encoding="utf-8") as handle:
+ json.dump({"databases": ["weknora_x"]}, handle)
+ os.symlink(outside, os.path.join(symlink_batch, "MANIFEST.json"))
+ symlinked = collect(symlink_root, now=fixed)
+ assert symlinked["batches"][0]["manifest_state"] == "invalid"
+ assert "常规文件" in symlinked["batches"][0]["manifest_error"]
+
+ incomplete_dir = os.path.join(root, "20261117T193001Z.incomplete")
+ os.makedirs(incomplete_dir)
+ with open(os.path.join(incomplete_dir, "MANIFEST.json"), "w", encoding="utf-8") as handle:
+ handle.write("{}")
+ ignored = collect(root, now=fixed)
+ assert ignored["incomplete_count"] == 1
+ assert [item["stamp"] for item in ignored["batches"]] == [stamp]
+
+ output = os.path.join(base, "out", "metadata.json")
+ write_snapshot(output, ignored)
+ with open(output, encoding="utf-8") as handle:
+ reloaded = json.load(handle)
+ assert reloaded["batches"][0]["stamp"] == stamp
+ assert not [name for name in os.listdir(os.path.dirname(output)) if name.startswith(".metadata-")]
+ print("collect_backup_metadata self-test ok")
+ _sys.stdout.flush()
+ finally:
+ shutil.rmtree(base, ignore_errors=True)
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description="备份目录只读元数据采集器")
+ parser.add_argument("--root", required=False, help="宿主机上的 rds-logical 目录")
+ parser.add_argument("--output", required=False, help="原子写出的 metadata.json")
+ parser.add_argument("--source", default="", help="展示来源,如 weknora-test:/srv/...")
+ parser.add_argument("--host", default="", help="采集主机名(默认当前主机)")
+ parser.add_argument("--max-batches", type=int, default=100)
+ parser.add_argument("--self-test", action="store_true")
+ args = parser.parse_args(argv)
+ if args.self_test:
+ _self_test()
+ return 0
+ if not args.root or not args.output:
+ parser.error("--root and --output are required unless --self-test")
+ try:
+ snapshot = collect(
+ args.root,
+ source=args.source,
+ host=args.host or None,
+ max_batches=max(1, args.max_batches),
+ )
+ write_snapshot(args.output, snapshot)
+ except (CollectError, OSError) as error:
+ print(f"collect failed: {error}", file=sys.stderr)
+ return 1
+ summary = {
+ "complete": snapshot["complete"],
+ "batches": len(snapshot["batches"]),
+ "incomplete_count": snapshot["incomplete_count"],
+ "collected_at": snapshot["collected_at"],
+ "output": args.output,
+ }
+ print(json.dumps(summary, ensure_ascii=False))
+ return 0 if snapshot["complete"] else 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
\ No newline at end of file
diff --git a/web/src/BackupScheduleSection.test.tsx b/web/src/BackupScheduleSection.test.tsx
index ba5fdb4..383a8fe 100644
--- a/web/src/BackupScheduleSection.test.tsx
+++ b/web/src/BackupScheduleSection.test.tsx
@@ -74,17 +74,37 @@ const diskFixture = (overrides: Partial = {}): StorageDi
const inventoryFixture = (overrides: Partial = {}): BackupInventory => {
const baseInventory: BackupInventory = {
wired: true,
- root: '/var/lib/knowledge-governance/backup-host/rds-logical',
+ 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: '/',
+ container_root: '',
mount_verified: true,
lives_on_container_root: false,
read_only: true,
- evidence: '挂载设备 20 与容器根盘 10 不同:容量按挂载文件系统计量',
+ evidence: '宿主采集器:/dev/sdb1 挂在 /srv/kb-backups(ext4),API 不遍历备份目录',
+ mount_point: '/srv/kb-backups',
+ device: '/dev/sdb1',
+ fs_type: 'ext4',
},
capacity: {
measured: true,
@@ -118,7 +138,7 @@ const inventoryFixture = (overrides: Partial = {}): BackupInven
present: true,
failed: false,
in_manifest: true,
- apparent_bytes: 696_320,
+ apparent_bytes: 700_000,
actual_bytes: 720_896,
file_count: 12,
},
@@ -175,6 +195,7 @@ const inventoryFixture = (overrides: Partial = {}): BackupInven
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: '不是批次目录' }],
@@ -229,7 +250,7 @@ describe('BackupScheduleView', () => {
'备份执行主机 weknora-test 本机直连 RDS',
'最近批次含 2 个数据库',
'weknora-test 本地备份根目录',
- '备份目录未接线或不可读,不在页面猜测',
+ '元数据快照未接线或不可用,不在页面猜测',
'整批 · 2 个数据库(weknora_test、dobotai_prod)',
'100.85.111.121:22',
'立即备份一次(整批 2 个数据库)',
@@ -261,7 +282,7 @@ describe('BackupScheduleView', () => {
it('目录/配额/预留没有后端字段:控件禁用并写明原因,不会假装可保存', () => {
const html = view()
expect(html).toContain('备份主机上的目录')
- expect(html).toContain('只读盘点未接线')
+ expect(html).toContain('元数据快照未接线')
expect(html).toContain('检查目录(不可用)')
expect(html).toContain('备份总配额(GiB)')
expect(html).toContain('磁盘预留(GiB)')
@@ -270,11 +291,11 @@ describe('BackupScheduleView', () => {
expect(html).toContain('disabled')
})
- it('只读盘点:展示全部批次、MANIFEST 状态、子库完整路径与实际占盘', () => {
+ it('宿主快照:展示全部批次、MANIFEST 状态、子库完整路径与实际占盘', () => {
const html = view({}, { inventory: inventoryFixture() })
for (const text of [
'备份记录',
- '2 批 · 只读盘点',
+ '2 批 · 元数据快照',
'最近批次 20261118T193001Z',
'清单完整',
'清单损坏',
@@ -299,32 +320,41 @@ describe('BackupScheduleView', () => {
expect(html).not.toContain('复制目录(不可用)')
})
- it('没有只读盘点:不展示任何历史批次或伪造路径', () => {
+ it('没有快照:不展示任何历史批次或伪造路径', () => {
const html = view()
- expect(html).toContain('尚未读取只读盘点')
+ expect(html).toContain('尚未读取宿主元数据快照')
expect(html).not.toContain('批次戳')
expect(html).not.toContain('/srv/kb-backups/rds-logical')
})
- it('盘点未接线:说明与 SSH 计划读回独立,未读到不等于没有备份', () => {
+ it('快照未接线:说明与 SSH 计划读回独立,未读到不等于没有备份', () => {
+ const base = inventoryFixture()
const html = view(
{},
{
inventory: inventoryFixture({
wired: false,
- error: '只读盘点未接线(BACKUP_HOST_READONLY_ROOT 未设置)',
+ 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).toContain('未读到批次不等于没有备份')
- expect(html).toContain('文件盘点未接线')
expect(html).not.toContain('/srv/kb-backups/rds-logical/20261118T193001Z')
})
- it('挂载可读但没有批次时说明不能据此判断成功/失败', () => {
+ it('快照可读但没有批次时说明不能据此判断成功/失败', () => {
const html = view(
{
last_run_stamp: '',
@@ -343,11 +373,12 @@ describe('BackupScheduleView', () => {
actual_bytes: 0,
latest_stamp: '',
latest_actual_bytes: 0,
+ complete: true,
},
}),
}
)
- expect(html).toContain('挂载可读,但没有批次目录')
+ expect(html).toContain('宿主快照可读,但没有批次目录')
expect(html).toContain('不能证明备份成功或失败')
})
@@ -402,7 +433,7 @@ describe('BackupScheduleView', () => {
expect(html).toContain('weknora-test · 连接失败')
expect(html).toContain('120.76.217.51:22')
expect(html).toContain('未知(未连上主机,未执行主机侧脚本)')
- expect(html).not.toContain('缺失')
+ expect(html).not.toContain('备份脚本缺失')
expect(html).toContain('主机连不上:以下"主机生效"状态未知')
expect(html).toContain('无法比对(主机不可达)')
})
@@ -451,18 +482,20 @@ describe('BackupScheduleView', () => {
expect(runMoment({ last_run_stamp: '20261009T060736Z', last_run_created_at: '2026-10-09T06:07:36Z' })).not.toBe('')
})
- it('体积格式化:MiB/GiB', () => {
- expect(formatBackupBytes(0)).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(2 * 1024 * 1024 * 1024)).toBe('2.00 GiB')
})
})
describe('整盘占用与告警', () => {
- it('没有只读盘点时:不显示示例容量,四条告警只报未知原因', () => {
+ it('没有快照时:不显示示例容量,四条告警只报未知原因', () => {
const html = view()
- expect(html).toContain('未接线 · 不显示估算容量')
- expect(html).toContain('容量来自只读挂载目录的 statfs 实测')
+ expect(html).toContain('占盘未知 · 不使用部分字节')
+ expect(html).toContain('宿主单项元数据采集器')
expect(html).toContain('无法判定')
expect(html).toContain('整盘总量 / 空闲 / 备份实际占盘:未接线')
// 原型里的示例容量不能被当成产品事实带进来。
@@ -521,7 +554,7 @@ describe('整盘占用与告警', () => {
expect(alerts.filter((item) => !item.known).map((item) => item.code)).toEqual(['disk_low', 'quota_low', 'both_low'])
})
- it('真实盘点:整盘色带取 statfs 容量与 st_blocks 实际占盘', () => {
+ it('真实快照:整盘色带取采集器容量与 st_blocks 实际占盘', () => {
const inventory = inventoryFixture()
const usage = inventoryUsage(inventory)
expect(usage).not.toBeNull()
@@ -535,35 +568,51 @@ describe('整盘占用与告警', () => {
expect(alerts.find((item) => item.code === 'quota_low')?.known).toBe(false)
const html = view({}, { inventory })
for (const text of [
- '只读挂载实测',
+ '宿主采集器实测',
'系统其他占用',
'备份实际占盘',
'可用',
'配额内/外 —(无配额字段)',
'文件系统已用',
- '挂载为只读',
- '挂载设备 20 与容器根盘 10 不同',
+ '只读挂载',
+ '宿主采集器:/dev/sdb1 挂在 /srv/kb-backups',
])
expect(html).toContain(text)
})
- it('挂载落在容器根盘:不把容器容量当主机磁盘,磁盘告警保持未知', () => {
+ it('不完整快照:容量图与占盘不使用部分字节', () => {
+ const base = inventoryFixture()
const inventory = inventoryFixture({
- mount: {
- container_root: '/',
- mount_verified: false,
- lives_on_container_root: true,
- read_only: true,
- evidence: '挂载设备与容器根盘相同(7):容量不代表备份主机磁盘',
+ 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(alerts.find((item) => item.code === 'disk_low')?.detail).toContain('不完整')
const html = view({}, { inventory })
- expect(html).toContain('容器根盘 · 不代表主机磁盘')
- expect(html).toContain('不据此判定备份主机磁盘')
+ expect(html).toContain('占盘未知 · 不使用部分字节')
+ expect(html).toContain('采集快照不完整:所有批次占盘与容量未知')
+ expect(html).toContain('占盘未知(采集不完整)')
expect(html).not.toContain('备份实际占盘 1.40 GiB')
})
diff --git a/web/src/BackupScheduleSection.tsx b/web/src/BackupScheduleSection.tsx
index f06567a..34554c1 100644
--- a/web/src/BackupScheduleSection.tsx
+++ b/web/src/BackupScheduleSection.tsx
@@ -13,8 +13,9 @@ import { fetchBackupInventory } from './backupInventory'
import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
import './storageBackup.css'
-export const formatBackupBytes = (bytes: number): string => {
- if (!bytes) return '—'
+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'
const mib = bytes / (1024 * 1024)
return mib >= 1024 ? `${(mib / 1024).toFixed(2)} GiB` : `${mib.toFixed(1)} MiB`
}
@@ -206,18 +207,27 @@ export interface InventoryUsage {
system_other: number
}
-// 只读挂载 + 实测容量 + 文件系统与容器根盘分离,三者同时成立才画整盘图。
-// 备份实际占盘取所有批次的 st_blocks 合计,不是 MANIFEST 的表观字节。
+// 完整新鲜的宿主快照 + 实测容量 + 采集器给出的文件系统,才画整盘图。
+// 备份实际占盘取快照的总实际分配,不是 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.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)
@@ -236,20 +246,29 @@ export function inventoryAlerts(inventory: BackupInventory | null): StorageAlert
const usage = inventoryUsage(inventory)
const latest = inventory?.batches[0]
const capacityKnown = Boolean(usage)
- const latestBytes = latest?.actual_bytes ?? 0
- const diskKnown = capacityKnown && latestBytes > 0
- const diskActive = diskKnown && latestBytes > usage!.free
+ const 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.mount.mount_verified
- ? '目录位于容器根盘,读数不代表备份主机磁盘'
- : !inventory.capacity.measured
- ? inventory.capacity.error || '未读到文件系统容量'
- : latestBytes <= 0
- ? '没有可参考的批次实际占盘'
- : `剩余可用 ${formatGib(usage!.free)} GiB,最近一批实际占盘 ${formatGib(latestBytes)} GiB(参考值,不含策略预留)`
+ ? '元数据快照未接线'
+ : !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',
@@ -308,6 +327,9 @@ export async function copyBackupPath(value: string, button?: HTMLButtonElement |
const manifestLabel = (batch: BackupInventoryBatch): string =>
batch.manifest_state === 'ok' ? '清单完整' : batch.manifest_state === 'missing' ? '清单缺失' : '清单损坏'
+const inventoryMetadataAvailable = (inventory: BackupInventory): boolean =>
+ inventory.metadata.present && inventory.metadata.valid && inventory.metadata.fresh
+
// 备份执行主机上的整库逻辑备份(全部业务库一次 pg_dump)。
// 页面只展示接口真实给出的读数;目录、配额、预留、子库路径、历史批次与恢复
// 验证在后端契约里还没有字段,保留原型位置并写明"未接线"。
@@ -407,8 +429,13 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
const alerts = disk ? storageAlerts(disk) : inventoryAlerts(inventory)
const latestBatch: BackupInventoryBatch | null = inventory?.batches[0] ?? null
const inventoryFigure = inventoryUsage(inventory)
- const inventoryReady = Boolean(inventory?.wired && !inventory.error)
- const readyInventory = inventory && inventory.wired && !inventory.error ? inventory : null
+ const inventoryReady = Boolean(
+ inventory?.wired && inventory.metadata.present && inventory.metadata.valid && inventory.metadata.fresh
+ )
+ const readyInventory =
+ inventory && inventory.wired && inventory.metadata.present && inventory.metadata.valid && inventory.metadata.fresh
+ ? inventory
+ : null
const inventoryDatabases = latestBatch?.databases.map((item) => item.name) ?? []
const scopeDatabases = inventoryDatabases.length ? inventoryDatabases : schedule.last_run_databases
const scopeDatabaseCount = scopeDatabases.length
@@ -443,12 +470,14 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
{inventoryLoading
- ? '文件盘点读取中'
+ ? '元数据读取中'
: inventoryReady
- ? '文件盘点已接线'
- : inventory?.error
- ? '文件盘点不可读'
- : '文件盘点未接线'}
+ ? inventory?.metadata.complete
+ ? '元数据快照有效'
+ : '元数据快照不完整'
+ : inventory?.metadata.error
+ ? '元数据快照不可用'
+ : '元数据未接线'}
@@ -461,7 +490,7 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
-
{inventory?.host_root || `${schedule.host_target || '(未配置)'} 本地备份根目录`}
- {inventoryReady ? '只读挂载盘点;平台没有写路径' : '备份目录未接线或不可读,不在页面猜测'}
+ {inventoryReady ? '宿主采集器快照(只读);平台没有写路径' : '元数据快照未接线或不可用,不在页面猜测'}
- 执行范围
@@ -480,7 +509,7 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
POST /api/v1/backup-schedule/run 没有单库参数,一次就是该主机全部业务库的整批
pg_dump。用单库按钮触发会连整批一起跑,因此本页不开放单库动作;单库恢复请复制「备份记录」里该库的
- 完整子目录(来自只读盘点),不要自己拼路径。
+ 完整子目录(来自宿主元数据快照),不要自己拼路径。
@@ -496,9 +525,13 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
{latestBatch
- ? `最近一批 ${latestBatch.stamp} · ${formatBackupMoment(latestBatch.created_at)} · ${scopeDatabaseCount} 个数据库 · 表观 ${formatBackupBytes(latestBatch.apparent_bytes)} · 实际占盘 ${formatBackupBytes(latestBatch.actual_bytes)} · ${latestBatch.duration_seconds} 秒`
+ ? `最近一批 ${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)}(文件盘点未接线,以下仅 SSH 结果)`
+ ? `SSH 读回最近一次 ${schedule.last_run_stamp} · ${databaseCount} 个数据库 · ${formatBackupBytes(schedule.last_run_total_bytes)}(元数据快照未接线,以下仅 SSH 结果)`
: '还没有从主机读到任何批次。'}
{schedule.running ? (
@@ -540,15 +573,7 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
整盘占用与告警
- {usage
- ? '已读到主机读数'
- : inventoryFigure
- ? inventory?.mount.read_only
- ? '只读挂载实测'
- : '实测(挂载可写)'
- : inventory?.capacity.measured
- ? '容器根盘(不可作主机容量)'
- : '未接线'}
+ {usage ? '已读到主机读数' : inventoryFigure ? '宿主采集器实测' : '占盘未知'}
{usage && disk ? (
@@ -652,33 +677,19 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
)· 文件系统已用 {formatGib(inventoryFigure.used)} GiB · 可用 {formatGib(inventoryFigure.free)} GiB
- {inventory.mount.evidence} · 挂载点 {inventory.root} · 采集于 {formatBackupMoment(inventory.observed_at)}
- {inventory.mount.read_only ? ' · 挂载为只读' : ' · 挂载不是只读(部署需改 :ro)'}
+ {inventory.mount.evidence} · 挂载点 {inventory.mount.mount_point || '—'} · 采集于{' '}
+ {formatBackupMoment(inventory.metadata.collected_at || inventory.observed_at)}
+ {inventory.mount.read_only ? ' · 只读挂载' : ' · 挂载可写(采集器只读)'}
>
- ) : inventory?.capacity.measured ? (
- <>
-
- 容器根盘 · 不代表主机磁盘
-
-
- 容器根盘实测 {formatGib(inventory.capacity.total_bytes)} GiB,可用{' '}
- {formatGib(inventory.capacity.available_bytes)} GiB:仅作排障,不据此判定备份主机磁盘。
-
- {inventory.mount.evidence}
- >
) : (
<>
- {inventoryLoading ? '正在读取只读挂载…' : '未接线 · 不显示估算容量'}
+ {inventoryLoading ? '正在读取宿主元数据快照…' : '占盘未知 · 不使用部分字节'}
{['系统其他占用', '备份实际占盘', '可用', '配额内/外'].map((label, index) => (
@@ -689,14 +700,15 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
))}
- 整盘总量 / 空闲 / 备份实际占盘:{inventoryError || inventory?.error || '未接线'}
+ 整盘总量 / 空闲 / 备份实际占盘:
+ {inventoryError || inventory?.metadata.error || inventory?.error || '未接线'}
>
)}
- 容量来自只读挂载目录的 statfs 实测,并与容器根盘比较设备号;同一设备时不把容器容量当主机容量。 备份占盘按文件
- st_blocks 统计(实际分配),不是 MANIFEST 的表观字节。配额与策略预留仍无后端字段,
- 四项告警中只有磁盘项能按实测判定。
+ 容量与实际占盘来自宿主单项元数据采集器(stat/du 元数据,不读数据库内容);API 不遍历备份目录。
+ 快照陈旧、缺失或不完整时,容量图与任何可写预测都不使用部分字节。配额与策略预留仍无后端字段,
+ 四项告警中只有磁盘项能按完整快照判定。
{storageAlertSummary(alerts)}
@@ -742,7 +754,7 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
value={inventory?.host_root || ''}
readOnly
disabled
- placeholder={inventoryReady ? '' : '只读盘点未接线'}
+ placeholder={inventoryReady ? '' : '元数据快照未接线'}
aria-label="备份主机上的目录(只读展示)"
/>
@@ -752,8 +764,8 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
{inventoryReady
- ? '目录来自只读挂载来源,只读展示;修改目录需部署变更,平台没有写接口。'
- : '只读盘点未接线:目录不可证明,不能按设置推定。'}
+ ? '目录来自宿主元数据快照,只读展示;修改目录需部署变更,平台没有写接口。'
+ : '元数据快照未接线:目录不可证明,不能按设置推定。'}
@@ -794,9 +840,19 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
检查目录(不可用)
- {inventoryReady
+ {snapshotPathsTrusted
? '目录来自宿主元数据快照,只读展示;修改目录需部署变更,平台没有写接口。'
- : '元数据快照未接线:目录不可证明,不能按设置推定。'}
+ : snapshotState === 'stale'
+ ? '元数据快照已过期:目录不可验证,不沿用旧路径;等待宿主重新采集。'
+ : snapshotState === 'missing'
+ ? '元数据快照缺失:目录不可验证,需先在备份主机运行采集器。'
+ : snapshotState === 'invalid'
+ ? '元数据快照无效:目录不可验证,需检查快照内容。'
+ : snapshotState === 'loading'
+ ? inventoryError
+ ? '元数据快照读取失败:目录不可验证,请检查 API 到快照挂载的接线。'
+ : '尚未读取元数据快照:目录不可验证。'
+ : '元数据快照未接线:目录不可证明,不能按设置推定。'}