Files
knowledge-governance/internal/releaseadapter/v071/library_backup_store.go
T
姚章浩 281699a431
build / build (push) Successful in 1m21s
feat(library): 生产整库真实读写/校验/恢复与本机真实服务验收
为什么:生产目标此前是"无条件失败"的占位,编排再完整也不能落地;本轮把它做成真实实现,
并在本机 WeKnora 测试栈的真实 PG/ES 上跑通导入、撤销、预备份与故障恢复。

- ProductionLibraryTarget:Current 读行数+身份摘要;Apply 按阶段真实写入(database/wiki
  同事务先删本库再插、resources 传对象、index 搬运原始文档与向量);Verify 比对身份摘要;
  Restore 按预备份快照回放。
- 撤销真正生效:索引阶段写入后 PruneScope 删除快照里没有的文档。
- ProductionBackupStore:导出前独立完整预备份,导出前后行数不一致即失败。
- worker 用注入配置装配目标与预备份;缺项把变量名写进阶段并失败,不再有占位对象。
- capacity 安全加法防溢出;保留策略组合语义明确(各维度都超限才候选)。
- 新增本机真实服务集成测试(一次性 kg_library_test_* 库 + 随机 ES 索引),
  覆盖导入/校验/撤销/预备份/故障注入/恢复。
2026-10-28 15:54:01 +08:00

132 lines
5.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package v071
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"knowledge-governance/internal/libraryrelease"
"knowledge-governance/internal/librarysnapshot"
)
// ProductionBackupStore 在生产写入前创建**独立完整预备份**:从生产读一次整库
// (PG RepeatableRead + ES 导出一致快照 + 资源对象),密封成归档里的一个版本。
//
// 为什么要有静默检查:预备份期间生产若仍在变,导出的 PG/ES/对象就不是同一个切点,
// 恢复它等于恢复到"没人见过的状态"。所以导出前后各读一次行数,不一致就失败,
// 让作业重试,而不是拿一个不一致的备份当恢复点。
type ProductionBackupStore struct {
pool *pgxpool.Pool
search *SearchExporter
objects ObjectReader
archiveRoot string
scope string
identity PostgresIdentity
compatibility librarysnapshot.Compatibility
maxDocuments int
maxObjectByte int64
now func() time.Time
}
type ProductionBackupConfig struct {
Pool *pgxpool.Pool
Search *SearchExporter
Objects ObjectReader
ArchiveRoot string
Scope string
Identity PostgresIdentity
Compatibility librarysnapshot.Compatibility
MaxDocuments int
MaxObjectByte int64
Now func() time.Time
}
func NewProductionBackupStore(config ProductionBackupConfig) (*ProductionBackupStore, error) {
if config.Pool == nil || config.Search == nil || config.Objects == nil || config.ArchiveRoot == "" ||
(config.Scope != "internal" && config.Scope != "external") || config.Identity.TenantID == 0 ||
!validSearchIdentifier(config.Identity.KnowledgeBaseID) || config.MaxDocuments < 1 {
return nil, errors.New("生产预备份配置不完整")
}
if config.MaxObjectByte <= 0 {
config.MaxObjectByte = 256 * 1024 * 1024
}
now := config.Now
if now == nil {
now = time.Now
}
return &ProductionBackupStore{pool: config.Pool, search: config.Search, objects: config.Objects,
archiveRoot: config.ArchiveRoot, scope: config.Scope, identity: config.Identity,
compatibility: config.Compatibility, maxDocuments: config.MaxDocuments,
maxObjectByte: config.MaxObjectByte, now: now}, nil
}
func (s *ProductionBackupStore) Prepare(ctx context.Context, _ string, current libraryrelease.CurrentState) (libraryrelease.BackupRef, error) {
archive, err := librarysnapshot.Open(s.archiveRoot, 256*1024*1024)
if err != nil {
return libraryrelease.BackupRef{}, errors.New("归档不可用,无法创建预备份")
}
defer archive.Close()
createdAt := s.now().UTC()
pg, err := ExportLibrary(ctx, s.pool, s.identity)
if err != nil {
return libraryrelease.BackupRef{}, fmt.Errorf("读取生产整库失败: %w", err)
}
// 整库导出用 ExportLibrary(按租户+知识库,不带单文档身份),
// 与封存路径复用同一份实现,避免两套范围规则。
es, err := s.search.ExportLibrary(ctx, SearchIdentity{TenantID: s.identity.TenantID,
KnowledgeBaseID: s.identity.KnowledgeBaseID}, s.maxDocuments)
if err != nil {
return libraryrelease.BackupRef{}, fmt.Errorf("读取生产索引失败: %w", err)
}
if es.MappingSHA256 != s.compatibility.IndexMappingSHA256 {
// 契约不符说明生产换了索引映射:此时备份出来的东西无法用同一套恢复,
// 宁可失败也不产出"看起来完整"的预备份。
return libraryrelease.BackupRef{}, errors.New("生产索引映射与归档契约不一致")
}
// ArchiveLibraryCandidate 自己按 resources 行读取对象字节并计算摘要,
// 所以这里直接给它生产对象读取器,不再重复导出一次资源。
snapshotID, err := ArchiveLibraryCandidate(ctx, archive, s.scope, s.identity, s.compatibility, pg, es, s.objects, createdAt)
if err != nil {
return libraryrelease.BackupRef{}, fmt.Errorf("密封预备份失败: %w", err)
}
// 静默检查:导出期间生产不能有变化,否则这份预备份不是一致切点。
after, err := s.rowCounts(ctx)
if err != nil {
return libraryrelease.BackupRef{}, err
}
for table, want := range current.Counts {
if table == "index" {
continue
}
if after[table] != want {
return libraryrelease.BackupRef{}, fmt.Errorf("预备份期间生产 %s 行数从 %d 变为 %d,切点不一致", table, want, after[table])
}
}
manifest, err := archive.Load(snapshotID)
if err != nil {
return libraryrelease.BackupRef{}, errors.New("预备份封存后无法校验")
}
var total int64
for _, part := range manifest.Parts {
total += part.Bytes
}
return libraryrelease.BackupRef{ID: "backup-" + snapshotID, SnapshotID: snapshotID, Bytes: total,
CreatedAt: createdAt}, nil
}
func (s *ProductionBackupStore) rowCounts(ctx context.Context) (map[string]int64, error) {
counts := map[string]int64{}
for _, table := range productionLibraryTables {
var count int64
if err := s.pool.QueryRow(ctx, fmt.Sprintf(`SELECT count(*) FROM %s WHERE %s`,
table, scopeWhere(table)), s.identity.TenantID, s.identity.KnowledgeBaseID).Scan(&count); err != nil {
return nil, fmt.Errorf("读取生产 %s 行数失败", table)
}
counts[table] = count
}
return counts, nil
}