feat(library): 首次发布接上目标权威基线与整库空判定
目标非空又没有生效版本时,首次发布以前只能停在"权威版本未知"。现在有了 真实入口:管理员发起 baseline 作业,worker 在维护隔离下把目标整库捕获成 归档快照,再用同一套 Verify 证明目标与快照逐类一致,最后登记 production_effective(证据写明 origin=target_baseline、快照 ID、逐表行数、 目标索引映射)。不写目标内容、不清空目标、不手写版本。 同时修两处会误导人的判定: - productionScopeEmpty 原来只数 knowledges,"文档删了但分块/Wiki/资源还在" 的目标会被当成空库;改用适配层同一份表清单与范围过滤逐表计数。 - 概览里的"测试封存候选"原来取该 scope 最新一份归档,而归档里还有生产 预备份与目标基线快照;改为只认版本登记里 kind=test_sealed 的那一份。 迁移 075 放开 kind='baseline' 并把它并入 sync/restore 的写互斥索引; worker 重启时用同一作业 id 接管未完成的基线窗口。维护接口补 capability, 页面才能区分"未运行维护"与"维护能力没接线"。 验证:go build ./... / go vet ./... 通过;新增用例覆盖管理员校验、已有生效 版本拒绝、目标读不到时零作业零版本、候选来自登记、缺项文案指向基线入口、 capability 逐项缺失;反向自检(把候选改回按最新归档取、把文案改回旧句、 去掉管理员判断)三项均按预期变红后复原。
This commit is contained in:
@@ -0,0 +1,150 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
// 建立目标权威基线:首次发布时目标已经有内容,却没有生效版本记录。
|
||||
//
|
||||
// 唯一诚实的解法是"维护隔离 + 真实整库捕获 + 逐类校验 + 登记版本":
|
||||
// - 不手写 production_effective,不伪造验收;
|
||||
// - 不清空目标换库绕过(那会把"非空但未知"变成"空");
|
||||
// - 页面只投递作业,停写入者、捕获、校验都在 worker 里执行。
|
||||
//
|
||||
// 这个入口只建作业,不签发发布授权:基线不等于发布,同步仍然要单独的 sync 授权。
|
||||
const libraryBaselineJobType = "library.baseline"
|
||||
|
||||
type libraryBaselineRequest struct {
|
||||
Scope string `json:"scope"`
|
||||
}
|
||||
|
||||
func libraryBaselineEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if r.Method != http.MethodPost {
|
||||
writeJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"})
|
||||
return
|
||||
}
|
||||
identity, ok := sessionFrom(r.Context())
|
||||
if !ok || roleRank(identity.Role) < roleRank(roleAdmin) {
|
||||
writeJSON(w, http.StatusForbidden, map[string]any{"error": "建立目标权威基线仅管理员可发起"})
|
||||
return
|
||||
}
|
||||
var request libraryBaselineRequest
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&request); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid request body"})
|
||||
return
|
||||
}
|
||||
if request.Scope != "internal" && request.Scope != "external" {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "scope must be internal or external"})
|
||||
return
|
||||
}
|
||||
store, ok := libraryStore(config)
|
||||
if !ok {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"code": "library_baseline_unavailable",
|
||||
"error": "版本登记存储不可用"})
|
||||
return
|
||||
}
|
||||
versions, err := store.LibraryVersions(r.Context(), request.Scope, 50)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read library versions"})
|
||||
return
|
||||
}
|
||||
for _, item := range versions {
|
||||
if item.Kind == governance.LibraryVersionProductionEffective && item.SupersededAt == nil {
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_baseline_exists",
|
||||
"error": "该目标已有生效版本,不需要再建基线;换版本请走同步或恢复",
|
||||
"snapshot_id": item.SnapshotID})
|
||||
return
|
||||
}
|
||||
}
|
||||
// 目标必须真的读得到:读不到就不是"非空无权威版本",而是另一个问题,
|
||||
// 不允许用建基线去掩盖连接/配置故障。
|
||||
empty, counts, probeErr := productionScopeState(r.Context(), config, request.Scope)
|
||||
if probeErr != nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"code": "library_baseline_unprobeable",
|
||||
"error": "无法读取目标整库状态,不能建立基线:" + probeErr.Error()})
|
||||
return
|
||||
}
|
||||
if empty {
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_baseline_target_empty",
|
||||
"error": "目标整库为空,不需要基线:首次同步会在写入前生成完整预备份并登记生效版本",
|
||||
"counts": counts})
|
||||
return
|
||||
}
|
||||
// 维护互斥与同步一致:基线要在目标上开维护窗口,目标正在维护时直接拒绝。
|
||||
if body, held := instanceMaintenanceGuard(r.Context(), config, request.Scope); held {
|
||||
writeJSON(w, http.StatusConflict, body)
|
||||
return
|
||||
}
|
||||
if maintenanceStore, ok := config.Store.(interface {
|
||||
LibraryMaintenanceOf(ctx context.Context, scope string) (*postgresstore.LibraryMaintenance, error)
|
||||
}); ok {
|
||||
if held, err := maintenanceStore.LibraryMaintenanceOf(r.Context(), request.Scope); err == nil && held != nil && held.ReleasedAt == nil {
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_target_in_maintenance",
|
||||
"error": "目标正在维护中,验证完成前不接受新的写入请求",
|
||||
"owner_job": held.OwnerJobID, "state": held.State})
|
||||
return
|
||||
}
|
||||
}
|
||||
digest, err := governance.LibraryRequestDigest(request.Scope, governance.LibraryJobBaseline,
|
||||
map[string]any{"scope": request.Scope})
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot digest request"})
|
||||
return
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
job, reused, err := store.CreateLibraryJob(r.Context(), governance.LibraryJob{
|
||||
ID: fmt.Sprintf("libbase-%s-%d", request.Scope, now.UnixNano()), Scope: request.Scope,
|
||||
Kind: governance.LibraryJobBaseline,
|
||||
IdempotencyKey: "library.baseline:" + request.Scope + ":" + now.Format("20060102T150405.000000000"),
|
||||
RequestDigest: digest, Actor: identity.Username,
|
||||
}, governance.BaselineStages(), now)
|
||||
if errors.Is(err, governance.ErrLibraryJobActive) {
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_write_active",
|
||||
"error": "该目标已有在飞的写作业(同步/恢复/基线互斥),等它结束再发起"})
|
||||
return
|
||||
}
|
||||
if errors.Is(err, governance.ErrLibraryJobIdempotencyConflict) {
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_baseline_conflict",
|
||||
"error": "同一幂等键对应了不同的请求"})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot create library baseline job"})
|
||||
return
|
||||
}
|
||||
if reused {
|
||||
writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": true})
|
||||
return
|
||||
}
|
||||
payload, err := json.Marshal(map[string]string{"library_job_id": job.ID, "scope": request.Scope})
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot build baseline payload"})
|
||||
return
|
||||
}
|
||||
queueJob, err := config.Store.Enqueue(r.Context(), jobs.EnqueueRequest{
|
||||
ID: governance.QueueJobIDFor(job.ID), Type: libraryBaselineJobType, Payload: payload,
|
||||
AvailableAt: now, MaxAttempts: 1, IdempotencyKey: "library.baseline.queue:" + job.ID,
|
||||
}, now)
|
||||
if err != nil || queueJob == nil {
|
||||
// 作业先落库、队列投递失败就把作业取消:不留下"看起来在跑"的空作业,
|
||||
// 否则它会一直占着该 scope 的写互斥。
|
||||
_ = store.CancelLibraryJob(r.Context(), job.ID, "队列投递失败,未开始建立基线", now)
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot enqueue baseline job"})
|
||||
return
|
||||
}
|
||||
if attachErr := store.AttachLibraryQueueJob(r.Context(), job.ID, queueJob.ID, now); attachErr != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot attach baseline job"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": false,
|
||||
"target_counts": counts})
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
)
|
||||
|
||||
// 建立目标权威基线的入口契约:
|
||||
// - 只有管理员能发起(它是生产侧维护动作);
|
||||
// - 已有生效版本时拒绝(基线只解决首次发布);
|
||||
// - 目标读不到时拒绝,且**不建作业、不登记版本**(不能用基线掩盖连接问题)。
|
||||
|
||||
func baselineRequest(body, role, username string) *http.Request {
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/library/baselines", strings.NewReader(body))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
ctx := context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: username, Role: role})
|
||||
return request.WithContext(ctx)
|
||||
}
|
||||
|
||||
func decodeBody(t *testing.T, recorder *httptest.ResponseRecorder) map[string]any {
|
||||
t.Helper()
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatalf("response is not JSON: %s", recorder.Body.String())
|
||||
}
|
||||
return payload
|
||||
}
|
||||
|
||||
func TestLibraryBaselineRequiresAdmin(t *testing.T) {
|
||||
store := &fakeLibraryStore{}
|
||||
recorder := httptest.NewRecorder()
|
||||
libraryBaselineEnqueue(recorder, baselineRequest(`{"scope":"internal"}`, roleEngineer, "eng"), Config{Store: store})
|
||||
if recorder.Code != http.StatusForbidden {
|
||||
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if store.createN != 0 {
|
||||
t.Fatal("non-admin must not create a baseline job")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryBaselineRefusesWhenEffectiveVersionExists(t *testing.T) {
|
||||
store := &fakeLibraryStore{versions: []governance.LibraryVersion{{
|
||||
ID: "libver-1", Scope: "internal", Kind: governance.LibraryVersionProductionEffective,
|
||||
SnapshotID: "snap-effective", CreatedAt: time.Now().UTC(),
|
||||
}}}
|
||||
recorder := httptest.NewRecorder()
|
||||
libraryBaselineEnqueue(recorder, baselineRequest(`{"scope":"internal"}`, roleAdmin, "admin"), Config{Store: store})
|
||||
if recorder.Code != http.StatusConflict {
|
||||
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if body := decodeBody(t, recorder); body["code"] != "library_baseline_exists" || body["snapshot_id"] != "snap-effective" {
|
||||
t.Fatalf("body=%v", body)
|
||||
}
|
||||
if store.createN != 0 {
|
||||
t.Fatal("existing effective version must not create another baseline job")
|
||||
}
|
||||
}
|
||||
|
||||
// 目标读不到(这里用"没配置目标库"复现):必须 503 并说明原因,
|
||||
// 既不能建作业,也不能顺手写一条版本记录来"解决"未知状态。
|
||||
func TestLibraryBaselineRefusesWhenTargetUnreadable(t *testing.T) {
|
||||
store := &fakeLibraryStore{}
|
||||
recorder := httptest.NewRecorder()
|
||||
libraryBaselineEnqueue(recorder, baselineRequest(`{"scope":"external"}`, roleAdmin, "admin"), Config{Store: store})
|
||||
if recorder.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
body := decodeBody(t, recorder)
|
||||
if body["code"] != "library_baseline_unprobeable" || !strings.Contains(func() string {
|
||||
text, _ := body["error"].(string)
|
||||
return text
|
||||
}(), "无法读取目标整库状态") {
|
||||
t.Fatalf("body=%v", body)
|
||||
}
|
||||
if store.createN != 0 {
|
||||
t.Fatal("unreadable target must not create a baseline job")
|
||||
}
|
||||
if len(store.versions) != 0 {
|
||||
t.Fatal("unreadable target must not record any version")
|
||||
}
|
||||
}
|
||||
|
||||
// 测试候选只认登记过 test_sealed 的那份快照:归档里同时存在更新的目标基线/
|
||||
// 预备份快照时,绝不能把它们当成"拟发布的测试版本"。
|
||||
func TestTestSealedCandidateComesFromRegistryNotNewestArchiveEntry(t *testing.T) {
|
||||
sealed := librarySnapshotView{SnapshotID: "snap-sealed", CreatedAt: time.Date(2026, 10, 29, 8, 54, 0, 0, time.UTC)}
|
||||
prebackup := librarySnapshotView{SnapshotID: "snap-prebackup", CreatedAt: time.Date(2026, 10, 29, 9, 30, 0, 0, time.UTC)}
|
||||
byID := map[string]librarySnapshotView{sealed.SnapshotID: sealed, prebackup.SnapshotID: prebackup}
|
||||
versions := []governance.LibraryVersion{
|
||||
{Kind: governance.LibraryVersionProductionPrebackup, SnapshotID: "snap-prebackup"},
|
||||
{Kind: governance.LibraryVersionTestSealed, SnapshotID: "snap-sealed"},
|
||||
}
|
||||
candidate, reason := testSealedOf(versions, byID)
|
||||
if reason != "" {
|
||||
t.Fatalf("reason=%q", reason)
|
||||
}
|
||||
if candidate == nil || candidate.SnapshotID != "snap-sealed" {
|
||||
t.Fatalf("candidate=%v, want the registered test seal", candidate)
|
||||
}
|
||||
|
||||
// 没有任何 test_sealed 登记:宁可说"还没有测试封存",也不拿别的快照顶替。
|
||||
none, reason := testSealedOf([]governance.LibraryVersion{
|
||||
{Kind: governance.LibraryVersionProductionPrebackup, SnapshotID: "snap-prebackup"},
|
||||
}, byID)
|
||||
if none != nil || !strings.Contains(reason, "还没有该目标的测试封存") {
|
||||
t.Fatalf("candidate=%v reason=%q", none, reason)
|
||||
}
|
||||
|
||||
// 登记过但它已经不在本机归档:说清是归档问题,不给候选。
|
||||
missing, reason := testSealedOf([]governance.LibraryVersion{
|
||||
{Kind: governance.LibraryVersionTestSealed, SnapshotID: "snap-gone"},
|
||||
}, byID)
|
||||
if missing != nil || !strings.Contains(reason, "不在本机归档里") {
|
||||
t.Fatalf("candidate=%v reason=%q", missing, reason)
|
||||
}
|
||||
}
|
||||
|
||||
// 非空但无权威版本时,缺项必须指向真实入口,而不是一句"未知"。
|
||||
func TestLibrarySyncGateNamesTheBaselineEntryForNonEmptyTarget(t *testing.T) {
|
||||
gate := librarySyncGateWithGrant(Config{ProductionReleaseRequestsEnabled: true,
|
||||
ProductionBackupRestoreVerified: true, LibraryProductionDatabaseURL: "postgres://prod.invalid/db",
|
||||
LibraryProductionInternalKB: "kb-int", LibraryCapacityBudgetBytes: 1 << 30},
|
||||
libraryKnownView{State: "unknown"}, libraryKnownView{State: "unknown"}, "snap-1", true)
|
||||
if gate.SyncAllowed {
|
||||
t.Fatal("unknown production version must block the sync")
|
||||
}
|
||||
joined := strings.Join(gate.Reasons, "|")
|
||||
if !strings.Contains(joined, "目标非空且没有生效版本记录") || !strings.Contains(joined, "目标权威基线") {
|
||||
t.Fatalf("reasons=%v", gate.Reasons)
|
||||
}
|
||||
}
|
||||
|
||||
// 维护能力是配置事实:配置齐全时必须说"已接线",缺项要列出缺哪个变量。
|
||||
func TestLibraryMaintenanceCapabilityReportsWiringInsteadOfOneVagueSentence(t *testing.T) {
|
||||
wired := libraryMaintenanceCapability(Config{
|
||||
LibraryTargetInstance: "kgseal-app", LibraryTargetProject: "kgseal-weknora",
|
||||
LibraryTargetWriters: []string{"app"}, LibraryTargetIngressURL: "http://kgseal-ingress:18084/health",
|
||||
LibraryTargetIngressService: "ingress", LibraryTargetJournalRoot: "/var/lib/knowledge-governance/journal",
|
||||
LibraryTargetDockerSocket: "/var/run/docker.sock",
|
||||
})
|
||||
if wired["configured"] != true {
|
||||
t.Fatalf("capability=%v", wired)
|
||||
}
|
||||
if wired["instance"] != "kgseal-app" {
|
||||
t.Fatalf("instance=%v", wired["instance"])
|
||||
}
|
||||
broken := libraryMaintenanceCapability(Config{LibraryTargetInstance: "kgseal-app"})
|
||||
if broken["configured"] != false {
|
||||
t.Fatalf("capability=%v", broken)
|
||||
}
|
||||
missing, _ := broken["missing"].([]string)
|
||||
if len(missing) == 0 || !strings.Contains(strings.Join(missing, ","), "LIBRARY_TARGET_WRITERS") {
|
||||
t.Fatalf("missing=%v", broken["missing"])
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
"knowledge-governance/internal/librarydiff"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
v071 "knowledge-governance/internal/releaseadapter/v071"
|
||||
)
|
||||
|
||||
// 整库版本/状态/差异读取契约 + 生产同步的 fail-closed 入口。
|
||||
@@ -56,30 +57,36 @@ type libraryKnownView struct {
|
||||
EmptyBaseline bool `json:"empty_baseline,omitempty"`
|
||||
}
|
||||
|
||||
// productionScopeEmpty 只读探测生产目标:真正连库数一遍,不用缓存或推断。
|
||||
func productionScopeEmpty(ctx context.Context, config Config, scope string) (bool, error) {
|
||||
// productionScopeState 只读探测生产目标:真正连库数一遍,不用缓存或推断。
|
||||
//
|
||||
// "空"必须是整库意义的空:只数 knowledges 会把"文档已删、分块/Wiki/资源还在"
|
||||
// 的目标当成首次发布的空基线,从而绕过基线初始化。所以这里用适配层同一份
|
||||
// 表清单与范围过滤(v071.ScopeContentEmpty),并把逐表行数交回调用方作为证据。
|
||||
func productionScopeState(ctx context.Context, config Config, scope string) (bool, map[string]int64, error) {
|
||||
if strings.TrimSpace(config.LibraryProductionDatabaseURL) == "" {
|
||||
return false, errors.New("生产整库目标未配置")
|
||||
return false, nil, errors.New("生产整库目标未配置")
|
||||
}
|
||||
kb := config.LibraryProductionInternalKB
|
||||
if scope == "external" {
|
||||
kb = config.LibraryProductionExternalKB
|
||||
}
|
||||
if kb == "" {
|
||||
return false, errors.New("生产知识库未配置")
|
||||
return false, nil, errors.New("该范围的目标知识库未配置")
|
||||
}
|
||||
pool, err := pgxpool.New(ctx, config.LibraryProductionDatabaseURL)
|
||||
if err != nil {
|
||||
return false, err
|
||||
return false, nil, 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
|
||||
return v071.ScopeContentEmpty(ctx, pool,
|
||||
v071.ProductionScope{TenantID: config.LibraryProductionTenantID, KnowledgeBaseID: kb})
|
||||
}
|
||||
|
||||
// productionScopeEmpty 保留"只问空不空"的调用形状;逐表行数在需要举证时用
|
||||
// productionScopeState 取。
|
||||
func productionScopeEmpty(ctx context.Context, config Config, scope string) (bool, error) {
|
||||
empty, _, err := productionScopeState(ctx, config, scope)
|
||||
return empty, err
|
||||
}
|
||||
|
||||
type libraryDiffView struct {
|
||||
@@ -508,6 +515,70 @@ func errString(err error) string {
|
||||
return err.Error()
|
||||
}
|
||||
|
||||
// shortSnapshot 只用于给人看的提示:完整摘要留给快照详情,别在原因句里塞 64 位。
|
||||
func shortSnapshot(id string) string {
|
||||
if len(id) <= 12 {
|
||||
return id
|
||||
}
|
||||
return id[:12]
|
||||
}
|
||||
|
||||
// testSealedOf 选"拟发布的测试封存":只有登记过 test_sealed 的那一份才算候选。
|
||||
//
|
||||
// 归档是共享的:生产预备份与目标基线快照同样带着 scope 写进同一个归档根,
|
||||
// 按"这个 scope 最新一份"挑会把目标自己的内容当成测试候选(页面会显示一份
|
||||
// 永远不该被发布的东西)。所以候选来自版本登记,再用归档确认它真的还在本地。
|
||||
func testSealedOf(versions []governance.LibraryVersion, byID map[string]librarySnapshotView) (*librarySnapshotView, string) {
|
||||
for _, item := range versions {
|
||||
if item.Kind != governance.LibraryVersionTestSealed {
|
||||
continue
|
||||
}
|
||||
snapshot, ok := byID[item.SnapshotID]
|
||||
if !ok {
|
||||
return nil, "最近一次测试封存 " + shortSnapshot(item.SnapshotID) + " 不在本机归档里(归档被清理或换了归档根)"
|
||||
}
|
||||
return &snapshot, ""
|
||||
}
|
||||
return nil, "还没有该目标的测试封存"
|
||||
}
|
||||
|
||||
// libraryMaintenanceCapability 用配置事实回答"这台机器上维护是否接线"。
|
||||
// 它刻意只说配置:能停写入者/关入口/证明排空的真实能力在 worker 侧(docker socket、
|
||||
// 闸门、排空文件),API 若声称"能力可用"就是拿配置字符串冒充执行证据。
|
||||
func libraryMaintenanceCapability(config Config) map[string]any {
|
||||
missing := make([]string, 0, 6)
|
||||
if config.LibraryTargetInstance == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_INSTANCE")
|
||||
}
|
||||
if config.LibraryTargetProject == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_PROJECT")
|
||||
}
|
||||
if len(config.LibraryTargetWriters) == 0 {
|
||||
missing = append(missing, "LIBRARY_TARGET_WRITERS")
|
||||
}
|
||||
if config.LibraryTargetIngressURL == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_INGRESS_URL")
|
||||
}
|
||||
if config.LibraryTargetIngressService == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_INGRESS_SERVICE")
|
||||
}
|
||||
if config.LibraryTargetJournalRoot == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_JOURNAL_ROOT")
|
||||
}
|
||||
if config.LibraryTargetDockerSocket == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_DOCKER_SOCKET")
|
||||
}
|
||||
return map[string]any{
|
||||
"configured": len(missing) == 0,
|
||||
"missing": missing,
|
||||
"instance": config.LibraryTargetInstance,
|
||||
"project": config.LibraryTargetProject,
|
||||
"writers": config.LibraryTargetWriters,
|
||||
"ingress_service": config.LibraryTargetIngressService,
|
||||
"note": "配置齐全只说明治理侧接线完整;停写入者、关入口与排空由 worker 在作业内校验并执行",
|
||||
}
|
||||
}
|
||||
|
||||
func librarySyncGate(config Config, production libraryKnownView, prebackup libraryKnownView, target string) libraryGateView {
|
||||
return librarySyncGateWithGrant(config, production, prebackup, target, false)
|
||||
}
|
||||
@@ -531,9 +602,11 @@ func librarySyncGateWithGrant(config Config, production libraryKnownView, prebac
|
||||
gate.Reasons = append(gate.Reasons, "生产整库目标未配置(LIBRARY_PRODUCTION_DATABASE_URL),无法核验生产当前状态")
|
||||
}
|
||||
// 首次发布:生产还没有"生效版本"记录,但只要生产目标可读且是空的,
|
||||
// 这就是一个合法的"空基线",不应该被永久挡住。非空但无权威版本仍然阻断。
|
||||
// 这就是一个合法的"空基线",不应该被永久挡住。非空但无权威版本仍然阻断,
|
||||
// 指向真实可行的入口(在维护隔离下捕获目标整库并校验后登记基线),
|
||||
// 而不是让人去手写版本或清空目标。
|
||||
if production.State != "known" && !production.EmptyBaseline {
|
||||
gate.Reasons = append(gate.Reasons, "生产当前权威版本未知,不能启动写入")
|
||||
gate.Reasons = append(gate.Reasons, "目标非空且没有生效版本记录:先建立目标权威基线(维护隔离下捕获整库并逐类校验),或确认目标确实是空库")
|
||||
}
|
||||
if target == "" {
|
||||
gate.Reasons = append(gate.Reasons, "还没有可同步的测试封存版本")
|
||||
@@ -569,21 +642,20 @@ func libraryOverviewHandler(w http.ResponseWriter, r *http.Request, config Confi
|
||||
// 可发起封存 = worker 真实探测到执行器可用且指向本实例;原因逐条给全。
|
||||
overview.CaptureAvailable, overview.CaptureReason, overview.Executor = libraryExecutorAvailability(r.Context(), config)
|
||||
|
||||
// 测试封存来自归档:它只是测试侧事实。
|
||||
// 测试封存来自归档 + 版本登记:归档里**不止**测试封存——生产预备份与目标基线
|
||||
// 快照同样带 scope,如果只按"这个 scope 最新一份"挑,页面就会把目标自己的内容
|
||||
// 当成拟发布的测试候选。所以候选只认登记过 kind=test_sealed 的那一份。
|
||||
snapshots, snapErr := readLibrarySnapshots(r.Context(), config.LibraryArchiveRoot)
|
||||
byID := map[string]librarySnapshotView{}
|
||||
archiveReadable := false
|
||||
if snapErr != nil {
|
||||
_, overview.TestSealedReason = libraryArchiveErrorStatus(snapErr, "归档不可读")
|
||||
} else if !snapshots.Available {
|
||||
overview.TestSealedReason = snapshots.Reason
|
||||
} else {
|
||||
for index := range snapshots.Snapshots {
|
||||
if snapshots.Snapshots[index].Scope == scope {
|
||||
overview.TestSealed = &snapshots.Snapshots[index]
|
||||
break
|
||||
}
|
||||
}
|
||||
if overview.TestSealed == nil {
|
||||
overview.TestSealedReason = "还没有该目标的测试封存"
|
||||
archiveReadable = true
|
||||
for _, snapshot := range snapshots.Snapshots {
|
||||
byID[snapshot.SnapshotID] = snapshot
|
||||
}
|
||||
}
|
||||
|
||||
@@ -593,6 +665,9 @@ func libraryOverviewHandler(w http.ResponseWriter, r *http.Request, config Confi
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read library versions"})
|
||||
return
|
||||
}
|
||||
if archiveReadable {
|
||||
overview.TestSealed, overview.TestSealedReason = testSealedOf(versions, byID)
|
||||
}
|
||||
overview.Production = libraryKnownView{State: "unknown", Reason: "还没有生产验证通过的生效版本记录"}
|
||||
overview.Prebackup = libraryKnownView{State: "unknown", Reason: "本次目标快照还没有生产预备份"}
|
||||
target := ""
|
||||
|
||||
@@ -148,6 +148,15 @@ type Config struct {
|
||||
// LibraryTargetInstance 是实例级维护的目标实例名;留空即"未接线",
|
||||
// 页面不能发起按预备份恢复,接口返回原因而不是假装能恢复。
|
||||
LibraryTargetInstance string
|
||||
// 维护能力的其余配置项只用于如实展示"是否接线":未运行维护与没有维护能力
|
||||
// 是两件事,页面不能混成一句"未接入"。真正停写入者/关入口的能力由 worker
|
||||
// 在执行作业时校验(socket、入口、排空文件都在 worker 侧)。
|
||||
LibraryTargetProject string
|
||||
LibraryTargetWriters []string
|
||||
LibraryTargetIngressURL string
|
||||
LibraryTargetIngressService string
|
||||
LibraryTargetDockerSocket string
|
||||
LibraryTargetJournalRoot string
|
||||
// LibrarySourceInstance 是死信解除记录的来源实例名(封存源),留空回落到目标实例名。
|
||||
LibrarySourceInstance string
|
||||
// LibraryAgentSocket 是主机侧封存 agent 的 unix socket;留空即页面不能发起封存。
|
||||
@@ -479,6 +488,8 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
return
|
||||
}
|
||||
response := map[string]any{"held": held != nil && held.ReleasedAt == nil, "maintenance": held}
|
||||
// 有没有维护能力是配置事实,和"此刻没有窗口"必须分开回答。
|
||||
response["capability"] = libraryMaintenanceCapability(config)
|
||||
// 实例级占用才是真正的互斥来源:跨 scope 也在这里体现。
|
||||
if instanceStore, ok := config.Store.(interface {
|
||||
InstanceMaintenanceOf(ctx context.Context, instance string) (*postgresstore.LibraryInstanceMaintenance, error)
|
||||
@@ -527,6 +538,10 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
mux.HandleFunc("POST /api/v1/library/syncs", func(w http.ResponseWriter, r *http.Request) {
|
||||
librarySyncEnqueue(w, r, config)
|
||||
})
|
||||
// 首次发布的目标权威基线:管理员在维护隔离下捕获目标整库并校验后登记版本。
|
||||
mux.HandleFunc("POST /api/v1/library/baselines", func(w http.ResponseWriter, r *http.Request) {
|
||||
libraryBaselineEnqueue(w, r, config)
|
||||
})
|
||||
// 全部 main 提交时间线(读本库缓存,不直接打 Gitea)
|
||||
mux.HandleFunc("GET /api/v1/version-history", func(w http.ResponseWriter, r *http.Request) {
|
||||
versionHistoryList(w, r, config)
|
||||
|
||||
Reference in New Issue
Block a user