ac3b395102
build / build (push) Successful in 1m21s
为什么:候选环境改用真实 WeKnora 表结构后,暴露出多处"按猜的列名/形状"的假设, 以及若干 varchar 长度、对象定位符、空索引基线问题,导致真实链路跑不通。 - knowledge_tag_relations 无 tenant_id/KB 列 → 归属走父表;resources 作用域=绑定+chunk 引用。 - 写入顺序按真实外键;无代理键表用内容摘要核对。 - 队列作业 ID / 版本记录 ID 改固定长度摘要(列宽 varchar(36)/varchar(64))。 - 对象定位符拆 storage://<backend>/oss://<bucket>/<key>;provider 可配置。 - 空索引基线全链路一致(Current/Export/Backup/Archive),非空仍严格比对映射。 - finalize 阶段:版本登记失败不报成功;崩溃接管复用已持久化预备份。 - 迁移 000069:同一目标的 sync/restore 跨 kind 互斥。
613 lines
21 KiB
Go
613 lines
21 KiB
Go
package v071
|
||
|
||
import (
|
||
"bytes"
|
||
"context"
|
||
"crypto/sha256"
|
||
"encoding/hex"
|
||
"encoding/json"
|
||
"errors"
|
||
"fmt"
|
||
"io"
|
||
"net/http"
|
||
"sort"
|
||
"strings"
|
||
"time"
|
||
|
||
"github.com/jackc/pgx/v5"
|
||
"github.com/jackc/pgx/v5/pgxpool"
|
||
|
||
"knowledge-governance/internal/libraryrelease"
|
||
"knowledge-governance/internal/librarysnapshot"
|
||
)
|
||
|
||
// 生产整库目标:真实读、真实写、真实校验、真实恢复。
|
||
//
|
||
// 只覆盖知识域(文档/分块/标签/资源绑定/Wiki/资源对象/检索索引),不写 users、
|
||
// sessions、api_keys 这类账号与会话表;索引直接搬运归档里的原始文档与向量,
|
||
// 不重新解析、不重新 Embedding。连接全部来自注入配置,代码里不存生产凭据。
|
||
|
||
var ErrProductionTargetUnconfigured = errors.New("生产整库目标未配置(需要生产数据库、索引、对象存储与知识库映射)")
|
||
|
||
// ProductionScope 是一个目标库在生产侧的身份。
|
||
type ProductionScope struct {
|
||
TenantID uint64
|
||
KnowledgeBaseID string
|
||
}
|
||
|
||
type ProductionLibraryConfig struct {
|
||
// Postgres 是生产 WeKnora 的数据库连接串(部署注入,不落代码/日志)。
|
||
Postgres string
|
||
// SearchURL 是生产 Elasticsearch 基址;SearchIndex 是知识域索引名。
|
||
SearchURL string
|
||
SearchIndex string
|
||
SearchToken string
|
||
// Objects 负责写入资源对象(既有 ObjectStore 接口);ObjectsReader 负责
|
||
// 备份时读回对象字节。同一个 S3 存储通常两者都实现。
|
||
Objects ObjectStore
|
||
ObjectsReader ObjectReader
|
||
ArchiveRoot string
|
||
MaxDocuments int
|
||
HTTPClient *http.Client
|
||
Now func() time.Time
|
||
}
|
||
|
||
func (config ProductionLibraryConfig) validate(scope ProductionScope) error {
|
||
if config.Postgres == "" || config.SearchURL == "" || config.SearchIndex == "" ||
|
||
config.Objects == nil || config.ObjectsReader == nil || config.ArchiveRoot == "" || config.MaxDocuments < 1 {
|
||
return ErrProductionTargetUnconfigured
|
||
}
|
||
if scope.TenantID == 0 || !validSearchIdentifier(scope.KnowledgeBaseID) {
|
||
return fmt.Errorf("%w:缺少目标知识库身份", ErrProductionTargetUnconfigured)
|
||
}
|
||
return nil
|
||
}
|
||
|
||
// 依赖顺序:插入按正序,删除按倒序。
|
||
// 真实 Schema 有外键(resource_bindings.resource_id → resources.id),
|
||
// 所以父表 resources 必须排在子表 resource_bindings 之前。
|
||
var productionLibraryTables = []string{
|
||
"knowledges", "chunks", "knowledge_tags", "knowledge_tag_relations",
|
||
"resources", "resource_bindings", "wiki_folders", "wiki_pages",
|
||
"wiki_page_issues", "wiki_log_entries",
|
||
}
|
||
|
||
type ProductionLibraryTarget struct {
|
||
pool *pgxpool.Pool
|
||
config ProductionLibraryConfig
|
||
scope ProductionScope
|
||
search *SearchExporter
|
||
now func() time.Time
|
||
}
|
||
|
||
func NewProductionLibraryTarget(ctx context.Context, config ProductionLibraryConfig, scope ProductionScope) (*ProductionLibraryTarget, error) {
|
||
if err := config.validate(scope); err != nil {
|
||
return nil, err
|
||
}
|
||
pool, err := pgxpool.New(ctx, config.Postgres)
|
||
if err != nil {
|
||
// 连接串本身不打印,错误里也只说明连不上。
|
||
return nil, errors.New("生产数据库连接失败")
|
||
}
|
||
client := config.HTTPClient
|
||
if client == nil {
|
||
client = &http.Client{Timeout: 2 * time.Minute}
|
||
}
|
||
search, err := NewSearchExporter(SearchExporterConfig{BaseURL: config.SearchURL, Index: config.SearchIndex,
|
||
AuthorizationToken: config.SearchToken, PageSize: 500, HTTPClient: client})
|
||
if err != nil {
|
||
pool.Close()
|
||
return nil, err
|
||
}
|
||
now := config.Now
|
||
if now == nil {
|
||
now = time.Now
|
||
}
|
||
return &ProductionLibraryTarget{pool: pool, config: config, scope: scope, search: search, now: now}, nil
|
||
}
|
||
|
||
func (t *ProductionLibraryTarget) Close() { t.pool.Close() }
|
||
|
||
// Pool/Search/Identity 暴露给预备份存储复用同一套生产连接,避免重复开连接池。
|
||
func (t *ProductionLibraryTarget) Pool() *pgxpool.Pool { return t.pool }
|
||
|
||
func (t *ProductionLibraryTarget) Search() *SearchExporter { return t.search }
|
||
|
||
func (t *ProductionLibraryTarget) Objects() ObjectReader { return t.config.ObjectsReader }
|
||
|
||
func (t *ProductionLibraryTarget) Identity() PostgresIdentity {
|
||
return PostgresIdentity{TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID}
|
||
}
|
||
|
||
// Current 读生产当前整库指纹:每张表的 (行数, 身份集合摘要) + 索引条数。
|
||
func (t *ProductionLibraryTarget) Current(ctx context.Context) (libraryrelease.CurrentState, error) {
|
||
state := libraryrelease.CurrentState{Counts: map[string]int64{}, Digests: map[string]string{},
|
||
CapturedAt: t.now().UTC()}
|
||
for _, table := range productionLibraryTables {
|
||
count, digest, err := t.tableState(ctx, table)
|
||
if err != nil {
|
||
return libraryrelease.CurrentState{}, err
|
||
}
|
||
state.Counts[table] = count
|
||
state.Digests[table] = digest
|
||
}
|
||
indexCount, err := t.search.Count(ctx, SearchIdentity{TenantID: t.scope.TenantID,
|
||
KnowledgeBaseID: t.scope.KnowledgeBaseID})
|
||
if errors.Is(err, errIndexMissing) {
|
||
// 生产索引不存在 = 空基线(零文档);不是故障,但也不会被当成"有内容"。
|
||
indexCount = 0
|
||
} else if err != nil {
|
||
return libraryrelease.CurrentState{}, err
|
||
}
|
||
state.Counts["index"] = indexCount
|
||
return state, nil
|
||
}
|
||
|
||
// scopeWhere 返回"这张表里属于本知识库的行"的过滤条件($1=tenant,$2=kb)。
|
||
// 不同表的归属列不同:关系表与绑定表没有 knowledge_base_id,必须走父表判定,
|
||
// 否则要么删错、要么把别的知识库数据算进来。
|
||
func scopeWhere(table string) string {
|
||
switch table {
|
||
case "knowledge_tag_relations":
|
||
// 真实 WeKnora 的这张表只有 knowledge_id/tag_id/created_at,
|
||
// 没有 tenant_id/knowledge_base_id:归属只能走父表 knowledges 判定。
|
||
return `knowledge_id IN (SELECT id FROM knowledges k
|
||
WHERE k.tenant_id=$1 AND k.knowledge_base_id=$2)`
|
||
case "resource_bindings":
|
||
return `tenant_id=$1 AND ((owner_type='knowledge' AND owner_id IN (SELECT id FROM knowledges k
|
||
WHERE k.tenant_id=$1 AND k.knowledge_base_id=$2)) OR (owner_type='chunk' AND owner_id IN
|
||
(SELECT id FROM chunks c WHERE c.tenant_id=$1 AND c.knowledge_base_id=$2)))`
|
||
case "resources":
|
||
// 必须把外层 resources.id 与绑定关系精确关联:只按 owner_id 判断会命中整张
|
||
// 资源表;同时要覆盖 chunk 绑定(图片/附件常只挂在分块上)并限制绑定租户。
|
||
// 两种归属都要算:显式绑定(knowledge/chunk)+ 被本库 chunk 正文以
|
||
// resource://<handle> 引用(图片/附件常见,可能没有绑定行)。
|
||
// 与归档侧收集资源部件的规则保持一致,否则校验会把导入的资源算成"多余"。
|
||
return `(EXISTS (
|
||
SELECT 1 FROM resource_bindings b
|
||
JOIN knowledges k ON k.id=b.owner_id AND k.tenant_id=b.tenant_id
|
||
WHERE b.resource_id=resources.id AND b.tenant_id=$1 AND b.owner_type='knowledge' AND k.knowledge_base_id=$2
|
||
UNION ALL
|
||
SELECT 1 FROM resource_bindings b
|
||
JOIN chunks c ON c.id=b.owner_id AND c.tenant_id=b.tenant_id
|
||
WHERE b.resource_id=resources.id AND b.tenant_id=$1 AND b.owner_type='chunk' AND c.knowledge_base_id=$2)
|
||
OR EXISTS (
|
||
SELECT 1 FROM chunks c
|
||
WHERE c.tenant_id=$1 AND c.knowledge_base_id=$2 AND c.deleted_at IS NULL
|
||
AND coalesce(resources.handle,'') <> ''
|
||
AND position('resource://'||resources.handle IN coalesce(c.content,'')) > 0))`
|
||
default:
|
||
return "tenant_id=$1 AND knowledge_base_id=$2"
|
||
}
|
||
}
|
||
|
||
// errMissingIdentity 表示归档里的这张表没有代理主键,只能靠内容摘要核对。
|
||
var errMissingIdentity = errors.New("missing stable identity")
|
||
|
||
// identityExpr 是"稳定身份"列:多数表就是 id,关系表没有 id 就用复合键。
|
||
func identityExpr(table string) string {
|
||
if table == "knowledge_tag_relations" {
|
||
return "knowledge_id||':'||tag_id"
|
||
}
|
||
return "id"
|
||
}
|
||
|
||
func (t *ProductionLibraryTarget) tableState(ctx context.Context, table string) (int64, string, error) {
|
||
rows, err := t.pool.Query(ctx, fmt.Sprintf(`SELECT %s FROM %s WHERE %s ORDER BY 1`,
|
||
identityExpr(table), table, scopeWhere(table)), t.scope.TenantID, t.scope.KnowledgeBaseID)
|
||
if err != nil {
|
||
return 0, "", fmt.Errorf("读取生产 %s 失败", table)
|
||
}
|
||
defer rows.Close()
|
||
ids := make([]string, 0, 64)
|
||
for rows.Next() {
|
||
var id string
|
||
if err := rows.Scan(&id); err != nil {
|
||
return 0, "", err
|
||
}
|
||
ids = append(ids, id)
|
||
}
|
||
if err := rows.Err(); err != nil {
|
||
return 0, "", err
|
||
}
|
||
return int64(len(ids)), digestIDs(ids), nil
|
||
}
|
||
|
||
func digestIDs(ids []string) string {
|
||
sum := sha256.Sum256([]byte(strings.Join(ids, "\n")))
|
||
return hex.EncodeToString(sum[:])
|
||
}
|
||
|
||
// Apply 把一类数据从归档写进生产;database 与 wiki 走同一个知识域事务。
|
||
func (t *ProductionLibraryTarget) Apply(ctx context.Context, stage libraryrelease.Stage, snapshotID string) error {
|
||
archive, err := librarysnapshot.Open(t.config.ArchiveRoot, 256*1024*1024)
|
||
if err != nil {
|
||
return errors.New("归档不可用")
|
||
}
|
||
defer archive.Close()
|
||
manifest, err := archive.Load(snapshotID)
|
||
if err != nil {
|
||
return errors.New("预发布快照不可读")
|
||
}
|
||
switch stage {
|
||
case libraryrelease.StageDatabase, libraryrelease.StageWiki:
|
||
kind := "database"
|
||
if stage == libraryrelease.StageWiki {
|
||
kind = "wiki"
|
||
}
|
||
return t.importRows(ctx, archive, manifest, kind)
|
||
case libraryrelease.StageResources:
|
||
return t.importResources(ctx, archive, manifest)
|
||
case libraryrelease.StageIndex:
|
||
return t.importIndex(ctx, archive, manifest)
|
||
default:
|
||
return fmt.Errorf("未知阶段 %q", stage)
|
||
}
|
||
}
|
||
|
||
func (t *ProductionLibraryTarget) importRows(ctx context.Context, archive *librarysnapshot.Archive, manifest librarysnapshot.Manifest, kind string) error {
|
||
parts := map[string]librarysnapshot.Part{}
|
||
for _, part := range manifest.Parts {
|
||
if part.Kind == kind {
|
||
parts[part.Name] = part
|
||
}
|
||
}
|
||
if len(parts) == 0 {
|
||
return fmt.Errorf("快照缺少 %s 部件", kind)
|
||
}
|
||
tx, err := t.pool.BeginTx(ctx, pgx.TxOptions{})
|
||
if err != nil {
|
||
return errors.New("开启生产事务失败")
|
||
}
|
||
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
|
||
for index := len(productionLibraryTables) - 1; index >= 0; index-- {
|
||
table := productionLibraryTables[index]
|
||
if _, ok := parts[table]; !ok {
|
||
continue
|
||
}
|
||
if err := t.deleteScope(ctx, tx, table); err != nil {
|
||
return err
|
||
}
|
||
}
|
||
for _, table := range productionLibraryTables {
|
||
part, ok := parts[table]
|
||
if !ok {
|
||
continue
|
||
}
|
||
if err := t.insertRows(ctx, tx, archive, part, table); err != nil {
|
||
return err
|
||
}
|
||
}
|
||
if err := tx.Commit(ctx); err != nil {
|
||
return errors.New("提交生产写入失败")
|
||
}
|
||
return nil
|
||
}
|
||
|
||
func (t *ProductionLibraryTarget) deleteScope(ctx context.Context, tx pgx.Tx, table string) error {
|
||
if table == "resources" {
|
||
// 资源可能被多个知识库共享:这里不删,只做插入/更新。
|
||
return nil
|
||
}
|
||
statement := fmt.Sprintf(`DELETE FROM %s WHERE %s`, table, scopeWhere(table))
|
||
if _, err := tx.Exec(ctx, statement, t.scope.TenantID, t.scope.KnowledgeBaseID); err != nil {
|
||
return fmt.Errorf("清理生产 %s 失败", table)
|
||
}
|
||
return nil
|
||
}
|
||
|
||
func (t *ProductionLibraryTarget) insertRows(ctx context.Context, tx pgx.Tx, archive *librarysnapshot.Archive, part librarysnapshot.Part, table string) error {
|
||
reader, err := archive.OpenPart(part)
|
||
if err != nil {
|
||
return fmt.Errorf("读取归档 %s 失败", part.Name)
|
||
}
|
||
defer reader.Close()
|
||
decoder := json.NewDecoder(reader)
|
||
token, err := decoder.Token()
|
||
if err != nil || token != json.Delim('[') {
|
||
return fmt.Errorf("归档 %s 不是行数组", part.Name)
|
||
}
|
||
var columns []string
|
||
statement := ""
|
||
for decoder.More() {
|
||
var row map[string]json.RawMessage
|
||
if err := decoder.Decode(&row); err != nil {
|
||
return fmt.Errorf("解析归档 %s 行失败", part.Name)
|
||
}
|
||
if len(row) == 0 {
|
||
continue
|
||
}
|
||
if columns == nil {
|
||
columns = make([]string, 0, len(row))
|
||
for key := range row {
|
||
columns = append(columns, key)
|
||
}
|
||
sort.Strings(columns)
|
||
// 本库行先删后插:除 resources(可能被多个知识库共享)外不需要 upsert。
|
||
if table == "resources" {
|
||
statement = fmt.Sprintf(`INSERT INTO %s SELECT * FROM jsonb_populate_record(NULL::%s, $1::jsonb)
|
||
ON CONFLICT (id) DO UPDATE SET %s`, table, table, updateAssignments(columns))
|
||
} else {
|
||
statement = fmt.Sprintf(`INSERT INTO %s SELECT * FROM jsonb_populate_record(NULL::%s, $1::jsonb)`,
|
||
table, table)
|
||
}
|
||
}
|
||
encoded, err := json.Marshal(row)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
if _, err := tx.Exec(ctx, statement, encoded); err != nil {
|
||
return fmt.Errorf("写入生产 %s 失败: %w", table, err)
|
||
}
|
||
}
|
||
return nil
|
||
}
|
||
|
||
func updateAssignments(columns []string) string {
|
||
assignments := make([]string, 0, len(columns))
|
||
for _, column := range columns {
|
||
if column == "id" {
|
||
continue
|
||
}
|
||
assignments = append(assignments, fmt.Sprintf("%s=EXCLUDED.%s", column, column))
|
||
}
|
||
if len(assignments) == 0 {
|
||
return "id=EXCLUDED.id"
|
||
}
|
||
return strings.Join(assignments, ", ")
|
||
}
|
||
|
||
// resourceLocation 是资源对象在生产存储里的位置与提供方(oss / s3 / minio…)。
|
||
type resourceLocation struct {
|
||
Path string
|
||
Provider string
|
||
}
|
||
|
||
func (t *ProductionLibraryTarget) importResources(ctx context.Context, archive *librarysnapshot.Archive, manifest librarysnapshot.Manifest) error {
|
||
paths, err := t.resourcePaths(ctx, resourcePartNames(manifest))
|
||
if err != nil {
|
||
return err
|
||
}
|
||
for _, part := range manifest.Parts {
|
||
if part.Kind != "resource" {
|
||
continue
|
||
}
|
||
location, ok := paths[part.Name]
|
||
if !ok || location.Path == "" {
|
||
return fmt.Errorf("生产缺少资源 %s 的存储路径", part.Name)
|
||
}
|
||
reader, err := archive.OpenPart(part)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
body, err := io.ReadAll(io.LimitReader(reader, part.Bytes+1))
|
||
reader.Close()
|
||
if err != nil || int64(len(body)) != part.Bytes {
|
||
return fmt.Errorf("资源 %s 字节与归档摘要不符", part.Name)
|
||
}
|
||
if err := t.config.Objects.Put(ctx, location.Provider, location.Path, bytes.NewReader(body), int64(len(body))); err != nil {
|
||
return fmt.Errorf("上传资源 %s 失败: %w", part.Name, err)
|
||
}
|
||
}
|
||
return nil
|
||
}
|
||
|
||
// verifyObjects 逐个比对生产对象的实际字节摘要与归档摘要:
|
||
// 只有"对象真的在、内容一致"才算通过,防止对象丢失或损坏被行数掩盖。
|
||
func (t *ProductionLibraryTarget) verifyObjects(ctx context.Context, archive *librarysnapshot.Archive, manifest librarysnapshot.Manifest) error {
|
||
paths, err := t.resourcePaths(ctx, resourcePartNames(manifest))
|
||
if err != nil {
|
||
return err
|
||
}
|
||
for _, part := range manifest.Parts {
|
||
if part.Kind != "resource" {
|
||
continue
|
||
}
|
||
location, ok := paths[part.Name]
|
||
if !ok || location.Path == "" {
|
||
return fmt.Errorf("生产缺少资源 %s", part.Name)
|
||
}
|
||
reader, err := t.config.ObjectsReader.Open(ctx, location.Provider, location.Path)
|
||
if err != nil {
|
||
return fmt.Errorf("读取生产资源 %s 失败: %w", part.Name, err)
|
||
}
|
||
hash := sha256.New()
|
||
size, err := io.Copy(hash, io.LimitReader(reader, part.Bytes+1))
|
||
reader.Close()
|
||
if err != nil {
|
||
return fmt.Errorf("读取生产资源 %s 失败", part.Name)
|
||
}
|
||
if size != part.Bytes || hex.EncodeToString(hash.Sum(nil)) != part.SHA256 {
|
||
return fmt.Errorf("生产资源 %s 与归档摘要不一致(%d 字节)", part.Name, size)
|
||
}
|
||
}
|
||
return nil
|
||
}
|
||
|
||
func resourcePartNames(manifest librarysnapshot.Manifest) []string {
|
||
names := make([]string, 0, 16)
|
||
for _, part := range manifest.Parts {
|
||
if part.Kind == "resource" {
|
||
names = append(names, part.Name)
|
||
}
|
||
}
|
||
return names
|
||
}
|
||
|
||
// resourcePaths 只在"本次要写的这些资源 ID"里解析路径,并且强制租户。
|
||
// 不按绑定范围扫全表:被 chunk 正文以 resource:// 引用的资源可能没有绑定行,
|
||
// 但它是这份快照的一部分;反过来按绑定扫会漏掉它们,按全表扫会读到别的库。
|
||
func (t *ProductionLibraryTarget) resourcePaths(ctx context.Context, ids []string) (map[string]resourceLocation, error) {
|
||
if len(ids) == 0 {
|
||
return map[string]resourceLocation{}, nil
|
||
}
|
||
rows, err := t.pool.Query(ctx, `SELECT id, coalesce(physical_path,''), coalesce(provider,'') FROM resources
|
||
WHERE tenant_id=$1 AND id = ANY($2::text[])`, t.scope.TenantID, ids)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("读取生产资源路径失败: %w", err)
|
||
}
|
||
defer rows.Close()
|
||
paths := map[string]resourceLocation{}
|
||
for rows.Next() {
|
||
var id, path, provider string
|
||
if err := rows.Scan(&id, &path, &provider); err != nil {
|
||
return nil, err
|
||
}
|
||
paths[id] = resourceLocation{Path: path, Provider: provider}
|
||
}
|
||
return paths, rows.Err()
|
||
}
|
||
|
||
func (t *ProductionLibraryTarget) importIndex(ctx context.Context, archive *librarysnapshot.Archive, manifest librarysnapshot.Manifest) error {
|
||
for _, part := range manifest.Parts {
|
||
if part.Kind != "index" {
|
||
continue
|
||
}
|
||
if part.Count > int64(t.config.MaxDocuments) {
|
||
return fmt.Errorf("索引条数 %d 超过上限 %d", part.Count, t.config.MaxDocuments)
|
||
}
|
||
reader, err := archive.OpenPart(part)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
documents, err := librarysnapshot.ReadIndexDocuments(reader)
|
||
reader.Close()
|
||
if err != nil {
|
||
return err
|
||
}
|
||
// 直接搬运原始文档与向量:不解析、不重新 Embedding。
|
||
identity := SearchIdentity{TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID}
|
||
if err := t.search.BulkIndex(ctx, documents, identity); err != nil {
|
||
return err
|
||
}
|
||
// 快照里没有的文档必须从生产索引删掉,否则撤销只在数据库生效。
|
||
keep := make([]string, 0, len(documents))
|
||
for _, document := range documents {
|
||
keep = append(keep, document.ID)
|
||
}
|
||
if _, err := t.search.PruneScope(ctx, identity, keep); err != nil {
|
||
return err
|
||
}
|
||
}
|
||
return nil
|
||
}
|
||
|
||
// Verify 用行数 + 身份集合摘要 + 索引条数核对生产与预发布快照是否一致。
|
||
func (t *ProductionLibraryTarget) Verify(ctx context.Context, expect libraryrelease.Expectation) error {
|
||
archive, err := librarysnapshot.Open(t.config.ArchiveRoot, 256*1024*1024)
|
||
if err != nil {
|
||
return errors.New("归档不可用")
|
||
}
|
||
defer archive.Close()
|
||
manifest, err := archive.Load(expect.SnapshotID)
|
||
if err != nil {
|
||
return errors.New("预发布快照不可读")
|
||
}
|
||
for _, part := range manifest.Parts {
|
||
if part.Kind != "database" && part.Kind != "wiki" {
|
||
continue
|
||
}
|
||
wantCount, wantDigest, err := archivedTableState(archive, part)
|
||
if errors.Is(err, errMissingIdentity) {
|
||
// 个别表(例如日志表)没有代理主键:身份集合无从比,但行数与逐行内容摘要仍然必须一致。
|
||
wantContentCount, wantContentDigest, columns, contentErr := archivedTableContent(archive, part)
|
||
if contentErr != nil {
|
||
return contentErr
|
||
}
|
||
contentCount, contentDigest, contentErr := t.productionTableContent(ctx, part.Name, columns)
|
||
if contentErr != nil {
|
||
return contentErr
|
||
}
|
||
if contentCount != wantContentCount || contentDigest != wantContentDigest {
|
||
return fmt.Errorf("生产 %s 内容与快照不一致:%d 行", part.Name, contentCount)
|
||
}
|
||
continue
|
||
}
|
||
if err != nil {
|
||
return err
|
||
}
|
||
count, digest, err := t.tableState(ctx, part.Name)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
if count != wantCount || digest != wantDigest {
|
||
return fmt.Errorf("生产 %s 与快照不一致:行数 %d/%d", part.Name, count, wantCount)
|
||
}
|
||
// 行数/身份一致还要比内容:同 ID 改正文、改 Wiki、改向量必须被发现。
|
||
wantContentCount, wantContentDigest, columns, err := archivedTableContent(archive, part)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
contentCount, contentDigest, err := t.productionTableContent(ctx, part.Name, columns)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
if contentCount != wantContentCount || contentDigest != wantContentDigest {
|
||
return fmt.Errorf("生产 %s 内容与快照不一致:%d 行 / 摘要不一致", part.Name, contentCount)
|
||
}
|
||
}
|
||
if err := t.verifyIndexDigest(ctx, archive, manifest); err != nil {
|
||
return err
|
||
}
|
||
if err := t.verifyObjects(ctx, archive, manifest); err != nil {
|
||
return err
|
||
}
|
||
return nil
|
||
}
|
||
|
||
func archivedTableState(archive *librarysnapshot.Archive, part librarysnapshot.Part) (int64, string, error) {
|
||
reader, err := archive.OpenPart(part)
|
||
if err != nil {
|
||
return 0, "", err
|
||
}
|
||
defer reader.Close()
|
||
decoder := json.NewDecoder(reader)
|
||
token, err := decoder.Token()
|
||
if err != nil || token != json.Delim('[') {
|
||
return 0, "", errors.New("归档部件不是行数组")
|
||
}
|
||
ids := make([]string, 0, 64)
|
||
for decoder.More() {
|
||
var row map[string]json.RawMessage
|
||
if err := decoder.Decode(&row); err != nil {
|
||
return 0, "", err
|
||
}
|
||
identity := archiveRowIdentity(part.Name, row)
|
||
if identity == "" {
|
||
return 0, "", errMissingIdentity
|
||
}
|
||
ids = append(ids, identity)
|
||
}
|
||
sort.Strings(ids)
|
||
return int64(len(ids)), digestIDs(ids), nil
|
||
}
|
||
|
||
func archiveRowIdentity(table string, row map[string]json.RawMessage) string {
|
||
value := func(key string) string {
|
||
var text string
|
||
_ = json.Unmarshal(row[key], &text)
|
||
return text
|
||
}
|
||
if table == "knowledge_tag_relations" {
|
||
knowledge, tag := value("knowledge_id"), value("tag_id")
|
||
if knowledge == "" || tag == "" {
|
||
return ""
|
||
}
|
||
return knowledge + ":" + tag
|
||
}
|
||
return value("id")
|
||
}
|
||
|
||
// Restore 用预备份把生产整库恢复回去:走同一条 Apply 路径,可重复执行。
|
||
func (t *ProductionLibraryTarget) Restore(ctx context.Context, backup libraryrelease.BackupRef) error {
|
||
if backup.SnapshotID == "" {
|
||
return errors.New("恢复需要绑定的预备份快照")
|
||
}
|
||
for _, stage := range libraryrelease.Stages() {
|
||
if err := t.Apply(ctx, stage, backup.SnapshotID); err != nil {
|
||
return fmt.Errorf("恢复阶段 %s 失败: %w", stage, err)
|
||
}
|
||
}
|
||
return nil
|
||
}
|