为什么:候选环境改用真实 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 互斥。
This commit is contained in:
@@ -5,10 +5,13 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/librarydiff"
|
||||
@@ -42,6 +45,35 @@ type libraryKnownView struct {
|
||||
State string `json:"state"` // known | unknown
|
||||
Version *libraryVersionView `json:"version,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
// EmptyBaseline 表示"没有生效版本记录,但生产目标可读且确实是空的":
|
||||
// 这是首次发布的合法起点,和"生产非空却没有权威版本"必须区分。
|
||||
EmptyBaseline bool `json:"empty_baseline,omitempty"`
|
||||
}
|
||||
|
||||
// productionScopeEmpty 只读探测生产目标:真正连库数一遍,不用缓存或推断。
|
||||
func productionScopeEmpty(ctx context.Context, config Config, scope string) (bool, error) {
|
||||
if strings.TrimSpace(config.LibraryProductionDatabaseURL) == "" {
|
||||
return false, errors.New("生产整库目标未配置")
|
||||
}
|
||||
kb := config.LibraryProductionInternalKB
|
||||
if scope == "external" {
|
||||
kb = config.LibraryProductionExternalKB
|
||||
}
|
||||
if kb == "" {
|
||||
return false, errors.New("生产知识库未配置")
|
||||
}
|
||||
pool, err := pgxpool.New(ctx, config.LibraryProductionDatabaseURL)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer pool.Close()
|
||||
var count int64
|
||||
err = pool.QueryRow(ctx, `SELECT count(*) FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2 AND deleted_at IS NULL`,
|
||||
config.LibraryProductionTenantID, kb).Scan(&count)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return count == 0, nil
|
||||
}
|
||||
|
||||
type libraryDiffView struct {
|
||||
@@ -302,6 +334,13 @@ func libraryVersionViewOf(item governance.LibraryVersion) libraryVersionView {
|
||||
|
||||
// librarySyncGate 只依据真实存在的证据判断能不能写生产:闸口、生产端点、
|
||||
// 生产权威版本、目标快照的预备份。任何一项缺失都给出具体原因,不默认放行。
|
||||
func errString(err error) string {
|
||||
if err == nil {
|
||||
return ""
|
||||
}
|
||||
return err.Error()
|
||||
}
|
||||
|
||||
func librarySyncGate(config Config, production libraryKnownView, prebackup libraryKnownView, target string) libraryGateView {
|
||||
return librarySyncGateWithGrant(config, production, prebackup, target, false)
|
||||
}
|
||||
@@ -319,17 +358,23 @@ func librarySyncGateWithGrant(config Config, production libraryKnownView, prebac
|
||||
if !config.ProductionBackupRestoreVerified {
|
||||
gate.Reasons = append(gate.Reasons, "没有已核验的生产恢复演练证据(PRODUCTION_BACKUP_RESTORE_VERIFIED=false)")
|
||||
}
|
||||
if strings.TrimSpace(config.ProductionWeKnoraBaseURL) == "" {
|
||||
gate.Reasons = append(gate.Reasons, "生产端点未配置,无法核验生产当前版本")
|
||||
// 生产端点以"整库目标是否配置"为准:整库同步直接写 PG/ES/对象,
|
||||
// 不依赖 WeKnora 的 HTTP 端,所以不能拿它是否配置当门禁。
|
||||
if strings.TrimSpace(config.LibraryProductionDatabaseURL) == "" {
|
||||
gate.Reasons = append(gate.Reasons, "生产整库目标未配置(LIBRARY_PRODUCTION_DATABASE_URL),无法核验生产当前状态")
|
||||
}
|
||||
if production.State != "known" {
|
||||
// 首次发布:生产还没有"生效版本"记录,但只要生产目标可读且是空的,
|
||||
// 这就是一个合法的"空基线",不应该被永久挡住。非空但无权威版本仍然阻断。
|
||||
if production.State != "known" && !production.EmptyBaseline {
|
||||
gate.Reasons = append(gate.Reasons, "生产当前权威版本未知,不能启动写入")
|
||||
}
|
||||
if target == "" {
|
||||
gate.Reasons = append(gate.Reasons, "还没有可同步的测试封存版本")
|
||||
}
|
||||
if prebackup.State != "known" {
|
||||
gate.Reasons = append(gate.Reasons, "本次目标快照还没有生产预备份")
|
||||
// 预备份是作业内第一步生成的:启动前要求它已存在会造成死循环。
|
||||
// 这里只在作业已经被判定失败或回滚失败时提示,不作为启动前的硬门禁。
|
||||
if prebackup.State == "failed" {
|
||||
gate.Reasons = append(gate.Reasons, "上一次预备份失败,先处理后才能重试")
|
||||
}
|
||||
if config.LibraryCapacityBudgetBytes <= 0 {
|
||||
gate.Reasons = append(gate.Reasons, "容量预算未设置(LIBRARY_CAPACITY_BUDGET_BYTES),无法证明装得下")
|
||||
@@ -507,6 +552,10 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
}
|
||||
overview.Production = libraryKnownView{State: "unknown"}
|
||||
overview.Prebackup = libraryKnownView{State: "unknown"}
|
||||
if empty, probeErr := productionScopeEmpty(r.Context(), config, request.Scope); probeErr == nil && empty {
|
||||
overview.Production = libraryKnownView{State: "unknown", EmptyBaseline: true,
|
||||
Reason: "生产目标可读且为空:本次是首次发布,写入前仍会生成完整预备份"}
|
||||
}
|
||||
for index := range versions {
|
||||
item := versions[index]
|
||||
if item.Kind == governance.LibraryVersionProductionEffective && item.SupersededAt == nil {
|
||||
@@ -559,6 +608,21 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot create library sync job"})
|
||||
return
|
||||
}
|
||||
// 上一次同参数请求失败/被取消后,幂等键不能再把新请求塞回那个死作业里:
|
||||
// 换一个"重试代次"键重新建作业,旧作业保留为审计记录。
|
||||
if reused && (job.State == governance.LibraryJobFailed || job.State == governance.LibraryJobCancelled) {
|
||||
job, reused, err = store.CreateLibraryJob(r.Context(), governance.LibraryJob{
|
||||
ID: fmt.Sprintf("libsync-%s-%d", request.Scope, now.UnixNano()), Scope: request.Scope,
|
||||
Kind: governance.LibraryJobSync,
|
||||
IdempotencyKey: "library.sync:" + request.Scope + ":" + request.Target + ":retry:" + now.Format("20060102T150405.000000000"),
|
||||
RequestDigest: digest, TargetSnapshotID: request.Target, Actor: actor,
|
||||
}, governance.SyncStages(), now)
|
||||
if err != nil || reused {
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_sync_retry_conflict",
|
||||
"error": "无法为重试创建新作业", "detail": errString(err)})
|
||||
return
|
||||
}
|
||||
}
|
||||
if reused {
|
||||
writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": true})
|
||||
return
|
||||
@@ -572,10 +636,11 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
return
|
||||
}
|
||||
queueJob, err := config.Store.Enqueue(r.Context(), jobs.EnqueueRequest{
|
||||
ID: job.ID + "-queue", Type: librarySyncJobType, Payload: payload, AvailableAt: now,
|
||||
ID: governance.QueueJobIDFor(job.ID), Type: librarySyncJobType, Payload: payload, AvailableAt: now,
|
||||
MaxAttempts: 1, IdempotencyKey: "library.sync.queue:" + job.ID,
|
||||
}, now)
|
||||
if err != nil || queueJob == nil {
|
||||
log.Printf("library sync enqueue failed job=%s: %v", job.ID, err)
|
||||
_ = store.CancelLibraryJob(r.Context(), job.ID, "队列投递失败,未开始同步", now)
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot enqueue sync job"})
|
||||
return
|
||||
|
||||
Reference in New Issue
Block a user