- 生产页保存对内/对外库时,在同一事务内把还没上传、原本瞄准旧生产库的待入库项改指向新库,并在保存提示里回报迁移条数;执行已开始的项目标保持冻结。 - 重排改为「上一次生效目标 → 新目标」成对过滤:测试与生产共用 test_publications,测试侧保存不再带走瞄准生产库的待入库(验收附带发现)。 - 用例补生产重排、测试侧保存不误搬生产作业、生产保存不动测试作业三组断言。
This commit is contained in:
@@ -1,5 +1,16 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## 开发快照 0.1.413(知识库绑定:生产侧待入库重排与按环境隔离)
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- **生产绑定保存重排待入库**:保存生产「知识库绑定」时,同一事务内把还没上传、
|
||||||
|
原本瞄准旧生产目标库的待入库项改指向新库,并在保存提示里回报迁移条数;已经
|
||||||
|
开始执行的发布项目标仍保持冻结,不会被改写。
|
||||||
|
- **测试侧保存不再误搬生产作业**:两边共用 `test_publications` 待入库通道,重排
|
||||||
|
现在只搬「上一次生效目标 → 新目标」成对的项;测试侧改绑不会再带走瞄准生产库的
|
||||||
|
待入库项,生产侧也不猜「同 ID 语义」下的空目标。
|
||||||
|
|
||||||
## 开发快照 0.1.412(知识库绑定:清密钥保留名称与绑定身份)
|
## 开发快照 0.1.412(知识库绑定:清密钥保留名称与绑定身份)
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ type RoutingBindingStore interface {
|
|||||||
SaveRoutingKBBindings(context.Context, string, string, string) error
|
SaveRoutingKBBindings(context.Context, string, string, string) error
|
||||||
// SaveRoutingKBBindingsWithReplan also re-points 待入库 publications that
|
// SaveRoutingKBBindingsWithReplan also re-points 待入库 publications that
|
||||||
// were still waiting for the previous knowledge base (same transaction).
|
// 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, now time.Time) (postgresstore.RoutingBindingReplanResult, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// KnowledgeBaseLister enumerates candidate knowledge bases in the connected
|
// KnowledgeBaseLister enumerates candidate knowledge bases in the connected
|
||||||
@@ -196,6 +196,9 @@ func (config Config) handleSaveRoutingBindings(w http.ResponseWriter, r *http.Re
|
|||||||
// The saved binding re-routes FUTURE annotations; pending 待入库 items that
|
// The saved binding re-routes FUTURE annotations; pending 待入库 items that
|
||||||
// have never been uploaded are re-pointed in the same transaction, otherwise
|
// have never been uploaded are re-pointed in the same transaction, otherwise
|
||||||
// they would keep aiming at the previous (possibly removed) knowledge base.
|
// they would keep aiming at the previous (possibly removed) knowledge base.
|
||||||
|
// Only items aimed at the PREVIOUS effective target of this side move, so a
|
||||||
|
// test-side save cannot carry off production-side pending work.
|
||||||
|
previousInternal, previousExternal := config.effectiveRoutingTargets(r.Context())
|
||||||
effectiveInternal := internal
|
effectiveInternal := internal
|
||||||
if effectiveInternal == "" {
|
if effectiveInternal == "" {
|
||||||
effectiveInternal = config.InternalRoutingKnowledgeBaseID
|
effectiveInternal = config.InternalRoutingKnowledgeBaseID
|
||||||
@@ -204,7 +207,12 @@ func (config Config) handleSaveRoutingBindings(w http.ResponseWriter, r *http.Re
|
|||||||
if effectiveExternal == "" {
|
if effectiveExternal == "" {
|
||||||
effectiveExternal = config.ExternalRoutingKnowledgeBaseID
|
effectiveExternal = config.ExternalRoutingKnowledgeBaseID
|
||||||
}
|
}
|
||||||
replan, err := config.RoutingBindings.SaveRoutingKBBindingsWithReplan(r.Context(), internal, external, effectiveInternal, effectiveExternal, actorFor(r), config.Now().UTC())
|
replan, err := config.RoutingBindings.SaveRoutingKBBindingsWithReplan(r.Context(), postgresstore.RoutingBindingSave{
|
||||||
|
InternalID: internal, ExternalID: external,
|
||||||
|
Previous: postgresstore.EffectiveKBIDs{Internal: previousInternal, External: previousExternal},
|
||||||
|
Effective: postgresstore.EffectiveKBIDs{Internal: effectiveInternal, External: effectiveExternal},
|
||||||
|
UpdatedBy: actorFor(r),
|
||||||
|
}, config.Now().UTC())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not save routing bindings"})
|
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not save routing bindings"})
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -18,7 +18,8 @@ type bindingStoreFake struct {
|
|||||||
external string
|
external string
|
||||||
saver string
|
saver string
|
||||||
// replan records what the last save asked for, so tests can assert that the
|
// replan records what the last save asked for, so tests can assert that the
|
||||||
// effective (env-fallback aware) targets were used.
|
// effective (env-fallback aware) targets and the previous pair were used.
|
||||||
|
replanPrevious [2]string
|
||||||
replanEffective [2]string
|
replanEffective [2]string
|
||||||
replanResult postgresstore.RoutingBindingReplanResult
|
replanResult postgresstore.RoutingBindingReplanResult
|
||||||
replanCallCount int
|
replanCallCount int
|
||||||
@@ -33,9 +34,10 @@ func (fake *bindingStoreFake) SaveRoutingKBBindings(_ context.Context, internal,
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (fake *bindingStoreFake) SaveRoutingKBBindingsWithReplan(_ context.Context, internal, external, effectiveInternal, effectiveExternal, updatedBy string, _ time.Time) (postgresstore.RoutingBindingReplanResult, error) {
|
func (fake *bindingStoreFake) SaveRoutingKBBindingsWithReplan(_ context.Context, save postgresstore.RoutingBindingSave, _ time.Time) (postgresstore.RoutingBindingReplanResult, error) {
|
||||||
fake.internal, fake.external, fake.saver = internal, external, updatedBy
|
fake.internal, fake.external, fake.saver = save.InternalID, save.ExternalID, save.UpdatedBy
|
||||||
fake.replanEffective = [2]string{effectiveInternal, effectiveExternal}
|
fake.replanPrevious = [2]string{save.Previous.Internal, save.Previous.External}
|
||||||
|
fake.replanEffective = [2]string{save.Effective.Internal, save.Effective.External}
|
||||||
fake.replanCallCount++
|
fake.replanCallCount++
|
||||||
return fake.replanResult, nil
|
return fake.replanResult, nil
|
||||||
}
|
}
|
||||||
@@ -134,6 +136,9 @@ func TestRoutingBindingsSaveReportsReplanAndUsesEffectiveTargets(t *testing.T) {
|
|||||||
if store.replanEffective != [2]string{"kb-in", "env-external"} {
|
if store.replanEffective != [2]string{"kb-in", "env-external"} {
|
||||||
t.Fatalf("effective targets = %#v, want the env fallback on the unbound side", store.replanEffective)
|
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 {
|
var envelope struct {
|
||||||
Data struct {
|
Data struct {
|
||||||
Replanned int `json:"replanned"`
|
Replanned int `json:"replanned"`
|
||||||
|
|||||||
@@ -30,11 +30,17 @@ func fakeCandidate(t *testing.T) *httptest.Server {
|
|||||||
}
|
}
|
||||||
switch {
|
switch {
|
||||||
case r.URL.Path == "/api/v1/knowledge-bases":
|
case r.URL.Path == "/api/v1/knowledge-bases":
|
||||||
_, _ = w.Write([]byte(`{"success":true,"total":2,"data":[{"id":"kb-in","name":"内部技术资料","knowledge_count":3},{"id":"kb-out","name":"客户使用手册","knowledge_count":4}]}`))
|
_, _ = w.Write([]byte(`{"success":true,"total":5,"data":[{"id":"kb-in","name":"内部技术资料","knowledge_count":3},{"id":"kb-out","name":"客户使用手册","knowledge_count":4},{"id":"p-internal","name":"生产内部资料","knowledge_count":5},{"id":"p-external","name":"生产客户手册","knowledge_count":6},{"id":"p-new-internal","name":"生产内部资料新版","knowledge_count":0}]}`))
|
||||||
case r.URL.Path == "/api/v1/knowledge-bases/kb-in":
|
case r.URL.Path == "/api/v1/knowledge-bases/kb-in":
|
||||||
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-in","name":"内部技术资料","tenant_id":10000}}`))
|
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-in","name":"内部技术资料","tenant_id":10000}}`))
|
||||||
case r.URL.Path == "/api/v1/knowledge-bases/kb-out":
|
case r.URL.Path == "/api/v1/knowledge-bases/kb-out":
|
||||||
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-out","name":"客户使用手册","tenant_id":10000}}`))
|
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-out","name":"客户使用手册","tenant_id":10000}}`))
|
||||||
|
case r.URL.Path == "/api/v1/knowledge-bases/p-internal":
|
||||||
|
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"p-internal","name":"生产内部资料","tenant_id":10000}}`))
|
||||||
|
case r.URL.Path == "/api/v1/knowledge-bases/p-external":
|
||||||
|
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"p-external","name":"生产客户手册","tenant_id":10000}}`))
|
||||||
|
case r.URL.Path == "/api/v1/knowledge-bases/p-new-internal":
|
||||||
|
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"p-new-internal","name":"生产内部资料新版","tenant_id":10000}}`))
|
||||||
default:
|
default:
|
||||||
w.WriteHeader(http.StatusNotFound)
|
w.WriteHeader(http.StatusNotFound)
|
||||||
}
|
}
|
||||||
@@ -69,11 +75,14 @@ func TestSaveReadsBackResolvesTheKeyAndReplansPendingInOneTransaction(t *testing
|
|||||||
if _, err := pool.Exec(ctx, `
|
if _, err := pool.Exec(ctx, `
|
||||||
INSERT INTO source_connections(id,source_type,name,enabled) VALUES('conn-kbb','manual','KBB',true);
|
INSERT INTO source_connections(id,source_type,name,enabled) VALUES('conn-kbb','manual','KBB',true);
|
||||||
INSERT INTO source_items(id,source_connection_id,stable_external_id,canonical_uri_hash,normalized_path,title,item_type,revision,visibility,visibility_origin) VALUES
|
INSERT INTO source_items(id,source_connection_id,stable_external_id,canonical_uri_hash,normalized_path,title,item_type,revision,visibility,visibility_origin) VALUES
|
||||||
('item-kbb','conn-kbb','n-kbb',repeat('c',64),'docs/kbb.docx','kbb.docx','document','locator:r1','internal','configured_scope');
|
('item-kbb','conn-kbb','n-kbb',repeat('c',64),'docs/kbb.docx','kbb.docx','document','locator:r1','internal','configured_scope'),
|
||||||
|
('item-prod-kbb','conn-kbb','n-prod-kbb',repeat('d',64),'docs/prod-kbb.docx','prod-kbb.docx','document','locator:r2','internal','configured_scope');
|
||||||
INSERT INTO source_item_versions(id,source_item_id,revision,content_object_id,content_state) VALUES
|
INSERT INTO source_item_versions(id,source_item_id,revision,content_object_id,content_state) VALUES
|
||||||
('version-kbb','item-kbb','locator:r1',NULL,'unknown');
|
('version-kbb','item-kbb','locator:r1',NULL,'unknown'),
|
||||||
|
('version-prod-kbb','item-prod-kbb','locator:r2',NULL,'unknown');
|
||||||
INSERT INTO test_publications(id,source_item_version_id,test_kb_id,processing_state,ingest_state,target_scope) VALUES
|
INSERT INTO test_publications(id,source_item_version_id,test_kb_id,processing_state,ingest_state,target_scope) VALUES
|
||||||
('pub-kbb','version-kbb','kb-old','planned','pending','internal');
|
('pub-kbb','version-kbb','kb-legacy-in','planned','pending','internal'),
|
||||||
|
('pub-prod-kbb','version-prod-kbb','p-internal','planned','pending','internal');
|
||||||
`); err != nil {
|
`); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -139,6 +148,15 @@ INSERT INTO test_publications(id,source_item_version_id,test_kb_id,processing_st
|
|||||||
if pendingKB != "kb-in" {
|
if pendingKB != "kb-in" {
|
||||||
t.Fatalf("pending publication target = %s, want kb-in", pendingKB)
|
t.Fatalf("pending publication target = %s, want kb-in", pendingKB)
|
||||||
}
|
}
|
||||||
|
// A save on the test card must not carry off pending work that already aims
|
||||||
|
// at the production binding: the two environments share test_publications.
|
||||||
|
var productionPending string
|
||||||
|
if err := pool.QueryRow(ctx, `SELECT test_kb_id FROM test_publications WHERE id='pub-prod-kbb'`).Scan(&productionPending); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if productionPending != "p-internal" {
|
||||||
|
t.Fatalf("test-side save moved a production pending item to %s", productionPending)
|
||||||
|
}
|
||||||
|
|
||||||
// A stale revision must not overwrite the saved connection or re-point work.
|
// A stale revision must not overwrite the saved connection or re-point work.
|
||||||
_, err = store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{
|
_, err = store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{
|
||||||
@@ -184,20 +202,46 @@ INSERT INTO test_publications(id,source_item_version_id,test_kb_id,processing_st
|
|||||||
|
|
||||||
prodView, err := store.Save(ctx, kbbinding.EnvProduction, kbbinding.SaveInput{
|
prodView, err := store.Save(ctx, kbbinding.EnvProduction, kbbinding.SaveInput{
|
||||||
BaseRevision: 0, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(),
|
BaseRevision: 0, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(),
|
||||||
InternalKBID: "kb-in", ExternalKBID: "kb-out",
|
InternalKBID: "p-internal", ExternalKBID: "p-external",
|
||||||
}, "admin", now)
|
}, "admin", now)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("production Save() error = %v", err)
|
t.Fatalf("production Save() error = %v", err)
|
||||||
}
|
}
|
||||||
if prodView.Environment != kbbinding.EnvProduction || prodView.Revision != 1 {
|
if prodView.Environment != kbbinding.EnvProduction || prodView.Revision != 1 || prodView.Replanned != 0 {
|
||||||
t.Fatalf("production view = %#v", prodView)
|
t.Fatalf("production view = %#v", prodView)
|
||||||
}
|
}
|
||||||
|
// Changing the production internal base must re-point pending 待入库 items
|
||||||
|
// that were waiting for p-internal (the C-006 failure), and must leave the
|
||||||
|
// test-lane publication on its own target.
|
||||||
|
prodMoved, err := store.Save(ctx, kbbinding.EnvProduction, kbbinding.SaveInput{
|
||||||
|
BaseRevision: prodView.Revision, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(),
|
||||||
|
InternalKBID: "p-new-internal", ExternalKBID: "p-external",
|
||||||
|
}, "admin", now.Add(time.Minute))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("production retarget Save() error = %v", err)
|
||||||
|
}
|
||||||
|
if prodMoved.Replanned != 1 || prodMoved.RetiredDuplicates != 0 {
|
||||||
|
t.Fatalf("production replan = %d/%d, want 1 moved / 0 retired", prodMoved.Replanned, prodMoved.RetiredDuplicates)
|
||||||
|
}
|
||||||
|
var movedProduction, stillTest string
|
||||||
|
if err := pool.QueryRow(ctx, `SELECT test_kb_id FROM test_publications WHERE id='pub-prod-kbb'`).Scan(&movedProduction); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if movedProduction != "p-new-internal" {
|
||||||
|
t.Fatalf("production pending target = %s, want p-new-internal", movedProduction)
|
||||||
|
}
|
||||||
|
if err := pool.QueryRow(ctx, `SELECT test_kb_id FROM test_publications WHERE id='pub-kbb'`).Scan(&stillTest); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if stillTest != "kb-in" {
|
||||||
|
t.Fatalf("test publication moved by a production save: %s", stillTest)
|
||||||
|
}
|
||||||
var productionInternal, productionURL string
|
var productionInternal, productionURL string
|
||||||
var productionTenant uint64
|
var productionTenant uint64
|
||||||
if err := pool.QueryRow(ctx, `SELECT internal_kb_id, internal_instance_url, internal_tenant_id FROM production_kb_bindings WHERE id='active'`).Scan(&productionInternal, &productionURL, &productionTenant); err != nil {
|
if err := pool.QueryRow(ctx, `SELECT internal_kb_id, internal_instance_url, internal_tenant_id FROM production_kb_bindings WHERE id='active'`).Scan(&productionInternal, &productionURL, &productionTenant); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if productionInternal != "kb-in" || productionURL != server.URL || productionTenant != 10000 {
|
if productionInternal != "p-new-internal" || productionURL != server.URL || productionTenant != 10000 {
|
||||||
t.Fatalf("production binding = %s / %s / %d", productionInternal, productionURL, productionTenant)
|
t.Fatalf("production binding = %s / %s / %d", productionInternal, productionURL, productionTenant)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+49
-16
@@ -8,6 +8,8 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
|
||||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||||
"knowledge-governance/internal/platform/weknora"
|
"knowledge-governance/internal/platform/weknora"
|
||||||
)
|
)
|
||||||
@@ -211,34 +213,58 @@ VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)`,
|
|||||||
}
|
}
|
||||||
replan := postgresstore.RoutingBindingReplanResult{}
|
replan := postgresstore.RoutingBindingReplanResult{}
|
||||||
if env == EnvTest {
|
if env == EnvTest {
|
||||||
|
// 只搬「上一次生效目标」下的待入库:路由行没有值的一侧由部署默认绑定
|
||||||
|
// 补齐(与 effectiveRoutingTargets 同一口径);两边都空就不要猜。
|
||||||
|
previous := postgresstore.EffectiveKBIDs{}
|
||||||
|
rowErr := tx.QueryRow(ctx, `SELECT internal_kb_id,external_kb_id FROM routing_kb_bindings WHERE id='active' FOR UPDATE`).
|
||||||
|
Scan(&previous.Internal, &previous.External)
|
||||||
|
if rowErr != nil && !errors.Is(rowErr, pgx.ErrNoRows) {
|
||||||
|
return View{}, ErrStorage
|
||||||
|
}
|
||||||
|
if (previous.Internal == "" || previous.External == "") && s.options.LegacyBinding != nil {
|
||||||
|
legacyInternal, legacyExternal, legacyErr := s.options.LegacyBinding(ctx, EnvTest)
|
||||||
|
if legacyErr != nil {
|
||||||
|
return View{}, ErrStorage
|
||||||
|
}
|
||||||
|
if previous.Internal == "" {
|
||||||
|
previous.Internal = legacyInternal
|
||||||
|
}
|
||||||
|
if previous.External == "" {
|
||||||
|
previous.External = legacyExternal
|
||||||
|
}
|
||||||
|
}
|
||||||
if err := postgresstore.SaveRoutingKBBindingsTx(ctx, tx, internal, external, actor, now.UTC()); err != nil {
|
if err := postgresstore.SaveRoutingKBBindingsTx(ctx, tx, internal, external, actor, now.UTC()); err != nil {
|
||||||
return View{}, ErrStorage
|
return View{}, ErrStorage
|
||||||
}
|
}
|
||||||
replan, err = postgresstore.ReplanPendingPublicationsTx(ctx, tx, internal, external, now.UTC())
|
replan, err = postgresstore.ReplanPendingPublicationsTx(ctx, tx, previous,
|
||||||
|
postgresstore.EffectiveKBIDs{Internal: internal, External: external}, now.UTC())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return View{}, ErrStorage
|
return View{}, ErrStorage
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// 生产页这里沿用「文档级发布」语义;整库发布目标由部署配置决定,本保存不写它。
|
// 生产页只改「文档级发布」的目标映射;整库发布目标仍由部署配置决定,
|
||||||
// 同时冻结候选实例地址与租户,执行器写入前必须与自己的目标一致。
|
// 本保存不写它。同时冻结候选实例地址与租户,执行器写入前必须与自己的
|
||||||
|
// 目标一致;执行已开始的项目标不会被重排改写。
|
||||||
|
var previous postgresstore.EffectiveKBIDs
|
||||||
|
var priorInternalTenant, priorExternalTenant uint64
|
||||||
|
rowErr := tx.QueryRow(ctx, `
|
||||||
|
SELECT internal_kb_id,external_kb_id,internal_tenant_id,external_tenant_id
|
||||||
|
FROM production_kb_bindings WHERE id='active' FOR UPDATE`).
|
||||||
|
Scan(&previous.Internal, &previous.External, &priorInternalTenant, &priorExternalTenant)
|
||||||
|
if rowErr != nil && !errors.Is(rowErr, pgx.ErrNoRows) {
|
||||||
|
return View{}, ErrStorage
|
||||||
|
}
|
||||||
internalTenant := selected[internal].TenantID
|
internalTenant := selected[internal].TenantID
|
||||||
externalTenant := selected[external].TenantID
|
externalTenant := selected[external].TenantID
|
||||||
if cleared {
|
if cleared {
|
||||||
// 同一条「只清密钥」口径:clear 不访问实例,租户不能被写成 0,
|
// 同一条「只清密钥」口径:clear 不访问实例,租户不能被写成 0,
|
||||||
// 否则执行器的实例一致性检查会把「只是没密钥」误判成「换了实例」。
|
// 否则执行器的实例一致性检查会把「只是没密钥」误判成换了实例。
|
||||||
// 仍然只在 ID 未变时沿用。
|
// 仍然只在 ID 未变时沿用。
|
||||||
var priorInternalID, priorExternalID string
|
if internal == previous.Internal {
|
||||||
var priorInternalTenant, priorExternalTenant uint64
|
internalTenant = priorInternalTenant
|
||||||
if priorErr := tx.QueryRow(ctx, `
|
}
|
||||||
SELECT internal_kb_id,external_kb_id,internal_tenant_id,external_tenant_id
|
if external == previous.External {
|
||||||
FROM production_kb_bindings WHERE id='active'`).
|
externalTenant = priorExternalTenant
|
||||||
Scan(&priorInternalID, &priorExternalID, &priorInternalTenant, &priorExternalTenant); priorErr == nil {
|
|
||||||
if internal == priorInternalID {
|
|
||||||
internalTenant = priorInternalTenant
|
|
||||||
}
|
|
||||||
if external == priorExternalID {
|
|
||||||
externalTenant = priorExternalTenant
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if err := postgresstore.SaveProductionKBBindingsWithIdentityTx(ctx, tx,
|
if err := postgresstore.SaveProductionKBBindingsWithIdentityTx(ctx, tx,
|
||||||
@@ -246,6 +272,13 @@ FROM production_kb_bindings WHERE id='active'`).
|
|||||||
internalTenant, externalTenant, actor, now.UTC()); err != nil {
|
internalTenant, externalTenant, actor, now.UTC()); err != nil {
|
||||||
return View{}, ErrStorage
|
return View{}, ErrStorage
|
||||||
}
|
}
|
||||||
|
// 生产页保存也要让「还没上传、原本瞄准旧生产库」的待入库项改指向新库;
|
||||||
|
// 只在国内/国外旧目标存在时搬,空的一侧是「同 ID 语义」,不能猜。
|
||||||
|
replan, err = postgresstore.ReplanPendingPublicationsTx(ctx, tx, previous,
|
||||||
|
postgresstore.EffectiveKBIDs{Internal: internal, External: external}, now.UTC())
|
||||||
|
if err != nil {
|
||||||
|
return View{}, ErrStorage
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if err := tx.Commit(ctx); err != nil {
|
if err := tx.Commit(ctx); err != nil {
|
||||||
return View{}, ErrStorage
|
return View{}, ErrStorage
|
||||||
|
|||||||
@@ -60,14 +60,33 @@ ON CONFLICT(id) DO UPDATE SET
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// replanRetireDuplicatesSQL retires a pending publication whose twin for the
|
// EffectiveKBIDs is the pair of knowledge base ids consumers actually route to:
|
||||||
// new knowledge base already exists — the unique key is
|
// the UI binding where it is set, the deployment default otherwise. A save must
|
||||||
// (source_item_version_id, test_kb_id), so the row cannot simply be moved.
|
// name both the pair it replaces and the pair it establishes, so re-planning
|
||||||
|
// only moves work that was aimed at THIS environment's previous target.
|
||||||
|
type EffectiveKBIDs struct {
|
||||||
|
Internal string
|
||||||
|
External string
|
||||||
|
}
|
||||||
|
|
||||||
|
// RoutingBindingSave is one binding change: the ids to persist plus the
|
||||||
|
// effective routing before and after it.
|
||||||
|
type RoutingBindingSave struct {
|
||||||
|
InternalID string
|
||||||
|
ExternalID string
|
||||||
|
Previous EffectiveKBIDs
|
||||||
|
Effective EffectiveKBIDs
|
||||||
|
UpdatedBy string
|
||||||
|
}
|
||||||
|
|
||||||
|
// replanRetireDuplicatesSQL retires a pending publication aimed at the previous
|
||||||
|
// target 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.
|
||||||
const replanRetireDuplicatesSQL = `
|
const replanRetireDuplicatesSQL = `
|
||||||
UPDATE test_publications stale
|
UPDATE test_publications stale
|
||||||
SET superseded_at = $3, updated_at = $3
|
SET superseded_at = $4, updated_at = $4
|
||||||
WHERE stale.superseded_at IS NULL
|
WHERE stale.superseded_at IS NULL
|
||||||
AND stale.test_kb_id <> $1
|
AND stale.test_kb_id = $1
|
||||||
AND stale.processing_state = 'planned'
|
AND stale.processing_state = 'planned'
|
||||||
AND stale.ingest_state = 'pending'
|
AND stale.ingest_state = 'pending'
|
||||||
AND stale.knowledge_id = ''
|
AND stale.knowledge_id = ''
|
||||||
@@ -77,7 +96,7 @@ WHERE stale.superseded_at IS NULL
|
|||||||
AND EXISTS (
|
AND EXISTS (
|
||||||
SELECT 1 FROM test_publications twin
|
SELECT 1 FROM test_publications twin
|
||||||
WHERE twin.source_item_version_id = stale.source_item_version_id
|
WHERE twin.source_item_version_id = stale.source_item_version_id
|
||||||
AND twin.test_kb_id = $1
|
AND twin.test_kb_id = $3
|
||||||
AND twin.superseded_at IS NULL)
|
AND twin.superseded_at IS NULL)
|
||||||
`
|
`
|
||||||
|
|
||||||
@@ -86,9 +105,9 @@ WHERE stale.superseded_at IS NULL
|
|||||||
// already in flight keeps its frozen target and stays visible in 待入库.
|
// already in flight keeps its frozen target and stays visible in 待入库.
|
||||||
const replanMovePendingSQL = `
|
const replanMovePendingSQL = `
|
||||||
UPDATE test_publications pending
|
UPDATE test_publications pending
|
||||||
SET test_kb_id = $1, test_instance_url = '', test_instance_tenant = 0, updated_at = $3
|
SET test_kb_id = $3, test_instance_url = '', test_instance_tenant = 0, updated_at = $4
|
||||||
WHERE pending.superseded_at IS NULL
|
WHERE pending.superseded_at IS NULL
|
||||||
AND pending.test_kb_id <> $1
|
AND pending.test_kb_id = $1
|
||||||
AND pending.processing_state = 'planned'
|
AND pending.processing_state = 'planned'
|
||||||
AND pending.ingest_state = 'pending'
|
AND pending.ingest_state = 'pending'
|
||||||
AND pending.knowledge_id = ''
|
AND pending.knowledge_id = ''
|
||||||
@@ -98,20 +117,20 @@ WHERE pending.superseded_at IS NULL
|
|||||||
AND NOT EXISTS (
|
AND NOT EXISTS (
|
||||||
SELECT 1 FROM test_publications twin
|
SELECT 1 FROM test_publications twin
|
||||||
WHERE twin.source_item_version_id = pending.source_item_version_id
|
WHERE twin.source_item_version_id = pending.source_item_version_id
|
||||||
AND twin.test_kb_id = $1
|
AND twin.test_kb_id = $3
|
||||||
AND twin.superseded_at IS NULL)
|
AND twin.superseded_at IS NULL)
|
||||||
`
|
`
|
||||||
|
|
||||||
// SaveRoutingKBBindingsWithReplan saves the binding and, in the SAME
|
// SaveRoutingKBBindingsWithReplan saves the test-side binding and, in the SAME
|
||||||
// transaction, re-points 待入库 items that were still waiting for the old
|
// transaction, re-points 待入库 items that were still waiting for the previous
|
||||||
// knowledge base. Without this, changing the binding left every pending
|
// knowledge base. Without this, changing the binding left every pending
|
||||||
// publication aimed at the previous (possibly deleted) KB, and re-marking the
|
// publication aimed at the previous (possibly deleted) KB, and re-marking the
|
||||||
// file created a SECOND publication instead of moving the first.
|
// file created a SECOND publication instead of moving the first.
|
||||||
//
|
//
|
||||||
// effectiveInternal/effectiveExternal are the ids the platform actually routes
|
// save.Previous is the effective pair before the change (stored binding, or the
|
||||||
// to (the saved binding, or the deployment default when a side is unbound);
|
// deployment default where a side was unbound); an empty or unchanged side is
|
||||||
// an empty effective id means that scope cannot be routed and is skipped.
|
// not guessed at.
|
||||||
func (s *Store) SaveRoutingKBBindingsWithReplan(ctx context.Context, internalID, externalID, effectiveInternal, effectiveExternal, updatedBy string, now time.Time) (RoutingBindingReplanResult, error) {
|
func (s *Store) SaveRoutingKBBindingsWithReplan(ctx context.Context, save RoutingBindingSave, now time.Time) (RoutingBindingReplanResult, error) {
|
||||||
var result RoutingBindingReplanResult
|
var result RoutingBindingReplanResult
|
||||||
if now.IsZero() {
|
if now.IsZero() {
|
||||||
return result, errors.New("binding replan requires a timestamp")
|
return result, errors.New("binding replan requires a timestamp")
|
||||||
@@ -121,10 +140,10 @@ func (s *Store) SaveRoutingKBBindingsWithReplan(ctx context.Context, internalID,
|
|||||||
return result, fmt.Errorf("begin routing binding save: %w", err)
|
return result, fmt.Errorf("begin routing binding save: %w", err)
|
||||||
}
|
}
|
||||||
defer func() { _ = tx.Rollback(ctx) }()
|
defer func() { _ = tx.Rollback(ctx) }()
|
||||||
if err := SaveRoutingKBBindingsTx(ctx, tx, internalID, externalID, updatedBy, now); err != nil {
|
if err := SaveRoutingKBBindingsTx(ctx, tx, save.InternalID, save.ExternalID, save.UpdatedBy, now); err != nil {
|
||||||
return result, err
|
return result, err
|
||||||
}
|
}
|
||||||
result, err = ReplanPendingPublicationsTx(ctx, tx, effectiveInternal, effectiveExternal, now)
|
result, err = ReplanPendingPublicationsTx(ctx, tx, save.Previous, save.Effective, now)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return RoutingBindingReplanResult{}, err
|
return RoutingBindingReplanResult{}, err
|
||||||
}
|
}
|
||||||
@@ -150,23 +169,27 @@ ON CONFLICT(id) DO UPDATE SET
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReplanPendingPublicationsTx re-points untouched 待入库 rows at the new targets
|
// ReplanPendingPublicationsTx re-points untouched 待入库 rows from the previous
|
||||||
// inside the caller's transaction. It only moves rows that were never uploaded
|
// effective targets to the new ones inside the caller's transaction. It only
|
||||||
// anywhere; anything already in flight keeps its frozen target.
|
// moves rows that were never uploaded anywhere AND were aimed at the previous
|
||||||
func ReplanPendingPublicationsTx(ctx context.Context, tx pgx.Tx, effectiveInternal, effectiveExternal string, now time.Time) (RoutingBindingReplanResult, error) {
|
// target: that target check is what keeps one environment's save from carrying
|
||||||
|
// off pending work belonging to the other environment (both envs share the
|
||||||
|
// test_publications lane until an item is executed). Anything already in flight
|
||||||
|
// keeps its frozen target.
|
||||||
|
func ReplanPendingPublicationsTx(ctx context.Context, tx pgx.Tx, previous, effective EffectiveKBIDs, now time.Time) (RoutingBindingReplanResult, error) {
|
||||||
var result RoutingBindingReplanResult
|
var result RoutingBindingReplanResult
|
||||||
for _, scope := range []struct{ name, kbID string }{
|
for _, scope := range []struct{ name, from, to string }{
|
||||||
{"internal", effectiveInternal},
|
{"internal", previous.Internal, effective.Internal},
|
||||||
{"external", effectiveExternal},
|
{"external", previous.External, effective.External},
|
||||||
} {
|
} {
|
||||||
if scope.kbID == "" {
|
if scope.from == "" || scope.to == "" || scope.from == scope.to {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
retired, err := tx.Exec(ctx, replanRetireDuplicatesSQL, scope.kbID, scope.name, now)
|
retired, err := tx.Exec(ctx, replanRetireDuplicatesSQL, scope.from, scope.name, scope.to, now)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return result, fmt.Errorf("retire duplicate pending publications: %w", err)
|
return result, fmt.Errorf("retire duplicate pending publications: %w", err)
|
||||||
}
|
}
|
||||||
moved, err := tx.Exec(ctx, replanMovePendingSQL, scope.kbID, scope.name, now)
|
moved, err := tx.Exec(ctx, replanMovePendingSQL, scope.from, scope.name, scope.to, now)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return result, fmt.Errorf("replan pending publications: %w", err)
|
return result, fmt.Errorf("replan pending publications: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,16 +33,19 @@ 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-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-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-sent','conn-replan','n-sent',repeat('b',64),'docs/sent.docx','sent.docx','document','locator:r3','internal','configured_scope'),
|
||||||
|
('item-prod','conn-replan','n-prod',repeat('b',64),'docs/prod.docx','prod.docx','document','locator:r5','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');
|
||||||
INSERT INTO source_item_versions(id,source_item_id,revision,content_object_id,content_state) VALUES
|
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-in','item-in','locator:r1',NULL,'unknown'),
|
||||||
('v-ext','item-ext','locator:r2',NULL,'unknown'),
|
('v-ext','item-ext','locator:r2',NULL,'unknown'),
|
||||||
('v-sent','item-sent','locator:r3',NULL,'unknown'),
|
('v-sent','item-sent','locator:r3',NULL,'unknown'),
|
||||||
|
('v-prod','item-prod','locator:r5',NULL,'unknown'),
|
||||||
('v-dup','item-dup','locator:r4',NULL,'unknown');
|
('v-dup','item-dup','locator:r4',NULL,'unknown');
|
||||||
INSERT INTO test_publications(id,source_item_version_id,test_kb_id,processing_state,ingest_state,target_scope) VALUES
|
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-in','v-in','kb-old-internal','planned','pending','internal'),
|
||||||
('pub-ext','v-ext','kb-old-external','planned','pending','external'),
|
('pub-ext','v-ext','kb-old-external','planned','pending','external'),
|
||||||
('pub-sent','v-sent','kb-old-internal','pending','uploaded','internal'),
|
('pub-sent','v-sent','kb-old-internal','pending','uploaded','internal'),
|
||||||
|
('pub-prod','v-prod','p-internal','planned','pending','internal'),
|
||||||
('pub-dup-old','v-dup','kb-old-internal','planned','pending','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');
|
||||||
INSERT INTO jobs(id,type,payload,state,idempotency_key) VALUES
|
INSERT INTO jobs(id,type,payload,state,idempotency_key) VALUES
|
||||||
@@ -53,12 +56,19 @@ INSERT INTO jobs(id,type,payload,state,idempotency_key) VALUES
|
|||||||
store := NewStore(pool)
|
store := NewStore(pool)
|
||||||
now := time.Date(2026, time.October, 8, 7, 0, 0, 0, time.UTC)
|
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",
|
||||||
|
Previous: EffectiveKBIDs{Internal: "kb-old-internal", External: "kb-old-external"},
|
||||||
|
Effective: EffectiveKBIDs{Internal: "kb-new-internal", External: "kb-new-external"},
|
||||||
|
UpdatedBy: "tester",
|
||||||
|
}, now)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("SaveRoutingKBBindingsWithReplan() error = %v", err)
|
t.Fatalf("SaveRoutingKBBindingsWithReplan() error = %v", err)
|
||||||
}
|
}
|
||||||
// pub-in and pub-ext move; pub-sent already has an upload job (untouched);
|
// pub-in and pub-ext move; pub-sent already has an upload job (untouched);
|
||||||
// pub-dup-old already has a twin for the new KB so it is retired instead.
|
// pub-dup-old already has a twin for the new KB so it is retired instead;
|
||||||
|
// pub-prod aims at the production binding and must not be carried off by a
|
||||||
|
// test-side save.
|
||||||
if result.Replanned != 2 || result.RetiredDuplicates != 1 {
|
if result.Replanned != 2 || result.RetiredDuplicates != 1 {
|
||||||
t.Fatalf("replan result = %#v, want 2 moved / 1 retired", result)
|
t.Fatalf("replan result = %#v, want 2 moved / 1 retired", result)
|
||||||
}
|
}
|
||||||
@@ -95,9 +105,17 @@ INSERT INTO jobs(id,type,payload,state,idempotency_key) VALUES
|
|||||||
if states["pub-dup-old"].kb != "kb-old-internal" || !states["pub-dup-old"].superseded {
|
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"])
|
t.Fatalf("the duplicate stale row must be retired: %#v", states["pub-dup-old"])
|
||||||
}
|
}
|
||||||
|
if states["pub-prod"].kb != "p-internal" || states["pub-prod"].superseded {
|
||||||
|
t.Fatalf("a pending item aimed at another environment's target must stay put: %#v", states["pub-prod"])
|
||||||
|
}
|
||||||
|
|
||||||
// Re-saving the same binding is a no-op: nothing left to move or retire.
|
// 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",
|
||||||
|
Previous: EffectiveKBIDs{Internal: "kb-new-internal", External: "kb-new-external"},
|
||||||
|
Effective: EffectiveKBIDs{Internal: "kb-new-internal", External: "kb-new-external"},
|
||||||
|
UpdatedBy: "tester",
|
||||||
|
}, now)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user