Files
knowledge-governance/web/src/knowledgeBaseBindings.ts
T
姚章浩 ce2a155ebc feat(settings): 知识库绑定按环境一次保存连接与内外库
原「知识库映射 → WeKnora 连接」把地址、文件和绑定分散在多处,页面无法输入密钥,
也看不到候选实例真实可读的库。现在测试 090 / 生产 090 各自一个工作区:草稿填地址
与 API Key,服务器真实分页列库并区分空库/无权限/不可达,选内外库后一次保存连接与
绑定,回读真实生效值。

服务端以修订号 + 行锁 + 单事务写连接、绑定与待入库重排;旧部署无新行时继续使用文件
凭据/默认绑定。密钥只存 AES-256-GCM 密文,主密钥在独立文件;换地址必须重录,旧密钥
不转发、不跨环境取用。消费端(readiness/上传轮询/列库/探活/生产列库)统一从该存储
解析当前连接,避免只保存了页面数据。

验证:go test ./...;前端 606 项;隔离 PostgreSQL 集成用例覆盖保存/冲突/重排/拒错;
make verify 在本提交上执行(结果见交付说明)。
2026-11-19 14:51:47 +08:00

226 lines
7.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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<string, unknown> =>
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<KBEnvironment, KBEnvironmentBinding>()
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<Record<string, unknown>> {
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<KBBindingSnapshot> {
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<KBCatalog> {
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<KBEnvironmentBinding> {
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)
}