refactor(reconciliation): 存储实现按层命名
为什么:arch-evidence 的分层模式按路径识别存储层;reconciliation.go 被误归到 Handler 层,评审表无法如实反映数据访问改动。 做什么:仅重命名 internal/platform/postgres/reconciliation.go -> reconciliation_store.go,无逻辑变化。 验证:go test ./internal/platform/postgres -run TestReconciliation。
This commit is contained in:
@@ -0,0 +1,601 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrReconciliationRunInProgress = errors.New("reconciliation run already in progress")
|
||||
ErrReconciliationNotFound = errors.New("reconciliation record not found")
|
||||
ErrReconciliationConflict = errors.New("reconciliation state or identity changed")
|
||||
ErrReconciliationNotRunning = errors.New("reconciliation run is not running")
|
||||
)
|
||||
|
||||
const reconciliationRunColumns = `id,test_kb_id,state,trigger,started_at,finished_at,ledger_count,kb_count,counts,previous_counts,window_overlapped,error_code`
|
||||
|
||||
func scanReconciliationRun(row rowScanner) (governance.ReconciliationRun, error) {
|
||||
var run governance.ReconciliationRun
|
||||
var counts, previous []byte
|
||||
if err := row.Scan(&run.ID, &run.KBID, &run.State, &run.Trigger, &run.StartedAt, &run.FinishedAt,
|
||||
&run.LedgerCount, &run.KBCount, &counts, &previous, &run.WindowOverlapped, &run.ErrorCode); err != nil {
|
||||
return governance.ReconciliationRun{}, err
|
||||
}
|
||||
if len(counts) > 0 {
|
||||
if err := json.Unmarshal(counts, &run.Counts); err != nil {
|
||||
return governance.ReconciliationRun{}, fmt.Errorf("decode reconciliation counts: %w", err)
|
||||
}
|
||||
}
|
||||
run.Counts = run.Counts.Normalize()
|
||||
if len(previous) > 0 {
|
||||
var value governance.ReconciliationCounts
|
||||
if err := json.Unmarshal(previous, &value); err != nil {
|
||||
return governance.ReconciliationRun{}, fmt.Errorf("decode previous reconciliation counts: %w", err)
|
||||
}
|
||||
run.PreviousCounts = value.Normalize()
|
||||
}
|
||||
return run, nil
|
||||
}
|
||||
|
||||
// ClaimReconciliationRun inserts a running batch. The partial unique index is
|
||||
// the concurrency authority; a friendly 409 is produced from ErrRunInProgress.
|
||||
func (s *Store) ClaimReconciliationRun(ctx context.Context, run governance.ReconciliationRun, now time.Time) (governance.ReconciliationRun, error) {
|
||||
counts, err := json.Marshal(run.Counts.Normalize())
|
||||
if err != nil {
|
||||
return governance.ReconciliationRun{}, err
|
||||
}
|
||||
row := s.db.QueryRow(ctx, `INSERT INTO reconciliation_runs
|
||||
(id,test_kb_id,state,trigger,started_at,counts,created_at)
|
||||
VALUES($1,$2,'running',$3,$4,$5::jsonb,$6)
|
||||
ON CONFLICT DO NOTHING
|
||||
RETURNING `+reconciliationRunColumns,
|
||||
run.ID, run.KBID, run.Trigger, run.StartedAt, counts, now)
|
||||
claimed, err := scanReconciliationRun(row)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return governance.ReconciliationRun{}, ErrReconciliationRunInProgress
|
||||
}
|
||||
if err != nil {
|
||||
return governance.ReconciliationRun{}, fmt.Errorf("claim reconciliation run: %w", err)
|
||||
}
|
||||
return claimed, nil
|
||||
}
|
||||
|
||||
func (s *Store) ClaimScheduledReconciliationRun(ctx context.Context, run governance.ReconciliationRun, since, now time.Time) (governance.ReconciliationRun, bool, error) {
|
||||
counts, err := json.Marshal(run.Counts.Normalize())
|
||||
if err != nil {
|
||||
return governance.ReconciliationRun{}, false, err
|
||||
}
|
||||
row := s.db.QueryRow(ctx, `INSERT INTO reconciliation_runs
|
||||
(id,test_kb_id,state,trigger,started_at,counts,created_at)
|
||||
SELECT $1,$2,'running','schedule',$3,$4::jsonb,$5
|
||||
WHERE NOT EXISTS(
|
||||
SELECT 1 FROM reconciliation_runs
|
||||
WHERE test_kb_id=$2 AND trigger='schedule' AND state IN ('running','succeeded') AND started_at >= $6
|
||||
)
|
||||
ON CONFLICT DO NOTHING
|
||||
RETURNING `+reconciliationRunColumns,
|
||||
run.ID, run.KBID, run.StartedAt, counts, now, since)
|
||||
claimed, err := scanReconciliationRun(row)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return governance.ReconciliationRun{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return governance.ReconciliationRun{}, false, fmt.Errorf("claim scheduled reconciliation run: %w", err)
|
||||
}
|
||||
return claimed, true, nil
|
||||
}
|
||||
|
||||
func (s *Store) ReapStaleReconciliationRuns(ctx context.Context, now time.Time, threshold time.Duration) (int64, error) {
|
||||
if threshold <= 0 {
|
||||
return 0, nil
|
||||
}
|
||||
tag, err := s.db.Exec(ctx, `UPDATE reconciliation_runs
|
||||
SET state='failed',finished_at=$2,error_code='stale_timeout'
|
||||
WHERE state='running' AND started_at < $3`, now, now.Add(-threshold))
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("reap stale reconciliation runs: %w", err)
|
||||
}
|
||||
return tag.RowsAffected(), nil
|
||||
}
|
||||
|
||||
func (s *Store) LoadReconciliationRun(ctx context.Context, id string) (governance.ReconciliationRun, error) {
|
||||
row := s.db.QueryRow(ctx, `SELECT `+reconciliationRunColumns+` FROM reconciliation_runs WHERE id=$1`, id)
|
||||
run, err := scanReconciliationRun(row)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return governance.ReconciliationRun{}, ErrReconciliationNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return governance.ReconciliationRun{}, fmt.Errorf("load reconciliation run: %w", err)
|
||||
}
|
||||
return run, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListReconciliationRuns(ctx context.Context, filter governance.ReconciliationRunFilter) (governance.ReconciliationRunPage, error) {
|
||||
page := governance.ReconciliationRunPage{Items: []governance.ReconciliationRun{}, Limit: filter.Limit, Offset: filter.Offset}
|
||||
if err := s.db.QueryRow(ctx, `SELECT COUNT(*)::integer FROM reconciliation_runs WHERE ($1='' OR test_kb_id=$1)`, filter.KBID).Scan(&page.Total); err != nil {
|
||||
return page, fmt.Errorf("count reconciliation runs: %w", err)
|
||||
}
|
||||
rows, err := s.db.Query(ctx, `SELECT `+reconciliationRunColumns+`
|
||||
FROM reconciliation_runs WHERE ($1='' OR test_kb_id=$1)
|
||||
ORDER BY started_at DESC,id DESC LIMIT $2 OFFSET $3`, filter.KBID, filter.Limit, filter.Offset)
|
||||
if err != nil {
|
||||
return page, fmt.Errorf("list reconciliation runs: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
run, err := scanReconciliationRun(rows)
|
||||
if err != nil {
|
||||
return page, fmt.Errorf("scan reconciliation run: %w", err)
|
||||
}
|
||||
page.Items = append(page.Items, run)
|
||||
}
|
||||
return page, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) LoadReconciliationLedger(ctx context.Context, kbID string) ([]governance.ReconciliationLedgerRow, error) {
|
||||
rows, err := s.db.Query(ctx, `SELECT publication.id,publication.knowledge_id,publication.processing_state,
|
||||
publication.retrieval_state,publication.target_scope,publication.processing_started_at,
|
||||
publication.updated_at,publication.upload_md5,
|
||||
item.id,item.title,COALESCE(NULLIF(item.normalized_path,''),''),connection.name,
|
||||
item.policy_state,COALESCE(content.sha256,'')
|
||||
FROM test_publications publication
|
||||
JOIN source_item_versions version ON version.id=publication.source_item_version_id
|
||||
JOIN source_items item ON item.id=version.source_item_id
|
||||
JOIN source_connections connection ON connection.id=item.source_connection_id
|
||||
LEFT JOIN content_objects content ON content.id=version.content_object_id
|
||||
WHERE publication.test_kb_id=$1 AND publication.superseded_at IS NULL
|
||||
ORDER BY publication.id`, kbID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load reconciliation ledger: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
out := make([]governance.ReconciliationLedgerRow, 0)
|
||||
for rows.Next() {
|
||||
var row governance.ReconciliationLedgerRow
|
||||
if err := rows.Scan(&row.PublicationID, &row.KnowledgeID, &row.ProcessingState, &row.RetrievalState,
|
||||
&row.TargetScope, &row.ProcessingStartedAt, &row.UpdatedAt, &row.UploadMD5,
|
||||
&row.SourceItemID, &row.Title, &row.Path, &row.SourceName, &row.PolicyState, &row.SHA256); err != nil {
|
||||
return nil, fmt.Errorf("scan reconciliation ledger: %w", err)
|
||||
}
|
||||
out = append(out, row)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) LoadPreviousReconciliationCounts(ctx context.Context, kbID string, before time.Time) (governance.ReconciliationCounts, bool, error) {
|
||||
var raw []byte
|
||||
err := s.db.QueryRow(ctx, `SELECT counts FROM reconciliation_runs
|
||||
WHERE test_kb_id=$1 AND state='succeeded' AND started_at < $2
|
||||
ORDER BY started_at DESC,id DESC LIMIT 1`, kbID, before).Scan(&raw)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("load previous reconciliation counts: %w", err)
|
||||
}
|
||||
var counts governance.ReconciliationCounts
|
||||
if err := json.Unmarshal(raw, &counts); err != nil {
|
||||
return nil, false, fmt.Errorf("decode previous reconciliation counts: %w", err)
|
||||
}
|
||||
return counts.Normalize(), true, nil
|
||||
}
|
||||
|
||||
func (s *Store) CompleteReconciliationRun(ctx context.Context, run governance.ReconciliationRun, findings []governance.ReconciliationFinding) error {
|
||||
beginner, ok := s.db.(interface {
|
||||
Begin(context.Context) (pgx.Tx, error)
|
||||
})
|
||||
if !ok {
|
||||
return errors.New("reconciliation transactions are unavailable")
|
||||
}
|
||||
tx, err := beginner.Begin(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin reconciliation completion: %w", err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
counts, err := json.Marshal(run.Counts.Normalize())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var previous any
|
||||
if run.PreviousCounts != nil {
|
||||
raw, err := json.Marshal(run.PreviousCounts.Normalize())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
previous = raw
|
||||
}
|
||||
tag, err := tx.Exec(ctx, `UPDATE reconciliation_runs
|
||||
SET state='succeeded',finished_at=$2,ledger_count=$3,kb_count=$4,counts=$5::jsonb,
|
||||
previous_counts=$6::jsonb,window_overlapped=$7,error_code=''
|
||||
WHERE id=$1 AND state='running'`, run.ID, run.FinishedAt, run.LedgerCount, run.KBCount, counts, previous, run.WindowOverlapped)
|
||||
if err != nil {
|
||||
return fmt.Errorf("complete reconciliation run: %w", err)
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
return ErrReconciliationNotRunning
|
||||
}
|
||||
for _, finding := range findings {
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO reconciliation_findings
|
||||
(id,run_id,finding_type,publication_id,knowledge_id,title,path,source,target_scope,
|
||||
ledger_state,weknora_parse_status,normalized_state,ledger_sha256,declared_sha256,
|
||||
weknora_file_md5,evidence_level,confirmation_state,detail,suggested_action,action_state,
|
||||
weknora_url,created_at)
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,'open',$20,$21)`,
|
||||
finding.ID, finding.RunID, finding.Type, finding.PublicationID, finding.DocumentID,
|
||||
finding.Title, finding.Path, finding.Source, finding.TargetScope, finding.LedgerState,
|
||||
finding.WeKnoraParseState, finding.NormalizedState, finding.LedgerSHA256, finding.DeclaredSHA256,
|
||||
finding.WeKnoraFileMD5, finding.EvidenceLevel, finding.ConfirmationState, finding.Detail,
|
||||
finding.SuggestedAction, finding.WeKnoraURL, run.FinishedAt); err != nil {
|
||||
return fmt.Errorf("insert reconciliation finding: %w", err)
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("commit reconciliation run: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) FailReconciliationRun(ctx context.Context, runID, code string, finished time.Time) error {
|
||||
_, err := s.db.Exec(ctx, `UPDATE reconciliation_runs
|
||||
SET state='failed',finished_at=$2,error_code=$3
|
||||
WHERE id=$1 AND state='running'`, runID, finished, code)
|
||||
if err != nil {
|
||||
return fmt.Errorf("fail reconciliation run: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) CleanupReconciliationFindings(ctx context.Context, now time.Time, keepRuns int, maxAge time.Duration) error {
|
||||
if keepRuns < 1 || maxAge <= 0 {
|
||||
return nil
|
||||
}
|
||||
_, err := s.db.Exec(ctx, `DELETE FROM reconciliation_findings
|
||||
WHERE run_id IN (
|
||||
SELECT id FROM reconciliation_runs
|
||||
WHERE started_at < $1
|
||||
OR id NOT IN (
|
||||
SELECT id FROM reconciliation_runs ORDER BY started_at DESC,id DESC LIMIT $2
|
||||
)
|
||||
)`, now.Add(-maxAge), keepRuns)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cleanup reconciliation findings: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) LibraryJobsActive(ctx context.Context) (bool, error) {
|
||||
var active bool
|
||||
if err := s.db.QueryRow(ctx, `SELECT EXISTS(
|
||||
SELECT 1 FROM jobs WHERE type LIKE 'library.%' AND state IN ('pending','running','retry')
|
||||
)`).Scan(&active); err != nil {
|
||||
return false, fmt.Errorf("inspect library jobs: %w", err)
|
||||
}
|
||||
return active, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListReconciliationRemovalCandidates(ctx context.Context, kbID string) ([]governance.ReconciliationLedgerRow, error) {
|
||||
rows, err := s.db.Query(ctx, `SELECT publication_id,knowledge_id,target_scope,
|
||||
source_item_version_id,source_item_id,title,normalized_path,source_name
|
||||
FROM removal_candidates WHERE test_kb_id=$1 ORDER BY publication_id`, kbID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list removal candidates: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
out := make([]governance.ReconciliationLedgerRow, 0)
|
||||
for rows.Next() {
|
||||
var row governance.ReconciliationLedgerRow
|
||||
var versionID string
|
||||
if err := rows.Scan(&row.PublicationID, &row.KnowledgeID, &row.TargetScope,
|
||||
&versionID, &row.SourceItemID, &row.Title, &row.Path, &row.SourceName); err != nil {
|
||||
return nil, fmt.Errorf("scan removal candidate: %w", err)
|
||||
}
|
||||
out = append(out, row)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
const reconciliationFindingColumns = `id,run_id,finding_type,publication_id,knowledge_id,title,path,source,
|
||||
target_scope,ledger_state,weknora_parse_status,normalized_state,ledger_sha256,declared_sha256,
|
||||
weknora_file_md5,evidence_level,confirmation_state,detail,suggested_action,action_state,weknora_url`
|
||||
|
||||
func scanReconciliationFinding(row rowScanner) (governance.ReconciliationFinding, error) {
|
||||
var finding governance.ReconciliationFinding
|
||||
if err := row.Scan(&finding.ID, &finding.RunID, &finding.Type, &finding.PublicationID, &finding.DocumentID,
|
||||
&finding.Title, &finding.Path, &finding.Source, &finding.TargetScope, &finding.LedgerState,
|
||||
&finding.WeKnoraParseState, &finding.NormalizedState, &finding.LedgerSHA256, &finding.DeclaredSHA256,
|
||||
&finding.WeKnoraFileMD5, &finding.EvidenceLevel, &finding.ConfirmationState, &finding.Detail,
|
||||
&finding.SuggestedAction, &finding.ActionState, &finding.WeKnoraURL); err != nil {
|
||||
return governance.ReconciliationFinding{}, err
|
||||
}
|
||||
return finding, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListReconciliationFindings(ctx context.Context, filter governance.ReconciliationFindingFilter) (governance.ReconciliationFindingPage, error) {
|
||||
page := governance.ReconciliationFindingPage{Items: []governance.ReconciliationFinding{}, Limit: filter.Limit, Offset: filter.Offset}
|
||||
if err := s.db.QueryRow(ctx, `SELECT COUNT(*)::integer FROM reconciliation_findings
|
||||
WHERE run_id=$1 AND ($2='' OR finding_type=$2)
|
||||
AND ($3='' OR strpos(lower(title || ' ' || path || ' ' || detail),lower($3))>0)`,
|
||||
filter.RunID, filter.Type, filter.Query).Scan(&page.Total); err != nil {
|
||||
return page, fmt.Errorf("count reconciliation findings: %w", err)
|
||||
}
|
||||
rows, err := s.db.Query(ctx, `SELECT `+reconciliationFindingColumns+`
|
||||
FROM reconciliation_findings
|
||||
WHERE run_id=$1 AND ($2='' OR finding_type=$2)
|
||||
AND ($3='' OR strpos(lower(title || ' ' || path || ' ' || detail),lower($3))>0)
|
||||
ORDER BY finding_type,publication_id,knowledge_id,id LIMIT $4 OFFSET $5`,
|
||||
filter.RunID, filter.Type, filter.Query, filter.Limit, filter.Offset)
|
||||
if err != nil {
|
||||
return page, fmt.Errorf("list reconciliation findings: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
finding, err := scanReconciliationFinding(rows)
|
||||
if err != nil {
|
||||
return page, fmt.Errorf("scan reconciliation finding: %w", err)
|
||||
}
|
||||
page.Items = append(page.Items, finding)
|
||||
}
|
||||
return page, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) GetReconciliationFinding(ctx context.Context, id string) (governance.ReconciliationFinding, error) {
|
||||
return getReconciliationFinding(ctx, s.db, id)
|
||||
}
|
||||
|
||||
func getReconciliationFinding(ctx context.Context, queryer interface {
|
||||
QueryRow(context.Context, string, ...any) pgx.Row
|
||||
}, id string) (governance.ReconciliationFinding, error) {
|
||||
row := queryer.QueryRow(ctx, `SELECT `+reconciliationFindingColumns+` FROM reconciliation_findings WHERE id=$1`, id)
|
||||
finding, err := scanReconciliationFinding(row)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return governance.ReconciliationFinding{}, ErrReconciliationNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return governance.ReconciliationFinding{}, fmt.Errorf("load reconciliation finding: %w", err)
|
||||
}
|
||||
return finding, nil
|
||||
}
|
||||
|
||||
func lockOpenReconciliationFinding(ctx context.Context, tx pgx.Tx, id string) error {
|
||||
var state string
|
||||
if err := tx.QueryRow(ctx, `SELECT action_state FROM reconciliation_findings WHERE id=$1 FOR UPDATE`, id).Scan(&state); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return ErrReconciliationNotFound
|
||||
}
|
||||
return fmt.Errorf("lock reconciliation finding: %w", err)
|
||||
}
|
||||
if state != "open" {
|
||||
return ErrReconciliationConflict
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) LoadReconciliationActionView(ctx context.Context, findingID string) (governance.ReconciliationActionView, error) {
|
||||
var view governance.ReconciliationActionView
|
||||
var currentExists bool
|
||||
row := s.db.QueryRow(ctx, `SELECT `+reconciliationFindingColumns+`,
|
||||
run.test_kb_id,run.started_at,
|
||||
publication.id IS NOT NULL,
|
||||
COALESCE(publication.processing_state,''),COALESCE(publication.knowledge_id,''),
|
||||
COALESCE(publication.superseded_at IS NOT NULL,FALSE),COALESCE(publication.retrieval_state,''),
|
||||
COALESCE(publication.target_scope,'')
|
||||
FROM reconciliation_findings finding
|
||||
JOIN reconciliation_runs run ON run.id=finding.run_id
|
||||
LEFT JOIN test_publications publication ON publication.id=finding.publication_id
|
||||
WHERE finding.id=$1`, findingID)
|
||||
if err := row.Scan(&view.Finding.ID, &view.Finding.RunID, &view.Finding.Type, &view.Finding.PublicationID,
|
||||
&view.Finding.DocumentID, &view.Finding.Title, &view.Finding.Path, &view.Finding.Source,
|
||||
&view.Finding.TargetScope, &view.Finding.LedgerState, &view.Finding.WeKnoraParseState,
|
||||
&view.Finding.NormalizedState, &view.Finding.LedgerSHA256, &view.Finding.DeclaredSHA256,
|
||||
&view.Finding.WeKnoraFileMD5, &view.Finding.EvidenceLevel, &view.Finding.ConfirmationState,
|
||||
&view.Finding.Detail, &view.Finding.SuggestedAction, &view.Finding.ActionState, &view.Finding.WeKnoraURL,
|
||||
&view.TestKBID, &view.RunStartedAt, ¤tExists, &view.CurrentProcessingState,
|
||||
&view.CurrentKnowledgeID, &view.CurrentSuperseded, &view.CurrentRetrievalState,
|
||||
&view.CurrentTargetScope); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return view, ErrReconciliationNotFound
|
||||
}
|
||||
return view, fmt.Errorf("load reconciliation action view: %w", err)
|
||||
}
|
||||
view.CurrentExists = currentExists
|
||||
return view, nil
|
||||
}
|
||||
|
||||
func (s *Store) ReconciliationOrphanStillUnowned(ctx context.Context, publicationID, knowledgeID string) (bool, error) {
|
||||
var owned bool
|
||||
if err := s.db.QueryRow(ctx, `SELECT EXISTS(
|
||||
SELECT 1 FROM test_publications
|
||||
WHERE superseded_at IS NULL AND (knowledge_id=$2 OR ($1<>'' AND id=$1))
|
||||
)`, publicationID, knowledgeID).Scan(&owned); err != nil {
|
||||
return false, fmt.Errorf("inspect orphan ownership: %w", err)
|
||||
}
|
||||
return !owned, nil
|
||||
}
|
||||
|
||||
func (s *Store) WritebackReconciliationFinding(ctx context.Context, findingID, targetState, actor, reason string, now time.Time) (governance.ReconciliationFinding, error) {
|
||||
beginner, ok := s.db.(interface {
|
||||
Begin(context.Context) (pgx.Tx, error)
|
||||
})
|
||||
if !ok {
|
||||
return governance.ReconciliationFinding{}, errors.New("reconciliation transactions are unavailable")
|
||||
}
|
||||
tx, err := beginner.Begin(ctx)
|
||||
if err != nil {
|
||||
return governance.ReconciliationFinding{}, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
if err := lockOpenReconciliationFinding(ctx, tx, findingID); err != nil {
|
||||
return governance.ReconciliationFinding{}, err
|
||||
}
|
||||
finding, err := getReconciliationFinding(ctx, tx, findingID)
|
||||
if errors.Is(err, ErrReconciliationNotFound) {
|
||||
return governance.ReconciliationFinding{}, err
|
||||
}
|
||||
if err != nil {
|
||||
return governance.ReconciliationFinding{}, err
|
||||
}
|
||||
if finding.Type != "R5" || finding.ActionState != "open" {
|
||||
return governance.ReconciliationFinding{}, ErrReconciliationConflict
|
||||
}
|
||||
var processingState string
|
||||
if err := tx.QueryRow(ctx, `SELECT processing_state FROM test_publications
|
||||
WHERE id=$1 AND superseded_at IS NULL FOR UPDATE`, finding.PublicationID).Scan(&processingState); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return governance.ReconciliationFinding{}, ErrReconciliationConflict
|
||||
}
|
||||
return governance.ReconciliationFinding{}, err
|
||||
}
|
||||
if processingState != finding.LedgerState {
|
||||
return governance.ReconciliationFinding{}, ErrReconciliationConflict
|
||||
}
|
||||
if processingState != targetState {
|
||||
if _, err := tx.Exec(ctx, `UPDATE test_publications SET processing_state=$2,updated_at=$3
|
||||
WHERE id=$1 AND processing_state=$4`, finding.PublicationID, targetState, now, finding.LedgerState); err != nil {
|
||||
return governance.ReconciliationFinding{}, err
|
||||
}
|
||||
if err := s.insertReconciliationActionTx(ctx, tx, finding, "writeback", actor, "started", reason, now); err != nil {
|
||||
return governance.ReconciliationFinding{}, err
|
||||
}
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `UPDATE reconciliation_findings SET action_state='done' WHERE id=$1 AND action_state='open'`, findingID); err != nil {
|
||||
return governance.ReconciliationFinding{}, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return governance.ReconciliationFinding{}, err
|
||||
}
|
||||
finding.ActionState = "done"
|
||||
return finding, nil
|
||||
}
|
||||
|
||||
func (s *Store) RequeueReconciliationPublication(ctx context.Context, findingID, expectedKnowledgeID, actor, reason string, now time.Time) (string, error) {
|
||||
beginner, ok := s.db.(interface {
|
||||
Begin(context.Context) (pgx.Tx, error)
|
||||
})
|
||||
if !ok {
|
||||
return "", errors.New("reconciliation transactions are unavailable")
|
||||
}
|
||||
tx, err := beginner.Begin(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
if err := lockOpenReconciliationFinding(ctx, tx, findingID); err != nil {
|
||||
return "", err
|
||||
}
|
||||
finding, err := getReconciliationFinding(ctx, tx, findingID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if (finding.Type != "R1" && finding.Type != "R4") || finding.ActionState != "open" {
|
||||
return "", ErrReconciliationConflict
|
||||
}
|
||||
var processingState, knowledgeID, targetScope, targetKB string
|
||||
if err := tx.QueryRow(ctx, `SELECT processing_state,knowledge_id,target_scope,test_kb_id
|
||||
FROM test_publications WHERE id=$1 AND superseded_at IS NULL FOR UPDATE`, finding.PublicationID).Scan(
|
||||
&processingState, &knowledgeID, &targetScope, &targetKB); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return "", ErrReconciliationConflict
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
if processingState != finding.LedgerState || knowledgeID != expectedKnowledgeID {
|
||||
return "", ErrReconciliationConflict
|
||||
}
|
||||
tag, err := tx.Exec(ctx, `UPDATE test_publications SET
|
||||
ingest_state='pending',processing_state='pending',knowledge_id='',poll_sequence=0,
|
||||
last_remote_status='',last_remote_updated_at=NULL,last_observed_at=NULL,
|
||||
processing_started_at=NULL,completed_at=NULL,stalled_at=NULL,last_error='',
|
||||
upload_md5='',test_instance_url='',test_instance_tenant=0,
|
||||
retry_count=retry_count+1,updated_at=$2
|
||||
WHERE id=$1 AND knowledge_id=$3 AND processing_state=$4`,
|
||||
finding.PublicationID, now, expectedKnowledgeID, finding.LedgerState)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("reset reconciliation publication: %w", err)
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
return "", ErrReconciliationConflict
|
||||
}
|
||||
payload, err := json.Marshal(map[string]string{
|
||||
"publication_id": finding.PublicationID,
|
||||
"target_scope": targetScope,
|
||||
"target_kb_id": targetKB,
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
jobID := orchestrationJobID("reconciliation.requeue", findingID)
|
||||
tag, err = tx.Exec(ctx, `INSERT INTO jobs(id,type,payload,state,priority,available_at,max_attempts,idempotency_key,created_at,updated_at)
|
||||
VALUES($1,'test.upload',$2,'pending',0,$3,5,$4,$3,$3)
|
||||
ON CONFLICT (idempotency_key) DO NOTHING`, jobID, payload, now, "reconciliation-requeue:"+findingID)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("enqueue reconciliation upload: %w", err)
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
if err := tx.QueryRow(ctx, `SELECT id FROM jobs WHERE idempotency_key=$1`, "reconciliation-requeue:"+findingID).Scan(&jobID); err != nil {
|
||||
return "", fmt.Errorf("reconciliation upload job missing: %w", err)
|
||||
}
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `UPDATE reconciliation_findings SET action_state='done' WHERE id=$1 AND action_state='open'`, findingID); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := s.insertReconciliationActionTx(ctx, tx, finding, "requeue", actor, "started", reason, now); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return jobID, nil
|
||||
}
|
||||
|
||||
func (s *Store) MarkReconciliationOrphanRemoved(ctx context.Context, findingID, actor, reason string, now time.Time) error {
|
||||
beginner, ok := s.db.(interface {
|
||||
Begin(context.Context) (pgx.Tx, error)
|
||||
})
|
||||
if !ok {
|
||||
return errors.New("reconciliation transactions are unavailable")
|
||||
}
|
||||
tx, err := beginner.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
if err := lockOpenReconciliationFinding(ctx, tx, findingID); err != nil {
|
||||
return err
|
||||
}
|
||||
finding, err := getReconciliationFinding(ctx, tx, findingID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if finding.Type != "R2" || finding.ActionState != "open" {
|
||||
return ErrReconciliationConflict
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `UPDATE reconciliation_findings SET action_state='done' WHERE id=$1 AND action_state='open'`, findingID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.insertReconciliationActionTx(ctx, tx, finding, "remove", actor, "started", reason, now); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (s *Store) insertReconciliationActionTx(ctx context.Context, tx pgx.Tx, finding governance.ReconciliationFinding, action, actor, outcome, detail string, now time.Time) error {
|
||||
id, err := newOpaqueID("rca-")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO reconciliation_finding_actions
|
||||
(id,finding_id,run_id,publication_id,knowledge_id,action,actor_ref,outcome,detail,created_at)
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`,
|
||||
id, finding.ID, finding.RunID, finding.PublicationID, finding.DocumentID, action, actor, outcome, detail, now)
|
||||
if err != nil {
|
||||
return fmt.Errorf("record reconciliation action: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user