fix(library): 打通恢复验证的正常恢复与页面联动
build / build (push) Successful in 1m35s

B1/B2:演练在同一维护切点做两次真实捕获(写前镜像与来源身份),
写集合在写第一笔之前落盘并登记;恢复走限定范围的 RestoreDrill,
复用同一份 DS01 身份合同与 Apply 原语整段回放,不再让同快照必被拒绝。
worker 接治理维护生命周期(实例+scope 行、真实入口状态、成功才释放),
held 保留行并由同 job 的 library.recover 收口(kind 过滤贯通 verify)。
B3:证据优先,failed/invalid 与读取错误即使 env=true 也拒绝。
B4/B5:GET 投影在飞作业,子面板回调父页面轮询;观测绑定 scope 与代次,
刷新失败明确过期,不再显示旧的"已验证"。
迁移 79 不自动 down;未部署、未调用业务目标。
This commit is contained in:
姚章浩
2026-11-03 11:14:27 +08:00
parent 5e1482e349
commit f9457fab52
22 changed files with 1145 additions and 136 deletions
+1
View File
@@ -154,6 +154,7 @@ const base: ViewProps = {
canRestore: false,
sync: { canSign: false, pendingGrant: false, onGrant: vi.fn(), canStart: false, pending: false, onStart: vi.fn() },
baseline: { canStart: false, pending: false, onStart: vi.fn() },
verification: { onAccepted: vi.fn(), onComplete: vi.fn() },
restore: null,
restoreNotice: null,
pendingRestore: false,
+46 -2
View File
@@ -117,6 +117,12 @@ interface ViewProps {
sync: ReleaseSyncActions
// 目标非空又没有生效版本时,唯一入口是"建立目标权威基线"(管理员)。
baseline: ReleaseBaselineActions
// 恢复验证(真实作业)的接受/终态要回到父页面:父级据此启动轮询并在终态读回
// overview/维护/闸口,不能只在子面板里刷新自己。
verification: {
onAccepted: (jobId: string) => void
onComplete: (jobId: string) => void
}
// 按版本恢复是管理员动作:工程师看得到条件,但拿不到恢复入口。
canRestore: boolean
restore: LibraryRestoreAvailability | null
@@ -724,6 +730,7 @@ function ProtectionCard({
baseline,
scope,
onOpen,
verification,
}: {
production: LibraryOverview['production'] | null
// 没有目标观测时显示的原因(加载中 / 整体读取失败 / 当前范围没数据)。
@@ -737,6 +744,10 @@ function ProtectionCard({
baseline: ReleaseBaselineActions
scope: Scope
onOpen: () => void
verification: {
onAccepted: (jobId: string) => void
onComplete: (jobId: string) => void
}
}) {
const backupKnown = prebackup.state === 'known' && prebackup.version
// 基线入口只在"目标非空、却没有生效版本"时才是答案;空库走首次同步(预备份+登记),
@@ -804,7 +815,12 @@ function ProtectionCard({
<dt>恢复条件</dt>
<dd>{gate.reasons.length === 0 ? '已满足' : `缺 ${gate.reasons.length} 项`}</dd>
</dl>
<RestoreVerificationSection scope={scope} isAdmin={sync.canSign} />
<RestoreVerificationSection
scope={scope}
isAdmin={sync.canSign}
onAccepted={verification.onAccepted}
onComplete={verification.onComplete}
/>
{gate.reasons.length > 0 ? (
<ul className="rel-gate" aria-label="恢复与启动条件">
{gate.reasons.map((reason) => (
@@ -853,6 +869,10 @@ interface ReadyProps {
onOpen: () => void
sync: ReleaseSyncActions
baseline: ReleaseBaselineActions
verification: {
onAccepted: (jobId: string) => void
onComplete: (jobId: string) => void
}
}
function ReadyBody({
@@ -866,6 +886,7 @@ function ReadyBody({
authorization,
sync,
baseline,
verification,
canCapture,
canWrite,
pendingCapture,
@@ -889,6 +910,7 @@ function ReadyBody({
baseline={baseline}
scope={view.scope}
onOpen={onOpen}
verification={verification}
/>
</div>
<div className="rel-panel rel-jobbar">
@@ -1412,6 +1434,7 @@ export function ReleaseTargetsView(props: ViewProps) {
canWrite,
sync,
baseline,
verification,
canRestore,
restore,
restoreNotice,
@@ -1635,6 +1658,7 @@ export function ReleaseTargetsView(props: ViewProps) {
authorization={authorization}
sync={sync}
baseline={baseline}
verification={verification}
canCapture={canCapture}
canWrite={canWrite}
pendingCapture={pendingCapture}
@@ -1793,6 +1817,9 @@ export function ReleaseTargets() {
// 只靠 jobs/overview 判断会让页面在投递后立刻停止轮询,恢复完成也停在旧状态(F12)。
const [pendingRecovery, setPendingRecovery] = useState(false)
const recoveryStartedAt = useRef(0)
// 恢复验证是独立业务作业:投递后父页面必须自己轮询 overview/维护/闸口,
// 只在子面板刷新证据会让页面停在点击前的状态(审核 B4)。
const [activeVerifyJob, setActiveVerifyJob] = useState('')
const [pendingGrant, setPendingGrant] = useState(false)
// 轮询覆盖"投递 → 终态读回":投递中的动作也算在跑(点完到 worker 落库之间
// 有一次空窗,只看已有作业会让页面停在"尚未启动")。终态(成功/失败/取消)
@@ -1800,7 +1827,14 @@ export function ReleaseTargets() {
const polling = libraryPollingActive({
captures: jobs,
overviews,
pending: pendingCapture || pendingSync || pendingBaseline || pendingRestore || pendingSyncGrant || pendingGrant,
pending:
pendingCapture ||
pendingSync ||
pendingBaseline ||
pendingRestore ||
pendingSyncGrant ||
pendingGrant ||
activeVerifyJob !== '',
recoveryPending: pendingRecovery,
maintenances,
})
@@ -1949,6 +1983,16 @@ export function ReleaseTargets() {
pending: pendingBaseline,
onStart: () => void startBaseline(),
}}
verification={{
onAccepted: (jobId) => {
setActiveVerifyJob(jobId)
void load()
},
onComplete: () => {
setActiveVerifyJob('')
void load()
},
}}
canRestore={canRestore}
restore={restore}
restoreNotice={restoreNotice}
@@ -0,0 +1,171 @@
// @vitest-environment jsdom
import { act } from 'react'
import { createRoot } from 'react-dom/client'
import type { Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { RestoreVerificationSection } from './RestoreVerificationSection'
// 审核 B4/B5 的挂载级回归(GPT-6 的离线挂载反例转成通过断言):
// 全部 fetch 都是 fake,不发任何 8088/云请求;这不是页面验收。
const target = {
instance: 'fixture',
project: 'fixture',
internal_kb: 'fixture-internal',
external_kb: 'fixture-external',
index: 'fixture-index',
s3_bucket: 'fixture-bucket',
tenant_id: 1,
database_configured: true,
}
const passed = {
id: 'e',
scope: 'internal',
status: 'passed',
snapshot_id: 'a'.repeat(64),
job_id: 'old-internal-job',
started_at: '2026-01-01T00:00:00Z',
finished_at: '2026-01-01T00:01:00Z',
}
const internalView = {
scope: 'internal',
verified: true,
reason: '',
target,
latest: passed,
history: [passed],
running: false,
}
const externalView = {
scope: 'external',
verified: false,
reason: '还没有对当前目标做过恢复验证',
target,
latest: null,
history: [],
running: false,
}
let container: HTMLDivElement
let root: Root
const jsonResponse = (body: unknown, status = 200) => ({
ok: status >= 200 && status < 300,
status,
json: async () => body,
})
const press = async (label: string) => {
const button = [...container.querySelectorAll('button')].find((item) => item.textContent === label)
if (!button) throw new Error(`button ${label} not found: ${container.textContent}`)
await act(async () => {
button.click()
})
}
beforeEach(() => {
;(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true
container = document.createElement('div')
document.body.appendChild(container)
root = createRoot(container)
})
afterEach(() => {
act(() => root.unmount())
container.remove()
vi.unstubAllGlobals()
})
describe('RestoreVerificationSection mounted (offline fixtures)', () => {
it('刷新失败时旧证据标成过期,不再显示"已验证(当前目标)"', async () => {
let mode: 'ok' | 'fail' = 'ok'
vi.stubGlobal('fetch', async () => {
if (mode === 'fail') throw new Error('offline fixture read failed')
return jsonResponse(internalView)
})
await act(async () => {
root.render(<RestoreVerificationSection scope="internal" isAdmin />)
})
expect(container.textContent).toContain('已验证(当前目标)')
mode = 'fail'
await press('刷新验证状态')
expect(container.textContent).not.toContain('已验证(当前目标)')
expect(container.textContent).toContain('上次观测已过期')
expect(container.textContent).toContain('刷新失败')
expect(container.textContent).toContain('offline fixture read failed')
})
it('切 scope 不沿用旧 scope 的通过证据', async () => {
vi.stubGlobal('fetch', async (url: string) => {
if (String(url).includes('scope=external')) return new Promise(() => undefined)
return jsonResponse(internalView)
})
await act(async () => {
root.render(<RestoreVerificationSection scope="internal" isAdmin />)
})
expect(container.textContent).toContain('old-internal-job')
await act(async () => {
root.render(<RestoreVerificationSection scope="external" isAdmin />)
})
// 新 scope 的观测还没回来:宁可显示"还没读到",也不能沿用旧 scope 的证据。
expect(container.textContent).toContain('还没有读到验证状态')
expect(container.textContent).not.toContain('fixture-internal')
expect(container.textContent).not.toContain('old-internal-job')
expect(container.textContent).not.toContain('已验证(当前目标)')
})
it('接受作业后父页面收到 onAccepted,终态收到 onComplete', async () => {
const onAccepted = vi.fn()
const onComplete = vi.fn()
let started = false
vi.stubGlobal('fetch', async (url: string, init?: { method?: string }) => {
if (init?.method === 'POST') {
started = true
return jsonResponse({ job: { id: 'libverify-internal-1', scope: 'internal' }, reused: false }, 202)
}
if (String(url).includes('scope=internal')) {
if (!started) return jsonResponse({ ...internalView, verified: false, latest: null, history: [] })
if (container.textContent?.includes('验证执行中')) {
return jsonResponse({
...externalView,
scope: 'internal',
latest: { ...passed, status: 'passed', job_id: 'libverify-internal-1' },
running: false,
})
}
return jsonResponse({
...externalView,
scope: 'internal',
running: true,
job_id: 'libverify-internal-1',
stage: 'restore',
})
}
return jsonResponse(externalView)
})
await act(async () => {
root.render(
<RestoreVerificationSection scope="internal" isAdmin onAccepted={onAccepted} onComplete={onComplete} />
)
})
await press('跑一次恢复验证(维护隔离)')
expect(onAccepted).toHaveBeenCalledWith('libverify-internal-1')
expect(container.textContent).toContain('验证执行中')
await press('刷新验证状态')
expect(onComplete).toHaveBeenCalledWith('libverify-internal-1')
})
it('HTTP 失败按失败显示,不把响应当通过证据', async () => {
vi.stubGlobal('fetch', async () =>
jsonResponse({ scope: 'internal', verified: true, reason: '证据读取失败', target, history: [] }, 503)
)
await act(async () => {
root.render(<RestoreVerificationSection scope="internal" isAdmin />)
})
expect(container.textContent).toContain('读取验证状态失败')
expect(container.textContent).not.toContain('已验证(当前目标)')
})
})
+42 -1
View File
@@ -25,7 +25,13 @@ const view = (overrides: Partial<LibraryVerificationView> = {}): LibraryVerifica
...overrides,
})
const render = (value: LibraryVerificationView | null, isAdmin = true, pending = false, error: string | null = null) =>
const render = (
value: LibraryVerificationView | null,
isAdmin = true,
pending = false,
error: string | null = null,
stale = false
) =>
renderToStaticMarkup(
<RestoreVerificationView
view={value}
@@ -34,6 +40,7 @@ const render = (value: LibraryVerificationView | null, isAdmin = true, pending =
pending={pending}
error={error}
notice=""
stale={stale}
onRun={() => undefined}
onReload={() => undefined}
/>
@@ -96,6 +103,40 @@ describe('RestoreVerificationView', () => {
expect(html).toContain('跑一次恢复验证')
})
// 审核 B5:刷新失败时旧证据必须明确标成过期,不能再显示"已验证(当前目标)"。
it('stale 观测不得显示当前已通过,并给出刷新失败说明', () => {
const html = render(
view({
verified: true,
reason: '',
latest: {
id: 'libverify-internal-job1',
scope: 'internal',
status: 'passed',
snapshot_id: '0f9b39a16738',
job_id: 'libverify-internal-1',
started_at: '2026-11-03T01:00:00Z',
finished_at: '2026-11-03T01:02:00Z',
},
}),
true,
false,
'读取验证状态失败:offline fixture read failed',
true
)
expect(html).not.toContain('已验证(当前目标)')
expect(html).toContain('上次观测已过期')
expect(html).toContain('刷新失败')
expect(html).toContain('offline fixture read failed')
})
// 审核 B4:在飞作业必须体现在按钮/状态上。
it('running 时显示执行中并禁用发起按钮', () => {
const html = render(view({ running: true, job_id: 'libverify-internal-9', stage: 'restore' }))
expect(html).toContain('验证执行中')
expect(html).toContain('disabled')
})
it('投递被拒时显示后端逐条原因', () => {
const html = render(view(), true, false, '恢复验证被拒绝:生产写入闸口关闭')
expect(html).toContain('生产写入闸口关闭')
+87 -22
View File
@@ -22,6 +22,8 @@ export interface RestoreVerificationViewProps {
pending: boolean
error: string | null
notice: string
// stale 表示这份 view 是上一次成功读取的结果,本次刷新失败,不能当当前结论。
stale: boolean
onRun: () => void
onReload: () => void
}
@@ -33,17 +35,22 @@ const stampText = (value: string): string => {
}
export function RestoreVerificationView(props: RestoreVerificationViewProps) {
const { view, scope, isAdmin, pending, error, notice, onRun, onReload } = props
const status = verificationStatusText(view)
const { view, scope, isAdmin, pending, error, notice, stale, onRun, onReload } = props
const status = verificationStatusText(view, stale)
const latest = view?.latest ?? null
const running = Boolean(view?.running)
const tone = view?.verified ? 'green' : latest?.status === 'failed' ? 'red' : 'gray'
const tone = stale ? 'gray' : view?.verified ? 'green' : latest?.status === 'failed' ? 'red' : 'gray'
return (
<section className="rel-verification" aria-label="恢复验证">
<header className="rel-between">
<h3>恢复验证(当前整库目标)</h3>
<span className={`rel-pill ${tone}`}>{status}</span>
</header>
{stale ? (
<p className="rel-warn">
刷新失败:下面是上一次成功读取的观测,已过期,不能代表当前目标;在刷新成功之前不得据此判断"已验证"。
</p>
) : null}
{view ? (
<ul className="rel-target-lines" aria-label="恢复验证目标">
{verificationTargetLines(view.target, scope).map((line) => (
@@ -81,36 +88,89 @@ export function RestoreVerificationView(props: RestoreVerificationViewProps) {
)
}
// 容器:挂载即读一次,之后每 5 秒刷新(验证作业在 worker 里跑,页面只读证据)。
export function RestoreVerificationSection({ scope, isAdmin }: { scope: string; isAdmin: boolean }) {
// 容器:挂载即读一次,之后每 3 秒刷新(验证作业在 worker 里跑,页面只读证据)。
//
// 两个身份必须分开:
// - 观测身份 = scope + 请求代次:切 scope 立即清旧结果,晚到的旧响应被丢弃;
// - 作业身份 = 投递返回的 job_id:它驱动父页面的 load/轮询,终态再通知一次。
export function RestoreVerificationSection({
scope,
isAdmin,
onAccepted,
onComplete,
}: {
scope: string
isAdmin: boolean
onAccepted?: (jobId: string) => void
onComplete?: (jobId: string) => void
}) {
const [view, setView] = useState<LibraryVerificationView | null>(null)
const [stale, setStale] = useState(false)
const [pending, setPending] = useState(false)
const [error, setError] = useState<string | null>(null)
const [notice, setNotice] = useState('')
const mounted = useRef(true)
const generation = useRef(0)
const viewScopeRef = useRef('')
const acceptedJob = useRef('')
const sawRunning = useRef(false)
const onCompleteRef = useRef(onComplete)
onCompleteRef.current = onComplete
const reload = useCallback(
(signal?: AbortSignal) => {
fetchLibraryVerification(scope, signal)
.then((next) => {
if (mounted.current && next) setView(next)
})
.catch(() => undefined)
},
[scope]
)
const reload = useCallback((targetScope: string, signal?: AbortSignal) => {
const request = ++generation.current
return fetchLibraryVerification(targetScope, signal)
.then((next) => {
// 晚到的旧 scope/旧代次响应一律丢弃:它不能改写当前 scope 的观测。
if (!mounted.current || request !== generation.current) return
setView(next)
viewScopeRef.current = next.scope
setStale(false)
setError(null)
const job = acceptedJob.current
if (!job) return
if (next.running) {
sawRunning.current = true
return
}
// 终态:本作业不再出现在在飞集合里(或被证据行点名),通知父页面做最后一次读回。
if (sawRunning.current || next.job_id === job || next.latest?.job_id === job) {
acceptedJob.current = ''
sawRunning.current = false
onCompleteRef.current?.(job)
}
})
.catch((err: unknown) => {
if (!mounted.current || request !== generation.current) return
if ((err as Error)?.name === 'AbortError') return
// 刷新失败:同 scope 的旧结果保留但明确标成过期;别的 scope 的旧结果直接丢掉。
setStale(true)
setView((current) => (viewScopeRef.current === targetScope ? current : null))
setError(err instanceof Error ? err.message : '读取恢复验证状态失败')
})
}, [])
useEffect(() => {
mounted.current = true
// 切 scope:旧 scope 的证据不能继续显示为"当前目标已验证"。
setView(null)
viewScopeRef.current = ''
setStale(false)
setError(null)
setNotice('')
acceptedJob.current = ''
sawRunning.current = false
const controller = new AbortController()
reload(controller.signal)
const timer = setInterval(() => reload(controller.signal), 5000)
void reload(scope, controller.signal)
const timer = setInterval(() => void reload(scope, controller.signal), 3000)
return () => {
mounted.current = false
controller.abort()
clearInterval(timer)
}
}, [reload])
// reload 依赖 viewScope(用于判断旧结果是否同 scope),不能让它的身份变化重启轮询。
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [scope])
const onRun = useCallback(() => {
setPending(true)
@@ -118,12 +178,16 @@ export function RestoreVerificationSection({ scope, isAdmin }: { scope: string;
setNotice('')
enqueueLibraryVerification(scope)
.then((accepted) => {
setNotice(`已投递恢复验证作业 ${accepted.job_id};进度在作业进度里可见,完成后这里显示证据。`)
reload()
acceptedJob.current = accepted.job_id
sawRunning.current = false
setNotice(`已投递恢复验证作业 ${accepted.job_id};页面会自动刷新进度与终态,父级作业/维护/闸口同步更新。`)
// 父页面必须立刻知道"有一个验证在跑":否则它不会轮询 overview/维护。
onAccepted?.(accepted.job_id)
void reload(scope)
})
.catch((err: unknown) => setError(err instanceof Error ? err.message : '投递恢复验证失败'))
.finally(() => setPending(false))
}, [scope, reload])
}, [scope, reload, onAccepted])
return (
<RestoreVerificationView
@@ -133,8 +197,9 @@ export function RestoreVerificationSection({ scope, isAdmin }: { scope: string;
pending={pending}
error={error}
notice={notice}
stale={stale}
onRun={onRun}
onReload={() => reload()}
onReload={() => void reload(scope)}
/>
)
}
+27 -1
View File
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
fetchLibraryVerification,
parseVerificationRecord,
parseVerificationView,
verificationStatusText,
@@ -29,6 +30,31 @@ const passed = {
finished_at: '2026-11-03T01:02:00Z',
}
const response = (body: unknown, status = 200) => ({
ok: status >= 200 && status < 300,
status,
json: async () => body,
})
afterEach(() => vi.unstubAllGlobals())
describe('fetchLibraryVerification 的失败与身份', () => {
it('HTTP 错误必须抛错,不能把响应当证据', async () => {
vi.stubGlobal('fetch', async () => response({ scope: 'internal', reason: '存储不可用' }, 503))
await expect(fetchLibraryVerification('internal')).rejects.toThrow('存储不可用')
})
it('响应 scope 与请求不一致时拒绝', async () => {
vi.stubGlobal('fetch', async () => response({ scope: 'external', verified: true, target, history: [] }))
await expect(fetchLibraryVerification('internal')).rejects.toThrow('不一致')
})
it('不可解析的响应按失败处理', async () => {
vi.stubGlobal('fetch', async () => response({ nope: true }))
await expect(fetchLibraryVerification('internal')).rejects.toThrow('不可解析')
})
})
describe('restoreVerification parsing', () => {
it('只把后端明确 true 当作已验证', () => {
const view = parseVerificationView({ scope: 'internal', target, verified: 'true', reason: '', history: [] })
+22 -6
View File
@@ -35,6 +35,8 @@ export interface LibraryVerificationView {
history: LibraryVerificationRecord[]
running?: boolean
job_id?: string
state?: string
stage?: string
}
function record(value: unknown): value is Record<string, unknown> {
@@ -97,19 +99,29 @@ export function parseVerificationView(value: unknown): LibraryVerificationView |
history,
running: bool(value.running),
job_id: text(value.job_id) || undefined,
state: text(value.state) || undefined,
stage: text(value.stage) || undefined,
}
}
export async function fetchLibraryVerification(
scope: string,
signal?: AbortSignal
): Promise<LibraryVerificationView | null> {
// fetchLibraryVerification 只返回**这份 scope** 的观测:
// HTTP 非 2xx、响应不可解析、或响应 scope 与请求不一致都抛错。
// 调用方据此把"读失败"和"没有证据"分开显示,不能拿旧绿色遮住失败(审核 B5)。
export async function fetchLibraryVerification(scope: string, signal?: AbortSignal): Promise<LibraryVerificationView> {
const response = await fetch(`/api/v1/library/verifications?scope=${encodeURIComponent(scope)}`, {
headers: { Accept: 'application/json' },
signal,
})
const value = (await response.json().catch(() => null)) as unknown
return parseVerificationView(value)
if (!response.ok) {
if (record(value) && text(value.reason)) throw new Error(`读取验证状态失败:${text(value.reason)}`)
throw new Error(`读取验证状态失败(HTTP ${response.status})`)
}
const parsed = parseVerificationView(value)
if (!parsed) throw new Error('读取验证状态失败:响应不可解析')
if (parsed.scope !== scope)
throw new Error(`读取验证状态失败:响应 scope=${parsed.scope || '空'} 与请求 ${scope} 不一致`)
return parsed
}
export interface LibraryVerificationAccepted {
@@ -150,8 +162,12 @@ export function verificationTargetLines(target: LibraryVerificationTarget, scope
]
}
export function verificationStatusText(view: LibraryVerificationView | null): string {
// verificationStatusText 只在**当前 scope 的新鲜观测**上允许说"已验证"。
// stale 表示这次刷新失败、显示的是上一次结果:它既不是当前结论,也不能是绿灯。
export function verificationStatusText(view: LibraryVerificationView | null, stale = false): string {
if (!view) return '还没有读到验证状态'
if (stale) return '上次观测已过期(刷新失败)'
if (view.running) return '验证执行中'
if (view.verified) return '已验证(当前目标)'
if (view.latest) return view.latest.status === 'failed' ? '最近一次未通过' : '未通过'
return '还没有验证记录'