package postgres import ( "context" "errors" "fmt" "time" "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 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) { binding, _, err := s.loadRoutingKBBinding(ctx) if err != nil { 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 { // Replanned counts untouched pending publications that were re-pointed at // the newly bound knowledge base for their scope. Replanned int // RetiredDuplicates counts pending publications that already had a twin for // the new knowledge base, so the stale row was superseded instead of moved. RetiredDuplicates int } // 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 = $4, updated_at = $4 WHERE stale.superseded_at IS NULL AND stale.test_kb_id = $3 AND stale.processing_state = 'planned' AND stale.ingest_state = 'pending' AND stale.knowledge_id = '' AND stale.retrieval_state = 'unpublished' AND stale.target_scope = $2 AND NOT EXISTS (SELECT 1 FROM jobs job WHERE job.type = 'test.upload' AND job.payload->>'publication_id' = stale.id) AND EXISTS ( SELECT 1 FROM test_publications twin WHERE twin.source_item_version_id = stale.source_item_version_id AND twin.test_kb_id = $1 AND twin.superseded_at IS NULL) ` // replanMovePendingSQL re-points the untouched remainder at the new knowledge // base. Only rows that have never been uploaded anywhere are eligible: anything // already in flight keeps its frozen target and stays visible in 待入库. const replanMovePendingSQL = ` UPDATE test_publications pending SET test_kb_id = $1, updated_at = $4 WHERE pending.superseded_at IS NULL AND pending.test_kb_id = $3 AND pending.processing_state = 'planned' AND pending.ingest_state = 'pending' AND pending.knowledge_id = '' AND pending.retrieval_state = 'unpublished' AND pending.target_scope = $2 AND NOT EXISTS (SELECT 1 FROM jobs job WHERE job.type = 'test.upload' AND job.payload->>'publication_id' = pending.id) AND NOT EXISTS ( SELECT 1 FROM test_publications twin WHERE twin.source_item_version_id = pending.source_item_version_id AND twin.test_kb_id = $1 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. // // 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") } tx, err := s.db.Begin(ctx) if err != nil { 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,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`, save.InternalID, save.ExternalID, internalName, externalName, save.UpdatedBy, now); err != nil { return result, errors.New("save routing kb bindings") } 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) } return result, nil }