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:
@@ -129,6 +129,11 @@ func classifyRole(method, path string) string {
|
||||
if path == "/api/v1/routing-bindings" && method != http.MethodGet {
|
||||
return roleAdmin
|
||||
}
|
||||
// Choosing the production base a release writes into is a production
|
||||
// authority change, exactly like the annotation binding above.
|
||||
if path == "/api/v1/production-kb-bindings" && method != http.MethodGet {
|
||||
return roleAdmin
|
||||
}
|
||||
// Everything else that mutates (review, batch, seal, confirm, start, retry,
|
||||
// route visibility, disable) is engineer work; viewers cannot POST at all.
|
||||
return roleEngineer
|
||||
|
||||
@@ -410,10 +410,13 @@ func TestClassifyRoleMatrix(t *testing.T) {
|
||||
http.MethodPost + " /api/v1/release-executions/rx-1/retry": roleAdmin,
|
||||
http.MethodPost + " /api/v1/users": roleAdmin,
|
||||
http.MethodPost + " /api/v1/source-connections/c-1/settings/revisions": roleAdmin,
|
||||
http.MethodPost + " /api/v1/review-candidates/tp-1/decision": roleEngineer,
|
||||
http.MethodPost + " /api/v1/release-batches/rb-1/seal": roleEngineer,
|
||||
http.MethodPost + " /api/v1/test-publications/start": roleEngineer,
|
||||
http.MethodGet + " /api/v1/release-plan": roleViewer,
|
||||
// Choosing a release's production base is a production authority change.
|
||||
http.MethodPut + " /api/v1/production-kb-bindings": roleAdmin,
|
||||
http.MethodGet + " /api/v1/production-kb-bindings": roleViewer,
|
||||
http.MethodPost + " /api/v1/review-candidates/tp-1/decision": roleEngineer,
|
||||
http.MethodPost + " /api/v1/release-batches/rb-1/seal": roleEngineer,
|
||||
http.MethodPost + " /api/v1/test-publications/start": roleEngineer,
|
||||
http.MethodGet + " /api/v1/release-plan": roleViewer,
|
||||
}
|
||||
for key, want := range cases {
|
||||
fields := strings.Fields(key)
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
)
|
||||
|
||||
// ProductionBindingStore persists the UI-managed 源库 → 目标库 mapping
|
||||
// (migration 000044). An empty side means "unbound": the release then keeps the
|
||||
// historical same-id semantics and fails closed at the contract check when no
|
||||
// such base exists on the target.
|
||||
type ProductionBindingStore interface {
|
||||
LoadProductionKBBindings(context.Context) (string, string, string, error)
|
||||
SaveProductionKBBindings(ctx context.Context, internalID, externalID, updatedBy string, now time.Time) error
|
||||
}
|
||||
|
||||
// ProductionKnowledgeBaseLister enumerates the knowledge bases of the production
|
||||
// WeKnora, resolved from the operator-managed service configuration.
|
||||
type ProductionKnowledgeBaseLister interface {
|
||||
ListProductionKnowledgeBases(ctx context.Context, baseURL string) ([]weknora.KnowledgeBase, error)
|
||||
}
|
||||
|
||||
type productionBindingView struct {
|
||||
InternalKBID string `json:"internal_kb_id"`
|
||||
ExternalKBID string `json:"external_kb_id"`
|
||||
InternalKBName string `json:"internal_kb_name"`
|
||||
ExternalKBName string `json:"external_kb_name"`
|
||||
UpdatedBy string `json:"updated_by"`
|
||||
ProductionBaseURL string `json:"production_base_url"`
|
||||
ProductionConnected bool `json:"production_connected"`
|
||||
ProductionMessage string `json:"production_message"`
|
||||
}
|
||||
|
||||
// productionTargetBaseURL is the production endpoint the picker reads from: the
|
||||
// operator-managed 「服务配置 · 生产地址」 first, the deployment default second.
|
||||
func (config Config) productionTargetBaseURL(ctx context.Context) string {
|
||||
if settings, err := config.Store.GetActiveUISettings(ctx); err == nil {
|
||||
if resolved := strings.TrimSpace(settings.ProductionWeKnoraBaseURL); resolved != "" {
|
||||
return resolved
|
||||
}
|
||||
}
|
||||
return strings.TrimSpace(config.ProductionWeKnoraBaseURL)
|
||||
}
|
||||
|
||||
// productionKnowledgeBases lists the production-side bases. The second return is
|
||||
// the honest reason a listing was impossible, so the page can say why instead of
|
||||
// pretending there are none.
|
||||
func (config Config) productionKnowledgeBases(ctx context.Context) ([]weknora.KnowledgeBase, string) {
|
||||
if config.ProductionKnowledgeBases == nil {
|
||||
return nil, "生产知识库列表未接入(PRODUCTION_WEKNORA_BASE_URL / PRODUCTION_WEKNORA_API_KEY_FILE)"
|
||||
}
|
||||
baseURL := config.productionTargetBaseURL(ctx)
|
||||
if baseURL == "" {
|
||||
return nil, "未配置生产地址(系统设置 → 服务配置)"
|
||||
}
|
||||
bases, err := config.ProductionKnowledgeBases.ListProductionKnowledgeBases(ctx, baseURL)
|
||||
if err != nil {
|
||||
return nil, "生产 WeKnora 不可用:" + err.Error()
|
||||
}
|
||||
return bases, ""
|
||||
}
|
||||
|
||||
func (config Config) productionBindingPayload(ctx context.Context) (productionBindingView, error) {
|
||||
storedInternal, storedExternal, updatedBy, err := config.ProductionBindings.LoadProductionKBBindings(ctx)
|
||||
if err != nil {
|
||||
return productionBindingView{}, err
|
||||
}
|
||||
bases, message := config.productionKnowledgeBases(ctx)
|
||||
names := make(map[string]string, len(bases))
|
||||
for _, base := range bases {
|
||||
names[base.ID] = base.Name
|
||||
}
|
||||
return productionBindingView{
|
||||
InternalKBID: storedInternal, ExternalKBID: storedExternal,
|
||||
InternalKBName: names[storedInternal], ExternalKBName: names[storedExternal],
|
||||
UpdatedBy: updatedBy, ProductionBaseURL: config.productionTargetBaseURL(ctx),
|
||||
ProductionConnected: message == "", ProductionMessage: message,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (config Config) handleProductionBindings(w http.ResponseWriter, r *http.Request) {
|
||||
if config.ProductionBindings == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "production bindings are not configured"})
|
||||
return
|
||||
}
|
||||
view, err := config.productionBindingPayload(r.Context())
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not load production bindings"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": view})
|
||||
}
|
||||
|
||||
func (config Config) handleProductionKnowledgeBaseOptions(w http.ResponseWriter, r *http.Request) {
|
||||
bases, message := config.productionKnowledgeBases(r.Context())
|
||||
if message != "" {
|
||||
writeJSON(w, http.StatusBadGateway, map[string]string{"error": message})
|
||||
return
|
||||
}
|
||||
options := make([]routingKnowledgeBaseOption, 0, len(bases))
|
||||
for _, base := range bases {
|
||||
options = append(options, routingKnowledgeBaseOption{ID: base.ID, Name: base.Name, KnowledgeCount: base.KnowledgeCount})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": options})
|
||||
}
|
||||
|
||||
// handleSaveProductionBindings stores the 源库 → 目标库 mapping. When the
|
||||
// production endpoint answers, the chosen base must exist there; when it cannot
|
||||
// be asked, the save still succeeds but the response says so honestly (a jittery
|
||||
// production endpoint must not block the operator, a wrong ID must).
|
||||
func (config Config) handleSaveProductionBindings(w http.ResponseWriter, r *http.Request) {
|
||||
if config.ProductionBindings == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "production bindings are not configured"})
|
||||
return
|
||||
}
|
||||
var input struct {
|
||||
InternalKBID string `json:"internal_kb_id"`
|
||||
ExternalKBID string `json:"external_kb_id"`
|
||||
}
|
||||
if err := decodeStrictJSON(r, &input); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid request body"})
|
||||
return
|
||||
}
|
||||
internal := strings.TrimSpace(input.InternalKBID)
|
||||
external := strings.TrimSpace(input.ExternalKBID)
|
||||
for _, id := range []string{internal, external} {
|
||||
if id != "" && !validCatalogID(id) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "knowledge base ID is invalid"})
|
||||
return
|
||||
}
|
||||
}
|
||||
if internal != "" && internal == external {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "对内与对外必须绑定不同的生产知识库"})
|
||||
return
|
||||
}
|
||||
if bases, message := config.productionKnowledgeBases(r.Context()); message == "" {
|
||||
names := make(map[string]string, len(bases))
|
||||
for _, base := range bases {
|
||||
names[base.ID] = base.Name
|
||||
}
|
||||
if internal != "" {
|
||||
if _, ok := names[internal]; !ok {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "对内绑定的生产知识库在该 WeKnora 实例中不存在"})
|
||||
return
|
||||
}
|
||||
}
|
||||
if external != "" {
|
||||
if _, ok := names[external]; !ok {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "对外绑定的生产知识库在该 WeKnora 实例中不存在"})
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := config.ProductionBindings.SaveProductionKBBindings(r.Context(), internal, external, actorFor(r), config.Now().UTC()); err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not save production bindings"})
|
||||
return
|
||||
}
|
||||
view, err := config.productionBindingPayload(r.Context())
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not load production bindings"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": view})
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
)
|
||||
|
||||
type productionBindingStoreFake struct {
|
||||
internal, external, saver string
|
||||
savedInternal, savedExternal string
|
||||
saveCallCount int
|
||||
}
|
||||
|
||||
func (fake *productionBindingStoreFake) LoadProductionKBBindings(context.Context) (string, string, string, error) {
|
||||
return fake.internal, fake.external, fake.saver, nil
|
||||
}
|
||||
|
||||
func (fake *productionBindingStoreFake) SaveProductionKBBindings(_ context.Context, internal, external, updatedBy string, _ time.Time) error {
|
||||
fake.savedInternal, fake.savedExternal = internal, external
|
||||
fake.saver = updatedBy
|
||||
fake.saveCallCount++
|
||||
fake.internal, fake.external = internal, external
|
||||
return nil
|
||||
}
|
||||
|
||||
type productionListerFake struct {
|
||||
bases []weknora.KnowledgeBase
|
||||
err error
|
||||
baseURL string
|
||||
}
|
||||
|
||||
func (fake *productionListerFake) ListProductionKnowledgeBases(_ context.Context, baseURL string) ([]weknora.KnowledgeBase, error) {
|
||||
fake.baseURL = baseURL
|
||||
return fake.bases, fake.err
|
||||
}
|
||||
|
||||
func productionBindingsHandler(t *testing.T, store ProductionBindingStore, lister ProductionKnowledgeBaseLister, settingsURL string) http.Handler {
|
||||
t.Helper()
|
||||
jobStore := &fakeJobStore{}
|
||||
jobStore.activeUISettingsResult = governance.UISettings{ProductionWeKnoraBaseURL: settingsURL}
|
||||
handler, err := NewHandler(Config{
|
||||
Store: jobStore,
|
||||
ProductionBindings: store, ProductionKnowledgeBases: lister,
|
||||
Now: func() time.Time { return time.Date(2026, time.October, 8, 8, 0, 0, 0, time.UTC) },
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewHandler: %v", err)
|
||||
}
|
||||
return handler
|
||||
}
|
||||
|
||||
func productionBases() []weknora.KnowledgeBase {
|
||||
return []weknora.KnowledgeBase{
|
||||
{ID: "kb-prod-internal", Name: "对内知识库-wiki", KnowledgeCount: 2069},
|
||||
{ID: "kb-prod-external", Name: "对外知识库-wiki", KnowledgeCount: 526},
|
||||
}
|
||||
}
|
||||
|
||||
// The picker reads the production endpoint from 「服务配置 · 生产地址」 and reports
|
||||
// the bound bases by NAME — ids never reach the page.
|
||||
func TestProductionBindingsReadUsesServiceConfiguredEndpoint(t *testing.T) {
|
||||
store := &productionBindingStoreFake{internal: "kb-prod-internal"}
|
||||
lister := &productionListerFake{bases: productionBases()}
|
||||
handler := productionBindingsHandler(t, store, lister, "https://weknora-test.dobot.cn/")
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/production-kb-bindings", nil))
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d body %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if lister.baseURL != "https://weknora-test.dobot.cn/" {
|
||||
t.Fatalf("lister baseURL = %q, want the operator-configured production address", lister.baseURL)
|
||||
}
|
||||
body := recorder.Body.String()
|
||||
if !strings.Contains(body, "对内知识库-wiki") || !strings.Contains(body, `"production_connected":true`) {
|
||||
t.Fatalf("body = %s", body)
|
||||
}
|
||||
}
|
||||
|
||||
// A chosen base that does not exist on the production endpoint must be refused
|
||||
// before anything is written.
|
||||
func TestProductionBindingsSaveRejectsUnknownBase(t *testing.T) {
|
||||
store := &productionBindingStoreFake{}
|
||||
handler := productionBindingsHandler(t, store, &productionListerFake{bases: productionBases()}, "https://weknora-test.dobot.cn/")
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodPut, "/api/v1/production-kb-bindings",
|
||||
strings.NewReader(`{"internal_kb_id":"kb-ghost","external_kb_id":""}`)))
|
||||
if recorder.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d body %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if store.saveCallCount != 0 {
|
||||
t.Fatal("a rejected binding must not be stored")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProductionBindingsSaveStoresValidatedPair(t *testing.T) {
|
||||
store := &productionBindingStoreFake{}
|
||||
handler := productionBindingsHandler(t, store, &productionListerFake{bases: productionBases()}, "https://weknora-test.dobot.cn/")
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodPut, "/api/v1/production-kb-bindings",
|
||||
strings.NewReader(`{"internal_kb_id":"kb-prod-internal","external_kb_id":"kb-prod-external"}`)))
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d body %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if store.savedInternal != "kb-prod-internal" || store.savedExternal != "kb-prod-external" {
|
||||
t.Fatalf("saved = %q/%q", store.savedInternal, store.savedExternal)
|
||||
}
|
||||
var envelope struct {
|
||||
Data productionBindingView `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &envelope); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if envelope.Data.InternalKBName != "对内知识库-wiki" || !envelope.Data.ProductionConnected {
|
||||
t.Fatalf("view = %#v", envelope.Data)
|
||||
}
|
||||
}
|
||||
|
||||
// A jittery production endpoint must not block the operator, but the response
|
||||
// must say the binding could not be checked.
|
||||
func TestProductionBindingsSaveWarnsWhenEndpointUnavailable(t *testing.T) {
|
||||
store := &productionBindingStoreFake{}
|
||||
handler := productionBindingsHandler(t, store, &productionListerFake{err: errors.New("dial tcp: timeout")}, "https://weknora-test.dobot.cn/")
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodPut, "/api/v1/production-kb-bindings",
|
||||
strings.NewReader(`{"internal_kb_id":"kb-prod-internal","external_kb_id":""}`)))
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d body %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if store.saveCallCount != 1 {
|
||||
t.Fatal("an unverifiable (not invalid) binding must still be stored")
|
||||
}
|
||||
var envelope struct {
|
||||
Data productionBindingView `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &envelope); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if envelope.Data.ProductionConnected || !strings.Contains(envelope.Data.ProductionMessage, "不可用") {
|
||||
t.Fatalf("view = %#v", envelope.Data)
|
||||
}
|
||||
}
|
||||
|
||||
// 对内 and 对外 must not point at the same production base.
|
||||
func TestProductionBindingsSaveRejectsIdenticalBases(t *testing.T) {
|
||||
store := &productionBindingStoreFake{}
|
||||
handler := productionBindingsHandler(t, store, &productionListerFake{bases: productionBases()}, "https://weknora-test.dobot.cn/")
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodPut, "/api/v1/production-kb-bindings",
|
||||
strings.NewReader(`{"internal_kb_id":"kb-prod-internal","external_kb_id":"kb-prod-internal"}`)))
|
||||
if recorder.Code != http.StatusBadRequest || store.saveCallCount != 0 {
|
||||
t.Fatalf("status = %d saves = %d", recorder.Code, store.saveCallCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProductionBindingOptionsReportUnavailableReason(t *testing.T) {
|
||||
handler := productionBindingsHandler(t, &productionBindingStoreFake{}, &productionListerFake{err: errors.New("no key")}, "https://weknora-test.dobot.cn/")
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/production-kb-bindings/options", nil))
|
||||
if recorder.Code != http.StatusBadGateway {
|
||||
t.Fatalf("status = %d body %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
recorder = httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/production-kb-bindings/options", nil))
|
||||
// and with a working endpoint the options carry names, not just ids
|
||||
handler = productionBindingsHandler(t, &productionBindingStoreFake{}, &productionListerFake{bases: productionBases()}, "https://weknora-test.dobot.cn/")
|
||||
recorder = httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/production-kb-bindings/options", nil))
|
||||
if recorder.Code != http.StatusOK || !strings.Contains(recorder.Body.String(), "对外知识库-wiki") {
|
||||
t.Fatalf("status = %d body %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,9 @@ import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
)
|
||||
|
||||
@@ -13,6 +15,9 @@ import (
|
||||
type RoutingBindingStore interface {
|
||||
LoadRoutingKBBindings(context.Context) (string, string, string, error)
|
||||
SaveRoutingKBBindings(context.Context, string, string, string) error
|
||||
// SaveRoutingKBBindingsWithReplan also re-points 待入库 publications that
|
||||
// were still waiting for the previous knowledge base (same transaction).
|
||||
SaveRoutingKBBindingsWithReplan(ctx context.Context, internalID, externalID, effectiveInternal, effectiveExternal, updatedBy string, now time.Time) (postgresstore.RoutingBindingReplanResult, error)
|
||||
}
|
||||
|
||||
// KnowledgeBaseLister enumerates candidate knowledge bases in the connected
|
||||
@@ -32,6 +37,10 @@ type routingBindingView struct {
|
||||
ExternalKBName string `json:"external_kb_name"`
|
||||
UpdatedBy string `json:"updated_by"`
|
||||
WeKnoraConnected bool `json:"weknora_connected"`
|
||||
// Replanned / RetiredDuplicates describe what THIS save did to 待入库 items
|
||||
// that had not been uploaded yet. A plain read reports zeros.
|
||||
Replanned int `json:"replanned"`
|
||||
RetiredDuplicates int `json:"retired_duplicates"`
|
||||
}
|
||||
|
||||
type routingKnowledgeBaseOption struct {
|
||||
@@ -77,21 +86,31 @@ func (config Config) routingBindingNames(ctx context.Context) (map[string]string
|
||||
return names, true
|
||||
}
|
||||
|
||||
func (config Config) handleRoutingBindings(w http.ResponseWriter, r *http.Request) {
|
||||
names, connected := config.routingBindingNames(r.Context())
|
||||
storedInternal, storedExternal, updatedBy, err := config.RoutingBindings.LoadRoutingKBBindings(r.Context())
|
||||
// routingBindingPayload builds the settings-page projection. replan carries the
|
||||
// counts of a binding change that just ran (zero on a plain read).
|
||||
func (config Config) routingBindingPayload(ctx context.Context, replan postgresstore.RoutingBindingReplanResult) (routingBindingView, error) {
|
||||
names, connected := config.routingBindingNames(ctx)
|
||||
storedInternal, storedExternal, updatedBy, err := config.RoutingBindings.LoadRoutingKBBindings(ctx)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not load routing bindings"})
|
||||
return
|
||||
return routingBindingView{}, err
|
||||
}
|
||||
internal, external := config.effectiveRoutingTargets(r.Context())
|
||||
view := routingBindingView{
|
||||
internal, external := config.effectiveRoutingTargets(ctx)
|
||||
return routingBindingView{
|
||||
InternalKBID: internal, ExternalKBID: external,
|
||||
InternalBoundByUI: storedInternal != "", ExternalBoundByUI: storedExternal != "",
|
||||
InternalEnvFallback: storedInternal == "" && config.InternalRoutingKnowledgeBaseID != "",
|
||||
ExternalEnvFallback: storedExternal == "" && config.ExternalRoutingKnowledgeBaseID != "",
|
||||
InternalKBName: names[storedInternal], ExternalKBName: names[storedExternal],
|
||||
UpdatedBy: updatedBy, WeKnoraConnected: connected,
|
||||
Replanned: replan.Replanned, RetiredDuplicates: replan.RetiredDuplicates,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (config Config) handleRoutingBindings(w http.ResponseWriter, r *http.Request) {
|
||||
view, err := config.routingBindingPayload(r.Context(), postgresstore.RoutingBindingReplanResult{})
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not load routing bindings"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": view})
|
||||
}
|
||||
@@ -152,9 +171,26 @@ func (config Config) handleSaveRoutingBindings(w http.ResponseWriter, r *http.Re
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := config.RoutingBindings.SaveRoutingKBBindings(r.Context(), internal, external, actorFor(r)); err != nil {
|
||||
// The saved binding re-routes FUTURE annotations; pending 待入库 items that
|
||||
// have never been uploaded are re-pointed in the same transaction, otherwise
|
||||
// they would keep aiming at the previous (possibly removed) knowledge base.
|
||||
effectiveInternal := internal
|
||||
if effectiveInternal == "" {
|
||||
effectiveInternal = config.InternalRoutingKnowledgeBaseID
|
||||
}
|
||||
effectiveExternal := external
|
||||
if effectiveExternal == "" {
|
||||
effectiveExternal = config.ExternalRoutingKnowledgeBaseID
|
||||
}
|
||||
replan, err := config.RoutingBindings.SaveRoutingKBBindingsWithReplan(r.Context(), internal, external, effectiveInternal, effectiveExternal, actorFor(r), config.Now().UTC())
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not save routing bindings"})
|
||||
return
|
||||
}
|
||||
config.handleRoutingBindings(w, r)
|
||||
view, err := config.routingBindingPayload(r.Context(), replan)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not load routing bindings"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": view})
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
)
|
||||
|
||||
@@ -16,6 +17,11 @@ type bindingStoreFake struct {
|
||||
internal string
|
||||
external string
|
||||
saver string
|
||||
// replan records what the last save asked for, so tests can assert that the
|
||||
// effective (env-fallback aware) targets were used.
|
||||
replanEffective [2]string
|
||||
replanResult postgresstore.RoutingBindingReplanResult
|
||||
replanCallCount int
|
||||
}
|
||||
|
||||
func (fake *bindingStoreFake) LoadRoutingKBBindings(context.Context) (string, string, string, error) {
|
||||
@@ -27,6 +33,13 @@ func (fake *bindingStoreFake) SaveRoutingKBBindings(_ context.Context, internal,
|
||||
return nil
|
||||
}
|
||||
|
||||
func (fake *bindingStoreFake) SaveRoutingKBBindingsWithReplan(_ context.Context, internal, external, effectiveInternal, effectiveExternal, updatedBy string, _ time.Time) (postgresstore.RoutingBindingReplanResult, error) {
|
||||
fake.internal, fake.external, fake.saver = internal, external, updatedBy
|
||||
fake.replanEffective = [2]string{effectiveInternal, effectiveExternal}
|
||||
fake.replanCallCount++
|
||||
return fake.replanResult, nil
|
||||
}
|
||||
|
||||
type kbListerFake struct {
|
||||
bases []weknora.KnowledgeBase
|
||||
err error
|
||||
@@ -104,6 +117,37 @@ func TestRoutingBindingsSaveValidatesAgainstWeKnora(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A binding change must also carry the 待入库 re-plan counts and pass the
|
||||
// EFFECTIVE targets (env fallback included) so an unbound side still routes.
|
||||
func TestRoutingBindingsSaveReportsReplanAndUsesEffectiveTargets(t *testing.T) {
|
||||
store := &bindingStoreFake{replanResult: postgresstore.RoutingBindingReplanResult{Replanned: 3, RetiredDuplicates: 1}}
|
||||
lister := &kbListerFake{bases: []weknora.KnowledgeBase{{ID: "kb-in", Name: "对内库"}, {ID: "kb-ex", Name: "对外库"}}}
|
||||
handler := bindingsTestHandler(t, store, lister, "env-internal", "env-external")
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodPut, "/api/v1/routing-bindings", strings.NewReader(`{"internal_kb_id":"kb-in","external_kb_id":""}`)))
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("save must succeed: %d %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if store.replanCallCount != 1 {
|
||||
t.Fatalf("save must go through the replanning path once, got %d", store.replanCallCount)
|
||||
}
|
||||
if store.replanEffective != [2]string{"kb-in", "env-external"} {
|
||||
t.Fatalf("effective targets = %#v, want the env fallback on the unbound side", store.replanEffective)
|
||||
}
|
||||
var envelope struct {
|
||||
Data struct {
|
||||
Replanned int `json:"replanned"`
|
||||
RetiredDuplicates int `json:"retired_duplicates"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &envelope); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if envelope.Data.Replanned != 3 || envelope.Data.RetiredDuplicates != 1 {
|
||||
t.Fatalf("replan counts = %#v", envelope.Data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteCatalogFilesUsesUIBinding(t *testing.T) {
|
||||
store := &bindingStoreFake{internal: "ui-internal", external: "ui-external"}
|
||||
handler := bindingsTestHandler(t, store, &kbListerFake{}, "env-internal", "env-external")
|
||||
|
||||
@@ -100,12 +100,17 @@ type Store interface {
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Store Store
|
||||
Monitor MonitorProvider
|
||||
InternalRoutingKnowledgeBaseID string
|
||||
ExternalRoutingKnowledgeBaseID string
|
||||
RoutingBindings RoutingBindingStore
|
||||
KnowledgeBases KnowledgeBaseLister
|
||||
Store Store
|
||||
Monitor MonitorProvider
|
||||
InternalRoutingKnowledgeBaseID string
|
||||
ExternalRoutingKnowledgeBaseID string
|
||||
RoutingBindings RoutingBindingStore
|
||||
KnowledgeBases KnowledgeBaseLister
|
||||
// ProductionBindings is the 源库 → 目标库 mapping store; ProductionKnowledgeBases
|
||||
// enumerates the production-side bases the operator can bind.
|
||||
ProductionBindings ProductionBindingStore
|
||||
ProductionKnowledgeBases ProductionKnowledgeBaseLister
|
||||
ProductionWeKnoraBaseURL string
|
||||
ServiceTargetVerifier ServiceTargetVerifier
|
||||
Now func() time.Time
|
||||
RequireWeKnoraReady bool
|
||||
@@ -231,6 +236,23 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
}
|
||||
config.handleSaveRoutingBindings(w, r)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/production-kb-bindings", func(w http.ResponseWriter, r *http.Request) {
|
||||
if config.ProductionBindings == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "production bindings storage unavailable"})
|
||||
return
|
||||
}
|
||||
config.handleProductionBindings(w, r)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/production-kb-bindings/options", func(w http.ResponseWriter, r *http.Request) {
|
||||
config.handleProductionKnowledgeBaseOptions(w, r)
|
||||
})
|
||||
mux.HandleFunc("PUT /api/v1/production-kb-bindings", func(w http.ResponseWriter, r *http.Request) {
|
||||
if config.ProductionBindings == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "production bindings storage unavailable"})
|
||||
return
|
||||
}
|
||||
config.handleSaveProductionBindings(w, r)
|
||||
})
|
||||
mux.HandleFunc("POST /api/v1/source-catalog/route", func(w http.ResponseWriter, r *http.Request) {
|
||||
routeCatalogFiles(w, r, config)
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user