feat(reconciliation): 实现导入对账后端

为什么:T6a 需要一张批次/差异表、全量只读扫描、R1-R8 判定和 finding 级处置;现有解析监控只转述台账状态,无法回答库内是否一致。
做什么:迁移 000084(upload_md5、runs/findings/actions、共享 removal_candidates 视图);WeKnora 字段与 1000/页扫描;runtime 只读客户端(0400 Key、503 降级);扫描/矩阵/动作/定时/僵死回收;9 条接口与 RBAC;overview 队列与删两张常量卡。
边界:只对测试库;对账零写请求;R1/R2 单条确认;R6 复用 /removal;R2 只管理员;生产链路未改。
验证:make verify 全绿(17 项);新增矩阵/扫描 R1-R8/零写/失败整批/动作/运行时/密钥权限测试。
This commit is contained in:
Zhero & Rin
2026-12-01 12:19:54 +08:00
committed by 姚章浩
parent 580695ca2e
commit 4528a55e6a
43 changed files with 3661 additions and 122 deletions
+51 -1
View File
@@ -31,8 +31,10 @@ import (
"knowledge-governance/internal/qaopsquality"
"knowledge-governance/internal/qawemail"
"knowledge-governance/internal/readiness"
"knowledge-governance/internal/reconciliation"
"knowledge-governance/internal/serviceverify"
"knowledge-governance/internal/version"
"knowledge-governance/internal/weknoraaccess"
)
// dingtalkSourceLister 是「系统设置 → 数据源配置」的数据源发现实现:只读列举钉钉知识库与
@@ -216,7 +218,54 @@ func run(ctx context.Context, getenv func(string) string) error {
allowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
allowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
}
monitorProvider, err := monitoring.NewRealProvider(monitoring.RealProviderConfig{DB: pool, WeKnoraBaseURL: config.TestWeKnoraBaseURL, TestWeKnoraResolver: testEndpointResolver, ProductionWeKnoraBaseURL: config.ProductionWeKnoraBaseURL, ProductionWeKnoraResolver: productionEndpointResolver, MinerUBaseURL: config.MinerUBaseURL, WeKnoraReadiness: weknoraProbe, WorkerStaleAfter: config.WorkerLivenessStaleAfter, AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP})
runtimeKey := ""
if config.WeKnoraRuntimeKeyFile != "" {
key, keyErr := weknora.ReadRuntimeKeyFile(config.WeKnoraRuntimeKeyFile)
if keyErr != nil {
log.Printf("WARN: WeKnora runtime read key is unavailable; runtime endpoints degrade to 503")
} else {
runtimeKey = key
}
}
runtimeProvider := reconciliation.NewRuntimeProvider(reconciliation.RuntimeConfig{
BaseURL: testEndpointResolver,
APIKey: runtimeKey,
Timeout: config.TestWeKnoraHTTPTimeout,
AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
})
reconciliationRemote := &weknoraaccess.Client{
Resolver: readiness.Resolver{
ResolveConnection: func(resolveCtx context.Context) (string, string, error) {
target, resolveErr := kbBindings.Resolve(resolveCtx, kbbinding.EnvTest)
return target.BaseURL, target.APIKey, resolveErr
},
DefaultKB: config.InternalRoutingKnowledgeBaseID,
},
Timeout: config.TestWeKnoraHTTPTimeout,
AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
}
var reconciliationService httpapi.ReconciliationService
if config.TestWeKnoraEnabled {
service, serviceErr := reconciliation.New(reconciliation.Config{
Store: actionStore,
Remote: reconciliationRemote,
Runtime: runtimeProvider,
Queue: actionStore,
Grace: config.ReconciliationGrace,
StallAfter: config.ReconciliationStallAfter,
StaleAfter: config.ReconciliationStaleAfter,
ConfirmConcurrency: config.ReconciliationConfirmConcurrency,
KeepRuns: config.ReconciliationKeepRuns,
MaxAge: config.ReconciliationMaxAge,
})
if serviceErr != nil {
return serviceErr
}
reconciliationService = service
}
monitorProvider, err := monitoring.NewRealProvider(monitoring.RealProviderConfig{DB: pool, WeKnoraBaseURL: config.TestWeKnoraBaseURL, TestWeKnoraResolver: testEndpointResolver, ProductionWeKnoraBaseURL: config.ProductionWeKnoraBaseURL, ProductionWeKnoraResolver: productionEndpointResolver, MinerUBaseURL: config.MinerUBaseURL, WeKnoraReadiness: weknoraProbe, WorkerStaleAfter: config.WorkerLivenessStaleAfter, AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP, RuntimeQueues: runtimeProvider})
if err != nil {
return err
}
@@ -291,6 +340,7 @@ func run(ctx context.Context, getenv func(string) string) error {
QAOpsProblem: qaSettings.Problem,
Store: postgresstore.NewStore(pool).WithLibraryTarget(config.LibraryTargetIdentity()).WithRoutingDefaults(config.InternalRoutingKnowledgeBaseID, config.ExternalRoutingKnowledgeBaseID),
Monitor: monitorProvider,
Reconciliation: reconciliationService,
InternalRoutingKnowledgeBaseID: config.InternalRoutingKnowledgeBaseID,
ExternalRoutingKnowledgeBaseID: config.ExternalRoutingKnowledgeBaseID,
RoutingBindings: postgresstore.NewStore(pool),
+3 -3
View File
@@ -55,7 +55,7 @@ func TestWorkerHandlersFollowWorkerRole(t *testing.T) {
VersionHistoryGiteaBaseURL: "https://gitea.invalid/Weknora/knowledge-governance",
VersionHistoryAllowedOrigins: []string{"https://gitea.invalid"},
}
handlers, err := workerHandlers(postgresstore.NewStore(nil), release, nil)
handlers, err := workerHandlers(postgresstore.NewStore(nil), release, nil, nil)
if err != nil {
t.Fatalf("release-executor workerHandlers() error = %v", err)
}
@@ -74,12 +74,12 @@ func TestWorkerHandlersFollowWorkerRole(t *testing.T) {
TestWeKnoraEnabled: true,
TestWeKnoraAPIKeyFile: "/nonexistent/api-key",
}
if _, err := workerHandlers(nil, capture, nil); err == nil || !strings.Contains(err.Error(), "test WeKnora API key") {
if _, err := workerHandlers(nil, capture, nil, nil); err == nil || !strings.Contains(err.Error(), "test WeKnora API key") {
t.Fatalf("capture role must reach the test WeKnora wiring, got %v", err)
}
capture.TestWeKnoraEnabled = false
capture.PPScanEnabled = false
handlers, err = workerHandlers(postgresstore.NewStore(nil), capture, nil)
handlers, err = workerHandlers(postgresstore.NewStore(nil), capture, nil, nil)
if err != nil {
t.Fatalf("capture workerHandlers() error = %v", err)
}
+54 -2
View File
@@ -27,6 +27,7 @@ import (
postgresstore "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/platform/weknora"
"knowledge-governance/internal/readiness"
"knowledge-governance/internal/reconciliation"
"knowledge-governance/internal/versionhistory"
"knowledge-governance/internal/weknoraaccess"
artifactfetch "knowledge-governance/internal/workflows/artifactfetch"
@@ -260,7 +261,44 @@ func run(ctx context.Context, getenv func(string) string) error {
} else if repaired > 0 {
log.Printf("library job reconcile: %d orphan job(s) marked failed", repaired)
}
handlers, err := workerHandlers(store, config, kbBindings)
var reconciliationService *reconciliation.Service
if config.TestWeKnoraEnabled && config.LibraryWorkerRole.ExecutesSourceWork() {
reconciliationRemote := &weknoraaccess.Client{
Resolver: readiness.Resolver{
LoadBinding: func(resolveCtx context.Context) (string, error) {
internal, _, _, bindingErr := store.LoadRoutingKBBindings(resolveCtx)
return internal, bindingErr
},
ResolveConnection: func(resolveCtx context.Context) (string, string, error) {
if kbBindings != nil {
target, resolveErr := kbBindings.Resolve(resolveCtx, kbbinding.EnvTest)
return target.BaseURL, target.APIKey, resolveErr
}
key, keyErr := weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile)
return config.TestWeKnoraBaseURL, key, keyErr
},
DefaultKB: config.InternalRoutingKnowledgeBaseID,
},
Timeout: config.TestWeKnoraHTTPTimeout,
AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
}
reconciliationService, err = reconciliation.New(reconciliation.Config{
Store: store,
Remote: reconciliationRemote,
Queue: store,
Grace: config.ReconciliationGrace,
StallAfter: config.ReconciliationStallAfter,
StaleAfter: config.ReconciliationStaleAfter,
ConfirmConcurrency: config.ReconciliationConfirmConcurrency,
KeepRuns: config.ReconciliationKeepRuns,
MaxAge: config.ReconciliationMaxAge,
})
if err != nil {
return err
}
}
handlers, err := workerHandlers(store, config, kbBindings, reconciliationService)
if err != nil {
return err
}
@@ -331,6 +369,9 @@ func run(ctx context.Context, getenv func(string) string) error {
go runSourceRefreshScheduler(ctx, store, config.SourceRefreshSchedulerInterval, func(err error) {
log.Printf("worker %s source refresh scheduler error: %v", config.WorkerID, err)
})
if reconciliationService != nil {
go runReconciliationScheduler(ctx, store, reconciliationService, config)
}
}
log.Printf("worker %s started role=%s release=%t source=%t (source refresh scheduler every %s)",
config.WorkerID, config.LibraryWorkerRole, config.LibraryWorkerRole.ExecutesRelease(),
@@ -373,7 +414,7 @@ func completeLibraryCaptureJob(ctx context.Context, store libraryCapturePersiste
return nil
}
func workerHandlers(store *postgresstore.Store, config appconfig.Config, kbBindings *kbbinding.Store) (map[string]jobs.Handler, error) {
func workerHandlers(store *postgresstore.Store, config appconfig.Config, kbBindings *kbbinding.Store, reconciliationService *reconciliation.Service) (map[string]jobs.Handler, error) {
handlers := map[string]jobs.Handler{
"demo": func(_ context.Context, job jobs.Job) error {
log.Printf("completed demo job id=%s", job.ID)
@@ -648,6 +689,17 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config, kbBindi
handlers["test.poll"] = poll.Handle
handlers["test.validate"] = validate.Handle
handlers["test.remove"] = remove.Handle
if reconciliationService != nil {
handlers["reconciliation.run"] = func(handlerCtx context.Context, job jobs.Job) error {
var payload struct {
RunID string `json:"run_id"`
}
if err := json.Unmarshal(job.Payload, &payload); err != nil || payload.RunID == "" {
return jobs.Permanent(jobs.ErrCodeHandlerFallback, errors.New("invalid reconciliation run payload"))
}
return reconciliationService.ExecuteRun(handlerCtx, payload.RunID)
}
}
return handlers, nil
}
+4 -4
View File
@@ -20,7 +20,7 @@ func TestRunRequiresDatabaseURL(t *testing.T) {
}
func TestWorkerHandlersExcludeReleaseAndTestJobsByDefault(t *testing.T) {
handlers, err := workerHandlers(nil, appconfig.Config{}, nil)
handlers, err := workerHandlers(nil, appconfig.Config{}, nil, nil)
if err != nil {
t.Fatalf("workerHandlers() error = %v", err)
}
@@ -46,7 +46,7 @@ func TestWorkerHandlersRegisterPPScanWhenExplicitlyEnabled(t *testing.T) {
PPScanLedgerPath: filepath.Join(root, "state.jsonl"),
PPScanManifestPath: filepath.Join(root, "manifest.json"),
}
handlers, err := workerHandlers(postgresstore.NewStore(nil), config, nil)
handlers, err := workerHandlers(postgresstore.NewStore(nil), config, nil, nil)
if err != nil {
t.Fatalf("workerHandlers() error = %v", err)
}
@@ -57,7 +57,7 @@ func TestWorkerHandlersRegisterPPScanWhenExplicitlyEnabled(t *testing.T) {
func TestWorkerHandlersRequireAPIKeyWhenTestWeKnoraEnabled(t *testing.T) {
config := appconfig.Config{TestWeKnoraEnabled: true, TestWeKnoraAPIKeyFile: "/nonexistent/api-key"}
_, err := workerHandlers(nil, config, nil)
_, err := workerHandlers(nil, config, nil, nil)
if err == nil || !strings.Contains(err.Error(), "read test WeKnora API key") {
t.Fatalf("workerHandlers() error = %v", err)
}
@@ -80,7 +80,7 @@ func TestWorkerHandlersRegisterTestJobsForExplicitDockerHTTP(t *testing.T) {
TestWeKnoraMaxUploadBytes: 1024,
TestAcceptancePolicyVersion: "structural-v1",
}
handlers, err := workerHandlers(postgresstore.NewStore(nil), config, nil)
handlers, err := workerHandlers(postgresstore.NewStore(nil), config, nil, nil)
if err != nil {
t.Fatalf("workerHandlers() error = %v", err)
}
+64
View File
@@ -0,0 +1,64 @@
package main
import (
"context"
"log"
"time"
"knowledge-governance/internal/appconfig"
"knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/reconciliation"
)
// runReconciliationScheduler claims at most one scheduled batch per test KB
// per local day. The claim is in PostgreSQL; multiple workers racing here are
// harmless. The first tick is delayed by one interval, like the source refresh
// scheduler, so startup does not enqueue a backlog before handlers are ready.
func runReconciliationScheduler(ctx context.Context, store *postgres.Store, service *reconciliation.Service, config appconfig.Config) {
if service == nil || !config.ReconciliationScheduleEnabled {
return
}
location, err := time.LoadLocation(config.ReconciliationTimezone)
if err != nil {
log.Printf("reconciliation scheduler disabled: invalid timezone %q", config.ReconciliationTimezone)
return
}
daily, err := time.Parse("15:04", config.ReconciliationDailyAt)
if err != nil {
log.Printf("reconciliation scheduler disabled: invalid daily time %q", config.ReconciliationDailyAt)
return
}
ticker := time.NewTicker(time.Minute)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case tick := <-ticker.C:
local := tick.In(location)
at := time.Date(local.Year(), local.Month(), local.Day(), daily.Hour(), daily.Minute(), 0, 0, location)
if local.Before(at) {
continue
}
internal, external, _, bindingErr := store.LoadRoutingKBBindings(ctx)
if bindingErr != nil {
log.Printf("reconciliation scheduler cannot read current bindings: %v", bindingErr)
continue
}
if internal == "" {
internal = config.InternalRoutingKnowledgeBaseID
}
if external == "" {
external = config.ExternalRoutingKnowledgeBaseID
}
created, scheduleErr := service.ScheduleDue(ctx, []string{internal, external}, at.UTC(), tick.UTC())
if scheduleErr != nil {
log.Printf("reconciliation scheduler error: %v", scheduleErr)
continue
}
if created > 0 {
log.Printf("reconciliation scheduler created %d batch(es) for local day %s", created, local.Format("2006-01-02"))
}
}
}
}