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

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

验证:make verify(含隔离 PostgreSQL 集成用例)15/15 通过
This commit is contained in:
狐友 GXXP & LEN
2026-11-23 12:47:22 +08:00
committed by 姚章浩
parent 8b900a9ffb
commit aac8538372
19 changed files with 633 additions and 140 deletions
+124 -55
View File
@@ -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)