From aac853837216f8fa5fe219254b3cae4776461fa0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8B=90=E5=8F=8B=20GXXP=20=26=20LEN?= Date: Mon, 23 Nov 2026 12:47:22 +0800 Subject: [PATCH] =?UTF-8?q?fix(settings):=20=E7=BB=91=E5=AE=9A=E7=95=99?= =?UTF-8?q?=E6=A1=A3=E5=90=8D=E7=A7=B0=E5=B9=B6=E6=8C=89=E6=97=A7=E7=9B=AE?= =?UTF-8?q?=E6=A0=87=E9=87=8D=E6=8C=87=E5=90=91=E5=BE=85=E5=85=A5=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 迁移 000084 保存对内/对外绑定名称快照;清除密钥后仍显示已绑定库,不再只显示裸 ID - 测试/生产换绑只重指向同一侧的旧目标,避免测试保存误改另一环境的待入库 - 已保存连接但没有可用密钥时拒绝改绑定,禁止静默回落文件 Key - 生产换绑返回重指向/退休数量,页面提示与测试侧一致 验证:make verify(含隔离 PostgreSQL 集成用例)15/15 通过 --- cmd/api/main.go | 9 + internal/httpapi/production_bindings.go | 75 ++++++-- internal/httpapi/production_bindings_test.go | 56 +++++- internal/httpapi/routing_bindings.go | 40 +++- internal/httpapi/routing_bindings_test.go | 90 ++++++++- .../migrations/000084_binding_names.down.sql | 7 + .../migrations/000084_binding_names.up.sql | 10 + internal/platform/postgres/migrations_test.go | 34 ++-- .../platform/postgres/production_bindings.go | 103 ++++++++-- .../production_bindings_integration_test.go | 12 +- .../platform/postgres/routing_bindings.go | 179 ++++++++++++------ ...outing_bindings_replan_integration_test.go | 84 +++++++- .../source_scan_migration_integration_test.go | 17 +- .../weknora_connections_integration_test.go | 18 +- internal/serviceverify/production_bases.go | 7 + internal/serviceverify/verifier.go | 6 + internal/weknoraconn/service.go | 15 ++ web/src/ProductionBindingsSection.tsx | 7 +- web/src/productionBindings.ts | 4 + 19 files changed, 633 insertions(+), 140 deletions(-) create mode 100644 internal/platform/postgres/migrations/000084_binding_names.down.sql create mode 100644 internal/platform/postgres/migrations/000084_binding_names.up.sql diff --git a/cmd/api/main.go b/cmd/api/main.go index 742b15d..1f7bd1e 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -292,6 +292,15 @@ func (lister connectionAwareBases) ListKnowledgeBases(ctx context.Context) ([]we } return client.ListKnowledgeBases(ctx) } + if lister.service != nil { + configured, err := lister.service.Configured(ctx, weknoraconn.EnvironmentTest) + if err != nil { + return nil, err + } + if configured { + return nil, errors.New("测试 WeKnora 已保存连接但没有可用密钥:请重新录入 API Key(不会回落到文件里的旧 Key)") + } + } if lister.fallback == nil { return nil, errors.New("测试 WeKnora 未配置:请先在系统设置里录入连接") } diff --git a/internal/httpapi/production_bindings.go b/internal/httpapi/production_bindings.go index 511a2e5..d4889c1 100644 --- a/internal/httpapi/production_bindings.go +++ b/internal/httpapi/production_bindings.go @@ -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 diff --git a/internal/httpapi/production_bindings_test.go b/internal/httpapi/production_bindings_test.go index c7b247f..6760cd6 100644 --- a/internal/httpapi/production_bindings_test.go +++ b/internal/httpapi/production_bindings_test.go @@ -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) + } +} diff --git a/internal/httpapi/routing_bindings.go b/internal/httpapi/routing_bindings.go index 03a45dc..8ebe396 100644 --- a/internal/httpapi/routing_bindings.go +++ b/internal/httpapi/routing_bindings.go @@ -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 diff --git a/internal/httpapi/routing_bindings_test.go b/internal/httpapi/routing_bindings_test.go index 5db1f62..241468e 100644 --- a/internal/httpapi/routing_bindings_test.go +++ b/internal/httpapi/routing_bindings_test.go @@ -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") + } +} diff --git a/internal/platform/postgres/migrations/000084_binding_names.down.sql b/internal/platform/postgres/migrations/000084_binding_names.down.sql new file mode 100644 index 0000000..97516b1 --- /dev/null +++ b/internal/platform/postgres/migrations/000084_binding_names.down.sql @@ -0,0 +1,7 @@ +ALTER TABLE production_kb_bindings + DROP COLUMN IF EXISTS internal_kb_name, + DROP COLUMN IF EXISTS external_kb_name; + +ALTER TABLE routing_kb_bindings + DROP COLUMN IF EXISTS internal_kb_name, + DROP COLUMN IF EXISTS external_kb_name; \ No newline at end of file diff --git a/internal/platform/postgres/migrations/000084_binding_names.up.sql b/internal/platform/postgres/migrations/000084_binding_names.up.sql new file mode 100644 index 0000000..808d5f7 --- /dev/null +++ b/internal/platform/postgres/migrations/000084_binding_names.up.sql @@ -0,0 +1,10 @@ +-- 「知识库绑定」保存选择时的库名快照:页面在密钥被清除或连接暂时不可达时 +-- 仍要显示「对内/对外绑定的是哪个库」,不能退化成裸 ID。库名只是展示缓存, +-- 路由与发布仍以 *_kb_id 为准;换库时保存路径会同步覆盖或清空对应快照。 +ALTER TABLE routing_kb_bindings + ADD COLUMN IF NOT EXISTS internal_kb_name TEXT NOT NULL DEFAULT '', + ADD COLUMN IF NOT EXISTS external_kb_name TEXT NOT NULL DEFAULT ''; + +ALTER TABLE production_kb_bindings + ADD COLUMN IF NOT EXISTS internal_kb_name TEXT NOT NULL DEFAULT '', + ADD COLUMN IF NOT EXISTS external_kb_name TEXT NOT NULL DEFAULT ''; \ No newline at end of file diff --git a/internal/platform/postgres/migrations_test.go b/internal/platform/postgres/migrations_test.go index a2250df..ea3c446 100644 --- a/internal/platform/postgres/migrations_test.go +++ b/internal/platform/postgres/migrations_test.go @@ -11,59 +11,67 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) { if err != nil { t.Fatalf("loadMigrations() error = %v", err) } - if len(migrations) != 76 { - t.Fatalf("migration count = %d, want 76", len(migrations)) + if len(migrations) != 77 { + t.Fatalf("migration count = %d, want 77", len(migrations)) + } + // 84 adds the display-name snapshots written with each binding save, so a + // cleared key keeps showing which base is bound instead of a raw id. + if names := migrations[len(migrations)-1]; names.Version != 84 || + !strings.Contains(names.UpSQL, "internal_kb_name") || + !strings.Contains(names.UpSQL, "production_kb_bindings") || + !strings.Contains(names.DownSQL, "DROP COLUMN IF EXISTS external_kb_name") { + t.Fatalf("migration 84 = %#v", names) } // 83 把「连接(地址 + 写-only 密钥)」从文件引用搬进治理库;编号必须 ≥83, // 因为现场 0.9.0 的 schema_migrations 已到 82,迁移器按号跳过且无顺序守卫。 - if connections := migrations[len(migrations)-1]; connections.Version != 83 || + if connections := migrations[len(migrations)-2]; connections.Version != 83 || !strings.Contains(connections.UpSQL, "weknora_environment_connections") || !strings.Contains(connections.UpSQL, "key_ciphertext") || !strings.Contains(connections.DownSQL, "DROP TABLE IF EXISTS weknora_environment_connections") { t.Fatalf("migration 83 = %#v", connections) } // 75 允许"建立目标权威基线"作为独立业务作业,并与 sync/restore 共用写互斥。 - if baseline := migrations[len(migrations)-2]; baseline.Version != 75 || + if baseline := migrations[len(migrations)-3]; baseline.Version != 75 || !strings.Contains(baseline.UpSQL, "library_jobs_write_target") || !strings.Contains(baseline.UpSQL, "'baseline'") { t.Fatalf("migration 75 = %#v", baseline) } // 74 记录封存执行器的运行时状态:页面可用性来自真实观测,不来自配置字符串。 - if executor := migrations[len(migrations)-3]; executor.Version != 74 || + if executor := migrations[len(migrations)-4]; executor.Version != 74 || !strings.Contains(executor.UpSQL, "library_executor_status") { t.Fatalf("migration 74 = %#v", executor) } // 73 记录死信精确解除:保留上游行,只绑定指纹、重放引用与观测摘要。 - if release := migrations[len(migrations)-4]; release.Version != 73 || + if release := migrations[len(migrations)-5]; release.Version != 73 || !strings.Contains(release.UpSQL, "library_dead_letter_releases") { t.Fatalf("migration 73 = %#v", release) } // 72 让维护占用按实例互斥(internal/external 不再各有各的锁)。 - if instance := migrations[len(migrations)-5]; instance.Version != 72 || + if instance := migrations[len(migrations)-6]; instance.Version != 72 || !strings.Contains(instance.UpSQL, "library_instance_maintenance") { t.Fatalf("migration 72 = %#v", instance) } // 71 让维护记录能区分实例级维护与仅治理库互斥。 - if level := migrations[len(migrations)-6]; level.Version != 71 || + if level := migrations[len(migrations)-7]; level.Version != 71 || !strings.Contains(level.UpSQL, "level") || !strings.Contains(level.UpSQL, "ingress_state") { t.Fatalf("migration 71 = %#v", level) } - if maint := migrations[len(migrations)-7]; maint.Version != 70 || !strings.Contains(maint.UpSQL, "library_maintenance") { + if maint := migrations[len(migrations)-8]; maint.Version != 70 || !strings.Contains(maint.UpSQL, "library_maintenance") { t.Fatalf("migration 70 = %#v", maint) } - if tail := migrations[len(migrations)-8]; tail.Version != 69 || + if tail := migrations[len(migrations)-9]; tail.Version != 69 || !strings.Contains(tail.UpSQL, "library_jobs_write_target") { t.Fatalf("migration 69 = %#v", tail) } - if restore := migrations[len(migrations)-9]; restore.Version != 68 || !strings.Contains(restore.UpSQL, "restore") { + if restore := migrations[len(migrations)-10]; restore.Version != 68 || !strings.Contains(restore.UpSQL, "restore") { t.Fatalf("migration 68 = %#v", restore) } - if last := migrations[len(migrations)-10]; last.Version != 67 || + if last := migrations[len(migrations)-11]; last.Version != 67 || !strings.Contains(last.UpSQL, "library_release_authorizations") || !strings.Contains(last.UpSQL, "params_digest") { t.Fatalf("migration 67 = %#v", last) } - if flow := migrations[len(migrations)-11]; flow.Version != 66 || + if flow := migrations[len(migrations)-12]; flow.Version != 66 || !strings.Contains(flow.UpSQL, "CREATE TABLE library_versions") || !strings.Contains(flow.UpSQL, "library_jobs_active") { t.Fatalf("migration 66 = %#v", flow) diff --git a/internal/platform/postgres/production_bindings.go b/internal/platform/postgres/production_bindings.go index b31b786..f602187 100644 --- a/internal/platform/postgres/production_bindings.go +++ b/internal/platform/postgres/production_bindings.go @@ -3,6 +3,7 @@ package postgres import ( "context" "errors" + "fmt" "time" "github.com/jackc/pgx/v5" @@ -13,43 +14,105 @@ import ( // right side is the production-side base this table chooses. An empty side // keeps the historical same-id semantics. type ProductionBinding struct { - InternalKBID string - ExternalKBID string + InternalKBID string + ExternalKBID string + InternalKBName string + ExternalKBName string + UpdatedBy string +} + +// ProductionBindingSave is one UI save of the production-side targets. Names +// are display snapshots; see RoutingBindingSave for the preserve rules. +type ProductionBindingSave struct { + InternalID string + ExternalID string + InternalName string + ExternalName string UpdatedBy string } +func (s *Store) loadProductionKBBinding(ctx context.Context) (ProductionBinding, bool, error) { + var binding ProductionBinding + err := s.db.QueryRow(ctx, ` +SELECT internal_kb_id,external_kb_id,internal_kb_name,external_kb_name,updated_by +FROM production_kb_bindings WHERE id='active'`). + Scan(&binding.InternalKBID, &binding.ExternalKBID, &binding.InternalKBName, &binding.ExternalKBName, &binding.UpdatedBy) + if errors.Is(err, pgx.ErrNoRows) { + return ProductionBinding{}, false, nil + } + if err != nil { + return ProductionBinding{}, false, errors.New("load production kb bindings") + } + return binding, true, nil +} + // LoadProductionKBBindings reads the single active mapping row. A missing row // reads back as unbound rather than an error. func (s *Store) LoadProductionKBBindings(ctx context.Context) (string, string, string, error) { - var binding ProductionBinding - err := s.db.QueryRow(ctx, `SELECT internal_kb_id,external_kb_id,updated_by FROM production_kb_bindings WHERE id='active'`). - Scan(&binding.InternalKBID, &binding.ExternalKBID, &binding.UpdatedBy) - if errors.Is(err, pgx.ErrNoRows) { - return "", "", "", nil - } + binding, _, err := s.loadProductionKBBinding(ctx) if err != nil { - return "", "", "", errors.New("load production kb bindings") + return "", "", "", err } return binding.InternalKBID, binding.ExternalKBID, binding.UpdatedBy, nil } -// SaveProductionKBBindings upserts the mapping row. The knowledge base ids must -// already have been validated against the live production WeKnora by the caller. -func (s *Store) SaveProductionKBBindings(ctx context.Context, internalID, externalID, updatedBy string, now time.Time) error { - if now.IsZero() { - return errors.New("production binding save requires a timestamp") +// LoadProductionKBBindingNames reads the display snapshot stored with the +// production mapping. +func (s *Store) LoadProductionKBBindingNames(ctx context.Context) (string, string, error) { + binding, _, err := s.loadProductionKBBinding(ctx) + if err != nil { + return "", "", err } - if _, err := s.db.Exec(ctx, ` -INSERT INTO production_kb_bindings(id,internal_kb_id,external_kb_id,updated_by,updated_at) -VALUES('active',$1,$2,$3,$4) + return binding.InternalKBName, binding.ExternalKBName, nil +} + +// SaveProductionKBBindingsWithReplan saves the production mapping and, in the +// SAME transaction, re-points 待入库 publications that were still waiting for +// the previous production target. Only rows already aimed at the previous +// production id move; a test-side publication with the same scope is untouched. +func (s *Store) SaveProductionKBBindingsWithReplan(ctx context.Context, save ProductionBindingSave, previous, effective EffectiveKBIDs, now time.Time) (RoutingBindingReplanResult, error) { + var result RoutingBindingReplanResult + if now.IsZero() { + return result, errors.New("production binding replan requires a timestamp") + } + tx, err := s.db.Begin(ctx) + if err != nil { + return result, fmt.Errorf("begin production binding save: %w", err) + } + defer func() { _ = tx.Rollback(ctx) }() + + var previousRow ProductionBinding + err = tx.QueryRow(ctx, ` +SELECT internal_kb_id,external_kb_id,internal_kb_name,external_kb_name +FROM production_kb_bindings WHERE id='active' FOR UPDATE`). + Scan(&previousRow.InternalKBID, &previousRow.ExternalKBID, &previousRow.InternalKBName, &previousRow.ExternalKBName) + if err != nil && !errors.Is(err, pgx.ErrNoRows) { + return result, errors.New("load previous production kb bindings") + } + internalName := preservedBindingName(save.InternalID, save.InternalName, previousRow.InternalKBID, previousRow.InternalKBName) + externalName := preservedBindingName(save.ExternalID, save.ExternalName, previousRow.ExternalKBID, previousRow.ExternalKBName) + + if _, err := tx.Exec(ctx, ` +INSERT INTO production_kb_bindings(id,internal_kb_id,external_kb_id,internal_kb_name,external_kb_name,updated_by,updated_at) +VALUES('active',$1,$2,$3,$4,$5,$6) ON CONFLICT(id) DO UPDATE SET internal_kb_id=EXCLUDED.internal_kb_id, external_kb_id=EXCLUDED.external_kb_id, + internal_kb_name=EXCLUDED.internal_kb_name, + external_kb_name=EXCLUDED.external_kb_name, updated_by=EXCLUDED.updated_by, - updated_at=EXCLUDED.updated_at`, internalID, externalID, updatedBy, now); err != nil { - return errors.New("save production kb bindings") + updated_at=EXCLUDED.updated_at`, + save.InternalID, save.ExternalID, internalName, externalName, save.UpdatedBy, now); err != nil { + return result, errors.New("save production kb bindings") } - return nil + result, err = replanPendingPublicationsTx(ctx, tx, previous, effective, now) + if err != nil { + return RoutingBindingReplanResult{}, err + } + if err := tx.Commit(ctx); err != nil { + return result, fmt.Errorf("commit production binding save: %w", err) + } + return result, nil } // ResolveProductionTargetKB maps a publication scope to the production base the diff --git a/internal/platform/postgres/production_bindings_integration_test.go b/internal/platform/postgres/production_bindings_integration_test.go index c39267f..023a57e 100644 --- a/internal/platform/postgres/production_bindings_integration_test.go +++ b/internal/platform/postgres/production_bindings_integration_test.go @@ -27,6 +27,12 @@ func TestProductionKBBindingsResolveAndFallBack(t *testing.T) { } store := NewStore(pool) now := time.Date(2026, time.October, 8, 9, 0, 0, 0, time.UTC) + save := func(internal, external, updatedBy string, at time.Time) error { + _, err := store.SaveProductionKBBindingsWithReplan(ctx, ProductionBindingSave{ + InternalID: internal, ExternalID: external, UpdatedBy: updatedBy, + }, EffectiveKBIDs{}, EffectiveKBIDs{}, at) + return err + } internal, external, _, err := store.LoadProductionKBBindings(ctx) if err != nil { @@ -39,7 +45,7 @@ func TestProductionKBBindingsResolveAndFallBack(t *testing.T) { t.Fatalf("unbound resolve = %q/%v, want the tested base", target, err) } - if err := store.SaveProductionKBBindings(ctx, "prod-internal", "prod-external", "admin", now); err != nil { + if err := save("prod-internal", "prod-external", "admin", now); err != nil { t.Fatal(err) } if target, err := store.ResolveProductionTargetKB(ctx, "internal", "test-kb"); err != nil || target != "prod-internal" { @@ -53,7 +59,7 @@ func TestProductionKBBindingsResolveAndFallBack(t *testing.T) { } // Unbinding one side returns that side to the same-id semantics only. - if err := store.SaveProductionKBBindings(ctx, "", "prod-external", "admin", now); err != nil { + if err := save("", "prod-external", "admin", now); err != nil { t.Fatal(err) } if target, err := store.ResolveProductionTargetKB(ctx, "internal", "test-kb"); err != nil || target != "test-kb" { @@ -66,7 +72,7 @@ func TestProductionKBBindingsResolveAndFallBack(t *testing.T) { if err != nil || saver != "admin" { t.Fatalf("updated_by = %q (%v)", saver, err) } - if err := store.SaveProductionKBBindings(ctx, "prod-internal", "", "admin", time.Time{}); err == nil { + if err := save("prod-internal", "", "admin", time.Time{}); err == nil { t.Fatal("a save without a timestamp must be rejected") } } diff --git a/internal/platform/postgres/routing_bindings.go b/internal/platform/postgres/routing_bindings.go index fba7bfb..f5efb55 100644 --- a/internal/platform/postgres/routing_bindings.go +++ b/internal/platform/postgres/routing_bindings.go @@ -9,29 +9,68 @@ import ( "github.com/jackc/pgx/v5" ) +// EffectiveKBIDs are the knowledge-base ids the platform actually routes to: +// the UI binding when set, the deployment default otherwise. +type EffectiveKBIDs struct { + Internal string + External string +} + +// RoutingBindingSave is one UI save of the test-side 对内/对外 targets. Names +// are display snapshots captured while the connected instance still answered; +// an empty name preserves the previous snapshot only when the id is unchanged. +type RoutingBindingSave struct { + InternalID string + ExternalID string + InternalName string + ExternalName string + UpdatedBy string +} + // RoutingBinding is the UI-managed knowledge base binding row. Empty ids mean // "not bound in the UI"; callers fall back to their environment defaults. type RoutingBinding struct { - InternalKBID string - ExternalKBID string - UpdatedBy string + InternalKBID string + ExternalKBID string + InternalKBName string + ExternalKBName string + UpdatedBy string +} + +func (s *Store) loadRoutingKBBinding(ctx context.Context) (RoutingBinding, bool, error) { + var binding RoutingBinding + err := s.db.QueryRow(ctx, ` +SELECT internal_kb_id,external_kb_id,internal_kb_name,external_kb_name,updated_by +FROM routing_kb_bindings WHERE id='active'`). + Scan(&binding.InternalKBID, &binding.ExternalKBID, &binding.InternalKBName, &binding.ExternalKBName, &binding.UpdatedBy) + if errors.Is(err, pgx.ErrNoRows) { + return RoutingBinding{}, false, nil + } + if err != nil { + return RoutingBinding{}, false, errors.New("load routing kb bindings") + } + return binding, true, nil } // LoadRoutingKBBindings reads the single active binding row. A missing row // reads back as unbound rather than an error. func (s *Store) LoadRoutingKBBindings(ctx context.Context) (string, string, string, error) { - var binding RoutingBinding - err := s.db.QueryRow(ctx, `SELECT internal_kb_id,external_kb_id,updated_by FROM routing_kb_bindings WHERE id='active'`). - Scan(&binding.InternalKBID, &binding.ExternalKBID, &binding.UpdatedBy) - if errors.Is(err, pgx.ErrNoRows) { - return "", "", "", nil - } + binding, _, err := s.loadRoutingKBBinding(ctx) if err != nil { - return "", "", "", errors.New("load routing kb bindings") + return "", "", "", err } return binding.InternalKBID, binding.ExternalKBID, binding.UpdatedBy, nil } +// LoadRoutingKBBindingNames reads the display snapshot stored with the binding. +func (s *Store) LoadRoutingKBBindingNames(ctx context.Context) (string, string, error) { + binding, _, err := s.loadRoutingKBBinding(ctx) + if err != nil { + return "", "", err + } + return binding.InternalKBName, binding.ExternalKBName, nil +} + // RoutingBindingReplanResult reports what a binding change did to publications // that were still waiting in 待入库. type RoutingBindingReplanResult struct { @@ -43,31 +82,16 @@ type RoutingBindingReplanResult struct { RetiredDuplicates int } -// SaveRoutingKBBindings upserts the binding row. Each side is either empty -// (unbind, fall back to env) or a knowledge base id validated by the caller. -func (s *Store) SaveRoutingKBBindings(ctx context.Context, internalID, externalID, updatedBy string) error { - _, err := s.db.Exec(ctx, ` -INSERT INTO routing_kb_bindings(id,internal_kb_id,external_kb_id,updated_by,updated_at) -VALUES('active',$1,$2,$3,NOW()) -ON CONFLICT(id) DO UPDATE SET - internal_kb_id=EXCLUDED.internal_kb_id, - external_kb_id=EXCLUDED.external_kb_id, - updated_by=EXCLUDED.updated_by, - updated_at=NOW()`, internalID, externalID, updatedBy) - if err != nil { - return errors.New("save routing kb bindings") - } - return nil -} - // replanRetireDuplicatesSQL retires a pending publication whose twin for the // new knowledge base already exists — the unique key is // (source_item_version_id, test_kb_id), so the row cannot simply be moved. +// It is scoped to the previous target ($3): a production-side pending row must +// never be retargeted by a test-side binding save. const replanRetireDuplicatesSQL = ` UPDATE test_publications stale -SET superseded_at = $3, updated_at = $3 +SET superseded_at = $4, updated_at = $4 WHERE stale.superseded_at IS NULL - AND stale.test_kb_id <> $1 + AND stale.test_kb_id = $3 AND stale.processing_state = 'planned' AND stale.ingest_state = 'pending' AND stale.knowledge_id = '' @@ -86,9 +110,9 @@ WHERE stale.superseded_at IS NULL // already in flight keeps its frozen target and stays visible in 待入库. const replanMovePendingSQL = ` UPDATE test_publications pending -SET test_kb_id = $1, updated_at = $3 +SET test_kb_id = $1, updated_at = $4 WHERE pending.superseded_at IS NULL - AND pending.test_kb_id <> $1 + AND pending.test_kb_id = $3 AND pending.processing_state = 'planned' AND pending.ingest_state = 'pending' AND pending.knowledge_id = '' @@ -102,16 +126,60 @@ WHERE pending.superseded_at IS NULL AND twin.superseded_at IS NULL) ` +func preservedBindingName(newID, newName, previousID, previousName string) string { + if newID == "" { + return "" + } + if newName != "" { + return newName + } + if newID == previousID { + return previousName + } + return "" +} + +// replanPendingPublicationsTx moves only rows aimed at the SAME side's previous +// effective target. Test and production bindings share test_publications, so +// matching on target_scope alone would let one environment steal the other's +// pending rows. +func replanPendingPublicationsTx(ctx context.Context, tx pgx.Tx, previous, effective EffectiveKBIDs, now time.Time) (RoutingBindingReplanResult, error) { + var result RoutingBindingReplanResult + for _, scope := range []struct { + name string + from, to string + }{ + {"internal", previous.Internal, effective.Internal}, + {"external", previous.External, effective.External}, + } { + if scope.from == "" || scope.to == "" || scope.from == scope.to { + continue + } + retired, err := tx.Exec(ctx, replanRetireDuplicatesSQL, scope.to, scope.name, scope.from, now) + if err != nil { + return result, fmt.Errorf("retire duplicate pending publications: %w", err) + } + moved, err := tx.Exec(ctx, replanMovePendingSQL, scope.to, scope.name, scope.from, now) + if err != nil { + return result, fmt.Errorf("replan pending publications: %w", err) + } + result.RetiredDuplicates += int(retired.RowsAffected()) + result.Replanned += int(moved.RowsAffected()) + } + return result, nil +} + // SaveRoutingKBBindingsWithReplan saves the binding and, in the SAME // transaction, re-points 待入库 items that were still waiting for the old // knowledge base. Without this, changing the binding left every pending // publication aimed at the previous (possibly deleted) KB, and re-marking the // file created a SECOND publication instead of moving the first. // -// effectiveInternal/effectiveExternal are the ids the platform actually routes -// to (the saved binding, or the deployment default when a side is unbound); -// an empty effective id means that scope cannot be routed and is skipped. -func (s *Store) SaveRoutingKBBindingsWithReplan(ctx context.Context, internalID, externalID, effectiveInternal, effectiveExternal, updatedBy string, now time.Time) (RoutingBindingReplanResult, error) { +// previous/effective are the ids this environment actually routed to before +// and after the save (the saved binding, or the deployment default when a side +// is unbound). An empty previous target skips that scope: there is no reliable +// row to move. +func (s *Store) SaveRoutingKBBindingsWithReplan(ctx context.Context, save RoutingBindingSave, previous, effective EffectiveKBIDs, now time.Time) (RoutingBindingReplanResult, error) { var result RoutingBindingReplanResult if now.IsZero() { return result, errors.New("binding replan requires a timestamp") @@ -121,33 +189,34 @@ func (s *Store) SaveRoutingKBBindingsWithReplan(ctx context.Context, internalID, return result, fmt.Errorf("begin routing binding save: %w", err) } defer func() { _ = tx.Rollback(ctx) }() + + var previousRow RoutingBinding + err = tx.QueryRow(ctx, ` +SELECT internal_kb_id,external_kb_id,internal_kb_name,external_kb_name +FROM routing_kb_bindings WHERE id='active' FOR UPDATE`). + Scan(&previousRow.InternalKBID, &previousRow.ExternalKBID, &previousRow.InternalKBName, &previousRow.ExternalKBName) + if err != nil && !errors.Is(err, pgx.ErrNoRows) { + return result, errors.New("load previous routing kb bindings") + } + internalName := preservedBindingName(save.InternalID, save.InternalName, previousRow.InternalKBID, previousRow.InternalKBName) + externalName := preservedBindingName(save.ExternalID, save.ExternalName, previousRow.ExternalKBID, previousRow.ExternalKBName) + if _, err := tx.Exec(ctx, ` -INSERT INTO routing_kb_bindings(id,internal_kb_id,external_kb_id,updated_by,updated_at) -VALUES('active',$1,$2,$3,$4) +INSERT INTO routing_kb_bindings(id,internal_kb_id,external_kb_id,internal_kb_name,external_kb_name,updated_by,updated_at) +VALUES('active',$1,$2,$3,$4,$5,$6) ON CONFLICT(id) DO UPDATE SET internal_kb_id=EXCLUDED.internal_kb_id, external_kb_id=EXCLUDED.external_kb_id, + internal_kb_name=EXCLUDED.internal_kb_name, + external_kb_name=EXCLUDED.external_kb_name, updated_by=EXCLUDED.updated_by, - updated_at=EXCLUDED.updated_at`, internalID, externalID, updatedBy, now); err != nil { + updated_at=EXCLUDED.updated_at`, + save.InternalID, save.ExternalID, internalName, externalName, save.UpdatedBy, now); err != nil { return result, errors.New("save routing kb bindings") } - for _, scope := range []struct{ name, kbID string }{ - {"internal", effectiveInternal}, - {"external", effectiveExternal}, - } { - if scope.kbID == "" { - continue - } - retired, err := tx.Exec(ctx, replanRetireDuplicatesSQL, scope.kbID, scope.name, now) - if err != nil { - return result, fmt.Errorf("retire duplicate pending publications: %w", err) - } - moved, err := tx.Exec(ctx, replanMovePendingSQL, scope.kbID, scope.name, now) - if err != nil { - return result, fmt.Errorf("replan pending publications: %w", err) - } - result.RetiredDuplicates += int(retired.RowsAffected()) - result.Replanned += int(moved.RowsAffected()) + result, err = replanPendingPublicationsTx(ctx, tx, previous, effective, now) + if err != nil { + return RoutingBindingReplanResult{}, err } if err := tx.Commit(ctx); err != nil { return result, fmt.Errorf("commit routing binding save: %w", err) diff --git a/internal/platform/postgres/routing_bindings_replan_integration_test.go b/internal/platform/postgres/routing_bindings_replan_integration_test.go index b51d0c6..b21613c 100644 --- a/internal/platform/postgres/routing_bindings_replan_integration_test.go +++ b/internal/platform/postgres/routing_bindings_replan_integration_test.go @@ -33,18 +33,21 @@ INSERT INTO source_items(id,source_connection_id,stable_external_id,canonical_ur ('item-in','conn-replan','n-in',repeat('b',64),'docs/in.docx','in.docx','document','locator:r1','internal','configured_scope'), ('item-ext','conn-replan','n-ext',repeat('b',64),'docs/ext.docx','ext.docx','document','locator:r2','external','configured_scope'), ('item-sent','conn-replan','n-sent',repeat('b',64),'docs/sent.docx','sent.docx','document','locator:r3','internal','configured_scope'), - ('item-dup','conn-replan','n-dup',repeat('b',64),'docs/dup.docx','dup.docx','document','locator:r4','internal','configured_scope'); + ('item-dup','conn-replan','n-dup',repeat('b',64),'docs/dup.docx','dup.docx','document','locator:r4','internal','configured_scope'), + ('item-prod','conn-replan','n-prod',repeat('b',64),'docs/prod.docx','prod.docx','document','locator:r5','internal','configured_scope'); INSERT INTO source_item_versions(id,source_item_id,revision,content_object_id,content_state) VALUES ('v-in','item-in','locator:r1',NULL,'unknown'), ('v-ext','item-ext','locator:r2',NULL,'unknown'), ('v-sent','item-sent','locator:r3',NULL,'unknown'), - ('v-dup','item-dup','locator:r4',NULL,'unknown'); + ('v-dup','item-dup','locator:r4',NULL,'unknown'), + ('v-prod','item-prod','locator:r5',NULL,'unknown'); INSERT INTO test_publications(id,source_item_version_id,test_kb_id,processing_state,ingest_state,target_scope) VALUES ('pub-in','v-in','kb-old-internal','planned','pending','internal'), ('pub-ext','v-ext','kb-old-external','planned','pending','external'), ('pub-sent','v-sent','kb-old-internal','pending','uploaded','internal'), ('pub-dup-old','v-dup','kb-old-internal','planned','pending','internal'), - ('pub-dup-new','v-dup','kb-new-internal','planned','pending','internal'); + ('pub-dup-new','v-dup','kb-new-internal','planned','pending','internal'), + ('pub-prod','v-prod','prod-old-internal','planned','pending','internal'); INSERT INTO jobs(id,type,payload,state,idempotency_key) VALUES ('job-sent','test.upload','{"publication_id":"pub-sent"}'::jsonb,'completed','test-start:pub-sent'); `); err != nil { @@ -53,7 +56,11 @@ INSERT INTO jobs(id,type,payload,state,idempotency_key) VALUES store := NewStore(pool) now := time.Date(2026, time.October, 8, 7, 0, 0, 0, time.UTC) - result, err := store.SaveRoutingKBBindingsWithReplan(ctx, "kb-new-internal", "kb-new-external", "kb-new-internal", "kb-new-external", "tester", now) + result, err := store.SaveRoutingKBBindingsWithReplan(ctx, RoutingBindingSave{ + InternalID: "kb-new-internal", ExternalID: "kb-new-external", + InternalName: "新对内库", ExternalName: "新对外库", UpdatedBy: "tester", + }, EffectiveKBIDs{Internal: "kb-old-internal", External: "kb-old-external"}, + EffectiveKBIDs{Internal: "kb-new-internal", External: "kb-new-external"}, now) if err != nil { t.Fatalf("SaveRoutingKBBindingsWithReplan() error = %v", err) } @@ -95,9 +102,39 @@ INSERT INTO jobs(id,type,payload,state,idempotency_key) VALUES if states["pub-dup-old"].kb != "kb-old-internal" || !states["pub-dup-old"].superseded { t.Fatalf("the duplicate stale row must be retired: %#v", states["pub-dup-old"]) } + // A production-side pending row with the same scope must not be stolen by + // the test-side binding change. + if states["pub-prod"].kb != "prod-old-internal" || states["pub-prod"].superseded { + t.Fatalf("production pending row was retargeted by a test save: %#v", states["pub-prod"]) + } + + // Production save moves only the row aimed at its previous target. + prodResult, err := store.SaveProductionKBBindingsWithReplan(ctx, ProductionBindingSave{ + InternalID: "prod-new-internal", ExternalID: "prod-new-external", + InternalName: "生产对内库", ExternalName: "生产对外库", UpdatedBy: "tester", + }, EffectiveKBIDs{Internal: "prod-old-internal", External: "prod-old-external"}, + EffectiveKBIDs{Internal: "prod-new-internal", External: "prod-new-external"}, now) + if err != nil { + t.Fatal(err) + } + if prodResult.Replanned != 1 || prodResult.RetiredDuplicates != 0 { + t.Fatalf("production replan result = %#v, want 1 moved", prodResult) + } + prodState := states["pub-prod"] + if err := pool.QueryRow(ctx, `SELECT test_kb_id FROM test_publications WHERE id='pub-prod'`).Scan(&prodState.kb); err != nil { + t.Fatal(err) + } + states["pub-prod"] = prodState + if states["pub-prod"].kb != "prod-new-internal" { + t.Fatalf("production pending row = %q", states["pub-prod"].kb) + } // Re-saving the same binding is a no-op: nothing left to move or retire. - again, err := store.SaveRoutingKBBindingsWithReplan(ctx, "kb-new-internal", "kb-new-external", "kb-new-internal", "kb-new-external", "tester", now) + again, err := store.SaveRoutingKBBindingsWithReplan(ctx, RoutingBindingSave{ + InternalID: "kb-new-internal", ExternalID: "kb-new-external", + InternalName: "新对内库", ExternalName: "新对外库", UpdatedBy: "tester", + }, EffectiveKBIDs{Internal: "kb-new-internal", External: "kb-new-external"}, + EffectiveKBIDs{Internal: "kb-new-internal", External: "kb-new-external"}, now) if err != nil { t.Fatal(err) } @@ -112,4 +149,41 @@ INSERT INTO jobs(id,type,payload,state,idempotency_key) VALUES if internal != "kb-new-internal" || external != "kb-new-external" || updatedBy != "tester" { t.Fatalf("binding row = %s / %s / %s", internal, external, updatedBy) } + var internalName, externalName string + if err = pool.QueryRow(ctx, `SELECT internal_kb_name, external_kb_name FROM routing_kb_bindings WHERE id='active'`). + Scan(&internalName, &externalName); err != nil { + t.Fatal(err) + } + if internalName != "新对内库" || externalName != "新对外库" { + t.Fatalf("binding names = %q / %q", internalName, externalName) + } + + // A disconnected/cleared-key save carries no live names. Unchanged ids keep + // the snapshot; a changed id must not inherit the old name. + if _, err := store.SaveRoutingKBBindingsWithReplan(ctx, RoutingBindingSave{ + InternalID: "kb-new-internal", ExternalID: "kb-new-external", UpdatedBy: "tester", + }, EffectiveKBIDs{Internal: "kb-new-internal", External: "kb-new-external"}, + EffectiveKBIDs{Internal: "kb-new-internal", External: "kb-new-external"}, now); err != nil { + t.Fatal(err) + } + if err := pool.QueryRow(ctx, `SELECT internal_kb_name, external_kb_name FROM routing_kb_bindings WHERE id='active'`). + Scan(&internalName, &externalName); err != nil { + t.Fatal(err) + } + if internalName != "新对内库" || externalName != "新对外库" { + t.Fatalf("same-id save lost the name snapshot: %q / %q", internalName, externalName) + } + if _, err := store.SaveRoutingKBBindingsWithReplan(ctx, RoutingBindingSave{ + InternalID: "kb-new-internal", ExternalID: "kb-other-external", UpdatedBy: "tester", + }, EffectiveKBIDs{Internal: "kb-new-internal", External: "kb-new-external"}, + EffectiveKBIDs{Internal: "kb-new-internal", External: "kb-other-external"}, now); err != nil { + t.Fatal(err) + } + if err := pool.QueryRow(ctx, `SELECT internal_kb_name, external_kb_name FROM routing_kb_bindings WHERE id='active'`). + Scan(&internalName, &externalName); err != nil { + t.Fatal(err) + } + if internalName != "新对内库" || externalName != "" { + t.Fatalf("changed id inherited a stale name: %q / %q", internalName, externalName) + } } diff --git a/internal/platform/postgres/source_scan_migration_integration_test.go b/internal/platform/postgres/source_scan_migration_integration_test.go index ad3571c..facbfe9 100644 --- a/internal/platform/postgres/source_scan_migration_integration_test.go +++ b/internal/platform/postgres/source_scan_migration_integration_test.go @@ -52,15 +52,20 @@ func TestProcessingConfirmationMigrationBackfillsHistoricalExternalPublication(t t.Fatal(err) } defer pool.Close() - migrations, err := loadMigrations() - if err != nil { - t.Fatal(err) - } - latest := int(migrations[len(migrations)-1].Version) if err := ApplyMigrations(ctx, pool); err != nil { t.Fatal(err) } - for version := latest; version > 10; version-- { + // Roll back by the applied ledger, not by number: migrations are not + // contiguous (76-82 are deliberately absent), so a numeric countdown would + // remove the earlier schema this test needs. + for { + var latest int + if err := pool.QueryRow(ctx, `SELECT MAX(version)::INTEGER FROM schema_migrations`).Scan(&latest); err != nil { + t.Fatal(err) + } + if latest <= 10 { + break + } if err := RollbackLatestMigration(ctx, pool); err != nil { t.Fatal(err) } diff --git a/internal/platform/postgres/weknora_connections_integration_test.go b/internal/platform/postgres/weknora_connections_integration_test.go index 325f800..ab23422 100644 --- a/internal/platform/postgres/weknora_connections_integration_test.go +++ b/internal/platform/postgres/weknora_connections_integration_test.go @@ -93,7 +93,23 @@ func TestWeKnoraConnectionsMigrationUpDownAndStore(t *testing.T) { t.Fatalf("empty execution counts = %d/%d", frozen, retargetable) } - // down 必须只删这三张新表,不碰既有绑定表。 + // down 必须只删这三张新表,不碰既有绑定表。Roll 84 first so this test + // keeps exercising 83 specifically as later migrations land. + for { + var latest int64 + if err := pool.QueryRow(ctx, "SELECT version FROM schema_migrations ORDER BY version DESC LIMIT 1").Scan(&latest); err != nil { + t.Fatalf("read latest migration: %v", err) + } + if latest == 83 { + break + } + if latest < 83 { + t.Fatalf("migration 83 is no longer applied (latest %d)", latest) + } + if err := RollbackLatestMigration(ctx, pool); err != nil { + t.Fatalf("rollback migration %d: %v", latest, err) + } + } if err := RollbackLatestMigration(ctx, pool); err != nil { t.Fatalf("rollback 83: %v", err) } diff --git a/internal/serviceverify/production_bases.go b/internal/serviceverify/production_bases.go index f0e0047..628f3a3 100644 --- a/internal/serviceverify/production_bases.go +++ b/internal/serviceverify/production_bases.go @@ -23,6 +23,13 @@ func (verifier *Verifier) ListProductionKnowledgeBases(ctx context.Context, base } return client.ListKnowledgeBases(ctx) } + configured, err := verifier.config.ConnectionResolver.Configured(ctx, "production") + if err != nil { + return nil, err + } + if configured { + return nil, errors.New("production WeKnora connection has no usable API key; re-enter it instead of falling back to the file") + } } resolved := firstNonEmpty(baseURL, verifier.config.ProductionBaseURLFallback) if resolved == "" { diff --git a/internal/serviceverify/verifier.go b/internal/serviceverify/verifier.go index a6d30bc..d4f29f5 100644 --- a/internal/serviceverify/verifier.go +++ b/internal/serviceverify/verifier.go @@ -50,6 +50,7 @@ type Config struct { // configure these, and a second source would drift. ConnectionResolver interface { Resolve(ctx context.Context, environment string) (string, string, bool) + Configured(ctx context.Context, environment string) (bool, error) } Timeout time.Duration Now func() time.Time @@ -89,9 +90,14 @@ func (verifier *Verifier) VerifyServiceTarget(ctx context.Context, target govern if verifier.config.ConnectionResolver != nil { if endpoint, key, ok := verifier.config.ConnectionResolver.Resolve(ctx, "test"); ok { testBaseURL, testKey = endpoint, key + } else if configured, err := verifier.config.ConnectionResolver.Configured(ctx, "test"); err == nil && configured { + // A cleared key must not silently fall back to the credential file. + testKey = "" } if endpoint, key, ok := verifier.config.ConnectionResolver.Resolve(ctx, "production"); ok { productionBaseURL, productionKey = endpoint, key + } else if configured, err := verifier.config.ConnectionResolver.Configured(ctx, "production"); err == nil && configured { + productionKey = "" } } diff --git a/internal/weknoraconn/service.go b/internal/weknoraconn/service.go index e691cb9..8c0568d 100644 --- a/internal/weknoraconn/service.go +++ b/internal/weknoraconn/service.go @@ -346,6 +346,21 @@ func (service *Service) Resolve(ctx context.Context, environment string) (string return saved.Endpoint, apiKey, true } +// Configured reports whether an operator has saved a connection row for this +// environment. It distinguishes "never configured, use bootstrap files" from +// "configured but the key was cleared", which must fail closed instead of +// silently falling back to an old file key. +func (service *Service) Configured(ctx context.Context, environment string) (bool, error) { + if !ValidEnvironment(environment) { + return false, ErrNotFound + } + _, exists, err := service.store.LoadWeKnoraConnection(ctx, environment) + if err != nil { + return false, err + } + return exists, nil +} + // HTTPPolicy exposes the endpoint policy the client uses, so a caller that // builds its own client stays in agreement with the service. func (service *Service) HTTPPolicy() weknora.HTTPPolicy { diff --git a/web/src/ProductionBindingsSection.tsx b/web/src/ProductionBindingsSection.tsx index a1f8ab6..c3feb66 100644 --- a/web/src/ProductionBindingsSection.tsx +++ b/web/src/ProductionBindingsSection.tsx @@ -45,9 +45,12 @@ export function ProductionBindingsSection() { const frozen = next.frozen + next.retargetable > 0 ? `;已冻结目标 ${next.frozen} 条(不会被改写),仍可改指向 ${next.retargetable} 条` : '' + const replan = next.replanned || next.retired_duplicates + ? `;同时把 ${next.replanned} 项还没上传的待入库重新指向新库${next.retired_duplicates ? `,${next.retired_duplicates} 项因新库里已有同篇而被退休` : ''}` + : '' setMessage(next.production_connected - ? `发布目标已更新:${where}${frozen}。之后新发布的“对内/对外”内容会写入这两个生产库。` - : `发布目标已保存:${where}${frozen};但当前核对不了生产端(${next.production_message}),下次发布前请确认。`) + ? `发布目标已更新:${where}${replan}${frozen}。之后新发布的“对内/对外”内容会写入这两个生产库。` + : `发布目标已保存:${where}${replan}${frozen};但当前核对不了生产端(${next.production_message}),下次发布前请确认。`) } catch (cause) { setError(cause instanceof Error ? cause.message : '保存生产知识库绑定失败') } finally { setSaving(false) } } diff --git a/web/src/productionBindings.ts b/web/src/productionBindings.ts index 660cf98..45690fb 100644 --- a/web/src/productionBindings.ts +++ b/web/src/productionBindings.ts @@ -13,6 +13,8 @@ export interface ProductionBindings { production_message: string frozen: number retargetable: number + replanned: number + retired_duplicates: number } const record = (value: unknown): value is Record => Boolean(value) && typeof value === 'object' && !Array.isArray(value) @@ -29,6 +31,8 @@ function projection(item: Record): ProductionBindings { production_message: typeof item.production_message === 'string' ? item.production_message : '', frozen: typeof item.frozen === 'number' ? item.frozen : 0, retargetable: typeof item.retargetable === 'number' ? item.retargetable : 0, + replanned: typeof item.replanned === 'number' ? item.replanned : 0, + retired_duplicates: typeof item.retired_duplicates === 'number' ? item.retired_duplicates : 0, } }