fe7edea1a3
build / build (push) Successful in 2m18s
enqueueRun 用 "job-" + run_id 当 jobs.id,而 jobs.id 是 VARCHAR(36);run_id 本身 已是 36 字符(rec- + 32 位 hex),拼出 40 字符,INSERT 必然失败,批次在 claim 之后 立刻被记成 failed/queue_unavailable——候选库里 19:37 起所有批次都是这个状态,C-101 起的用例全部无法开始。 改为 job 自带 "job-"+32 位 hex 的 id(36 字符),幂等仍由唯一 idempotency_key (reconciliation-run:<run_id>)保证。补单测:CreateRun 入队请求 id 必须正好 36 字符、 type/idempotency_key/payload 与 run 一致。 验证:go test ./internal/reconciliation/ 通过;make verify 17 项 = 16 success + identity skipped。
460 lines
16 KiB
Go
460 lines
16 KiB
Go
package reconciliation
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"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")
|
|
)
|
|
|
|
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 {
|
|
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 weknora.StatusCode(err) == 404:
|
|
return governance.ReconciliationProgress{}, ErrNotFound
|
|
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
|
|
}
|