feat(library): 快照搬运先于维护、双向校验与云端版本回传
为什么改:云端 release-executor 与目标同机后,本机封存的快照必须"先到、先验证" 才允许开维护窗口。此前只有 pack/unpack 两条人工命令:UI 点发布时执行器读到的是 本机归档路径,云端根本没有这份快照,作业只能在装配阶段失败;而预备份落在云端, 本机页面也读不到。用户已批准补齐这条链路。 搬运(新包 internal/libraryhandoff):本机 Load 逐 blob 重算 → Pack → SSH 流式写入 云端暂存 → 原子改名 → 云端 snapshot-unpack 再逐 blob 校验 → 读回版本清单摘要自证 → scope/tenant/知识库身份与治理库作业一致。只有全部通过才投递 library.sync|restore, 失败时发布作业根本不存在(目标不进维护、不写知识)。远端命令是固定 argv,容器名与 路径只来自部署配置;同 ID 异内容拒绝;同一快照本机 flock 串行化;暂存 bundle 用后即删, 归档本体永不自动清理。 回传:capture 角色按已成功作业的 snapshot_id 扫描,把本机缺失的云端快照 Fetch 回来 (云端 pack → SSH 流回 → 本机 Unpack 逐 blob 校验)。回传成功后 API/页面既有的列表、 详情、差异、存储与历史恢复路径读到的就是真实字节;失败则版本不出现在本机,不会被误报成可恢复。 角色:搬运与回传只注册在 capture;若接线到 full(同时消费发布作业)启动即失败, 避免与云端执行器抢同一批作业。release-executor 仍不拥有治理库 DDL,也不消费 QA/邮件/来源扫描。 验证:internal/libraryhandoff 全绿(跨进程 push/fetch、身份不符拒绝、幂等复用、 并发串行、篡改与未知快照不落版本、路径穿越拒绝、远端错误不当作"没有"); cmd/worker 在隔离 fixture 库(独立测试 PG)上验证"校验通过才入队发布、失败不入队"; httpapi 队列决策单测;相关包 go test 全绿;go vet 全仓通过。 未部署、未推送、未构建镜像:云端接线与验收仍由父执行。真实云链路(含 SSH 通道) 本轮没有云侧写操作,只有本机跨进程与隔离 fixture 证据。
This commit is contained in:
@@ -3,6 +3,7 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
@@ -17,6 +18,7 @@ import (
|
||||
"knowledge-governance/internal/backuphost"
|
||||
"knowledge-governance/internal/dingtalkdiscovery"
|
||||
"knowledge-governance/internal/httpapi"
|
||||
"knowledge-governance/internal/libraryhandoff"
|
||||
"knowledge-governance/internal/monitoring"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
@@ -168,7 +170,14 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
if getenv("DOBOTAI_OPS_TENANT_KEY") != "" {
|
||||
qaSyncStore = qaOrganizationStore
|
||||
}
|
||||
// 快照搬运是否接线:只用于决定"发布/恢复作业先入哪个队列"。
|
||||
// 配置不完整即启动失败(半接线会让作业以"快照不在执行器"失败)。
|
||||
_, handoffConfigured, handoffErr := libraryhandoff.FromEnv(getenv)
|
||||
if handoffErr != nil {
|
||||
return fmt.Errorf("快照搬运接线无效: %w", handoffErr)
|
||||
}
|
||||
handler, err := httpapi.NewHandler(httpapi.Config{
|
||||
LibraryHandoffEnabled: handoffConfigured,
|
||||
QAAI: qaopsai.NewFromEnvironment(pool, getenv, config.DatabaseURL),
|
||||
QAWeeklyMail: qawemail.NewStore(pool, qaSettings.TenantKey, getenv("QA_AI_MASTER_KEY_FILE"), nil),
|
||||
QAAITrustTLSProxy: getenv("QA_AI_TRUST_TLS_PROXY") == "true",
|
||||
|
||||
@@ -34,6 +34,7 @@ import (
|
||||
|
||||
"knowledge-governance/internal/librarydeadletter"
|
||||
"knowledge-governance/internal/libraryfreeze"
|
||||
"knowledge-governance/internal/libraryhandoff"
|
||||
"knowledge-governance/internal/librarymaintenance"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
v071 "knowledge-governance/internal/releaseadapter/v071"
|
||||
@@ -60,6 +61,9 @@ type options struct {
|
||||
job string
|
||||
dryRun bool
|
||||
snapshot string
|
||||
// kb/tenant 是 snapshot-push 要核对的期望身份(来自治理库作业,不是 bundle 自报)。
|
||||
kb string
|
||||
tenant uint64
|
||||
// bundle 是快照跨主机包路径(snapshot-pack 输出 / snapshot-unpack 输入)。
|
||||
bundle string
|
||||
// releasedDeadLetters 是治理平台审计过的精确解除指纹(逗号分隔)。它只让这些
|
||||
@@ -106,6 +110,10 @@ func main() {
|
||||
runErr = runSnapshotPack(opts)
|
||||
case "snapshot-unpack":
|
||||
runErr = runSnapshotUnpack(opts)
|
||||
case "snapshot-push":
|
||||
runErr = runSnapshotPush(opts)
|
||||
case "snapshot-fetch":
|
||||
runErr = runSnapshotFetch(opts)
|
||||
default:
|
||||
usage()
|
||||
os.Exit(2)
|
||||
@@ -130,6 +138,8 @@ func usage() {
|
||||
snapshot-pack export one sealed snapshot into a single verifiable bundle file
|
||||
snapshot-unpack verify a bundle and install it into this archive (content-addressed,
|
||||
version manifest is the commit point; repeated import is idempotent)
|
||||
snapshot-push send one sealed snapshot to the cloud release executor (verify on both sides)
|
||||
snapshot-fetch bring a cloud-held snapshot back into this archive (verified)
|
||||
|
||||
Flags (defaults target the local WKNFull test stack):
|
||||
-source-app WKNFull-app container whose env describes the source
|
||||
@@ -187,6 +197,8 @@ func parseFlags(command string, args []string) (options, []string, error) {
|
||||
set.StringVar(&opts.snapshot, "snapshot", "", "snapshot id for verify")
|
||||
set.StringVar(&opts.releasedDeadLetters, "released-dead-letters", "", "audited dead-letter fingerprints (comma separated)")
|
||||
set.StringVar(&opts.bundle, "bundle", "", "snapshot bundle path (snapshot-pack / snapshot-unpack)")
|
||||
set.StringVar(&opts.kb, "kb", "", "expected knowledge base id (snapshot-push)")
|
||||
set.Uint64Var(&opts.tenant, "tenant", 0, "expected tenant id (snapshot-push)")
|
||||
if err := set.Parse(args); err != nil {
|
||||
return opts, nil, err
|
||||
}
|
||||
@@ -1206,3 +1218,54 @@ func runSnapshotUnpack(opts options) error {
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// runSnapshotPush 把一份本机封存快照送到云端发布执行器(先校验字节,再校验身份)。
|
||||
// 只读本机归档;远端只写暂存目录与目标归档,不做任何目标库动作。
|
||||
func runSnapshotPush(opts options) error {
|
||||
if opts.snapshot == "" || opts.scope == "" || opts.kb == "" || opts.tenant == 0 {
|
||||
return errors.New("snapshot-push 需要 -snapshot <id> -scope internal|external -tenant <n> -kb <uuid>")
|
||||
}
|
||||
handoff, err := openHandoff(opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
evidence, err := handoff.Push(context.Background(), libraryhandoff.Identity{
|
||||
SnapshotID: opts.snapshot, Scope: opts.scope, TenantID: opts.tenant, KnowledgeBaseID: opts.kb})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
printJSON(evidence)
|
||||
return nil
|
||||
}
|
||||
|
||||
// runSnapshotFetch 把云端的快照取回本机归档(预备份/云端版本的读回)。
|
||||
func runSnapshotFetch(opts options) error {
|
||||
if opts.snapshot == "" {
|
||||
return errors.New("snapshot-fetch 需要 -snapshot <id>")
|
||||
}
|
||||
handoff, err := openHandoff(opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
evidence, err := handoff.Fetch(context.Background(), opts.snapshot)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
printJSON(evidence)
|
||||
return nil
|
||||
}
|
||||
|
||||
// openHandoff 只认部署注入的配置:CLI 不接受调用方指定远端路径/容器/上游地址。
|
||||
func openHandoff(opts options) (*libraryhandoff.Handoff, error) {
|
||||
config, configured, err := libraryhandoff.FromEnv(os.Getenv)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !configured {
|
||||
return nil, errors.New("快照搬运未接线(缺少 LIBRARY_HANDOFF_*)")
|
||||
}
|
||||
if opts.archiveRoot != "" && config.LocalArchive == "" {
|
||||
config.LocalArchive = opts.archiveRoot
|
||||
}
|
||||
return libraryhandoff.New(config, nil)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/appconfig"
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/libraryhandoff"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
// libraryHandoffJobType 与 API 侧常量同值:API 用它把"发布/恢复"拆成
|
||||
// "先搬运、后发布"。搬运作业由 capture 角色执行(只有本机有源归档与 SSH 凭据),
|
||||
// release-executor 永不注册它——云端没有源归档,也没有回本机的通道。
|
||||
const libraryHandoffJobType = "library.snapshot.handoff"
|
||||
|
||||
// libraryHandoffStage 是搬运在作业阶段表里的名字(页面能看出卡在搬运还是发布)。
|
||||
const libraryHandoffStage = "handoff"
|
||||
|
||||
type libraryHandoffPayload struct {
|
||||
LibraryJobID string `json:"library_job_id"`
|
||||
Scope string `json:"scope"`
|
||||
TargetSnapshotID string `json:"target_snapshot_id"`
|
||||
NextType string `json:"next_type"`
|
||||
}
|
||||
|
||||
// registerLibraryHandoffHandlers 注册"先把快照送到执行器"的作业。
|
||||
//
|
||||
// 顺序是这条链的安全边界:push 成功(云端逐 blob 校验通过、清单摘要自证、身份一致)
|
||||
// 之后才投递真正的发布作业。push 失败时发布作业根本不存在,executor 不会开维护窗口、
|
||||
// 不会写任何知识数据。
|
||||
func registerLibraryHandoffHandlers(handlers map[string]jobs.Handler, store *postgresstore.Store,
|
||||
config appconfig.Config, handoff *libraryhandoff.Handoff) {
|
||||
handlers[libraryHandoffJobType] = func(ctx context.Context, job jobs.Job) error {
|
||||
var payload libraryHandoffPayload
|
||||
if err := json.Unmarshal(job.Payload, &payload); err != nil ||
|
||||
payload.LibraryJobID == "" || payload.TargetSnapshotID == "" ||
|
||||
(payload.Scope != "internal" && payload.Scope != "external") {
|
||||
return fmt.Errorf("invalid library handoff payload")
|
||||
}
|
||||
return runLibraryHandoff(ctx, store, config, handoff, payload)
|
||||
}
|
||||
}
|
||||
|
||||
func runLibraryHandoff(ctx context.Context, store *postgresstore.Store, config appconfig.Config,
|
||||
handoff *libraryhandoff.Handoff, payload libraryHandoffPayload) error {
|
||||
now := time.Now().UTC()
|
||||
// 作业身份必须与载荷逐项一致:载荷来自队列,业务作业才是治理库的事实。
|
||||
record, err := store.LibraryJob(ctx, payload.LibraryJobID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("读不到业务作业 %s:%w", payload.LibraryJobID, err)
|
||||
}
|
||||
if record.Scope != payload.Scope || record.TargetSnapshotID != payload.TargetSnapshotID {
|
||||
return failLibraryHandoff(ctx, store, payload, "队列载荷与业务作业不一致(scope/快照),拒绝搬运")
|
||||
}
|
||||
switch payload.NextType {
|
||||
case librarySyncJobType:
|
||||
if record.Kind != governance.LibraryJobSync {
|
||||
return failLibraryHandoff(ctx, store, payload, "作业类型是恢复,但搬运要求投递同步,拒绝")
|
||||
}
|
||||
case libraryRestoreJobType:
|
||||
if record.Kind != governance.LibraryJobRestore {
|
||||
return failLibraryHandoff(ctx, store, payload, "作业类型是同步,但搬运要求投递恢复,拒绝")
|
||||
}
|
||||
default:
|
||||
return failLibraryHandoff(ctx, store, payload, "未知的后续作业类型,拒绝搬运")
|
||||
}
|
||||
if record.State == governance.LibraryJobFailed || record.State == governance.LibraryJobCancelled ||
|
||||
record.State == governance.LibraryJobSucceeded {
|
||||
return failLibraryHandoff(ctx, store, payload, "业务作业已终态,不再搬运")
|
||||
}
|
||||
|
||||
knowledgeBase := config.LibraryProductionInternalKB
|
||||
if payload.Scope == "external" {
|
||||
knowledgeBase = config.LibraryProductionExternalKB
|
||||
}
|
||||
if config.LibraryProductionTenantID == 0 || knowledgeBase == "" {
|
||||
return failLibraryHandoff(ctx, store, payload, "目标身份未配置(租户/知识库),无法核对快照归属")
|
||||
}
|
||||
want := libraryhandoff.Identity{SnapshotID: payload.TargetSnapshotID, Scope: payload.Scope,
|
||||
TenantID: config.LibraryProductionTenantID, KnowledgeBaseID: knowledgeBase}
|
||||
|
||||
_ = store.UpdateLibraryStage(ctx, payload.LibraryJobID, libraryHandoffStage, "running", nil, nil, nil, nil,
|
||||
"正在把快照送到发布执行器并校验", now)
|
||||
evidence, err := handoff.Push(ctx, want)
|
||||
if err != nil {
|
||||
message := "快照未送到发布执行器:" + err.Error()
|
||||
_ = store.UpdateLibraryStage(ctx, payload.LibraryJobID, libraryHandoffStage, "failed", nil, nil, nil, nil, message, time.Now().UTC())
|
||||
// 目标没有被停用、没有任何知识写入:恢复责任就是"修好搬运再重试"。
|
||||
_ = store.AdvanceLibraryJob(ctx, payload.LibraryJobID, governance.LibraryJobFailed, libraryHandoffStage,
|
||||
message, "未进入维护窗口、未写任何知识;修正搬运接线或重新封存后重试", "", "", time.Now().UTC())
|
||||
return fmt.Errorf("%s", message)
|
||||
}
|
||||
|
||||
// 只有搬运校验通过后,发布作业才存在。
|
||||
payloadRaw, marshalErr := json.Marshal(map[string]string{
|
||||
"library_job_id": payload.LibraryJobID, "scope": payload.Scope, "target_snapshot_id": payload.TargetSnapshotID,
|
||||
})
|
||||
if marshalErr != nil {
|
||||
return failLibraryHandoff(ctx, store, payload, "无法构造发布作业载荷")
|
||||
}
|
||||
queueJob, enqueueErr := store.Enqueue(ctx, jobs.EnqueueRequest{
|
||||
ID: governance.QueueJobIDFor(payload.LibraryJobID), Type: payload.NextType, Payload: payloadRaw,
|
||||
AvailableAt: time.Now().UTC(), MaxAttempts: 1,
|
||||
IdempotencyKey: payload.NextType + ".queue:" + payload.LibraryJobID,
|
||||
}, time.Now().UTC())
|
||||
if enqueueErr != nil || queueJob == nil {
|
||||
return failLibraryHandoff(ctx, store, payload, "快照已在执行器就绪,但发布作业投递失败")
|
||||
}
|
||||
if attachErr := store.AttachLibraryQueueJob(ctx, payload.LibraryJobID, queueJob.ID, time.Now().UTC()); attachErr != nil {
|
||||
return failLibraryHandoff(ctx, store, payload, "发布作业已投递但无法关联业务作业")
|
||||
}
|
||||
detail := fmt.Sprintf("快照已在校验后送达执行器(parts=%d bytes=%d reused=%t)", evidence.Parts, evidence.Bytes, evidence.Reused)
|
||||
_ = store.UpdateLibraryStage(ctx, payload.LibraryJobID, libraryHandoffStage, "succeeded", nil, nil, nil, nil, detail, time.Now().UTC())
|
||||
log.Printf("library handoff completed job=%s scope=%s snapshot=%s parts=%d reused=%t",
|
||||
payload.LibraryJobID, payload.Scope, payload.TargetSnapshotID, evidence.Parts, evidence.Reused)
|
||||
return nil
|
||||
}
|
||||
|
||||
func failLibraryHandoff(ctx context.Context, store *postgresstore.Store, payload libraryHandoffPayload, message string) error {
|
||||
_ = store.UpdateLibraryStage(ctx, payload.LibraryJobID, libraryHandoffStage, "failed", nil, nil, nil, nil, message, time.Now().UTC())
|
||||
_ = store.AdvanceLibraryJob(ctx, payload.LibraryJobID, governance.LibraryJobFailed, libraryHandoffStage, message,
|
||||
"未进入维护窗口、未写任何知识;修正后重试", "", "", time.Now().UTC())
|
||||
return fmt.Errorf("%s", message)
|
||||
}
|
||||
|
||||
// runLibraryArchivePullLoop 把云端产生的快照(预备份等)取回本机归档。
|
||||
//
|
||||
// 为什么要回传而不是"页面直接读云端":API 的所有归档消费点(列表/详情/差异/存储/
|
||||
// 容量/恢复寻址)都读本机 LIBRARY_ARCHIVE_ROOT,回传后它们读到的就是真实字节,
|
||||
// 不需要给每条读路径加远端分支,也不会把两端路径当成全局身份(身份始终是 snapshot ID)。
|
||||
//
|
||||
// 失败只记日志:本机没有这份版本时页面按"无此版本/不可读"展示,不会被误报成可恢复。
|
||||
func runLibraryArchivePullLoop(ctx context.Context, store *postgresstore.Store, handoff *libraryhandoff.Handoff,
|
||||
archiveRoot string, interval time.Duration, report func(error)) {
|
||||
if interval <= 0 {
|
||||
interval = 5 * time.Minute
|
||||
}
|
||||
pull := func() {
|
||||
archive, err := librarysnapshot.Open(archiveRoot, 256*1024*1024)
|
||||
if err != nil {
|
||||
report(fmt.Errorf("归档不可读,跳过回传:%w", err))
|
||||
return
|
||||
}
|
||||
defer archive.Close()
|
||||
for _, scope := range []string{"internal", "external"} {
|
||||
ids, listErr := store.LibraryJobSnapshots(ctx, scope, 50)
|
||||
if listErr != nil {
|
||||
report(fmt.Errorf("读不到 %s 的已完成作业快照:%w", scope, listErr))
|
||||
continue
|
||||
}
|
||||
for _, id := range ids {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return
|
||||
}
|
||||
if _, loadErr := archive.LoadManifest(id); loadErr == nil {
|
||||
continue
|
||||
}
|
||||
evidence, fetchErr := handoff.Fetch(ctx, id)
|
||||
if fetchErr != nil {
|
||||
report(fmt.Errorf("回传快照 %s 失败:%w", id, fetchErr))
|
||||
continue
|
||||
}
|
||||
log.Printf("library archive pull snapshot=%s scope=%s parts=%d bytes=%d reused=%t",
|
||||
evidence.Snapshot, evidence.Scope, evidence.Parts, evidence.Bytes, evidence.Reused)
|
||||
}
|
||||
}
|
||||
}
|
||||
pull()
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
pull()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"knowledge-governance/internal/appconfig"
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/libraryhandoff"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
// 这条测试回答一个业务问题:搬运没成功时,发布作业到底存不存在。
|
||||
// 用隔离 fixture 库(KG_TEST_DSN 指向专门的测试库),不碰任何业务库。
|
||||
func TestHandoffChainGatesReleaseJobOnVerifiedTransfer(t *testing.T) {
|
||||
dsn := os.Getenv("KG_TEST_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("KG_TEST_DSN 未设置:跳过隔离 fixture 库上的搬运链测试")
|
||||
}
|
||||
ctx := context.Background()
|
||||
pool, err := pgxpool.New(ctx, dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pool.Close()
|
||||
if err := postgresstore.ApplyMigrations(ctx, pool); err != nil {
|
||||
t.Fatalf("migrate fixture db: %v", err)
|
||||
}
|
||||
store := postgresstore.NewStore(pool)
|
||||
// 隔离 fixture 库会被反复使用:先把上一次运行残留的在飞 fixture 作业收掉,
|
||||
// 否则 (scope,kind) 的唯一索引会把本次新建当成冲突。只动 handoff fixture 的行。
|
||||
if _, err := pool.Exec(ctx, `UPDATE library_jobs SET state='failed', finished_at=now(), updated_at=now()
|
||||
WHERE id LIKE 'libsync-handoff-%' AND state IN ('pending','running')`); err != nil {
|
||||
t.Fatalf("reset fixture jobs: %v", err)
|
||||
}
|
||||
fixture := newHandoffFixture(t)
|
||||
config := appconfig.Config{LibraryProductionTenantID: fixture.tenant,
|
||||
LibraryProductionInternalKB: fixture.kb, LibraryProductionExternalKB: fixture.kb}
|
||||
|
||||
snapshot := fixture.seal(t)
|
||||
job := createFixtureJob(t, store, "internal", snapshot)
|
||||
payload := libraryHandoffPayload{LibraryJobID: job.ID, Scope: "internal",
|
||||
TargetSnapshotID: snapshot, NextType: librarySyncJobType}
|
||||
if err := runLibraryHandoff(ctx, store, config, fixture.handoff, payload); err != nil {
|
||||
t.Fatalf("runLibraryHandoff() error = %v", err)
|
||||
}
|
||||
record, err := store.LibraryJob(ctx, job.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if record.State == governance.LibraryJobFailed {
|
||||
t.Fatalf("verified handoff left the job failed: %s", record.Error)
|
||||
}
|
||||
releaseID := governance.QueueJobIDFor(job.ID)
|
||||
var queueType string
|
||||
if err := pool.QueryRow(ctx, `SELECT type FROM jobs WHERE id=$1`, releaseID).Scan(&queueType); err != nil {
|
||||
t.Fatalf("release queue job missing after verified handoff: %v", err)
|
||||
}
|
||||
if queueType != librarySyncJobType {
|
||||
t.Fatalf("release queue type = %q", queueType)
|
||||
}
|
||||
if record.QueueJobID != releaseID {
|
||||
t.Fatalf("library job not attached to release queue job: %q", record.QueueJobID)
|
||||
}
|
||||
// 云端确实拿到了可校验的快照。
|
||||
if _, err := os.Stat(filepath.Join(fixture.remoteArchive, "versions", snapshot+".json")); err != nil {
|
||||
t.Fatalf("executor archive lacks the handoff snapshot: %v", err)
|
||||
}
|
||||
|
||||
// 负例:快照根本不存在 → 发布作业不得入队,作业必须失败。
|
||||
// 用 external scope:同一 (scope, kind) 只允许一个在飞作业,负例不能挤在 internal 上。
|
||||
unknown := fixture.unknownSnapshotID()
|
||||
badJob := createFixtureJob(t, store, "external", unknown)
|
||||
badPayload := libraryHandoffPayload{LibraryJobID: badJob.ID, Scope: "external",
|
||||
TargetSnapshotID: unknown, NextType: librarySyncJobType}
|
||||
if err := runLibraryHandoff(ctx, store, config, fixture.handoff, badPayload); err == nil {
|
||||
t.Fatal("runLibraryHandoff() reported success for a snapshot that does not exist")
|
||||
}
|
||||
badRecord, err := store.LibraryJob(ctx, badJob.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if badRecord.State != governance.LibraryJobFailed {
|
||||
t.Fatalf("failed handoff left job state = %s", badRecord.State)
|
||||
}
|
||||
var queued int
|
||||
if err := pool.QueryRow(ctx, `SELECT count(*) FROM jobs WHERE id=$1`,
|
||||
governance.QueueJobIDFor(badJob.ID)).Scan(&queued); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if queued != 0 {
|
||||
t.Fatal("a failed handoff still enqueued the release job: the target could be put into maintenance")
|
||||
}
|
||||
}
|
||||
|
||||
func createFixtureJob(t *testing.T, store *postgresstore.Store, scope, snapshot string) governance.LibraryJob {
|
||||
t.Helper()
|
||||
now := time.Now().UTC()
|
||||
// 每次运行用唯一后缀:fixture 库会被反复使用,固定 ID 会撞上上一次的行。
|
||||
unique := fmt.Sprintf("%d", now.UnixNano())
|
||||
job, reused, err := store.CreateLibraryJob(context.Background(), governance.LibraryJob{
|
||||
ID: "libsync-handoff-" + unique, Scope: scope, Kind: governance.LibraryJobSync,
|
||||
IdempotencyKey: "handoff-fixture:" + unique, RequestDigest: "fixture-" + unique,
|
||||
OperationID: "op-" + unique, TargetSnapshotID: snapshot, Actor: "fixture",
|
||||
}, governance.SyncStages(), now)
|
||||
if err != nil {
|
||||
t.Fatalf("create fixture job: %v", err)
|
||||
}
|
||||
if reused {
|
||||
t.Fatalf("fixture job unexpectedly reused")
|
||||
}
|
||||
return job
|
||||
}
|
||||
|
||||
type handoffFixture struct {
|
||||
root string
|
||||
remoteArchive string
|
||||
staging string
|
||||
archiveRoot string
|
||||
tenant uint64
|
||||
kb string
|
||||
handoff *libraryhandoff.Handoff
|
||||
}
|
||||
|
||||
func newHandoffFixture(t *testing.T) handoffFixture {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
remoteArchive := filepath.Join(root, "remote-archive")
|
||||
staging := filepath.Join(root, "remote-staging")
|
||||
bundles := filepath.Join(root, "bundles")
|
||||
localArchive := filepath.Join(root, "local-archive")
|
||||
for _, dir := range []string{remoteArchive, staging, bundles, localArchive} {
|
||||
if err := os.MkdirAll(dir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
binary := os.Getenv("KG_TEST_LIBRARYCTL")
|
||||
if binary == "" {
|
||||
t.Skip("KG_TEST_LIBRARYCTL 未设置:搬运链测试需要真实 libraryctl 二进制")
|
||||
}
|
||||
t.Setenv("LIBRARY_HANDOFF_LIBRARYCTL", binary)
|
||||
handoff, err := libraryhandoff.New(libraryhandoff.Config{
|
||||
Transport: libraryhandoff.TransportLocal, LocalRoot: root, LocalArchive: localArchive,
|
||||
ExecutorContainer: "fixture-executor", BundleDir: bundles, RemoteArchive: remoteArchive,
|
||||
StagingDir: filepath.Join(root, "staging"), MaxBundleBytes: 8 << 20, OpTimeout: time.Minute,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return handoffFixture{root: root, remoteArchive: remoteArchive, staging: staging,
|
||||
archiveRoot: localArchive, tenant: 10000, kb: "kb-handoff-fixture", handoff: handoff}
|
||||
}
|
||||
|
||||
func (f handoffFixture) unknownSnapshotID() string {
|
||||
value := bytes.Repeat([]byte{9}, 32)
|
||||
return hex.EncodeToString(value)
|
||||
}
|
||||
|
||||
// seal 在本机归档里造一份合法的封存快照(身份与 fixture 的 tenant/kb 一致)。
|
||||
func (f handoffFixture) seal(t *testing.T) string {
|
||||
t.Helper()
|
||||
archive, err := librarysnapshot.Open(f.archiveRoot, 256*1024*1024)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer archive.Close()
|
||||
part, err := archive.Put(bytes.NewBufferString("[]"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mapping := sha256.Sum256([]byte("fixture-mapping"))
|
||||
manifest := librarysnapshot.Manifest{
|
||||
Format: librarysnapshot.Format, Scope: "internal", TenantID: f.tenant,
|
||||
KnowledgeBaseID: f.kb, CreatedAt: time.Date(2026, 10, 30, 0, 0, 0, 0, time.UTC),
|
||||
Compatibility: librarysnapshot.Compatibility{
|
||||
WeKnoraVersion: "v0.7.1", SchemaVersion: 74, RetrieverEngine: "elasticsearch_v8",
|
||||
EmbeddingModel: "fixture-model", EmbeddingDimension: 1024,
|
||||
IndexMappingSHA256: hex.EncodeToString(mapping[:]),
|
||||
},
|
||||
}
|
||||
for _, name := range []string{"knowledges", "chunks", "resources", "resource_bindings", "knowledge_tags", "knowledge_tag_relations"} {
|
||||
current := part
|
||||
current.Kind, current.Name = "database", name
|
||||
manifest.Parts = append(manifest.Parts, current)
|
||||
}
|
||||
for _, name := range []string{"wiki_pages", "wiki_folders", "wiki_page_issues", "wiki_log_entries"} {
|
||||
current := part
|
||||
current.Kind, current.Name = "wiki", name
|
||||
manifest.Parts = append(manifest.Parts, current)
|
||||
}
|
||||
index := part
|
||||
index.Kind, index.Name = "index", "chunks"
|
||||
manifest.Parts = append(manifest.Parts, index)
|
||||
id, err := archive.Seal(manifest)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// 保持 encoding/json 参与(payload 结构与 API 一致),避免测试与线上 struct 漂移。
|
||||
var _ = json.Marshal
|
||||
@@ -3,6 +3,7 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
@@ -17,6 +18,7 @@ import (
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/libraryagent"
|
||||
"knowledge-governance/internal/libraryhandoff"
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
@@ -183,6 +185,24 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
return err
|
||||
}
|
||||
if config.LibraryWorkerRole.ExecutesSourceWork() {
|
||||
// 快照搬运(本机 → 云端执行器)与云端版本回传都只有 capture 角色做:
|
||||
// 它持有源归档与 SSH 凭据;release-executor 在云端没有回本机的通道。
|
||||
if handoffConfig, configured, handoffErr := libraryhandoff.FromEnv(getenv); handoffErr != nil {
|
||||
return fmt.Errorf("快照搬运接线无效: %w", handoffErr)
|
||||
} else if configured {
|
||||
if config.LibraryWorkerRole.ExecutesRelease() {
|
||||
return errors.New("快照搬运只能接在 capture 角色上:full 角色同时消费发布作业,会与云端执行器抢同一批作业")
|
||||
}
|
||||
handoff, buildErr := libraryhandoff.New(handoffConfig, nil)
|
||||
if buildErr != nil {
|
||||
return buildErr
|
||||
}
|
||||
registerLibraryHandoffHandlers(handlers, store, config, handoff)
|
||||
go runLibraryArchivePullLoop(ctx, store, handoff, config.LibraryArchiveRoot, handoffConfig.PullInterval,
|
||||
func(err error) { log.Printf("library archive pull: %v", err) })
|
||||
log.Printf("library handoff enabled: executor=%s archive=%s pull_every=%s",
|
||||
handoffConfig.ExecutorContainer, handoffConfig.RemoteArchive, handoffConfig.PullInterval)
|
||||
}
|
||||
if syncErr := configureDirectorySync(pool, getenv, handlers); syncErr != nil {
|
||||
log.Print("QA directory synchronization unavailable; handler was not registered")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user