feat(version-history): 「版本记录」页 —— 追踪远端 main 全部提交(只读 + 管理员手动同步)
build / build (push) Successful in 57s
build / build (push) Successful in 57s
按已确认的契约实现(口径见 docs/VERSION_HISTORY.md):
- **版本号口径(只给有证据的)**:注释 tag + tag 指向该提交 + 该提交内 CHANGELOG 顶部三者一致 ⇒ 正式版本;
tag 之后的提交按 `<主>.<次>.<自该 tag 的提交数>` 显示开发号(与 scripts/version.py **同规则**);
证据不足 ⇒ 「历史提交 · 短SHA」+ 原因码,**不补造版本号**。完整 SHA 是唯一身份、版本号不是唯一键
(tag 之后两条并行分支各自的第 1 个提交都算 0.1.1 ⇒ 两条都保留,用短 SHA 区分)。
- **迁移 000046**:version_history_commits(提交记录,主键 repo_key+commit_sha)+ version_history_sync_runs
(同步状态)。快照 = 一次同步:抓完并与 X-Total-Count 对账通过才切换;失败不切换快照、不清空历史、
last_success_at 不动(页面显示"上次同步失败(原因)· 仍展示上次成功数据");「同步成功」≠「历史完整」。
- **只读客户端(匿名,不使用任何凭据)**:白名单 origin + 固定仓库、拒绝任意 URL 与跨主机重定向、
响应上限 5MB / 超时 15s、仅 5xx/429 退避重试(最多 3 次);逐页抓到短页为止;每次全量扫 tag
⇒ 旧提交后补的 tag 会更新既有记录(不新增第二行)。
- **接口**(三个都登记进 api/openapi.yaml):GET /api/v1/build-info(viewer)、
GET /api/v1/version-history(viewer;游标绑定快照,过期返回 409 cursor_expired;不返回伪造 total)、
POST /api/v1/version-history/sync(admin;并发同步复用同一作业,靠 IdempotencyKey)。
- **「当前运行」只认精确匹配**:产物注入的完整 SHA 命中某条记录才标该条;开发构建显式标注"开发构建";
没有可用标识 ⇒ "当前运行版本未知";**不拿最新 main / 最新 tag 顶替**,CI 成功不等于已部署。
- **前端**:一级菜单第 5 项(版本记录)+ 时间线页面(全部/正式/开发/历史四段筛选、正文展开、
加载更多、760px 单列无横向溢出、提交正文与变更记录按纯文本渲染);无打 tag / 发布 / 部署入口。
新增配置(留空即未接线,页面降级):VERSION_HISTORY_GITEA_BASE_URL / _REPO / _ALLOWED_ORIGINS /
_HTTP_TIMEOUT / _MAX_PAGES。
验证:`make verify` 15/15 success(tests-go 578 通过 / 0 失败;tests-web 209 通过 / 0 失败);
新增 Go 用例 30(版本口径与图遍历 12、客户端守卫 6、同步编排 5、接口 7);前端新增 18(组件 10 + 客户端 8);
真实仓库匿名快照拉取(`VERSION_HISTORY_LIVE_BASE_URL=… go test -run TestLiveSyncAgainstRealRepository`):
抓到 113 条与 X-Total-Count 一致、v0.1.0 是注释 tag 且目标与 `git rev-parse v0.1.0^{commit}` 一致、
开发号逐个等于 `git rev-list --count v0.1.0..<sha>`(正式 1 / 开发 22 / 历史 90)。
This commit is contained in:
@@ -139,6 +139,11 @@ func classifyRole(method, path string) string {
|
||||
if strings.HasPrefix(path, "/api/v1/backup-schedule") && method != http.MethodGet {
|
||||
return roleAdmin
|
||||
}
|
||||
// 版本记录的同步会拉起一次对远端仓库的抓取(消耗网络与数据库写入),
|
||||
// 与"谁能改生产绑定"同级:读任何角色可看,同步只能管理员。
|
||||
if strings.HasPrefix(path, "/api/v1/version-history") && method != http.MethodGet {
|
||||
return roleAdmin
|
||||
}
|
||||
// Everything else that mutates (review, batch, seal, confirm, start, retry,
|
||||
// route visibility, disable) is engineer work; viewers cannot POST at all.
|
||||
return roleEngineer
|
||||
|
||||
@@ -111,6 +111,10 @@ type Config struct {
|
||||
// enumerates the production-side bases the operator can bind.
|
||||
// BackupSchedule 是「系统设置 → 存储与备份」的计划存储;BackupHost 负责在目标库
|
||||
// 所在主机上读回/下发计划并触发一次整库备份(未接线时页面降级展示)。
|
||||
// VersionHistory 是「版本记录」页的只读查询面;VersionHistoryRepo 是固定的仓库标识
|
||||
// (owner/name)。两者都给才接线,否则页面降级为"未接线"(不报 500)。
|
||||
VersionHistory VersionHistoryStore
|
||||
VersionHistoryRepo string
|
||||
BackupSchedule BackupScheduleStore
|
||||
BackupHost BackupHost
|
||||
BackupRuns *BackupRunTracker
|
||||
@@ -318,6 +322,18 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
mux.HandleFunc("GET /api/v1/monitor/overview", func(w http.ResponseWriter, r *http.Request) {
|
||||
monitorOverview(w, r, config.Monitor)
|
||||
})
|
||||
// 「版本记录」:当前运行的构建身份(只读,与监控同级可见)
|
||||
mux.HandleFunc("GET /api/v1/build-info", func(w http.ResponseWriter, r *http.Request) {
|
||||
buildInfo(w, r)
|
||||
})
|
||||
// 全部 main 提交时间线(读本库缓存,不直接打 Gitea)
|
||||
mux.HandleFunc("GET /api/v1/version-history", func(w http.ResponseWriter, r *http.Request) {
|
||||
versionHistoryList(w, r, config)
|
||||
})
|
||||
// 手动同步一次(仅管理员;并发同步合并成同一个作业)
|
||||
mux.HandleFunc("POST /api/v1/version-history/sync", func(w http.ResponseWriter, r *http.Request) {
|
||||
versionHistorySync(w, r, config)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/monitor/knowledge-bases/{id}/files", func(w http.ResponseWriter, r *http.Request) {
|
||||
monitorFiles(w, r, config.Monitor)
|
||||
})
|
||||
|
||||
@@ -1489,16 +1489,19 @@ func TestHandlerRejectsCatalogMutationsWithoutOperationID(t *testing.T) {
|
||||
}
|
||||
|
||||
type fakeJobStore struct {
|
||||
createSettingsConnectionID string
|
||||
createSettingsDraft postgresstore.SourceSettingsDraft
|
||||
createSettingsOperationID string
|
||||
createSettingsErr error
|
||||
createSettingsReplayed bool
|
||||
activateSettingsConnectionID string
|
||||
activateSettingsRevisionID string
|
||||
activateSettingsOperationID string
|
||||
activateSettingsReplayed bool
|
||||
activateSettingsErr error
|
||||
createSettingsConnectionID string
|
||||
createSettingsDraft postgresstore.SourceSettingsDraft
|
||||
createSettingsOperationID string
|
||||
createSettingsErr error
|
||||
createSettingsReplayed bool
|
||||
activateSettingsConnectionID string
|
||||
activateSettingsRevisionID string
|
||||
activateSettingsOperationID string
|
||||
activateSettingsReplayed bool
|
||||
activateSettingsErr error
|
||||
// enqueueEchoRequestedID:幂等"首次入队"语义 —— 返回调用方请求的那个 id
|
||||
// (默认 false 时返回 enqueueResult,即"复用已有任务"的路径)。
|
||||
enqueueEchoRequestedID bool
|
||||
listSettingsConnectionID string
|
||||
listSettingsErr error
|
||||
settingsRevisions []governance.SourceConnectionRevision
|
||||
@@ -1867,6 +1870,9 @@ func (s *fakeJobStore) ActivateUISettingsWithOperation(_ context.Context, revisi
|
||||
|
||||
func (s *fakeJobStore) Enqueue(_ context.Context, request jobs.EnqueueRequest, _ time.Time) (*jobs.Job, error) {
|
||||
s.enqueued = request
|
||||
if s.enqueueEchoRequestedID {
|
||||
return &jobs.Job{ID: request.ID, Type: request.Type, State: jobs.StatePending}, nil
|
||||
}
|
||||
return s.enqueueResult, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/version"
|
||||
"knowledge-governance/internal/versionhistory"
|
||||
)
|
||||
|
||||
// 「版本记录」页的服务面:**只读查询** + 管理员手动同步。
|
||||
//
|
||||
// 设计口径(见 docs/RELEASE_RUNBOOK.md 与 internal/governance/version_history.go):
|
||||
// - 列表只读本库缓存(Gitea 不可达也能看),游标绑定快照 ⇒ 翻页不重不漏;
|
||||
// - 同步只有一个入口,且只允许管理员触发;并发同步合并成同一个作业;
|
||||
// - 「当前运行」只认构建产物注入的**完整 SHA 精确匹配**,拿不到就显示未知。
|
||||
|
||||
// 版本记录的作业类型(worker 侧注册同名 handler;值来自 versionhistory,避免两处写死)。
|
||||
const VersionHistoryJobType = versionhistory.JobType
|
||||
|
||||
const (
|
||||
versionHistoryDefaultPageSize = 30
|
||||
versionHistoryMaxPageSize = 100
|
||||
)
|
||||
|
||||
// VersionHistoryStore 是版本记录页需要的只读查询面(由 postgres.Store 实现)。
|
||||
type VersionHistoryStore interface {
|
||||
ActiveVersionHistorySnapshot(ctx context.Context, repoKey string) (int64, error)
|
||||
LoadVersionHistoryPage(ctx context.Context, repoKey, kind, cursor string, limit int) (
|
||||
[]governance.VersionHistoryCommit, string, bool, int64, error)
|
||||
LoadVersionHistorySyncState(ctx context.Context, repoKey string) (governance.VersionHistorySyncRun, error)
|
||||
VersionHistorySyncInFlight(ctx context.Context, repoKey string, now time.Time) (bool, error)
|
||||
}
|
||||
|
||||
type versionHistoryTag struct {
|
||||
Name string `json:"name"`
|
||||
URL string `json:"url"`
|
||||
}
|
||||
|
||||
type versionHistoryItem struct {
|
||||
CommitSHA string `json:"commit_sha"`
|
||||
ShortSHA string `json:"short_sha"`
|
||||
Parents []string `json:"parents"`
|
||||
CommittedAt string `json:"committed_at"`
|
||||
AuthorDisplay string `json:"author_display"`
|
||||
Subject string `json:"subject"`
|
||||
Body string `json:"body"`
|
||||
RecordKind string `json:"record_kind"`
|
||||
VersionLabel string `json:"version_label"`
|
||||
VersionState string `json:"version_state"`
|
||||
ReleaseTags []versionHistoryTag `json:"release_tags"`
|
||||
ReleaseNotes string `json:"release_notes"`
|
||||
CommitURL string `json:"commit_url"`
|
||||
VersionReason string `json:"version_reason"`
|
||||
CurrentRunning bool `json:"is_current_running"`
|
||||
}
|
||||
|
||||
type versionHistorySyncState struct {
|
||||
Available bool `json:"available"`
|
||||
Status string `json:"status"`
|
||||
Complete bool `json:"complete"`
|
||||
LastSuccessAt string `json:"last_success_at"`
|
||||
FetchedCount int `json:"fetched_count"`
|
||||
ExpectedCount *int `json:"expected_count"`
|
||||
ErrorCode string `json:"error_code"`
|
||||
SourceHeadSHA string `json:"source_head_sha"`
|
||||
ActiveSnapshotID int64 `json:"active_snapshot_id"`
|
||||
Repo string `json:"repo"`
|
||||
}
|
||||
|
||||
type versionHistoryCurrentRunning struct {
|
||||
State string `json:"state"`
|
||||
CommitSHA string `json:"commit_sha"`
|
||||
DisplayVersion string `json:"display_version"`
|
||||
MatchedCommitSHA string `json:"matched_commit_sha"`
|
||||
}
|
||||
|
||||
type versionHistoryResponse struct {
|
||||
Items []versionHistoryItem `json:"items"`
|
||||
NextCursor string `json:"next_cursor"`
|
||||
HasMore bool `json:"has_more"`
|
||||
Sync versionHistorySyncState `json:"sync"`
|
||||
CurrentRunning versionHistoryCurrentRunning `json:"current_running"`
|
||||
}
|
||||
|
||||
func versionHistoryError(w http.ResponseWriter, status int, code, message string) {
|
||||
writeJSON(w, status, map[string]string{"error": message, "code": code})
|
||||
}
|
||||
|
||||
// currentRunning 判定「当前运行」:只在完整 SHA 精确命中时标记,否则明确说未知。
|
||||
func currentRunning(items []governance.VersionHistoryCommit) (versionHistoryCurrentRunning, string) {
|
||||
info := version.Snapshot()
|
||||
if !info.IdentityAvailable || info.CommitSHA == nil {
|
||||
return versionHistoryCurrentRunning{State: "unknown",
|
||||
DisplayVersion: info.DisplayVersion}, ""
|
||||
}
|
||||
sha := *info.CommitSHA
|
||||
for _, item := range items {
|
||||
if item.CommitSHA == sha {
|
||||
return versionHistoryCurrentRunning{State: "matched", CommitSHA: sha,
|
||||
DisplayVersion: info.DisplayVersion, MatchedCommitSHA: sha}, sha
|
||||
}
|
||||
}
|
||||
state := "unknown"
|
||||
if info.BuildKind == "development" {
|
||||
state = "development"
|
||||
}
|
||||
// 开发构建:产物带完整 SHA,但它不在已同步的提交里 ⇒ 说明"当前运行"与页面记录不重合
|
||||
return versionHistoryCurrentRunning{State: state, CommitSHA: sha,
|
||||
DisplayVersion: info.DisplayVersion}, ""
|
||||
}
|
||||
|
||||
func versionHistoryList(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if config.VersionHistory == nil || config.VersionHistoryRepo == "" {
|
||||
writeJSON(w, http.StatusOK, versionHistoryResponse{Items: []versionHistoryItem{},
|
||||
Sync: versionHistorySyncState{Available: false},
|
||||
CurrentRunning: func() versionHistoryCurrentRunning {
|
||||
running, _ := currentRunning(nil)
|
||||
return running
|
||||
}()})
|
||||
return
|
||||
}
|
||||
kind := strings.TrimSpace(r.URL.Query().Get("kind"))
|
||||
if kind == "" {
|
||||
kind = "all"
|
||||
}
|
||||
limit := versionHistoryDefaultPageSize
|
||||
if raw := strings.TrimSpace(r.URL.Query().Get("limit")); raw != "" {
|
||||
parsed, err := strconv.Atoi(raw)
|
||||
if err != nil || parsed <= 0 || parsed > versionHistoryMaxPageSize {
|
||||
versionHistoryError(w, http.StatusBadRequest, "invalid_limit",
|
||||
fmt.Sprintf("limit 必须是 1..%d 的整数", versionHistoryMaxPageSize))
|
||||
return
|
||||
}
|
||||
limit = parsed
|
||||
}
|
||||
cursor := strings.TrimSpace(r.URL.Query().Get("cursor"))
|
||||
|
||||
items, nextCursor, hasMore, _, err := config.VersionHistory.LoadVersionHistoryPage(
|
||||
r.Context(), config.VersionHistoryRepo, kind, cursor, limit)
|
||||
if err != nil {
|
||||
if errors.Is(err, postgresstore.ErrVersionHistoryCursorExpired) {
|
||||
versionHistoryError(w, http.StatusConflict, "cursor_expired",
|
||||
"这次翻页依据的记录快照已被清理,请刷新页面重新加载")
|
||||
return
|
||||
}
|
||||
versionHistoryError(w, http.StatusInternalServerError, "version_history_unavailable", "读取版本记录失败")
|
||||
return
|
||||
}
|
||||
if items == nil {
|
||||
items = []governance.VersionHistoryCommit{}
|
||||
}
|
||||
state, err := config.VersionHistory.LoadVersionHistorySyncState(r.Context(), config.VersionHistoryRepo)
|
||||
if err != nil {
|
||||
versionHistoryError(w, http.StatusInternalServerError, "version_history_unavailable", "读取同步状态失败")
|
||||
return
|
||||
}
|
||||
running, matchedSHA := currentRunning(items)
|
||||
payload := versionHistoryResponse{
|
||||
Items: make([]versionHistoryItem, 0, len(items)),
|
||||
NextCursor: nextCursor, HasMore: hasMore, CurrentRunning: running,
|
||||
Sync: versionHistorySyncState{Available: true, Status: state.Status, Complete: state.Complete,
|
||||
LastSuccessAt: versionHistoryTime(state.LastSuccessAt), FetchedCount: state.FetchedCount,
|
||||
ExpectedCount: state.ExpectedCount, ErrorCode: state.ErrorCode,
|
||||
SourceHeadSHA: state.SourceHeadSHA, ActiveSnapshotID: state.ActiveSnapshotID,
|
||||
Repo: config.VersionHistoryRepo},
|
||||
}
|
||||
for _, item := range items {
|
||||
record := versionHistoryItem{
|
||||
CommitSHA: item.CommitSHA, ShortSHA: shortSHA(item.CommitSHA), Parents: item.Parents,
|
||||
CommittedAt: versionHistoryTime(item.CommittedAt), AuthorDisplay: item.AuthorDisplay,
|
||||
Subject: item.Subject, Body: item.Body, RecordKind: item.RecordKind,
|
||||
VersionLabel: item.VersionLabel, VersionState: item.VersionState,
|
||||
ReleaseNotes: item.ReleaseNotes, CommitURL: item.CommitURL,
|
||||
VersionReason: item.VersionEvidence.Reason,
|
||||
ReleaseTags: make([]versionHistoryTag, 0, len(item.ReleaseTags)),
|
||||
CurrentRunning: matchedSHA != "" && item.CommitSHA == matchedSHA,
|
||||
}
|
||||
for _, tag := range item.ReleaseTags {
|
||||
record.ReleaseTags = append(record.ReleaseTags, versionHistoryTag{Name: tag.Name, URL: tag.URL})
|
||||
}
|
||||
payload.Items = append(payload.Items, record)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, payload)
|
||||
}
|
||||
|
||||
func versionHistorySync(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if config.VersionHistory == nil || config.VersionHistoryRepo == "" {
|
||||
versionHistoryError(w, http.StatusServiceUnavailable, "version_history_unavailable",
|
||||
"版本记录未接线:没有配置只读的仓库来源")
|
||||
return
|
||||
}
|
||||
now := config.Now().UTC()
|
||||
inFlight, err := config.VersionHistory.VersionHistorySyncInFlight(r.Context(), config.VersionHistoryRepo, now)
|
||||
if err != nil {
|
||||
versionHistoryError(w, http.StatusInternalServerError, "version_history_unavailable", "查询同步状态失败")
|
||||
return
|
||||
}
|
||||
if inFlight {
|
||||
state, err := config.VersionHistory.LoadVersionHistorySyncState(r.Context(), config.VersionHistoryRepo)
|
||||
if err != nil {
|
||||
versionHistoryError(w, http.StatusInternalServerError, "version_history_unavailable", "查询同步状态失败")
|
||||
return
|
||||
}
|
||||
// 已经在跑:不重复入队,明确告诉调用方复用现有任务
|
||||
writeJSON(w, http.StatusOK, map[string]any{"job_id": state.JobID, "sync_run_id": state.ID,
|
||||
"status": state.Status, "reused": true})
|
||||
return
|
||||
}
|
||||
triggeredBy := ""
|
||||
if identity, ok := sessionFrom(r.Context()); ok {
|
||||
triggeredBy = identity.Username
|
||||
}
|
||||
payload, err := json.Marshal(map[string]string{"repo_key": config.VersionHistoryRepo, "triggered_by": triggeredBy})
|
||||
if err != nil {
|
||||
versionHistoryError(w, http.StatusInternalServerError, "version_history_unavailable", "构造同步任务失败")
|
||||
return
|
||||
}
|
||||
requestedID := fmt.Sprintf("version-history-sync-%d", now.UnixNano())
|
||||
job, err := config.Store.Enqueue(r.Context(), jobs.EnqueueRequest{ID: requestedID,
|
||||
Type: VersionHistoryJobType, Payload: payload, AvailableAt: now, MaxAttempts: 3,
|
||||
IdempotencyKey: "version-history.sync:" + config.VersionHistoryRepo}, now)
|
||||
if err != nil || job == nil {
|
||||
versionHistoryError(w, http.StatusInternalServerError, "version_history_unavailable", "入队同步任务失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusAccepted, map[string]any{"job_id": job.ID, "status": job.State,
|
||||
"reused": job.ID != requestedID})
|
||||
}
|
||||
|
||||
// buildInfo:当前运行产物的构建身份(只读;与监控接口同级可见)。
|
||||
func buildInfo(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, http.StatusOK, version.Snapshot())
|
||||
}
|
||||
|
||||
func versionHistoryTime(value time.Time) string {
|
||||
if value.IsZero() {
|
||||
return ""
|
||||
}
|
||||
return value.UTC().Format(time.RFC3339)
|
||||
}
|
||||
|
||||
func shortSHA(sha string) string {
|
||||
if len(sha) > 12 {
|
||||
return sha[:12]
|
||||
}
|
||||
return sha
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/version"
|
||||
)
|
||||
|
||||
type fakeVersionHistoryStore struct {
|
||||
items []governance.VersionHistoryCommit
|
||||
nextCursor string
|
||||
hasMore bool
|
||||
snapshot int64
|
||||
pageErr error
|
||||
state governance.VersionHistorySyncRun
|
||||
stateErr error
|
||||
inFlight bool
|
||||
inFlightErr error
|
||||
lastKind string
|
||||
lastCursor string
|
||||
lastLimit int
|
||||
}
|
||||
|
||||
func (f *fakeVersionHistoryStore) ActiveVersionHistorySnapshot(context.Context, string) (int64, error) {
|
||||
return f.snapshot, nil
|
||||
}
|
||||
|
||||
func (f *fakeVersionHistoryStore) LoadVersionHistoryPage(_ context.Context, _, kind, cursor string, limit int) (
|
||||
[]governance.VersionHistoryCommit, string, bool, int64, error) {
|
||||
f.lastKind, f.lastCursor, f.lastLimit = kind, cursor, limit
|
||||
if f.pageErr != nil {
|
||||
return nil, "", false, f.snapshot, f.pageErr
|
||||
}
|
||||
return f.items, f.nextCursor, f.hasMore, f.snapshot, nil
|
||||
}
|
||||
|
||||
func (f *fakeVersionHistoryStore) LoadVersionHistorySyncState(context.Context, string) (governance.VersionHistorySyncRun, error) {
|
||||
return f.state, f.stateErr
|
||||
}
|
||||
|
||||
func (f *fakeVersionHistoryStore) VersionHistorySyncInFlight(context.Context, string, time.Time) (bool, error) {
|
||||
return f.inFlight, f.inFlightErr
|
||||
}
|
||||
|
||||
func decodeVersionHistoryBody(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("响应不是 JSON:%v(%s)", err, recorder.Body.String())
|
||||
}
|
||||
return payload
|
||||
}
|
||||
|
||||
// 注入的完整 SHA 决定「当前运行」;不注入就只能是未知 —— 绝不拿最新版本顶替。
|
||||
func withInjectedIdentity(t *testing.T, sha, kind string) {
|
||||
t.Helper()
|
||||
previousSHA, previousKind, previousRelease := version.CommitSHA, version.BuildKind, version.ReleaseVersion
|
||||
version.CommitSHA, version.BuildKind, version.ReleaseVersion = sha, kind, "0.1.0"
|
||||
t.Cleanup(func() {
|
||||
version.CommitSHA, version.BuildKind, version.ReleaseVersion = previousSHA, previousKind, previousRelease
|
||||
})
|
||||
}
|
||||
|
||||
func TestBuildInfoReportsIdentityAvailability(t *testing.T) {
|
||||
sha := strings.Repeat("a", 40)
|
||||
withInjectedIdentity(t, sha, "development")
|
||||
recorder := httptest.NewRecorder()
|
||||
buildInfo(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/build-info", nil))
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("状态码 = %d", recorder.Code)
|
||||
}
|
||||
payload := decodeVersionHistoryBody(t, recorder)
|
||||
if payload["identity_available"] != true || payload["commit_sha"] != sha {
|
||||
t.Fatalf("完整注入时应给出身份:%v", payload)
|
||||
}
|
||||
if payload["build_kind"] != "development" {
|
||||
t.Fatalf("构建类型 = %v", payload["build_kind"])
|
||||
}
|
||||
|
||||
withInjectedIdentity(t, "unknown", "release")
|
||||
recorder = httptest.NewRecorder()
|
||||
buildInfo(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/build-info", nil))
|
||||
payload = decodeVersionHistoryBody(t, recorder)
|
||||
if payload["identity_available"] != false || payload["commit_sha"] != nil || payload["display_version"] != "dev" {
|
||||
t.Fatalf("身份不可用时必须明确说未知:%v", payload)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVersionHistoryListUnconfiguredStaysReadable(t *testing.T) {
|
||||
withInjectedIdentity(t, "unknown", "development")
|
||||
recorder := httptest.NewRecorder()
|
||||
versionHistoryList(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/version-history", nil), Config{})
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("未接线也必须 200(页面降级展示):%d", recorder.Code)
|
||||
}
|
||||
payload := decodeVersionHistoryBody(t, recorder)
|
||||
sync, _ := payload["sync"].(map[string]any)
|
||||
if sync["available"] != false {
|
||||
t.Fatalf("未接线时 sync.available 必须为 false:%v", sync)
|
||||
}
|
||||
items, _ := payload["items"].([]any)
|
||||
if len(items) != 0 {
|
||||
t.Fatalf("未接线时不该有记录:%v", items)
|
||||
}
|
||||
running, _ := payload["current_running"].(map[string]any)
|
||||
if running["state"] != "unknown" {
|
||||
t.Fatalf("拿不到身份必须显示未知:%v", running)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVersionHistoryListMarksOnlyExactMatchAndKeepsSameNumberApart(t *testing.T) {
|
||||
sha := strings.Repeat("b", 40)
|
||||
other := strings.Repeat("c", 40)
|
||||
withInjectedIdentity(t, sha, "development")
|
||||
store := &fakeVersionHistoryStore{snapshot: 7, hasMore: true, nextCursor: "cursor-1",
|
||||
items: []governance.VersionHistoryCommit{
|
||||
{CommitSHA: sha, CommittedAt: time.Date(2026, 10, 13, 10, 0, 0, 0, time.UTC),
|
||||
Subject: "feat: 当前运行的这条", RecordKind: governance.RecordKindDevelopment,
|
||||
VersionLabel: "0.1.3", VersionState: governance.VersionStateVerified,
|
||||
VersionEvidence: governance.VersionEvidence{Reason: "counted_commits_since_base_tag"}},
|
||||
{CommitSHA: other, CommittedAt: time.Date(2026, 10, 13, 9, 0, 0, 0, time.UTC),
|
||||
Subject: "feat: 同号的另一条", RecordKind: governance.RecordKindDevelopment,
|
||||
VersionLabel: "0.1.3", VersionState: governance.VersionStateVerified},
|
||||
}}
|
||||
config := Config{VersionHistory: store, VersionHistoryRepo: "WeknorA/knowledge-governance"}
|
||||
recorder := httptest.NewRecorder()
|
||||
versionHistoryList(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/version-history?kind=development&limit=2", nil), config)
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("状态码 = %d", recorder.Code)
|
||||
}
|
||||
if store.lastKind != "development" || store.lastLimit != 2 {
|
||||
t.Fatalf("查询参数没透传:kind=%s limit=%d", store.lastKind, store.lastLimit)
|
||||
}
|
||||
payload := decodeVersionHistoryBody(t, recorder)
|
||||
items, _ := payload["items"].([]any)
|
||||
if len(items) != 2 {
|
||||
t.Fatalf("记录数 = %d", len(items))
|
||||
}
|
||||
flagged := 0
|
||||
for _, raw := range items {
|
||||
item, _ := raw.(map[string]any)
|
||||
if item["is_current_running"] == true {
|
||||
flagged++
|
||||
if item["commit_sha"] != sha {
|
||||
t.Fatalf("只允许精确匹配的那条被标记:%v", item)
|
||||
}
|
||||
}
|
||||
// 同号不同 SHA:两条都在,且都带自己的短 SHA
|
||||
if item["version_label"] != "0.1.3" || item["short_sha"] == "" {
|
||||
t.Fatalf("同号的记录应各自保留并以短 SHA 区分:%v", item)
|
||||
}
|
||||
}
|
||||
if flagged != 1 {
|
||||
t.Fatalf("被标记为当前运行的条数 = %d", flagged)
|
||||
}
|
||||
if payload["has_more"] != true || payload["next_cursor"] != "cursor-1" {
|
||||
t.Fatalf("分页游标没透传:%v", payload)
|
||||
}
|
||||
running, _ := payload["current_running"].(map[string]any)
|
||||
if running["state"] != "matched" || running["matched_commit_sha"] != sha {
|
||||
t.Fatalf("当前运行判定不对:%v", running)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVersionHistoryListDevelopmentBuildNotInRecordsIsNotMarked(t *testing.T) {
|
||||
withInjectedIdentity(t, strings.Repeat("d", 40), "development")
|
||||
store := &fakeVersionHistoryStore{snapshot: 3, items: []governance.VersionHistoryCommit{
|
||||
{CommitSHA: strings.Repeat("e", 40), VersionLabel: "0.1.5", RecordKind: governance.RecordKindDevelopment}}}
|
||||
config := Config{VersionHistory: store, VersionHistoryRepo: "o/r"}
|
||||
recorder := httptest.NewRecorder()
|
||||
versionHistoryList(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/version-history", nil), config)
|
||||
payload := decodeVersionHistoryBody(t, recorder)
|
||||
items, _ := payload["items"].([]any)
|
||||
for _, raw := range items {
|
||||
item, _ := raw.(map[string]any)
|
||||
if item["is_current_running"] == true {
|
||||
t.Fatalf("产物 SHA 不在记录里就不得标记任何条目:%v", item)
|
||||
}
|
||||
}
|
||||
running, _ := payload["current_running"].(map[string]any)
|
||||
if running["state"] != "development" || running["commit_sha"] == "" {
|
||||
t.Fatalf("开发构建要显式标为开发构建,而不是标成某条记录:%v", running)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVersionHistoryListRejectsBadLimitAndExpiredCursor(t *testing.T) {
|
||||
withInjectedIdentity(t, "unknown", "development")
|
||||
store := &fakeVersionHistoryStore{snapshot: 5}
|
||||
config := Config{VersionHistory: store, VersionHistoryRepo: "o/r"}
|
||||
recorder := httptest.NewRecorder()
|
||||
versionHistoryList(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/version-history?limit=999", nil), config)
|
||||
if recorder.Code != http.StatusBadRequest {
|
||||
t.Fatalf("limit 越界应 400,得到 %d", recorder.Code)
|
||||
}
|
||||
if code := decodeVersionHistoryBody(t, recorder)["code"]; code != "invalid_limit" {
|
||||
t.Fatalf("错误码 = %v", code)
|
||||
}
|
||||
|
||||
store.pageErr = postgresstore.ErrVersionHistoryCursorExpired
|
||||
recorder = httptest.NewRecorder()
|
||||
versionHistoryList(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/version-history?cursor=stale", nil), config)
|
||||
if recorder.Code != http.StatusConflict {
|
||||
t.Fatalf("游标过期应 409,得到 %d", recorder.Code)
|
||||
}
|
||||
if code := decodeVersionHistoryBody(t, recorder)["code"]; code != "cursor_expired" {
|
||||
t.Fatalf("错误码 = %v", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVersionHistorySyncRequiresAdminAndEnqueuesOnce(t *testing.T) {
|
||||
// 角色:读任何角色可看,同步只能管理员
|
||||
if got := classifyRole(http.MethodGet, "/api/v1/version-history"); got != roleViewer {
|
||||
t.Fatalf("GET 的最小角色 = %q", got)
|
||||
}
|
||||
if got := classifyRole(http.MethodPost, "/api/v1/version-history/sync"); got != roleAdmin {
|
||||
t.Fatalf("同步的最小角色 = %q,必须是 %q", got, roleAdmin)
|
||||
}
|
||||
|
||||
now := time.Date(2026, 10, 13, 12, 0, 0, 0, time.UTC)
|
||||
queue := &fakeJobStore{enqueueEchoRequestedID: true}
|
||||
store := &fakeVersionHistoryStore{snapshot: 9}
|
||||
config := Config{Store: queue, VersionHistory: store, VersionHistoryRepo: "Weknora/knowledge-governance",
|
||||
Now: func() time.Time { return now }}
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
versionHistorySync(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/version-history/sync", nil), config)
|
||||
if recorder.Code != http.StatusAccepted {
|
||||
t.Fatalf("首次同步应 202,得到 %d(%s)", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if queue.enqueued.Type != VersionHistoryJobType || queue.enqueued.IdempotencyKey != "version-history.sync:Weknora/knowledge-governance" {
|
||||
t.Fatalf("入队参数不对:%+v", queue.enqueued)
|
||||
}
|
||||
if queue.enqueued.MaxAttempts != 3 || queue.enqueued.AvailableAt != now {
|
||||
t.Fatalf("入队参数不对:%+v", queue.enqueued)
|
||||
}
|
||||
payload := decodeVersionHistoryBody(t, recorder)
|
||||
if payload["reused"] != false {
|
||||
t.Fatalf("首次不该标成复用:%v", payload)
|
||||
}
|
||||
|
||||
// 已经在跑:不重复入队,明确返回已有任务
|
||||
store.inFlight = true
|
||||
store.state = governance.VersionHistorySyncRun{ID: 11, JobID: "job-running", Status: "running"}
|
||||
queue.enqueued = jobs.EnqueueRequest{}
|
||||
recorder = httptest.NewRecorder()
|
||||
versionHistorySync(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/version-history/sync", nil), config)
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("并发同步应 200 + 复用已有任务,得到 %d", recorder.Code)
|
||||
}
|
||||
payload = decodeVersionHistoryBody(t, recorder)
|
||||
if payload["reused"] != true || payload["job_id"] != "job-running" {
|
||||
t.Fatalf("应复用已有任务:%v", payload)
|
||||
}
|
||||
if queue.enqueued.Type != "" {
|
||||
t.Fatalf("已在跑时不得再次入队:%+v", queue.enqueued)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVersionHistorySyncUnavailableWhenNotWired(t *testing.T) {
|
||||
recorder := httptest.NewRecorder()
|
||||
versionHistorySync(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/version-history/sync", nil), Config{})
|
||||
if recorder.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("未接线应 503,得到 %d", recorder.Code)
|
||||
}
|
||||
if code := decodeVersionHistoryBody(t, recorder)["code"]; code != "version_history_unavailable" {
|
||||
t.Fatalf("错误码 = %v", code)
|
||||
}
|
||||
// 未接线时页面仍然可读(只是没有记录)
|
||||
store := &fakeVersionHistoryStore{stateErr: errors.New("boom")}
|
||||
recorder = httptest.NewRecorder()
|
||||
config := Config{VersionHistory: store, VersionHistoryRepo: "o/r"}
|
||||
versionHistoryList(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/version-history", nil), config)
|
||||
if recorder.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("查询异常应 500,得到 %d", recorder.Code)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user