feat(release): 发布目标知识库可选(源库 → 目标库映射)
- 迁移 000044:production_kb_bindings + release_item_executions.target_knowledge_base_id - 系统设置新增「生产知识库绑定(对内/对外)」:从生产 WeKnora 实际列表选库, 保存时真校验(不存在拒收;生产端不可达只提示并如实回报),仅管理员可改 - 执行计划按绑定解析目标库并冻结进 release_item_executions;空目标直接拒收; 已发布过的条目保留原目标(重试/回滚回到同一处) - DocumentBundle.RemapKnowledgeBase:knowledges/chunks/knowledge_tags/wiki_pages/ wiki_folders 的 knowledge_base_id 与 ES 文档字段改写为目标库,重算表/文档摘要并重新封装 - 契约比对改为「声明的映射对」(KnowledgeBaseMapping),其余字段继续 fail-closed - 契约检查器 / 目标身份 / 验证器全部走映射后的目标库;对象通道无需改写 - Compose 拆分:数据面接线 compose.release-sim.yaml + 两道门禁 compose.release-gates.yaml - 测试:RemapKnowledgeBase 全通道/无操作/fail-closed、映射契约、绑定接口、RBAC、真实 PG 集成
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
|
||||
import { useOptionalAuth } from './auth'
|
||||
import { fetchProductionBindingOptions, fetchProductionBindings, saveProductionBindings } from './productionBindings'
|
||||
import type { ProductionBindings } from './productionBindings'
|
||||
import type { KnowledgeBaseOption } from './routingBindings'
|
||||
|
||||
// 「生产知识库绑定」:发布链路的 源库 → 目标库 映射。这里选的是发布要写入的
|
||||
// 生产(目标)知识库,与上面的「知识库绑定」(测试端收件库)是两件事。
|
||||
export function ProductionBindingsSection() {
|
||||
const auth = useOptionalAuth()
|
||||
const isAdmin = auth?.identity?.role === 'admin'
|
||||
const [bindings, setBindings] = useState<ProductionBindings | null>(null)
|
||||
const [options, setOptions] = useState<KnowledgeBaseOption[]>([])
|
||||
const [internalDraft, setInternalDraft] = useState('')
|
||||
const [externalDraft, setExternalDraft] = useState('')
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [message, setMessage] = useState('')
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true); setError(null)
|
||||
try {
|
||||
const next = await fetchProductionBindings()
|
||||
setBindings(next)
|
||||
setInternalDraft(next.internal_kb_id)
|
||||
setExternalDraft(next.external_kb_id)
|
||||
try { setOptions(await fetchProductionBindingOptions()) } catch { setOptions([]) }
|
||||
} catch (cause) { setError(cause instanceof Error ? cause.message : '读取生产知识库绑定失败') }
|
||||
finally { setLoading(false) }
|
||||
}, [])
|
||||
useEffect(() => { void load() }, [load])
|
||||
|
||||
const dirty = bindings !== null && (internalDraft !== bindings.internal_kb_id || externalDraft !== bindings.external_kb_id)
|
||||
const sameSelection = internalDraft !== '' && internalDraft === externalDraft
|
||||
|
||||
const save = async () => {
|
||||
setSaving(true); setError(null); setMessage('')
|
||||
try {
|
||||
const next = await saveProductionBindings({ internal_kb_id: internalDraft, external_kb_id: externalDraft })
|
||||
setBindings(next)
|
||||
const where = `对内 ${next.internal_kb_name || next.internal_kb_id.slice(0, 8) || '未绑定'} · 对外 ${next.external_kb_name || next.external_kb_id.slice(0, 8) || '未绑定'}`
|
||||
setMessage(next.production_connected
|
||||
? `发布目标已更新:${where}。之后新发布的“对内/对外”内容会写入这两个生产库(已发布过的条目仍回到原目标)。`
|
||||
: `发布目标已保存:${where};但当前核对不了生产端(${next.production_message}),下次发布前请确认。`)
|
||||
} catch (cause) { setError(cause instanceof Error ? cause.message : '保存生产知识库绑定失败') }
|
||||
finally { setSaving(false) }
|
||||
}
|
||||
|
||||
const optionLabel = (base: KnowledgeBaseOption) => `${base.name}(${base.knowledge_count} 文档)`
|
||||
const renderSide = (label: string, boundID: string, boundName: string) => (
|
||||
<div className={`kb-binding-side ${boundID ? 'bound' : 'warn'}`}>
|
||||
<b>{label}</b>
|
||||
<span>{boundID ? (boundName || `${boundID.slice(0, 8)}…`) : '未绑定 · 按同 ID 语义发布(目标端须存在同 ID 库)'}</span>
|
||||
<small>{boundID ? 'UI 绑定 · 发布写入此库' : '未绑定:沿用测试库 ID'}</small>
|
||||
</div>
|
||||
)
|
||||
const editorFor = (value: string, onChange: (next: string) => void, placeholder: string) => (
|
||||
options.length > 0
|
||||
? <select value={value} onChange={(event) => onChange(event.target.value)} aria-label={placeholder}>
|
||||
<option value="">{placeholder}</option>
|
||||
{options.map((base) => <option key={base.id} value={base.id}>{optionLabel(base)}</option>)}
|
||||
</select>
|
||||
: <input value={value} onChange={(event) => onChange(event.target.value.trim())} placeholder={`${placeholder}(输入生产知识库 ID)`} aria-label={placeholder} />
|
||||
)
|
||||
|
||||
return <section className="settings-panel wide" id="settings-production-bindings">
|
||||
<div className="settings-section-heading"><div><h2>生产知识库绑定</h2><p>发布链路的“源库 → 目标库”:新发布的对内 / 对外内容按这里的绑定写入生产 WeKnora 的对应知识库。留空表示未绑定,按同 ID 语义发布。</p></div><button onClick={() => void load()} disabled={loading}>{loading ? '读取中…' : '重新读取'}</button></div>
|
||||
{error ? <p className="error-message" role="alert">{error}</p> : null}
|
||||
{bindings ? <div className="kb-binding-grid">
|
||||
{renderSide('对内生产知识库', bindings.internal_kb_id, bindings.internal_kb_name)}
|
||||
{renderSide('对外生产知识库', bindings.external_kb_id, bindings.external_kb_name)}
|
||||
</div> : null}
|
||||
{bindings && !bindings.production_connected ? <p className="hint">生产端核对不可用:{bindings.production_message}。{bindings.production_base_url ? `(生产地址:${bindings.production_base_url})` : ''}</p> : null}
|
||||
{bindings && bindings.production_connected && bindings.production_base_url ? <p className="hint">生产端:{bindings.production_base_url}{bindings.updated_by ? ` · 最近修改:${bindings.updated_by}` : ''}</p> : null}
|
||||
{isAdmin && bindings ? <div className="kb-binding-editor">
|
||||
<label>对内目标库 {editorFor(internalDraft, setInternalDraft, '选择对内生产知识库')}</label>
|
||||
<label>对外目标库 {editorFor(externalDraft, setExternalDraft, '选择对外生产知识库')}</label>
|
||||
<p className="hint">保存时会向生产端核对所选的库是否真实存在;对不上会拒收,生产端不可达则只提示。</p>
|
||||
{sameSelection ? <p className="error-message">对内与对外必须绑定不同的生产知识库</p> : null}
|
||||
<button onClick={() => void save()} disabled={saving || !dirty || sameSelection}>{saving ? '正在核对并保存…' : '保存发布目标'}</button>
|
||||
{message ? <p className="success-message" role="status">{message}</p> : null}
|
||||
</div> : null}
|
||||
{!isAdmin ? <p className="hint">仅管理员可修改发布目标。</p> : null}
|
||||
</section>
|
||||
}
|
||||
@@ -37,7 +37,10 @@ export function RoutingBindingsSection() {
|
||||
try {
|
||||
const next = await saveRoutingBindings({ internal_kb_id: internalDraft, external_kb_id: externalDraft })
|
||||
setBindings(next)
|
||||
setMessage(`绑定已生效:对内 ${next.internal_kb_name || next.internal_kb_id.slice(0, 8) || '未绑定'} · 对外 ${next.external_kb_name || next.external_kb_id.slice(0, 8) || '未绑定'}。此后“来源与目录”的标记按新绑定路由。`)
|
||||
const replan = next.replanned || next.retired_duplicates
|
||||
? `;同时把 ${next.replanned} 项还没上传的待入库重新指向新库${next.retired_duplicates ? `,${next.retired_duplicates} 项因新库里已有同篇而被退休` : ''}`
|
||||
: ''
|
||||
setMessage(`绑定已生效:对内 ${next.internal_kb_name || next.internal_kb_id.slice(0, 8) || '未绑定'} · 对外 ${next.external_kb_name || next.external_kb_id.slice(0, 8) || '未绑定'}。此后“来源与目录”的标记按新绑定路由${replan}。`)
|
||||
} catch (cause) { setError(cause instanceof Error ? cause.message : '保存知识库绑定失败') }
|
||||
finally { setSaving(false) }
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { useCallback, useEffect, useState } from 'react'
|
||||
import { MembersSection } from './MembersSection'
|
||||
import { DingtalkSessionControl } from './DingtalkSessionControl'
|
||||
import { RoutingBindingsSection } from './RoutingBindingsSection'
|
||||
import { ProductionBindingsSection } from './ProductionBindingsSection'
|
||||
import { DingtalkSpaceRegistrar } from './DingtalkSpaceRegistrar'
|
||||
import { FilenameFilterEditor } from './FilenameFilterEditor'
|
||||
import { useOptionalAuth } from './auth'
|
||||
@@ -35,12 +36,13 @@ interface Props {
|
||||
initialSection?: SectionKey
|
||||
}
|
||||
|
||||
type SectionKey = 'sources' | 'services' | 'bindings' | 'storage' | 'refresh' | 'members'
|
||||
type SectionKey = 'sources' | 'services' | 'bindings' | 'production-bindings' | 'storage' | 'refresh' | 'members'
|
||||
|
||||
const sections: { key: SectionKey; label: string; adminOnly?: boolean }[] = [
|
||||
{ key: 'sources', label: '数据源配置' },
|
||||
{ key: 'services', label: '服务配置' },
|
||||
{ key: 'bindings', label: '知识库绑定' },
|
||||
{ key: 'production-bindings', label: '生产知识库绑定' },
|
||||
{ key: 'storage', label: '存储与备份' },
|
||||
{ key: 'refresh', label: '刷新策略' },
|
||||
{ key: 'members', label: '成员与角色', adminOnly: true },
|
||||
@@ -261,6 +263,7 @@ export function SystemSettingsView({ sources, connections, monitor, settings, pr
|
||||
: <small>服务配置仅管理员可修改;当前值:测试地址 {settings.test_weknora_base_url || '未配置'} · 生产地址 {settings.production_weknora_base_url || '未配置'} · 生产 ID {settings.production_tenant_id || '未配置'} · 知识库 ID {settings.production_knowledge_base_id || '未配置'}。</small>}
|
||||
</section> : null}
|
||||
{section === 'bindings' ? <RoutingBindingsSection /> : null}
|
||||
{section === 'production-bindings' ? <ProductionBindingsSection /> : null}
|
||||
{section === 'storage' ? <section className="settings-panel wide storage-settings-panel" id="settings-storage">
|
||||
<div className="settings-section-heading"><div><h2>存储与备份</h2><p>文件资源与生产发布前快照使用独立受限配置。</p></div></div>
|
||||
<div className="storage-settings-grid"><dl><dt>Endpoint / Bucket</dt><dd>尚未配置</dd><dt>AccessKey / Secret</dt><dd>仅保存凭据引用,不可回读</dd><dt>CDN / 公开访问域名</dt><dd>尚未配置</dd><dt>临时签名有效期</dt><dd>待配置</dd></dl><dl><dt>测试备份前缀</dt><dd>/backup/weknora/test/</dd><dt>生产备份前缀</dt><dd>/backup/weknora/prod/</dd><dt>快照保留</dt><dd>最近 30 个生产快照</dd><dt>恢复验证</dt><dd>由生产门禁读回</dd></dl><ul className="target-list"><li>PostgreSQL <b>未配置</b></li><li>Elasticsearch <b>未配置</b></li><li>对象存储 <b>未配置</b></li><li>Neo4j <b>未配置</b></li><li>生产发布请求 <b>{productionEnabled ? '等待管理员核对' : '关闭'}</b></li><li>Release Worker <b>网页不可启用</b></li></ul></div>
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { fetchProductionBindingOptions, fetchProductionBindings, saveProductionBindings } from './productionBindings'
|
||||
|
||||
const binding = {
|
||||
internal_kb_id: '0b217e8a-2a65-40a3-ab8f-34ac5c7a6f05', external_kb_id: '',
|
||||
internal_kb_name: '对内知识库-wiki', external_kb_name: '', updated_by: 'admin',
|
||||
production_base_url: 'https://weknora-test.dobot.cn/', production_connected: true, production_message: '',
|
||||
}
|
||||
|
||||
describe('production bindings API', () => {
|
||||
it('reads the 源库 → 目标库 projection without leaking extra fields', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: { ...binding, api_key: 'drop' } }), { status: 200 })))
|
||||
const result = await fetchProductionBindings()
|
||||
expect(result.internal_kb_name).toBe('对内知识库-wiki')
|
||||
expect(result.production_connected).toBe(true)
|
||||
expect(result).not.toHaveProperty('api_key')
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
it('lists production knowledge base options for the picker', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: [{ id: 'kb-1', name: '对内知识库-wiki', knowledge_count: 2069 }, { id: '', name: '坏行' }] }), { status: 200 })))
|
||||
expect(await fetchProductionBindingOptions()).toEqual([{ id: 'kb-1', name: '对内知识库-wiki', knowledge_count: 2069 }])
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
it('saves with an idempotency key and surfaces a rejected base', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({ data: binding }), { status: 200 }))
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({ error: '对内绑定的生产知识库在该 WeKnora 实例中不存在' }), { status: 400 }))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
await expect(saveProductionBindings({ internal_kb_id: 'kb-1', external_kb_id: '' })).resolves.toMatchObject({ internal_kb_name: '对内知识库-wiki' })
|
||||
const [, init] = fetchMock.mock.calls[0]
|
||||
expect(init.method).toBe('PUT')
|
||||
expect(init.headers['Idempotency-Key']).toBeTruthy()
|
||||
await expect(saveProductionBindings({ internal_kb_id: 'kb-ghost', external_kb_id: '' })).rejects.toThrow('不存在')
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
it('reports an unverified save honestly instead of pretending it was checked', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: { ...binding, production_connected: false, production_message: '生产 WeKnora 不可用:dial tcp: timeout' } }), { status: 200 })))
|
||||
const result = await saveProductionBindings({ internal_kb_id: 'kb-1', external_kb_id: '' })
|
||||
expect(result.production_connected).toBe(false)
|
||||
expect(result.production_message).toContain('不可用')
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,65 @@
|
||||
import { newOperationID } from './operationKey'
|
||||
import type { KnowledgeBaseOption } from './routingBindings'
|
||||
|
||||
// 源库 → 目标库(生产)映射:系统设置里选择发布要写入的生产知识库。
|
||||
export interface ProductionBindings {
|
||||
internal_kb_id: string
|
||||
external_kb_id: string
|
||||
internal_kb_name: string
|
||||
external_kb_name: string
|
||||
updated_by: string
|
||||
production_base_url: string
|
||||
production_connected: boolean
|
||||
production_message: string
|
||||
}
|
||||
|
||||
const record = (value: unknown): value is Record<string, unknown> => Boolean(value) && typeof value === 'object' && !Array.isArray(value)
|
||||
|
||||
function projection(item: Record<string, unknown>): ProductionBindings {
|
||||
return {
|
||||
internal_kb_id: typeof item.internal_kb_id === 'string' ? item.internal_kb_id : '',
|
||||
external_kb_id: typeof item.external_kb_id === 'string' ? item.external_kb_id : '',
|
||||
internal_kb_name: typeof item.internal_kb_name === 'string' ? item.internal_kb_name : '',
|
||||
external_kb_name: typeof item.external_kb_name === 'string' ? item.external_kb_name : '',
|
||||
updated_by: typeof item.updated_by === 'string' ? item.updated_by : '',
|
||||
production_base_url: typeof item.production_base_url === 'string' ? item.production_base_url : '',
|
||||
production_connected: item.production_connected === true,
|
||||
production_message: typeof item.production_message === 'string' ? item.production_message : '',
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchProductionBindings(signal?: AbortSignal): Promise<ProductionBindings> {
|
||||
const response = await fetch('/api/v1/production-kb-bindings', { signal, headers: { Accept: 'application/json' } })
|
||||
if (!response.ok) throw new Error(`读取生产知识库绑定失败(HTTP ${response.status})`)
|
||||
const value = await response.json() as unknown
|
||||
if (!record(value) || !record(value.data)) throw new Error('生产知识库绑定响应无效')
|
||||
return projection(value.data)
|
||||
}
|
||||
|
||||
export async function fetchProductionBindingOptions(signal?: AbortSignal): Promise<KnowledgeBaseOption[]> {
|
||||
const response = await fetch('/api/v1/production-kb-bindings/options', { signal, headers: { Accept: 'application/json' } })
|
||||
if (!response.ok) throw new Error(`读取生产知识库列表失败(HTTP ${response.status})`)
|
||||
const value = await response.json() as unknown
|
||||
if (!record(value) || !Array.isArray(value.data)) throw new Error('生产知识库列表响应无效')
|
||||
return value.data.filter(record).map((item) => ({
|
||||
id: typeof item.id === 'string' ? item.id : '',
|
||||
name: typeof item.name === 'string' ? item.name : '',
|
||||
knowledge_count: typeof item.knowledge_count === 'number' ? item.knowledge_count : 0,
|
||||
})).filter((item) => item.id)
|
||||
}
|
||||
|
||||
export async function saveProductionBindings(input: { internal_kb_id: string; external_kb_id: string }, signal?: AbortSignal): Promise<ProductionBindings> {
|
||||
const response = await fetch('/api/v1/production-kb-bindings', {
|
||||
method: 'PUT', signal,
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'Idempotency-Key': newOperationID() },
|
||||
body: JSON.stringify(input),
|
||||
})
|
||||
if (!response.ok) {
|
||||
let reason = `保存生产知识库绑定失败(HTTP ${response.status})`
|
||||
try { const body = await response.json() as unknown; if (record(body) && typeof body.error === 'string') reason = body.error } catch { /* keep status text */ }
|
||||
throw new Error(reason)
|
||||
}
|
||||
const value = await response.json() as unknown
|
||||
if (!record(value) || !record(value.data)) throw new Error('生产知识库绑定响应无效')
|
||||
return projection(value.data)
|
||||
}
|
||||
@@ -11,6 +11,9 @@ export interface RoutingBindings {
|
||||
external_kb_name: string
|
||||
updated_by: string
|
||||
weknora_connected: boolean
|
||||
// 本次保存把多少条「还没上传」的待入库项重新指向了新库(读取时为 0)。
|
||||
replanned: number
|
||||
retired_duplicates: number
|
||||
}
|
||||
|
||||
export interface KnowledgeBaseOption {
|
||||
@@ -33,6 +36,8 @@ function bindingProjection(item: Record<string, unknown>): RoutingBindings {
|
||||
external_kb_name: typeof item.external_kb_name === 'string' ? item.external_kb_name : '',
|
||||
updated_by: typeof item.updated_by === 'string' ? item.updated_by : '',
|
||||
weknora_connected: item.weknora_connected === true,
|
||||
replanned: typeof item.replanned === 'number' ? item.replanned : 0,
|
||||
retired_duplicates: typeof item.retired_duplicates === 'number' ? item.retired_duplicates : 0,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user