feat(release): 发布前快照硬门禁 + 云内快照 + ES/OSS 保护

按生产级备份组合落地:

- internal/releasesnapshot:新增门禁包,要求 root 下存在覆盖目标库、未过期
  (默认 24h)、含 wiki_pages.jsonl 与 sha256 的快照;本地文件再校验哈希。
  7 条单测(过期/换库/篡改/缺页/未接线/半成品)。
- 发布器:写目标库之前(Publish/Delete/Rollback 三条路)先过门禁;映射目标
  (源库→目标库,共享真实库)或 policy=always 时必须有快照;门禁未接线
  同样拒绝(fail-closed)。新错误码 release_target_snapshot_missing(不可重试)
  + 页面中文提示。6 条发布器单测。
- worker 配置新增 target_snapshot{root,max_age_hours,policy},校验 policy/
  max_age/绝对路径;compose.release-sim.yaml 只读挂载快照目录。
- scripts/target_kb_snapshot.sh:默认云内执行(与 DB 同 VPC,凭据取自 WeKnora
  容器)+ 默认不导 chunks(44s 出 8 张表);修复 \copy 不能跨行/不能带 WITH、
  ES 计数改用 knowledge_base_id.keyword。
- ES:注册 kb_backup 仓库(path.repo),首个快照 36s/4.7GB/0 分片失败,
  SLM kb-hourly(3d)+kb-daily(7d) 已建并执行成功。
- OSS:目标桶开启版本控制(此前未开启)。
- 文档 P6 增补硬门禁与云内执行;真实快照目录上门禁实测:两个绑定库通过、
  未覆盖库拒绝、未接线拒绝。
This commit is contained in:
姚章浩
2026-10-09 10:59:55 +08:00
parent f4e1ecc5f1
commit 1fa35e9870
14 changed files with 836 additions and 70 deletions
+189
View File
@@ -0,0 +1,189 @@
// Package releasesnapshot 实现"发布前必须有目标知识库快照"的硬门禁。
//
// 背景:发布链本身不做发布前备份(DocumentTarget.Prepare 只归档本包、解析
// previousRevision),而 wiki 通道在共享真实知识库上会覆盖整库页面。留档由
// scripts/target_kb_snapshot.sh 产生(KB 维度只读行级 JSONL + MANIFEST.json),
// 本包只负责在写目标库之前证明"这份现场确实存在且是新的"。
package releasesnapshot
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strings"
"time"
)
const manifestKind = "weknora-target-kb-snapshot"
// ErrNoFreshSnapshot 表示找不到覆盖目标库、且在有效期内的快照。
var ErrNoFreshSnapshot = errors.New("no fresh target knowledge base snapshot")
type manifestFile struct {
File string `json:"file"`
Rows int `json:"rows"`
// Bytes/SHA256 由快照脚本写入;本地文件会再校验一次。
Bytes int64 `json:"bytes"`
SHA256 string `json:"sha256"`
Location string `json:"location"`
}
type manifest struct {
Kind string `json:"kind"`
CreatedAt string `json:"created_at"`
KnowledgeBaseIDs []string `json:"knowledge_base_ids"`
Files []manifestFile `json:"files"`
}
// Guard 在快照根目录下寻找覆盖目标库的有效快照。
type Guard struct {
// Root 是快照根目录(每份快照一个子目录,内含 MANIFEST.json)。
Root string
// MaxAge 是允许的快照最大年龄(0 表示不限制年龄,仅要求存在)。
MaxAge time.Duration
// Now 便于测试注入时间。
Now func() time.Time
// VerifyLocalFiles 为真时校验本地 JSONL 的 sha256("可恢复"的最低证明)。
VerifyLocalFiles bool
}
// Check 要求 Root 下存在一份覆盖 knowledgeBaseID 的快照:类型正确、在有效期内、
// 含 wiki_pages.jsonl 且其 sha256 非空(本地文件再按哈希校验一次)。
// 找到即返回 nil;否则返回包装了 ErrNoFreshSnapshot 的原因。
func (guard Guard) Check(knowledgeBaseID string) error {
if strings.TrimSpace(knowledgeBaseID) == "" {
return fmt.Errorf("%w: 目标知识库为空", ErrNoFreshSnapshot)
}
root := strings.TrimSpace(guard.Root)
if root == "" {
return fmt.Errorf("%w: 未配置快照根目录(RELEASE_SNAPSHOT_ROOT)", ErrNoFreshSnapshot)
}
entries, err := os.ReadDir(root)
if err != nil {
return fmt.Errorf("%w: 读取快照目录失败: %v", ErrNoFreshSnapshot, err)
}
now := guard.now()
names := make([]string, 0, len(entries))
for _, entry := range entries {
if entry.IsDir() {
names = append(names, entry.Name())
}
}
// 目录名以 UTC 时间戳开头(<ts>-<kb前缀>),倒序即从最新开始找。
sort.Sort(sort.Reverse(sort.StringSlice(names)))
var newestProblem error
for _, name := range names {
ok, problem := guard.inspect(filepath.Join(root, name), knowledgeBaseID, now)
if ok {
return nil
}
if problem != nil && newestProblem == nil {
newestProblem = problem
}
}
if newestProblem != nil {
return newestProblem
}
return fmt.Errorf("%w: 未找到覆盖目标库 %s 的快照", ErrNoFreshSnapshot, knowledgeBaseID)
}
func (guard Guard) now() time.Time {
if guard.Now != nil {
return guard.Now().UTC()
}
return time.Now().UTC()
}
// inspect 判断一份快照是否可用;ok=true 表示通过。
func (guard Guard) inspect(directory, knowledgeBaseID string, now time.Time) (bool, error) {
path := filepath.Join(directory, "MANIFEST.json")
payload, err := os.ReadFile(path)
if err != nil {
return false, nil // 目录里没有清单(半成品),跳过
}
var parsed manifest
if err := json.Unmarshal(payload, &parsed); err != nil {
return false, fmt.Errorf("%w: 快照清单无法解析(%s)", ErrNoFreshSnapshot, filepath.Base(directory))
}
if parsed.Kind != manifestKind {
return false, nil
}
covered := false
for _, id := range parsed.KnowledgeBaseIDs {
if id == knowledgeBaseID {
covered = true
break
}
}
if !covered {
return false, nil
}
created, err := parseStamp(parsed.CreatedAt)
if err != nil {
return false, fmt.Errorf("%w: 快照时间戳无法识别(%s)", ErrNoFreshSnapshot, filepath.Base(directory))
}
if guard.MaxAge > 0 && now.Sub(created) > guard.MaxAge {
return false, fmt.Errorf("%w: 最新快照已过期(%s,超过 %s)",
ErrNoFreshSnapshot, created.Format(time.RFC3339), guard.MaxAge)
}
wiki, present := findFile(parsed.Files, "wiki_pages.jsonl")
if !present || wiki.SHA256 == "" {
return false, fmt.Errorf("%w: 快照缺少 wiki_pages.jsonl 或哈希(%s)",
ErrNoFreshSnapshot, filepath.Base(directory))
}
if guard.VerifyLocalFiles {
if err := verifyLocal(directory, wiki); err != nil {
return false, err
}
}
return true, nil
}
// parseStamp 接受脚本写出的 20261009T025017Z,也接受 RFC3339。
func parseStamp(value string) (time.Time, error) {
value = strings.TrimSpace(value)
if created, err := time.Parse("20060102T150405Z", value); err == nil {
return created.UTC(), nil
}
if created, err := time.Parse(time.RFC3339, value); err == nil {
return created.UTC(), nil
}
return time.Time{}, errors.New("unrecognized snapshot timestamp")
}
func findFile(files []manifestFile, name string) (manifestFile, bool) {
for _, file := range files {
if file.File == name {
return file, true
}
}
return manifestFile{}, false
}
// verifyLocal 校验本地 JSONL 的 sha256,作为"这份快照还能用"的最小证明。
// 放在云主机上(location=cloud:...)的文件无法在这里校验,跳过。
func verifyLocal(directory string, file manifestFile) error {
if strings.HasPrefix(file.Location, "cloud:") {
return nil
}
handle, err := os.Open(filepath.Join(directory, file.File))
if err != nil {
return fmt.Errorf("%w: 快照文件不可读(%s)", ErrNoFreshSnapshot, file.File)
}
defer handle.Close()
digest := sha256.New()
if _, err := io.Copy(digest, handle); err != nil {
return fmt.Errorf("%w: 快照文件校验失败(%s)", ErrNoFreshSnapshot, file.File)
}
actual := hex.EncodeToString(digest.Sum(nil))
if actual != file.SHA256 {
return fmt.Errorf("%w: 快照文件哈希不匹配(%s)", ErrNoFreshSnapshot, file.File)
}
return nil
}
+123
View File
@@ -0,0 +1,123 @@
package releasesnapshot
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func writeSnapshot(t *testing.T, root, name, createdAt string, kbIDs []string, wikiContent string, hashOverride string) string {
t.Helper()
directory := filepath.Join(root, name)
if err := os.MkdirAll(directory, 0o755); err != nil {
t.Fatal(err)
}
if wikiContent != "" {
if err := os.WriteFile(filepath.Join(directory, "wiki_pages.jsonl"), []byte(wikiContent), 0o644); err != nil {
t.Fatal(err)
}
}
digest := sha256.Sum256([]byte(wikiContent))
sha := hex.EncodeToString(digest[:])
if hashOverride != "" {
sha = hashOverride
}
files := []map[string]any{}
if wikiContent != "" {
files = append(files, map[string]any{
"file": "wiki_pages.jsonl", "rows": 1, "bytes": len(wikiContent), "sha256": sha, "location": "local",
})
}
manifestPayload, err := json.Marshal(map[string]any{
"kind": manifestKind, "created_at": createdAt, "knowledge_base_ids": kbIDs, "files": files,
})
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(directory, "MANIFEST.json"), manifestPayload, 0o644); err != nil {
t.Fatal(err)
}
return directory
}
func fixedNow() func() time.Time {
return func() time.Time { return time.Date(2026, time.October, 9, 3, 0, 0, 0, time.UTC) }
}
func TestGuardAcceptsFreshSnapshotCoveringTargetKnowledgeBase(t *testing.T) {
root := t.TempDir()
writeSnapshot(t, root, "20261009T025017Z-0b217e8a", "20261009T025017Z", []string{"kb-a", "kb-b"}, "{}\n", "")
guard := Guard{Root: root, MaxAge: 24 * time.Hour, Now: fixedNow(), VerifyLocalFiles: true}
if err := guard.Check("kb-a"); err != nil {
t.Fatalf("fresh snapshot must pass: %v", err)
}
}
// 过期快照不算数:门禁的语义是"发布前刚留过档"。
func TestGuardRejectsExpiredSnapshot(t *testing.T) {
root := t.TempDir()
writeSnapshot(t, root, "20261006T025017Z-0b217e8a", "20261006T025017Z", []string{"kb-a"}, "{}\n", "")
guard := Guard{Root: root, MaxAge: 24 * time.Hour, Now: fixedNow(), VerifyLocalFiles: true}
err := guard.Check("kb-a")
if !errors.Is(err, ErrNoFreshSnapshot) {
t.Fatalf("expired snapshot must be refused, got %v", err)
}
}
// 不覆盖目标库的快照不能用(另一个库的快照救不了这个库)。
func TestGuardRejectsSnapshotOfAnotherKnowledgeBase(t *testing.T) {
root := t.TempDir()
writeSnapshot(t, root, "20261009T025017Z-0b217e8a", "20261009T025017Z", []string{"kb-other"}, "{}\n", "")
guard := Guard{Root: root, Now: fixedNow()}
if err := guard.Check("kb-a"); !errors.Is(err, ErrNoFreshSnapshot) {
t.Fatalf("snapshot of another base must be refused, got %v", err)
}
}
// 关键文件哈希对不上 = 这份快照不可恢复,必须拒绝。
func TestGuardRejectsTamperedSnapshot(t *testing.T) {
root := t.TempDir()
writeSnapshot(t, root, "20261009T025017Z-0b217e8a", "20261009T025017Z", []string{"kb-a"}, "{}\n",
strings.Repeat("0", 64))
guard := Guard{Root: root, Now: fixedNow(), VerifyLocalFiles: true}
if err := guard.Check("kb-a"); !errors.Is(err, ErrNoFreshSnapshot) {
t.Fatalf("tampered snapshot must be refused, got %v", err)
}
}
// 没有 wiki_pages.jsonl 的快照不算"现场留档"。
func TestGuardRejectsSnapshotWithoutWikiPages(t *testing.T) {
root := t.TempDir()
writeSnapshot(t, root, "20261009T025017Z-0b217e8a", "20261009T025017Z", []string{"kb-a"}, "", "")
guard := Guard{Root: root, Now: fixedNow()}
if err := guard.Check("kb-a"); !errors.Is(err, ErrNoFreshSnapshot) {
t.Fatalf("snapshot without wiki pages must be refused, got %v", err)
}
}
// 根目录未配置(门禁未接线)必须拒绝,而不是放行。
func TestGuardFailsClosedWithoutRoot(t *testing.T) {
guard := Guard{Root: "", Now: fixedNow()}
if err := guard.Check("kb-a"); !errors.Is(err, ErrNoFreshSnapshot) {
t.Fatalf("unconfigured guard must fail closed, got %v", err)
}
}
// 半成品目录(清单写了一半/缺失)要被跳过,最新那份可用即可。
func TestGuardSkipsHalfWrittenSnapshotAndPicksNewestValid(t *testing.T) {
root := t.TempDir()
if err := os.MkdirAll(filepath.Join(root, "20261009T030000Z-0b217e8a"), 0o755); err != nil {
t.Fatal(err)
}
writeSnapshot(t, root, "20261009T025017Z-0b217e8a", "20261009T025017Z", []string{"kb-a"}, "{}\n", "")
guard := Guard{Root: root, MaxAge: 24 * time.Hour, Now: fixedNow(), VerifyLocalFiles: true}
if err := guard.Check("kb-a"); err != nil {
t.Fatalf("valid snapshot behind a half-written dir must still pass: %v", err)
}
}
+6 -2
View File
@@ -27,7 +27,10 @@ const (
ErrorCodeRollbackArtifactMissing = "release_rollback_artifact_missing"
ErrorCodeRollbackFailed = "release_rollback_failed"
ErrorCodeStoppedAfterFailure = "release_stopped_after_failure"
ErrorCodeInternal = "release_internal_error"
// ErrorCodeTargetSnapshotMissing:写目标库之前必须存在覆盖该库的、未过期的
// 快照留档(scripts/target_kb_snapshot.sh 产出),否则拒绝发布。
ErrorCodeTargetSnapshotMissing = "release_target_snapshot_missing"
ErrorCodeInternal = "release_internal_error"
)
var (
@@ -305,7 +308,8 @@ func ValidErrorCode(code string) bool {
switch code {
case ErrorCodeContractMismatch, ErrorCodeBundleInvalid, ErrorCodeTargetUnavailable,
ErrorCodeTargetWriteFailed, ErrorCodeVerificationFailed, ErrorCodeRollbackArtifactMissing,
ErrorCodeRollbackFailed, ErrorCodeStoppedAfterFailure, ErrorCodeInternal:
ErrorCodeRollbackFailed, ErrorCodeStoppedAfterFailure, ErrorCodeTargetSnapshotMissing,
ErrorCodeInternal:
return true
default:
return false
@@ -34,13 +34,73 @@ type SidecarTarget interface {
type SidecarPublisher struct {
exporter BundleExporter
target SidecarTarget
// snapshots 是"写目标库前必须存在目标库快照"的门禁;nil 表示未接线。
snapshots TargetSnapshotGuard
snapshotPolicy SnapshotPolicy
}
func NewSidecarPublisher(exporter BundleExporter, target SidecarTarget) (*SidecarPublisher, error) {
// TargetSnapshotGuard 由 internal/releasesnapshot.Guard 实现。
type TargetSnapshotGuard interface {
Check(knowledgeBaseID string) error
}
// SnapshotPolicy 决定门禁对哪些项生效。
type SnapshotPolicy int
const (
// SnapshotPolicyMapped:只对"源库 → 目标库"映射的项强制(共享真实库)。
SnapshotPolicyMapped SnapshotPolicy = iota
// SnapshotPolicyAlways:所有写入目标库的项都要有快照。
SnapshotPolicyAlways
)
// PublisherOption 用于给发布器加装配件(保持既有两参构造的兼容)。
type PublisherOption func(*SidecarPublisher) error
// WithTargetSnapshots 装上快照门禁:写入目标库之前先证明"现场已留档"。
func WithTargetSnapshots(guard TargetSnapshotGuard, policy SnapshotPolicy) PublisherOption {
return func(publisher *SidecarPublisher) error {
if guard == nil {
return errors.New("target snapshot guard is required")
}
publisher.snapshots = guard
publisher.snapshotPolicy = policy
return nil
}
}
func NewSidecarPublisher(exporter BundleExporter, target SidecarTarget, options ...PublisherOption) (*SidecarPublisher, error) {
if exporter == nil || target == nil {
return nil, errors.New("release sidecar dependencies are required")
}
return &SidecarPublisher{exporter: exporter, target: target}, nil
publisher := &SidecarPublisher{exporter: exporter, target: target}
for _, option := range options {
if option == nil {
continue
}
if err := option(publisher); err != nil {
return nil, err
}
}
return publisher, nil
}
// ensureTargetSnapshot 在任何写目标库的动作之前调用:目标库是共享真实库
// (源库 → 目标库 映射)或策略要求"一律"时,必须存在覆盖该库的新快照。
// 门禁未接线(root 未配置)时对这类项**拒绝放行**,而不是跳过校验。
func (publisher *SidecarPublisher) ensureTargetSnapshot(item PlanItem) error {
required := publisher.snapshotPolicy == SnapshotPolicyAlways || item.TargetBase() != item.TestKnowledgeBaseID
if !required {
return nil
}
if publisher.snapshots == nil {
return newSidecarError(ErrorCodeTargetSnapshotMissing, false,
errors.New("发布前快照门禁未配置(release config target_snapshot.root)"))
}
if err := publisher.snapshots.Check(item.TargetBase()); err != nil {
return newSidecarError(ErrorCodeTargetSnapshotMissing, false, err)
}
return nil
}
// releaseItemMapping declares which production base this item must land in: the
@@ -53,6 +113,9 @@ func releaseItemMapping(item PlanItem) releasebundle.KnowledgeBaseMapping {
}
func (publisher *SidecarPublisher) Publish(ctx context.Context, item PlanItem) (ItemResult, error) {
if err := publisher.ensureTargetSnapshot(item); err != nil {
return ItemResult{}, err
}
bundle, err := publisher.exporter.Export(ctx, item)
if err != nil {
return ItemResult{}, newSidecarError(ErrorCodeTargetUnavailable, true, err)
@@ -95,6 +158,9 @@ func (publisher *SidecarPublisher) Publish(ctx context.Context, item PlanItem) (
}
func (publisher *SidecarPublisher) Rollback(ctx context.Context, item PlanItem) (ItemResult, error) {
if err := publisher.ensureTargetSnapshot(item); err != nil {
return ItemResult{}, err
}
if !validRevision(item.PreviousProductionRevision) {
return ItemResult{}, newSidecarError(ErrorCodeRollbackArtifactMissing, false, errors.New("missing rollback revision"))
}
@@ -112,6 +178,9 @@ func (publisher *SidecarPublisher) Rollback(ctx context.Context, item PlanItem)
}
func (publisher *SidecarPublisher) Delete(ctx context.Context, item PlanItem) (ItemResult, error) {
if err := publisher.ensureTargetSnapshot(item); err != nil {
return ItemResult{}, err
}
bundle, err := publisher.exporter.Export(ctx, item)
if err != nil {
return ItemResult{}, newSidecarError(ErrorCodeTargetUnavailable, true, err)
@@ -215,3 +215,148 @@ func testManifest() releasebundle.Manifest {
func testTargetContract() releasebundle.TargetContract {
return releasebundle.TargetContract{WeKnoraVersion: releasebundle.WeKnoraVersionV071, MigrationVersion: releasebundle.WeKnoraMigrationV071, TenantID: 10000, KnowledgeBaseID: "kb-safe", RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "bge-m3", EmbeddingDimension: releasebundle.EmbeddingDimensionV071, ElasticsearchMappingSHA256: strings.Repeat("a", 64)}
}
// --- 发布前快照门禁 ---------------------------------------------------------
type stubSnapshotGuard struct {
checked []string
err error
}
func (guard *stubSnapshotGuard) Check(knowledgeBaseID string) error {
guard.checked = append(guard.checked, knowledgeBaseID)
return guard.err
}
func mappedPlanItem() PlanItem {
item := testPlanItem()
item.TargetKnowledgeBaseID = "kb-production"
return item
}
// 共享真实库(源库 → 目标库 映射)没有快照时必须拒绝,且不得碰目标库。
func TestSidecarPublisherRefusesMappedItemWithoutSnapshot(t *testing.T) {
calls := []string{}
manifest, err := releasebundle.Seal(testManifest())
if err != nil {
t.Fatal(err)
}
exporter := &fakeExporter{manifest: manifest, calls: &calls}
target := &fakeSidecarTarget{contract: testTargetContract(), calls: &calls, prepared: PreparedChange{PreviousRevision: "prod-v0", ProductionRevision: "prod-v1"}}
guard := &stubSnapshotGuard{err: errors.New("no fresh target knowledge base snapshot")}
publisher, err := NewSidecarPublisher(exporter, target, WithTargetSnapshots(guard, SnapshotPolicyMapped))
if err != nil {
t.Fatal(err)
}
_, publishErr := publisher.Publish(context.Background(), mappedPlanItem())
var itemErr *ItemError
if !errors.As(publishErr, &itemErr) || itemErr.Code != ErrorCodeTargetSnapshotMissing {
t.Fatalf("err=%v want code %s", publishErr, ErrorCodeTargetSnapshotMissing)
}
if len(guard.checked) != 1 || guard.checked[0] != "kb-production" {
t.Fatalf("guard must be asked about the production target: %v", guard.checked)
}
if len(calls) != 0 {
t.Fatalf("a refused release must not touch the target: %v", calls)
}
}
// 门禁未接线(target_snapshot.root 未配置)时,映射项也要拒绝——不能静默放行。
func TestSidecarPublisherFailsClosedWhenSnapshotGateUnconfigured(t *testing.T) {
calls := []string{}
manifest, err := releasebundle.Seal(testManifest())
if err != nil {
t.Fatal(err)
}
exporter := &fakeExporter{manifest: manifest, calls: &calls}
target := &fakeSidecarTarget{contract: testTargetContract(), calls: &calls, prepared: PreparedChange{PreviousRevision: "prod-v0", ProductionRevision: "prod-v1"}}
publisher, err := NewSidecarPublisher(exporter, target)
if err != nil {
t.Fatal(err)
}
_, publishErr := publisher.Publish(context.Background(), mappedPlanItem())
var itemErr *ItemError
if !errors.As(publishErr, &itemErr) || itemErr.Code != ErrorCodeTargetSnapshotMissing {
t.Fatalf("err=%v want code %s", publishErr, ErrorCodeTargetSnapshotMissing)
}
if len(calls) != 0 {
t.Fatalf("calls=%v", calls)
}
}
// 同 ID 目标(历史语义 / 本地演练)不需要快照,策略为 mapped 时门禁不介入。
func TestSidecarPublisherSkipsSnapshotGateForSameBaseTarget(t *testing.T) {
calls := []string{}
manifest, err := releasebundle.Seal(testManifest())
if err != nil {
t.Fatal(err)
}
exporter := &fakeExporter{manifest: manifest, calls: &calls}
target := &fakeSidecarTarget{contract: testTargetContract(), calls: &calls, prepared: PreparedChange{PreviousRevision: "prod-v0", ProductionRevision: "prod-v1"}}
guard := &stubSnapshotGuard{err: errors.New("must not be consulted")}
publisher, err := NewSidecarPublisher(exporter, target, WithTargetSnapshots(guard, SnapshotPolicyMapped))
if err != nil {
t.Fatal(err)
}
if _, err := publisher.Publish(context.Background(), testPlanItem()); err != nil {
t.Fatalf("same-base target must publish without a snapshot: %v", err)
}
if len(guard.checked) != 0 {
t.Fatalf("guard must not run for same-base targets: %v", guard.checked)
}
}
// policy=always 时,同 ID 目标同样要求快照。
func TestSidecarPublisherAlwaysPolicyChecksSameBaseTarget(t *testing.T) {
calls := []string{}
manifest, err := releasebundle.Seal(testManifest())
if err != nil {
t.Fatal(err)
}
exporter := &fakeExporter{manifest: manifest, calls: &calls}
target := &fakeSidecarTarget{contract: testTargetContract(), calls: &calls, prepared: PreparedChange{PreviousRevision: "prod-v0", ProductionRevision: "prod-v1"}}
guard := &stubSnapshotGuard{}
publisher, err := NewSidecarPublisher(exporter, target, WithTargetSnapshots(guard, SnapshotPolicyAlways))
if err != nil {
t.Fatal(err)
}
if _, err := publisher.Publish(context.Background(), testPlanItem()); err != nil {
t.Fatal(err)
}
if len(guard.checked) != 1 || guard.checked[0] != "kb-safe" {
t.Fatalf("always policy must check every target: %v", guard.checked)
}
}
// 撤权(delete)与回滚同样先过门禁。
func TestSidecarPublisherGatesDeleteAndRollbackToo(t *testing.T) {
for _, operation := range []string{"delete", "rollback"} {
calls := []string{}
manifest, err := releasebundle.Seal(testManifest())
if err != nil {
t.Fatal(err)
}
exporter := &fakeExporter{manifest: manifest, calls: &calls}
target := &fakeSidecarTarget{contract: testTargetContract(), calls: &calls, prepared: PreparedChange{PreviousRevision: "prod-v0", ProductionRevision: "prod-v1"}}
guard := &stubSnapshotGuard{err: errors.New("stale")}
publisher, err := NewSidecarPublisher(exporter, target, WithTargetSnapshots(guard, SnapshotPolicyMapped))
if err != nil {
t.Fatal(err)
}
item := mappedPlanItem()
item.Action = operation
var publishErr error
if operation == "delete" {
_, publishErr = publisher.Delete(context.Background(), item)
} else {
_, publishErr = publisher.Rollback(context.Background(), item)
}
var itemErr *ItemError
if !errors.As(publishErr, &itemErr) || itemErr.Code != ErrorCodeTargetSnapshotMissing {
t.Fatalf("%s: err=%v want %s", operation, publishErr, ErrorCodeTargetSnapshotMissing)
}
if len(calls) != 0 {
t.Fatalf("%s touched the target: %v", operation, calls)
}
}
}