feat(library): 整库发布身份、写集合与收尾边界
build / build (push) Successful in 1m45s

执行时真实时钟与持久授权回读(撤销/过期即停并保留预备份)、写集合写前落盘、
租约与 attempt 身份、恢复队列与原发送身份分离、成功收尾必须释放维护后再登记终态。
This commit is contained in:
姚章浩
2026-11-01 11:35:10 +08:00
parent 5afd8c0140
commit 8d838d9cb4
82 changed files with 4809 additions and 551 deletions
+45
View File
@@ -0,0 +1,45 @@
import { afterEach, expect, it, vi } from 'vitest'
import { renderToStaticMarkup } from 'react-dom/server'
import { associateLegacySource, LegacySourceAssociation } from './LegacySourceAssociation'
afterEach(() => vi.unstubAllGlobals())
const reply = (status: number, data: unknown) => new Response(JSON.stringify(data), { status })
it('only sends exact snapshot and scope; association is not publishing', async () => {
const fetchMock = vi
.fn()
.mockResolvedValue(
reply(200, { associated: true, published: false, snapshot_id: 'snapshot', source_id: 'a'.repeat(64) })
)
vi.stubGlobal('fetch', fetchMock)
expect(await associateLegacySource('internal', 'snapshot')).toBe('a'.repeat(64))
expect(fetchMock.mock.calls).toHaveLength(1)
expect(fetchMock.mock.calls[0][0]).toBe('/api/v1/library/source-associations')
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({ scope: 'internal', snapshot_id: 'snapshot' })
})
it('rejects wrong-snapshot and incomplete readback, and shows evidence errors', async () => {
for (const value of [
{ associated: true, published: false, snapshot_id: 'wrong', source_id: 'a'.repeat(64) },
{ associated: true, snapshot_id: 'snapshot' },
]) {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(reply(200, value)))
await expect(associateLegacySource('internal', 'snapshot')).rejects.toThrow('来源关联回执')
}
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(reply(409, { error: 'original capture identity mismatch' })))
await expect(associateLegacySource('internal', 'snapshot')).rejects.toThrow('original capture identity mismatch')
})
it('hides association controls from non-admin and distinguishes it from publication', () => {
expect(
renderToStaticMarkup(
<LegacySourceAssociation scope="internal" snapshots={[]} admin={false} onBound={async () => {}} />
)
).toBe('')
const html = renderToStaticMarkup(
<LegacySourceAssociation scope="internal" snapshots={[]} admin onBound={async () => {}} />
)
expect(html).toContain('只追加治理关联')
expect(html).toContain('disabled')
expect(html).toContain('核验原证据并关联')
})
+83
View File
@@ -0,0 +1,83 @@
import { useState } from 'react'
import type { LibrarySnapshot } from './librarySnapshots'
export async function associateLegacySource(scope: string, snapshotID: string): Promise<string> {
const response = await fetch('/api/v1/library/source-associations', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({ scope, snapshot_id: snapshotID }),
})
const value = (await response.json().catch(() => null)) as Record<string, unknown> | null
if (!response.ok)
throw new Error(typeof value?.error === 'string' ? value.error : `来源关联失败(HTTP ${response.status})`)
if (
value?.associated !== true ||
value.published !== false ||
value.snapshot_id !== snapshotID ||
typeof value.source_id !== 'string' ||
!/^[a-f0-9]{64}$/.test(value.source_id)
) {
throw new Error('来源关联回执不完整或快照身份不符')
}
return value.source_id
}
export function LegacySourceAssociation({
scope,
snapshots,
admin,
onBound,
}: {
scope: string
snapshots: LibrarySnapshot[]
admin: boolean
onBound: () => Promise<void>
}) {
const [snapshotID, setSnapshotID] = useState('')
const [pending, setPending] = useState(false)
const [notice, setNotice] = useState('')
if (!admin) return null
const choices = snapshots.filter((item) => item.scope === scope)
const bind = async () => {
if (pending || !choices.some((item) => item.snapshot_id === snapshotID)) return
setPending(true)
setNotice('')
try {
const sourceID = await associateLegacySource(scope, snapshotID)
setNotice(`来源证据已核验关联:${sourceID}。没有发布内容;发布授权与写入闸门仍独立检查。`)
await onBound()
} catch (error) {
setNotice(error instanceof Error ? error.message : '来源关联失败')
} finally {
setPending(false)
}
}
return (
<details className="rel-source-identity">
<summary>关联旧封存的原始来源证据(管理员)</summary>
<p>
只追加治理关联,保留原快照与摘要。服务端核对原捕获响应、执行器指纹及清单;备份、来源不符或证据缺失均拒绝,不凭同一范围认领。
</p>
<label>
待核验的历史快照
<select
aria-label="待核验的历史快照"
value={snapshotID}
disabled={pending}
onChange={(event) => setSnapshotID(event.target.value)}
>
<option value="">选择准确快照摘要</option>
{choices.map((item) => (
<option key={item.snapshot_id} value={item.snapshot_id}>
{item.snapshot_id}
</option>
))}
</select>
</label>
<button type="button" disabled={pending || !snapshotID} onClick={() => void bind()}>
{pending ? '核验中…' : '核验原证据并关联'}
</button>
{notice ? <p role="status">{notice}</p> : null}
</details>
)
}
+71 -48
View File
@@ -1,3 +1,4 @@
import { LegacySourceAssociation } from './LegacySourceAssociation'
import { useCallback, useEffect, useRef, useState } from 'react'
import {
createLibraryRestoreAuthorization,
@@ -1474,6 +1475,19 @@ export function ReleaseTargetsView(props: ViewProps) {
<dd>{target ? '完整快照' : '未接入'}</dd>
</div>
</dl>
{target?.source_identity ? (
<details className="rel-source-identity">
<summary>来源身份与完整摘要</summary>
<p>
来源实例:{target.source_identity.project} / {target.source_identity.app}
</p>
<p>
来源租户 / 知识库:{target.source_identity.tenant_id} / {target.source_identity.knowledge_base_id}
</p>
<p>来源身份:{target.source_id}</p>
<p>快照摘要:{target.snapshot_id}</p>
</details>
) : null}
<ul className="rel-checklist">
<li className={target ? 'ok' : 'unknown'}>
{target
@@ -1639,14 +1653,14 @@ export function ReleaseTargets() {
}
const startSync = async () => {
if (!targetSnapshot) {
setNotice('还没有可发布的测试封存')
if (!targetSnapshot || !current?.test_sealed?.source_id) {
setNotice('还没有与当前来源绑定的可发布封存,请刷新状态')
return
}
setPendingSync(true)
setNotice(null)
try {
const accepted = await enqueueLibrarySync(scope, targetSnapshot)
const accepted = await enqueueLibrarySync(scope, targetSnapshot, current?.test_sealed?.source_id ?? '')
setNotice(`已投递同步:${accepted.job_id}(先固定测试版本并生成预备份,再写目标)`)
await load()
} catch (syncError) {
@@ -1801,50 +1815,59 @@ export function ReleaseTargets() {
}, [pendingRecovery, maintenances, scope, load])
return (
<ReleaseTargetsView
page={page}
jobs={jobs}
overview={overviews[scope]}
loading={loading}
error={error}
notice={notice}
scope={scope}
onScope={(next) => {
setScope(next)
setExpandedSnapshot(null)
}}
drawerOpen={drawerOpen}
onDrawer={setDrawerOpen}
expandedSnapshot={expandedSnapshot}
onExpandSnapshot={setExpandedSnapshot}
pendingCapture={pendingCapture}
canCapture={canCapture}
canWrite={canWrite}
sync={{
canSign: canSignSync,
pendingGrant: pendingSyncGrant,
onGrant: () => void grantSync(),
canStart: current?.gate.sync_allowed === true,
pending: pendingSync,
onStart: () => void startSync(),
}}
baseline={{
canStart: canSignSync,
pending: pendingBaseline,
onStart: () => void startBaseline(),
}}
canRestore={canRestore}
restore={restore}
restoreNotice={restoreNotice}
pendingRestore={pendingRestore}
pendingGrant={pendingGrant}
onGrantRestore={() => void grantRestore()}
onRestore={() => void startRestore()}
maintenance={maintenances[scope]}
now={now}
onRefresh={() => void load()}
onCapture={() => void startCapture()}
onRecover={(windowJobID) => void recover(windowJobID)}
/>
<>
<ReleaseTargetsView
page={page}
jobs={jobs}
overview={overviews[scope]}
loading={loading}
error={error}
notice={notice}
scope={scope}
onScope={(next) => {
setScope(next)
setExpandedSnapshot(null)
}}
drawerOpen={drawerOpen}
onDrawer={setDrawerOpen}
expandedSnapshot={expandedSnapshot}
onExpandSnapshot={setExpandedSnapshot}
pendingCapture={pendingCapture}
canCapture={canCapture}
canWrite={canWrite}
sync={{
canSign: canSignSync,
pendingGrant: pendingSyncGrant,
onGrant: () => void grantSync(),
canStart: current?.gate.sync_allowed === true && Boolean(current?.test_sealed?.source_id),
pending: pendingSync,
onStart: () => void startSync(),
}}
baseline={{
canStart: canSignSync,
pending: pendingBaseline,
onStart: () => void startBaseline(),
}}
canRestore={canRestore}
restore={restore}
restoreNotice={restoreNotice}
pendingRestore={pendingRestore}
pendingGrant={pendingGrant}
onGrantRestore={() => void grantRestore()}
onRestore={() => void startRestore()}
maintenance={maintenances[scope]}
now={now}
onRefresh={() => void load()}
onCapture={() => void startCapture()}
onRecover={(windowJobID) => void recover(windowJobID)}
/>
<LegacySourceAssociation
key={scope}
scope={scope}
snapshots={page?.snapshots ?? []}
admin={role === 'admin'}
onBound={() => load()}
/>
</>
)
}
+18 -2
View File
@@ -22,6 +22,8 @@ export interface LibraryCompatibility {
}
export interface LibrarySnapshot {
source_id?: string
source_identity?: { project: string; app: string; scope: string; tenant_id: number; knowledge_base_id: string }
snapshot_id: string
scope: string
knowledge_base_id: string
@@ -104,6 +106,16 @@ function parseSnapshot(raw: unknown): LibrarySnapshot | null {
}
return {
snapshot_id: snapshotID,
source_id: text(raw.source_id) || undefined,
source_identity: record(raw.source_identity)
? {
project: text(raw.source_identity.project),
app: text(raw.source_identity.app),
scope: text(raw.source_identity.scope),
tenant_id: num(raw.source_identity.tenant_id),
knowledge_base_id: text(raw.source_identity.knowledge_base_id),
}
: undefined,
scope: text(raw.scope),
knowledge_base_id: text(raw.knowledge_base_id),
tenant_id: num(raw.tenant_id),
@@ -288,11 +300,15 @@ export interface LibrarySyncAccepted {
}
// 启动同步:闸口未齐时接口返回 503 与逐条缺项,页面照实显示,不假装已启动。
export async function enqueueLibrarySync(scope: string, targetSnapshotID: string): Promise<LibrarySyncAccepted> {
export async function enqueueLibrarySync(
scope: string,
targetSnapshotID: string,
sourceID: string
): Promise<LibrarySyncAccepted> {
const response = await fetch('/api/v1/library/syncs', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({ scope, target_snapshot_id: targetSnapshotID }),
body: JSON.stringify({ scope, target_snapshot_id: targetSnapshotID, source_id: sourceID }),
})
const value = (await response.json().catch(() => null)) as unknown
if (!response.ok) {
+7 -3
View File
@@ -33,11 +33,15 @@ describe('发布页的同步授权与执行接线', () => {
.fn()
.mockResolvedValue(jsonResponse(202, { job: { id: 'libsync-internal-1', scope: 'internal' }, reused: false }))
vi.stubGlobal('fetch', fetchMock)
const accepted = await enqueueLibrarySync('internal', 'snap-1')
const accepted = await enqueueLibrarySync('internal', 'snap-1', 'source-bound')
expect(accepted.job_id).toBe('libsync-internal-1')
const [url, init] = fetchMock.mock.calls[0]
expect(url).toBe('/api/v1/library/syncs')
expect(JSON.parse(init.body)).toEqual({ scope: 'internal', target_snapshot_id: 'snap-1' })
expect(JSON.parse(init.body)).toEqual({
scope: 'internal',
target_snapshot_id: 'snap-1',
source_id: 'source-bound',
})
})
it('闸口未齐时把接口给的缺项原样抛出,而不是假装已启动', async () => {
@@ -50,7 +54,7 @@ describe('发布页的同步授权与执行接线', () => {
})
)
)
await expect(enqueueLibrarySync('internal', 'snap-1')).rejects.toThrow(
await expect(enqueueLibrarySync('internal', 'snap-1', 'source-bound')).rejects.toThrow(
/目标非空且没有生效版本记录;没有与目标快照匹配的有效发布授权/
)
})