bceb7ba682
台账里会残留已被删除的测试库(test_publications.test_kb_id 聚合出下拉候选), 页面默认又取排序最靠前的一项,于是「立即对账」打在死库上,远端回 404 被统一 映射成 remote_unavailable,页面提示「检查地址与 Key」——把工程师引去改一个根本 没坏的配置。 - 后端:BeginTask 的 404 单独落 remote_kb_missing,其余仍为 remote_unavailable - 前端:新增文案「所选测试知识库已不存在」;默认选中当前绑定的测试库并在下拉里 标注(当前绑定),用户自己选过(含「全部测试库」)后不再改写
499 lines
18 KiB
Go
499 lines
18 KiB
Go
package reconciliation
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
"time"
|
|
|
|
"knowledge-governance/internal/governance"
|
|
"knowledge-governance/internal/jobs"
|
|
postgresstore "knowledge-governance/internal/platform/postgres"
|
|
"knowledge-governance/internal/platform/weknora"
|
|
)
|
|
|
|
var (
|
|
ErrRunInProgress = errors.New("reconciliation run in progress")
|
|
ErrNotFound = errors.New("reconciliation record not found")
|
|
ErrActionConflict = errors.New("reconciliation state or identity changed")
|
|
ErrActionNotAllowed = errors.New("reconciliation action not allowed")
|
|
ErrRemoteFailed = errors.New("reconciliation remote call failed")
|
|
ErrRuntimeUnavailable = errors.New("weknora runtime read unavailable")
|
|
// ErrRuntimeForbidden / ErrRuntimeUnreachable 把「Key 无权限」与「连不上」
|
|
// 从 ErrRuntimeUnavailable 里拆出来:页面要给两种不同的中文,不能再折叠。
|
|
ErrRuntimeForbidden = errors.New("weknora runtime key forbidden")
|
|
ErrRuntimeUnreachable = errors.New("weknora runtime read unreachable")
|
|
)
|
|
|
|
// RuntimeErrorCode is the stable code the browser branches on. Unclassified
|
|
// failures return "" so callers keep their generic fallback instead of guessing.
|
|
func RuntimeErrorCode(err error) string {
|
|
switch {
|
|
case errors.Is(err, ErrRuntimeForbidden):
|
|
return "runtime_key_forbidden"
|
|
case errors.Is(err, ErrRuntimeUnreachable):
|
|
return "runtime_unreachable"
|
|
case errors.Is(err, ErrRuntimeUnavailable):
|
|
return "runtime_read_unavailable"
|
|
default:
|
|
return ""
|
|
}
|
|
}
|
|
|
|
// knowledgeBaseMissing 只认 WeKnora 明确回答的 404 —— 库被删掉、或 ID 属于
|
|
// 别的环境/租户。它与网络不通、Key 无权限要分开:这三种情况的处置完全不同,
|
|
// 页面把 404 说成「检查地址与 Key」会让工程师去改一个根本没坏的配置。
|
|
func knowledgeBaseMissing(err error) bool {
|
|
var httpErr *weknora.HTTPError
|
|
return errors.As(err, &httpErr) && httpErr.StatusCode == http.StatusNotFound
|
|
}
|
|
|
|
type Store interface {
|
|
ReapStaleReconciliationRuns(context.Context, time.Time, time.Duration) (int64, error)
|
|
ClaimReconciliationRun(context.Context, governance.ReconciliationRun, time.Time) (governance.ReconciliationRun, error)
|
|
ClaimScheduledReconciliationRun(context.Context, governance.ReconciliationRun, time.Time, time.Time) (governance.ReconciliationRun, bool, error)
|
|
LoadReconciliationRun(context.Context, string) (governance.ReconciliationRun, error)
|
|
ListReconciliationRuns(context.Context, governance.ReconciliationRunFilter) (governance.ReconciliationRunPage, error)
|
|
ListReconciliationFindings(context.Context, governance.ReconciliationFindingFilter) (governance.ReconciliationFindingPage, error)
|
|
GetReconciliationFinding(context.Context, string) (governance.ReconciliationFinding, error)
|
|
LoadReconciliationLedger(context.Context, string) ([]governance.ReconciliationLedgerRow, error)
|
|
LoadPreviousReconciliationCounts(context.Context, string, time.Time) (governance.ReconciliationCounts, bool, error)
|
|
CompleteReconciliationRun(context.Context, governance.ReconciliationRun, []governance.ReconciliationFinding) error
|
|
FailReconciliationRun(context.Context, string, string, time.Time) error
|
|
CleanupReconciliationFindings(context.Context, time.Time, int, time.Duration) error
|
|
LibraryJobsActive(context.Context) (bool, error)
|
|
ListReconciliationRemovalCandidates(context.Context, string) ([]governance.ReconciliationLedgerRow, error)
|
|
LoadReconciliationActionView(context.Context, string) (governance.ReconciliationActionView, error)
|
|
ReconciliationOrphanStillUnowned(context.Context, string, string) (bool, error)
|
|
WritebackReconciliationFinding(context.Context, string, string, string, string, time.Time) (governance.ReconciliationFinding, error)
|
|
RequeueReconciliationPublication(context.Context, string, string, string, string, time.Time) (string, error)
|
|
MarkReconciliationOrphanRemoved(context.Context, string, string, string, time.Time) error
|
|
}
|
|
|
|
type Remote interface {
|
|
BeginTask(context.Context, string) (context.Context, weknora.InstanceIdentity, error)
|
|
ListKnowledge(context.Context, string, int, int) ([]weknora.Knowledge, int64, error)
|
|
GetKnowledge(context.Context, string) (weknora.Knowledge, error)
|
|
DeleteKnowledge(context.Context, string) error
|
|
}
|
|
|
|
type Runtime interface {
|
|
DocumentProgress(context.Context, string) (governance.ReconciliationProgress, error)
|
|
}
|
|
|
|
type Queue interface {
|
|
Enqueue(context.Context, jobs.EnqueueRequest, time.Time) (*jobs.Job, error)
|
|
}
|
|
|
|
type Config struct {
|
|
Store Store
|
|
Remote Remote
|
|
Runtime Runtime
|
|
Queue Queue
|
|
Now func() time.Time
|
|
Grace time.Duration
|
|
StallAfter time.Duration
|
|
StaleAfter time.Duration
|
|
ConfirmConcurrency int
|
|
KeepRuns int
|
|
MaxAge time.Duration
|
|
// WeKnoraWebBase resolves the WeKnora origin used to build the finding's
|
|
// jump link. Empty or nil leaves weknora_url empty, which the contract allows.
|
|
WeKnoraWebBase func(context.Context) string
|
|
}
|
|
|
|
type Service struct {
|
|
store Store
|
|
remote Remote
|
|
runtime Runtime
|
|
queue Queue
|
|
now func() time.Time
|
|
grace time.Duration
|
|
stallAfter time.Duration
|
|
staleAfter time.Duration
|
|
confirmConcurrency int
|
|
keepRuns int
|
|
maxAge time.Duration
|
|
weKnoraWebBase func(context.Context) string
|
|
}
|
|
|
|
func New(config Config) (*Service, error) {
|
|
if config.Store == nil || config.Remote == nil {
|
|
return nil, errors.New("reconciliation store and remote client are required")
|
|
}
|
|
if config.Now == nil {
|
|
config.Now = time.Now
|
|
}
|
|
if config.Grace <= 0 {
|
|
config.Grace = 30 * time.Minute
|
|
}
|
|
if config.StallAfter <= 0 {
|
|
config.StallAfter = 2 * time.Hour
|
|
}
|
|
if config.StaleAfter <= 0 {
|
|
config.StaleAfter = 6 * time.Hour
|
|
}
|
|
if config.ConfirmConcurrency < 1 {
|
|
config.ConfirmConcurrency = 1
|
|
}
|
|
if config.ConfirmConcurrency > 8 {
|
|
config.ConfirmConcurrency = 8
|
|
}
|
|
if config.KeepRuns < 1 {
|
|
config.KeepRuns = 30
|
|
}
|
|
if config.MaxAge <= 0 {
|
|
config.MaxAge = 90 * 24 * time.Hour
|
|
}
|
|
return &Service{
|
|
store: config.Store, remote: config.Remote, runtime: config.Runtime, queue: config.Queue,
|
|
now: config.Now, grace: config.Grace, stallAfter: config.StallAfter, staleAfter: config.StaleAfter,
|
|
confirmConcurrency: config.ConfirmConcurrency, keepRuns: config.KeepRuns, maxAge: config.MaxAge,
|
|
weKnoraWebBase: config.WeKnoraWebBase,
|
|
}, nil
|
|
}
|
|
|
|
func newID(prefix string) (string, error) {
|
|
var value [16]byte
|
|
if _, err := rand.Read(value[:]); err != nil {
|
|
return "", err
|
|
}
|
|
return prefix + hex.EncodeToString(value[:]), nil
|
|
}
|
|
|
|
func (s *Service) CreateRun(ctx context.Context, kbID, trigger string) (governance.ReconciliationRun, error) {
|
|
if kbID == "" || len(kbID) > 255 {
|
|
return governance.ReconciliationRun{}, errors.New("invalid test knowledge base")
|
|
}
|
|
now := s.now().UTC()
|
|
if _, err := s.store.ReapStaleReconciliationRuns(ctx, now, s.staleAfter); err != nil {
|
|
return governance.ReconciliationRun{}, err
|
|
}
|
|
id, err := newID("rec-")
|
|
if err != nil {
|
|
return governance.ReconciliationRun{}, err
|
|
}
|
|
run, err := s.store.ClaimReconciliationRun(ctx, governance.ReconciliationRun{
|
|
ID: id, KBID: kbID, State: "running", Trigger: trigger, StartedAt: now,
|
|
Counts: governance.ReconciliationCounts{},
|
|
}, now)
|
|
if err != nil {
|
|
if errors.Is(err, postgresstore.ErrReconciliationRunInProgress) {
|
|
return governance.ReconciliationRun{}, ErrRunInProgress
|
|
}
|
|
return governance.ReconciliationRun{}, err
|
|
}
|
|
if s.queue == nil {
|
|
_ = s.store.FailReconciliationRun(ctx, id, "queue_unavailable", now)
|
|
return governance.ReconciliationRun{}, errors.New("reconciliation queue is not configured")
|
|
}
|
|
if err := s.enqueueRun(ctx, run.ID, now); err != nil {
|
|
_ = s.store.FailReconciliationRun(ctx, run.ID, "queue_unavailable", now)
|
|
return governance.ReconciliationRun{}, err
|
|
}
|
|
return run, nil
|
|
}
|
|
|
|
// ScheduleDue claims one scheduled batch per test KB per local day. The caller
|
|
// computes `since` as today's configured wall-clock instant in the configured
|
|
// timezone; this method only enforces the claim and enqueue.
|
|
func (s *Service) ScheduleDue(ctx context.Context, kbIDs []string, since, now time.Time) (int, error) {
|
|
if _, err := s.store.ReapStaleReconciliationRuns(ctx, now, s.staleAfter); err != nil {
|
|
return 0, err
|
|
}
|
|
created := 0
|
|
seen := map[string]bool{}
|
|
for _, kbID := range kbIDs {
|
|
if kbID == "" || seen[kbID] {
|
|
continue
|
|
}
|
|
seen[kbID] = true
|
|
id, err := newID("rec-")
|
|
if err != nil {
|
|
return created, err
|
|
}
|
|
run, claimed, err := s.store.ClaimScheduledReconciliationRun(ctx, governance.ReconciliationRun{
|
|
ID: id, KBID: kbID, State: "running", Trigger: "schedule", StartedAt: now,
|
|
Counts: governance.ReconciliationCounts{},
|
|
}, since, now)
|
|
if err != nil {
|
|
return created, err
|
|
}
|
|
if !claimed {
|
|
continue
|
|
}
|
|
if err := s.enqueueRun(ctx, run.ID, now); err != nil {
|
|
_ = s.store.FailReconciliationRun(ctx, run.ID, "queue_unavailable", now)
|
|
return created, err
|
|
}
|
|
created++
|
|
}
|
|
return created, nil
|
|
}
|
|
|
|
func (s *Service) enqueueRun(ctx context.Context, runID string, now time.Time) error {
|
|
if s.queue == nil {
|
|
return errors.New("reconciliation queue is not configured")
|
|
}
|
|
payload, err := json.Marshal(map[string]string{"run_id": runID})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
// jobs.id is VARCHAR(36) and the run id alone already fills it ("rec-" + 32 hex),
|
|
// so the job carries its own id; idempotency is guaranteed by the unique
|
|
// idempotency_key below, not by deriving the id from the run.
|
|
jobID, err := newID("job-")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = s.queue.Enqueue(ctx, jobs.EnqueueRequest{
|
|
ID: jobID,
|
|
Type: "reconciliation.run",
|
|
Payload: payload,
|
|
Priority: 5,
|
|
AvailableAt: now,
|
|
MaxAttempts: 1,
|
|
IdempotencyKey: "reconciliation-run:" + runID,
|
|
}, now)
|
|
return err
|
|
}
|
|
|
|
func (s *Service) ExecuteRun(ctx context.Context, runID string) error {
|
|
run, err := s.store.LoadReconciliationRun(ctx, runID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if run.State != "running" {
|
|
return nil
|
|
}
|
|
finished := func(code string) error {
|
|
if code == "" {
|
|
return nil
|
|
}
|
|
return s.store.FailReconciliationRun(context.WithoutCancel(ctx), run.ID, code, s.now().UTC())
|
|
}
|
|
pinned, _, err := s.remote.BeginTask(ctx, run.KBID)
|
|
if err != nil {
|
|
if knowledgeBaseMissing(err) {
|
|
return finished("remote_kb_missing")
|
|
}
|
|
return finished("remote_unavailable")
|
|
}
|
|
ledger, err := s.store.LoadReconciliationLedger(pinned, run.KBID)
|
|
if err != nil {
|
|
return finished("ledger_unavailable")
|
|
}
|
|
overlappedStart, err := s.store.LibraryJobsActive(pinned)
|
|
if err != nil {
|
|
return finished("overlap_check_failed")
|
|
}
|
|
items, err := s.scanKnowledge(pinned, run.KBID)
|
|
if err != nil {
|
|
if errors.Is(err, ErrRemoteFailed) {
|
|
return finished("remote_scan_failed")
|
|
}
|
|
return finished("scan_failed")
|
|
}
|
|
overlappedEnd, err := s.store.LibraryJobsActive(pinned)
|
|
if err != nil {
|
|
return finished("overlap_check_failed")
|
|
}
|
|
overlapped := overlappedStart || overlappedEnd
|
|
findings, err := s.buildFindings(pinned, run, ledger, items, overlapped)
|
|
if err != nil {
|
|
if errors.Is(err, ErrRemoteFailed) {
|
|
return finished("remote_confirm_failed")
|
|
}
|
|
return finished("scan_failed")
|
|
}
|
|
previous, hasPrevious, err := s.store.LoadPreviousReconciliationCounts(pinned, run.KBID, run.StartedAt)
|
|
if err != nil {
|
|
return finished("previous_counts_failed")
|
|
}
|
|
counts := governance.ReconciliationCounts{}
|
|
for _, finding := range findings {
|
|
counts[finding.Type]++
|
|
}
|
|
run.Counts = counts.Normalize()
|
|
if hasPrevious {
|
|
run.PreviousCounts = previous
|
|
}
|
|
run.LedgerCount = len(ledger)
|
|
run.KBCount = len(items)
|
|
run.WindowOverlapped = overlapped
|
|
finishedAt := s.now().UTC()
|
|
run.FinishedAt = &finishedAt
|
|
if err := s.store.CompleteReconciliationRun(pinned, run, findings); err != nil {
|
|
return finished("complete_failed")
|
|
}
|
|
_ = s.store.CleanupReconciliationFindings(context.WithoutCancel(ctx), s.now().UTC(), s.keepRuns, s.maxAge)
|
|
return nil
|
|
}
|
|
|
|
func (s *Service) ListRuns(ctx context.Context, filter governance.ReconciliationRunFilter) (governance.ReconciliationRunPage, error) {
|
|
return s.store.ListReconciliationRuns(ctx, filter)
|
|
}
|
|
|
|
func (s *Service) GetRun(ctx context.Context, id string) (governance.ReconciliationRun, error) {
|
|
run, err := s.store.LoadReconciliationRun(ctx, id)
|
|
if errors.Is(err, postgresstore.ErrReconciliationNotFound) {
|
|
return governance.ReconciliationRun{}, ErrNotFound
|
|
}
|
|
return run, err
|
|
}
|
|
|
|
func (s *Service) ListFindings(ctx context.Context, filter governance.ReconciliationFindingFilter) (governance.ReconciliationFindingPage, error) {
|
|
return s.store.ListReconciliationFindings(ctx, filter)
|
|
}
|
|
|
|
func (s *Service) Progress(ctx context.Context, documentID string) (governance.ReconciliationProgress, error) {
|
|
if s.runtime == nil {
|
|
return governance.ReconciliationProgress{}, ErrRuntimeUnavailable
|
|
}
|
|
progress, err := s.runtime.DocumentProgress(ctx, documentID)
|
|
switch {
|
|
case err == nil:
|
|
return progress, nil
|
|
case errors.Is(err, ErrRuntimeForbidden), errors.Is(err, ErrRuntimeUnreachable), errors.Is(err, ErrRuntimeUnavailable):
|
|
// Provider 已经分好类;这里若再折叠,页面就永远看不到两种不同原因。
|
|
return governance.ReconciliationProgress{}, err
|
|
case weknora.StatusCode(err) == 404:
|
|
return governance.ReconciliationProgress{}, ErrNotFound
|
|
case errors.Is(err, ErrRuntimeUnavailable), errors.Is(err, ErrRuntimeForbidden), errors.Is(err, ErrRuntimeUnreachable):
|
|
// The provider already classified the failure; collapsing it here would
|
|
// erase the distinction between "no binding", "no permission" and
|
|
// "unreachable" that the page needs.
|
|
return governance.ReconciliationProgress{}, err
|
|
default:
|
|
return governance.ReconciliationProgress{}, ErrRuntimeUnavailable
|
|
}
|
|
}
|
|
|
|
func (s *Service) Writeback(ctx context.Context, findingID, actor, reason string) (governance.ReconciliationFinding, error) {
|
|
view, err := s.actionView(ctx, findingID)
|
|
if err != nil {
|
|
return governance.ReconciliationFinding{}, err
|
|
}
|
|
if view.Finding.ActionState == "done" {
|
|
return view.Finding, nil
|
|
}
|
|
target := view.Finding.NormalizedState
|
|
if view.Finding.Type != "R5" || !AllowedWriteback(view.Finding.LedgerState, target) {
|
|
return governance.ReconciliationFinding{}, ErrActionNotAllowed
|
|
}
|
|
finding, err := s.store.WritebackReconciliationFinding(ctx, findingID, target, actor, trim(reason), s.now().UTC())
|
|
if errors.Is(err, postgresstore.ErrReconciliationConflict) {
|
|
return governance.ReconciliationFinding{}, ErrActionConflict
|
|
}
|
|
return finding, err
|
|
}
|
|
|
|
func (s *Service) Requeue(ctx context.Context, findingID, actor, reason string) (governance.ReconciliationFinding, error) {
|
|
view, err := s.actionView(ctx, findingID)
|
|
if err != nil {
|
|
return governance.ReconciliationFinding{}, err
|
|
}
|
|
if view.Finding.ActionState == "done" {
|
|
return view.Finding, nil
|
|
}
|
|
if view.Finding.Type != "R1" && view.Finding.Type != "R4" {
|
|
return governance.ReconciliationFinding{}, ErrActionNotAllowed
|
|
}
|
|
if view.Finding.DocumentID == "" {
|
|
return governance.ReconciliationFinding{}, ErrActionConflict
|
|
}
|
|
item, getErr := s.remote.GetKnowledge(ctx, view.Finding.DocumentID)
|
|
switch {
|
|
case getErr == nil:
|
|
if view.Finding.Type == "R1" {
|
|
// R1 said 404; if it is back now, a human must decide again.
|
|
return governance.ReconciliationFinding{}, ErrActionConflict
|
|
}
|
|
if item.KnowledgeBaseID != view.TestKBID {
|
|
return governance.ReconciliationFinding{}, ErrActionConflict
|
|
}
|
|
// R4 must remove the stale object first. Only a successful delete (or
|
|
// 404, handled below) allows the ledger reset.
|
|
if err := s.remote.DeleteKnowledge(ctx, view.Finding.DocumentID); err != nil && !weknora.IsNotFound(err) {
|
|
return governance.ReconciliationFinding{}, ErrRemoteFailed
|
|
}
|
|
case weknora.IsNotFound(getErr):
|
|
// R1/R4 both proceed: the old object is already gone.
|
|
default:
|
|
return governance.ReconciliationFinding{}, ErrRemoteFailed
|
|
}
|
|
if _, err := s.store.RequeueReconciliationPublication(ctx, findingID, view.Finding.DocumentID, actor, trim(reason), s.now().UTC()); err != nil {
|
|
if errors.Is(err, postgresstore.ErrReconciliationConflict) {
|
|
return governance.ReconciliationFinding{}, ErrActionConflict
|
|
}
|
|
return governance.ReconciliationFinding{}, err
|
|
}
|
|
return s.reloadFinding(ctx, findingID)
|
|
}
|
|
|
|
func (s *Service) Remove(ctx context.Context, findingID, actor, reason string) (governance.ReconciliationFinding, error) {
|
|
view, err := s.actionView(ctx, findingID)
|
|
if err != nil {
|
|
return governance.ReconciliationFinding{}, err
|
|
}
|
|
if view.Finding.ActionState == "done" {
|
|
return view.Finding, nil
|
|
}
|
|
if view.Finding.Type != "R2" || view.Finding.DocumentID == "" {
|
|
return governance.ReconciliationFinding{}, ErrActionNotAllowed
|
|
}
|
|
orphan, err := s.store.ReconciliationOrphanStillUnowned(ctx, view.Finding.PublicationID, view.Finding.DocumentID)
|
|
if err != nil {
|
|
return governance.ReconciliationFinding{}, err
|
|
}
|
|
if !orphan {
|
|
return governance.ReconciliationFinding{}, ErrActionConflict
|
|
}
|
|
item, err := s.remote.GetKnowledge(ctx, view.Finding.DocumentID)
|
|
if err != nil {
|
|
if !weknora.IsNotFound(err) {
|
|
return governance.ReconciliationFinding{}, ErrRemoteFailed
|
|
}
|
|
} else {
|
|
if item.KnowledgeBaseID != view.TestKBID {
|
|
return governance.ReconciliationFinding{}, ErrActionConflict
|
|
}
|
|
if err := s.remote.DeleteKnowledge(ctx, view.Finding.DocumentID); err != nil && !weknora.IsNotFound(err) {
|
|
return governance.ReconciliationFinding{}, ErrRemoteFailed
|
|
}
|
|
}
|
|
if err := s.store.MarkReconciliationOrphanRemoved(ctx, findingID, actor, trim(reason), s.now().UTC()); err != nil {
|
|
if errors.Is(err, postgresstore.ErrReconciliationConflict) {
|
|
return governance.ReconciliationFinding{}, ErrActionConflict
|
|
}
|
|
return governance.ReconciliationFinding{}, err
|
|
}
|
|
return s.reloadFinding(ctx, findingID)
|
|
}
|
|
|
|
func (s *Service) actionView(ctx context.Context, findingID string) (governance.ReconciliationActionView, error) {
|
|
view, err := s.store.LoadReconciliationActionView(ctx, findingID)
|
|
if errors.Is(err, postgresstore.ErrReconciliationNotFound) {
|
|
return view, ErrNotFound
|
|
}
|
|
return view, err
|
|
}
|
|
|
|
func (s *Service) reloadFinding(ctx context.Context, id string) (governance.ReconciliationFinding, error) {
|
|
finding, err := s.store.GetReconciliationFinding(ctx, id)
|
|
if errors.Is(err, postgresstore.ErrReconciliationNotFound) {
|
|
return finding, ErrNotFound
|
|
}
|
|
return finding, err
|
|
}
|
|
|
|
func trim(value string) string {
|
|
if len(value) > 500 {
|
|
return value[:500]
|
|
}
|
|
return value
|
|
}
|