fix(settings): 绑定留档名称并按旧目标重指向待入库
build / build (push) Successful in 1m48s

- 迁移 000084 保存对内/对外绑定名称快照;清除密钥后仍显示已绑定库,不再只显示裸 ID
- 测试/生产换绑只重指向同一侧的旧目标,避免测试保存误改另一环境的待入库
- 已保存连接但没有可用密钥时拒绝改绑定,禁止静默回落文件 Key
- 生产换绑返回重指向/退休数量,页面提示与测试侧一致

验证:make verify(含隔离 PostgreSQL 集成用例)15/15 通过
This commit is contained in:
狐友 GXXP & LEN
2026-11-23 12:47:22 +08:00
committed by 姚章浩
parent 8b900a9ffb
commit aac8538372
19 changed files with 633 additions and 140 deletions
+64 -11
View File
@@ -6,6 +6,7 @@ import (
"strings"
"time"
postgresstore "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/platform/weknora"
)
@@ -15,7 +16,10 @@ import (
// 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
LoadProductionKBBindingNames(context.Context) (string, string, error)
// SaveProductionKBBindingsWithReplan also re-points 待入库 publications
// that were still waiting for the previous production target.
SaveProductionKBBindingsWithReplan(ctx context.Context, save postgresstore.ProductionBindingSave, previous, effective postgresstore.EffectiveKBIDs, now time.Time) (postgresstore.RoutingBindingReplanResult, error)
// ProductionExecutionCounts reports frozen vs still re-targetable release
// items. A binding change never rewrites a target that was already frozen
// when an execution started; the count is how the page says so.
@@ -40,12 +44,30 @@ type productionBindingView struct {
// Frozen / Retargetable describe what a binding change can still affect.
Frozen int `json:"frozen"`
Retargetable int `json:"retargetable"`
// Replanned / RetiredDuplicates describe what THIS save did to 待入库 items.
Replanned int `json:"replanned"`
RetiredDuplicates int `json:"retired_duplicates"`
}
// WeKnoraConnectionResolver reads the admin-managed connection for one
// environment. When it answers, that endpoint is the only truth.
type WeKnoraConnectionResolver interface {
Resolve(ctx context.Context, environment string) (endpoint string, apiKey string, ok bool)
Configured(ctx context.Context, environment string) (bool, error)
}
// connectionKeyUnusable distinguishes "a saved row whose key was cleared or
// cannot be decrypted" from "saved and usable, but the endpoint is down". Only
// the former must block a binding save; the latter stays an honest warning.
func (config Config) connectionKeyUnusable(ctx context.Context, environment string) bool {
if config.WeKnoraConnectionResolver == nil {
return false
}
if _, _, ok := config.WeKnoraConnectionResolver.Resolve(ctx, environment); ok {
return false
}
configured, err := config.WeKnoraConnectionResolver.Configured(ctx, environment)
return err == nil && configured
}
// productionTargetBaseURL is the production endpoint the picker reads from: the
@@ -83,26 +105,40 @@ func (config Config) productionKnowledgeBases(ctx context.Context) ([]weknora.Kn
return bases, ""
}
func (config Config) productionBindingPayload(ctx context.Context) (productionBindingView, error) {
func (config Config) productionBindingPayload(ctx context.Context, replan postgresstore.RoutingBindingReplanResult) (productionBindingView, error) {
storedInternal, storedExternal, updatedBy, err := config.ProductionBindings.LoadProductionKBBindings(ctx)
if err != nil {
return productionBindingView{}, err
}
storedInternalName, storedExternalName, err := config.ProductionBindings.LoadProductionKBBindingNames(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
}
nameFor := func(id, storedName string) string {
if id == "" {
return ""
}
if message == "" {
return names[id]
}
return storedName
}
frozen, retargetable := 0, 0
if frozenItems, retargetableItems, countsErr := config.ProductionBindings.ProductionExecutionCounts(ctx); countsErr == nil {
frozen, retargetable = frozenItems, retargetableItems
}
return productionBindingView{
InternalKBID: storedInternal, ExternalKBID: storedExternal,
InternalKBName: names[storedInternal], ExternalKBName: names[storedExternal],
InternalKBName: nameFor(storedInternal, storedInternalName), ExternalKBName: nameFor(storedExternal, storedExternalName),
UpdatedBy: updatedBy, ProductionBaseURL: config.productionTargetBaseURL(ctx),
ProductionConnected: message == "", ProductionMessage: message,
Frozen: frozen, Retargetable: retargetable,
Replanned: replan.Replanned, RetiredDuplicates: replan.RetiredDuplicates,
}, nil
}
@@ -111,7 +147,7 @@ func (config Config) handleProductionBindings(w http.ResponseWriter, r *http.Req
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "production bindings are not configured"})
return
}
view, err := config.productionBindingPayload(r.Context())
view, err := config.productionBindingPayload(r.Context(), postgresstore.RoutingBindingReplanResult{})
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not load production bindings"})
return
@@ -161,11 +197,16 @@ func (config Config) handleSaveProductionBindings(w http.ResponseWriter, r *http
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
}
bases, message := config.productionKnowledgeBases(r.Context())
if message != "" && config.connectionKeyUnusable(r.Context(), "production") {
writeJSON(w, http.StatusConflict, map[string]string{"error": "生产 WeKnora 已保存连接但没有可用密钥:请重新录入 API Key 并测通后再改发布目标"})
return
}
names := make(map[string]string, len(bases))
for _, base := range bases {
names[base.ID] = base.Name
}
if message == "" {
if internal != "" {
if _, ok := names[internal]; !ok {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "对内绑定的生产知识库在该 WeKnora 实例中不存在"})
@@ -179,11 +220,23 @@ func (config Config) handleSaveProductionBindings(w http.ResponseWriter, r *http
}
}
}
if err := config.ProductionBindings.SaveProductionKBBindings(r.Context(), internal, external, actorFor(r), config.Now().UTC()); err != nil {
previousInternal, previousExternal, _, err := config.ProductionBindings.LoadProductionKBBindings(r.Context())
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not load production bindings"})
return
}
replan, err := config.ProductionBindings.SaveProductionKBBindingsWithReplan(r.Context(), postgresstore.ProductionBindingSave{
InternalID: internal, ExternalID: external,
InternalName: names[internal], ExternalName: names[external],
UpdatedBy: actorFor(r),
}, postgresstore.EffectiveKBIDs{Internal: previousInternal, External: previousExternal},
postgresstore.EffectiveKBIDs{Internal: internal, External: external},
config.Now().UTC())
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not save production bindings"})
return
}
view, err := config.productionBindingPayload(r.Context())
view, err := config.productionBindingPayload(r.Context(), replan)
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not load production bindings"})
return
+47 -9
View File
@@ -11,26 +11,40 @@ import (
"time"
"knowledge-governance/internal/governance"
postgresstore "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/platform/weknora"
)
type productionBindingStoreFake struct {
internal, external, saver string
savedInternal, savedExternal string
saveCallCount int
frozen, retargetable int
internal, external, saver string
internalName, externalName string
savedInternal, savedExternal string
savedInternalName, savedExternalName string
previousInternal, previousExternal string
effectiveInternal, effectiveExternal string
saveCallCount int
frozen, retargetable int
replanResult postgresstore.RoutingBindingReplanResult
}
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
func (fake *productionBindingStoreFake) LoadProductionKBBindingNames(context.Context) (string, string, error) {
return fake.internalName, fake.externalName, nil
}
func (fake *productionBindingStoreFake) SaveProductionKBBindingsWithReplan(_ context.Context, save postgresstore.ProductionBindingSave, previous, effective postgresstore.EffectiveKBIDs, _ time.Time) (postgresstore.RoutingBindingReplanResult, error) {
fake.savedInternal, fake.savedExternal = save.InternalID, save.ExternalID
fake.savedInternalName, fake.savedExternalName = save.InternalName, save.ExternalName
fake.previousInternal, fake.previousExternal = previous.Internal, previous.External
fake.effectiveInternal, fake.effectiveExternal = effective.Internal, effective.External
fake.saver = save.UpdatedBy
fake.saveCallCount++
fake.internal, fake.external = internal, external
return nil
fake.internal, fake.external = save.InternalID, save.ExternalID
fake.internalName, fake.externalName = save.InternalName, save.ExternalName
return fake.replanResult, nil
}
func (fake *productionBindingStoreFake) ProductionExecutionCounts(context.Context) (int, int, error) {
@@ -118,6 +132,9 @@ func TestProductionBindingsSaveStoresValidatedPair(t *testing.T) {
if store.savedInternal != "kb-prod-internal" || store.savedExternal != "kb-prod-external" {
t.Fatalf("saved = %q/%q", store.savedInternal, store.savedExternal)
}
if store.savedInternalName != "对内知识库-wiki" || store.savedExternalName != "对外知识库-wiki" {
t.Fatalf("saved names = %q/%q", store.savedInternalName, store.savedExternalName)
}
var envelope struct {
Data productionBindingView `json:"data"`
}
@@ -183,3 +200,24 @@ func TestProductionBindingOptionsReportUnavailableReason(t *testing.T) {
t.Fatalf("status = %d body %s", recorder.Code, recorder.Body.String())
}
}
// A cleared production key must not erase the display snapshot: the page keeps
// saying which production bases are bound even when it cannot list them.
func TestProductionBindingsReadFallsBackToStoredNamesWhenUnavailable(t *testing.T) {
store := &productionBindingStoreFake{internal: "kb-prod-internal", external: "kb-prod-external", internalName: "对内知识库-wiki", externalName: "对外知识库-wiki"}
handler := productionBindingsHandler(t, store, &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", nil))
if recorder.Code != http.StatusOK {
t.Fatalf("status = %d body %s", recorder.Code, recorder.Body.String())
}
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.ExternalKBName != "对外知识库-wiki" || envelope.Data.ProductionConnected {
t.Fatalf("view = %#v", envelope.Data)
}
}
+35 -5
View File
@@ -14,10 +14,10 @@ import (
// (migration 000034). Empty stored values fall back to env defaults.
type RoutingBindingStore interface {
LoadRoutingKBBindings(context.Context) (string, string, string, error)
SaveRoutingKBBindings(context.Context, string, string, string) error
LoadRoutingKBBindingNames(context.Context) (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)
SaveRoutingKBBindingsWithReplan(ctx context.Context, save postgresstore.RoutingBindingSave, previous, effective postgresstore.EffectiveKBIDs, now time.Time) (postgresstore.RoutingBindingReplanResult, error)
}
// KnowledgeBaseLister enumerates candidate knowledge bases in the connected
@@ -97,14 +97,33 @@ func (config Config) routingBindingPayload(ctx context.Context, replan postgress
if err != nil {
return routingBindingView{}, err
}
internal, external := config.effectiveRoutingTargets(ctx)
storedInternalName, storedExternalName, err := config.RoutingBindings.LoadRoutingKBBindingNames(ctx)
if err != nil {
return routingBindingView{}, err
}
internal, external := storedInternal, storedExternal
if internal == "" {
internal = config.InternalRoutingKnowledgeBaseID
}
if external == "" {
external = config.ExternalRoutingKnowledgeBaseID
}
nameFor := func(id, storedName string) string {
if id == "" {
return ""
}
if connected {
return names[id]
}
return storedName
}
return routingBindingView{
InternalKBID: internal, ExternalKBID: external,
InternalBoundByUI: storedInternal != "", ExternalBoundByUI: storedExternal != "",
InternalEnvFallback: storedInternal == "" && config.InternalRoutingKnowledgeBaseID != "",
ExternalEnvFallback: storedExternal == "" && config.ExternalRoutingKnowledgeBaseID != "",
InternalFallbackKBID: config.InternalRoutingKnowledgeBaseID, ExternalFallbackKBID: config.ExternalRoutingKnowledgeBaseID,
InternalKBName: names[storedInternal], ExternalKBName: names[storedExternal],
InternalKBName: nameFor(internal, storedInternalName), ExternalKBName: nameFor(external, storedExternalName),
UpdatedBy: updatedBy, WeKnoraConnected: connected,
Replanned: replan.Replanned, RetiredDuplicates: replan.RetiredDuplicates,
}, nil
@@ -161,6 +180,10 @@ func (config Config) handleSaveRoutingBindings(w http.ResponseWriter, r *http.Re
// offline saves fall through to the DB so the page never hard-fails, but
// the response reports connected=false honestly.
names, connected := config.routingBindingNames(r.Context())
if !connected && config.connectionKeyUnusable(r.Context(), "test") {
writeJSON(w, http.StatusConflict, map[string]string{"error": "测试 WeKnora 已保存连接但没有可用密钥:请重新录入 API Key 并测通后再改绑定"})
return
}
if connected {
if internal != "" {
if _, ok := names[internal]; !ok {
@@ -186,7 +209,14 @@ func (config Config) handleSaveRoutingBindings(w http.ResponseWriter, r *http.Re
if effectiveExternal == "" {
effectiveExternal = config.ExternalRoutingKnowledgeBaseID
}
replan, err := config.RoutingBindings.SaveRoutingKBBindingsWithReplan(r.Context(), internal, external, effectiveInternal, effectiveExternal, actorFor(r), config.Now().UTC())
previousInternal, previousExternal := config.effectiveRoutingTargets(r.Context())
replan, err := config.RoutingBindings.SaveRoutingKBBindingsWithReplan(r.Context(), postgresstore.RoutingBindingSave{
InternalID: internal, ExternalID: external,
InternalName: names[internal], ExternalName: names[external],
UpdatedBy: actorFor(r),
}, postgresstore.EffectiveKBIDs{Internal: previousInternal, External: previousExternal},
postgresstore.EffectiveKBIDs{Internal: effectiveInternal, External: effectiveExternal},
config.Now().UTC())
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not save routing bindings"})
return
+80 -10
View File
@@ -3,6 +3,7 @@ package httpapi
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
@@ -14,11 +15,14 @@ import (
)
type bindingStoreFake struct {
internal string
external string
saver string
internal string
external string
internalName string
externalName string
saver string
// replan records what the last save asked for, so tests can assert that the
// effective (env-fallback aware) targets were used.
// previous and effective (env-fallback aware) targets were used.
replanPrevious [2]string
replanEffective [2]string
replanResult postgresstore.RoutingBindingReplanResult
replanCallCount int
@@ -28,14 +32,15 @@ func (fake *bindingStoreFake) LoadRoutingKBBindings(context.Context) (string, st
return fake.internal, fake.external, fake.saver, nil
}
func (fake *bindingStoreFake) SaveRoutingKBBindings(_ context.Context, internal, external, updatedBy string) error {
fake.internal, fake.external, fake.saver = internal, external, updatedBy
return nil
func (fake *bindingStoreFake) LoadRoutingKBBindingNames(context.Context) (string, string, error) {
return fake.internalName, fake.externalName, 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}
func (fake *bindingStoreFake) SaveRoutingKBBindingsWithReplan(_ context.Context, save postgresstore.RoutingBindingSave, previous, effective postgresstore.EffectiveKBIDs, _ time.Time) (postgresstore.RoutingBindingReplanResult, error) {
fake.internal, fake.external, fake.saver = save.InternalID, save.ExternalID, save.UpdatedBy
fake.internalName, fake.externalName = save.InternalName, save.ExternalName
fake.replanPrevious = [2]string{previous.Internal, previous.External}
fake.replanEffective = [2]string{effective.Internal, effective.External}
fake.replanCallCount++
return fake.replanResult, nil
}
@@ -134,6 +139,9 @@ func TestRoutingBindingsSaveReportsReplanAndUsesEffectiveTargets(t *testing.T) {
if store.replanEffective != [2]string{"kb-in", "env-external"} {
t.Fatalf("effective targets = %#v, want the env fallback on the unbound side", store.replanEffective)
}
if store.replanPrevious != [2]string{"env-internal", "env-external"} {
t.Fatalf("previous targets = %#v, want the pre-save effective pair", store.replanPrevious)
}
var envelope struct {
Data struct {
Replanned int `json:"replanned"`
@@ -163,3 +171,65 @@ func TestRouteCatalogFilesUsesUIBinding(t *testing.T) {
t.Fatalf("capabilities = %#v", envelope.Data)
}
}
// Clearing the API key must not blank the already-saved binding names: the
// page has no live listing then, so it reads the snapshot written at save time.
func TestRoutingBindingsReadFallsBackToStoredNamesWhenDisconnected(t *testing.T) {
store := &bindingStoreFake{internal: "kb-in", external: "kb-ex", internalName: "对内库", externalName: "对外库"}
handler := bindingsTestHandler(t, store, &kbListerFake{err: errors.New("no key")}, "", "")
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/routing-bindings", nil))
if recorder.Code != http.StatusOK {
t.Fatalf("status = %d body %s", recorder.Code, recorder.Body.String())
}
var envelope struct {
Data routingBindingView `json:"data"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &envelope); err != nil {
t.Fatal(err)
}
if envelope.Data.InternalKBName != "对内库" || envelope.Data.ExternalKBName != "对外库" || envelope.Data.WeKnoraConnected {
t.Fatalf("view = %#v", envelope.Data)
}
}
type connectionResolverFake struct {
resolveOK bool
configured bool
}
func (fake connectionResolverFake) Resolve(context.Context, string) (string, string, bool) {
if !fake.resolveOK {
return "", "", false
}
return "http://127.0.0.1:8092", "key", true
}
func (fake connectionResolverFake) Configured(context.Context, string) (bool, error) {
return fake.configured, nil
}
// A saved row whose key was cleared must reject a binding save instead of
// silently falling back to the deployment file key or writing unverifiable ids.
func TestRoutingBindingsSaveRejectsClearedConnectionKey(t *testing.T) {
store := &bindingStoreFake{internal: "kb-old", external: "kb-old-external"}
handler, err := NewHandler(Config{
Store: &fakeJobStore{}, RoutingBindings: store,
KnowledgeBases: &kbListerFake{err: errors.New("no key")},
WeKnoraConnectionResolver: connectionResolverFake{configured: true},
InternalRoutingKnowledgeBaseID: "env-internal", ExternalRoutingKnowledgeBaseID: "env-external",
Now: func() time.Time { return time.Date(2026, time.October, 8, 9, 0, 0, 0, time.UTC) },
})
if err != nil {
t.Fatal(err)
}
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodPut, "/api/v1/routing-bindings",
strings.NewReader(`{"internal_kb_id":"kb-new","external_kb_id":"kb-old-external"}`)))
if recorder.Code != http.StatusConflict {
t.Fatalf("status = %d body %s", recorder.Code, recorder.Body.String())
}
if store.replanCallCount != 0 {
t.Fatal("a cleared-key save must not reach the store")
}
}