From f91359f881077d1fad17fca021973c6beb54553f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A7=9A=E7=AB=A0=E6=B5=A9?= Date: Wed, 28 Oct 2026 15:04:44 +0800 Subject: [PATCH] =?UTF-8?q?feat(library):=20=E5=AD=98=E5=82=A8=E7=AE=A1?= =?UTF-8?q?=E7=90=86=E7=9C=9F=E5=AE=9E=E5=8C=96=E2=80=94=E2=80=94=E5=AE=B9?= =?UTF-8?q?=E9=87=8F=E9=97=A8=E7=A6=81=E3=80=81=E4=BE=9D=E8=B5=96=E4=BF=9D?= =?UTF-8?q?=E6=8A=A4=E4=B8=8E=E6=B8=85=E7=90=86=E9=A2=84=E8=A7=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 为什么:存储页原来只有占用数字,保留/依赖保护/清理预览写"未接线";这些都不需要生产写权限, 按"未设置就不做决定"的口径实现成只读计算。 - internal/libraryretention:按保留数量/天数生成预览;生产生效、每库最近封存、每次生产预备份、 在飞作业引用一律受保护;回收预览只算独占字节,共享 blob 不计。 - internal/libraryretention.CheckCapacity:预算未设置即不放行(无法证明装得下),超预算阻断; 已并入 POST /library/syncs 的 gate 缺项。 - 新增 GET /api/v1/library/storage:真实归档用量 + 三类版本保护依据 + 策略 + 预览 + 容量,只读。 - 系统设置→存储管理改为读该接口:策略未设置时明确"全部保留、不生成候选",自动清理恒关闭。 - 配置项 LIBRARY_CAPACITY_BUDGET_BYTES / LIBRARY_RETENTION_VERSIONS / LIBRARY_RETENTION_DAYS(未设=0)。 --- api/openapi.yaml | 23 +++ cmd/api/main.go | 17 +- internal/appconfig/config.go | 23 ++- internal/httpapi/library_flow.go | 3 + internal/httpapi/library_flow_test.go | 12 +- internal/httpapi/library_storage.go | 201 ++++++++++++++++++++ internal/httpapi/server.go | 11 +- internal/libraryretention/capacity.go | 35 ++++ internal/libraryretention/retention.go | 109 +++++++++++ internal/libraryretention/retention_test.go | 95 +++++++++ web/src/LibraryStorageSection.tsx | 167 ++++++++++++---- web/src/librarySnapshots.ts | 76 ++++++++ web/src/libraryStorage.css | 33 ++++ 13 files changed, 756 insertions(+), 49 deletions(-) create mode 100644 internal/httpapi/library_storage.go create mode 100644 internal/libraryretention/capacity.go create mode 100644 internal/libraryretention/retention.go create mode 100644 internal/libraryretention/retention_test.go diff --git a/api/openapi.yaml b/api/openapi.yaml index 1aa291e..53800cc 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -898,6 +898,29 @@ } } }, + "/api/v1/library/storage": { + "get": { + "tags": [ + "Runtime" + ], + "operationId": "getLibraryStorage", + "summary": "存储管理(只读):容量、保留策略、依赖保护与清理预览;自动清理关闭,不提供删除动作", + "responses": { + "200": { + "$ref": "#/components/responses/Envelope" + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "500": { + "$ref": "#/components/responses/InternalError" + }, + "503": { + "description": "归档未配置或不可读" + } + } + } + }, "/api/v1/library/overview": { "get": { "tags": [ diff --git a/cmd/api/main.go b/cmd/api/main.go index a41db1b..2290b68 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -196,13 +196,16 @@ func run(ctx context.Context, getenv func(string) string) error { ProductionReleaseAuthorizerRef: config.ProductionReleaseAuthorizerRef, ProductionReleaseAuthorizationToken: releaseAuthorizationToken, // 数据源发现(系统设置 → 数据源配置):用与 worker 同一份 dws 状态做只读列举。 - DingtalkSources: dingtalkSourceLister{}, - DingtalkDocuments: dingtalkSourceLister{}, - BackupSchedule: postgresstore.NewStore(pool), - VersionHistory: versionHistoryStore, - VersionHistoryRepo: versionHistoryRepo, - LibraryArchiveRoot: config.LibraryArchiveRoot, - LibraryAgentSocket: config.LibraryAgentSocket, + DingtalkSources: dingtalkSourceLister{}, + DingtalkDocuments: dingtalkSourceLister{}, + BackupSchedule: postgresstore.NewStore(pool), + VersionHistory: versionHistoryStore, + VersionHistoryRepo: versionHistoryRepo, + LibraryArchiveRoot: config.LibraryArchiveRoot, + LibraryAgentSocket: config.LibraryAgentSocket, + LibraryCapacityBudgetBytes: config.LibraryCapacityBudgetBytes, + LibraryRetentionVersions: config.LibraryRetentionVersions, + LibraryRetentionDays: config.LibraryRetentionDays, BackupHost: backuphost.New(backuphost.Config{ SSHConfig: config.BackupHostSSHConfig, Target: config.BackupHostTarget, diff --git a/internal/appconfig/config.go b/internal/appconfig/config.go index ee44bc8..ed121e8 100644 --- a/internal/appconfig/config.go +++ b/internal/appconfig/config.go @@ -72,6 +72,11 @@ type Config struct { // LibraryArchiveRoot 是整库封存产物的只读归档根(主机私有 0700 目录的只读挂载)。 // 留空即"未接线":页面只显示原因,不显示空表冒充没有快照。 LibraryArchiveRoot string + // LibraryCapacityBudgetBytes 是整库归档容量预算;0 表示未设置(容量门禁不放行)。 + LibraryCapacityBudgetBytes int64 + // LibraryRetentionVersions / Days 是保留策略;都为 0 表示未设置(不生成清理候选)。 + LibraryRetentionVersions int + LibraryRetentionDays int // LibraryAgentSocket 是主机侧封存 agent 的 unix socket(只由 worker 连接)。 // 留空即"未接线":页面不显示可用的封存入口,接口返回原因而不是假装已排队。 LibraryAgentSocket string @@ -81,6 +86,20 @@ type Config struct { } func Load(getenv func(string) string) (Config, error) { + // 容量与保留策略:未设置一律 0(= 不做决定),由使用方按 fail-closed 处理。 + capacityBudget, err := positiveInt64OrDefault(strings.TrimSpace(getenv("LIBRARY_CAPACITY_BUDGET_BYTES")), 0) + if err != nil { + return Config{}, errors.New("LIBRARY_CAPACITY_BUDGET_BYTES must be a positive integer") + } + retentionVersions64, err := positiveInt64OrDefault(strings.TrimSpace(getenv("LIBRARY_RETENTION_VERSIONS")), 0) + if err != nil { + return Config{}, errors.New("LIBRARY_RETENTION_VERSIONS must be a positive integer") + } + retentionDays64, err := positiveInt64OrDefault(strings.TrimSpace(getenv("LIBRARY_RETENTION_DAYS")), 0) + if err != nil { + return Config{}, errors.New("LIBRARY_RETENTION_DAYS must be a positive integer") + } + retentionVersions, retentionDays := int(retentionVersions64), int(retentionDays64) config := Config{ DatabaseURL: getenv("DATABASE_URL"), AppAddr: valueOrDefault(getenv("APP_ADDR"), ":8080"), @@ -124,6 +143,9 @@ func Load(getenv func(string) string) (Config, error) { VersionHistoryAllowedOrigins: splitOrigins(getenv("VERSION_HISTORY_ALLOWED_ORIGINS")), LibraryArchiveRoot: strings.TrimSpace(getenv("LIBRARY_ARCHIVE_ROOT")), LibraryAgentSocket: strings.TrimSpace(getenv("LIBRARY_AGENT_SOCKET")), + LibraryCapacityBudgetBytes: capacityBudget, + LibraryRetentionVersions: retentionVersions, + LibraryRetentionDays: retentionDays, VersionHistoryLinkOrigin: strings.TrimSpace(getenv("VERSION_HISTORY_LINK_ORIGIN")), VersionHistoryHTTPTimeout: 15 * time.Second, VersionHistoryMaxPages: valueOrDefaultInt(getenv("VERSION_HISTORY_MAX_PAGES"), 200), @@ -131,7 +153,6 @@ func Load(getenv func(string) string) (Config, error) { if config.DatabaseURL == "" { return Config{}, errors.New("DATABASE_URL is required") } - var err error if config.PollInterval, err = durationOrDefault(getenv("WORKER_POLL_INTERVAL"), config.PollInterval); err != nil { return Config{}, fmt.Errorf("WORKER_POLL_INTERVAL: %w", err) } diff --git a/internal/httpapi/library_flow.go b/internal/httpapi/library_flow.go index ebc2169..00bebfb 100644 --- a/internal/httpapi/library_flow.go +++ b/internal/httpapi/library_flow.go @@ -199,6 +199,9 @@ func librarySyncGate(config Config, production libraryKnownView, prebackup libra if prebackup.State != "known" { gate.Reasons = append(gate.Reasons, "本次目标快照还没有生产预备份") } + if config.LibraryCapacityBudgetBytes <= 0 { + gate.Reasons = append(gate.Reasons, "容量预算未设置(LIBRARY_CAPACITY_BUDGET_BYTES),无法证明装得下") + } gate.SyncAllowed = len(gate.Reasons) == 0 return gate } diff --git a/internal/httpapi/library_flow_test.go b/internal/httpapi/library_flow_test.go index c53844d..0367ea0 100644 --- a/internal/httpapi/library_flow_test.go +++ b/internal/httpapi/library_flow_test.go @@ -109,12 +109,22 @@ func TestLibrarySyncGateRequiresEveryPieceOfEvidence(t *testing.T) { reason: "没有已核验的生产恢复演练证据", }, { - name: "everything present", + name: "capacity budget missing blocks even when everything else is present", config: Config{ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true, ProductionWeKnoraBaseURL: "http://prod.invalid"}, production: known, prebackup: known, target: "snap-1", + allowed: false, + reason: "容量预算未设置", + }, + { + name: "everything present", + config: Config{ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true, + ProductionWeKnoraBaseURL: "http://prod.invalid", LibraryCapacityBudgetBytes: 1 << 40}, + production: known, + prebackup: known, + target: "snap-1", allowed: true, }, } diff --git a/internal/httpapi/library_storage.go b/internal/httpapi/library_storage.go new file mode 100644 index 0000000..3757a48 --- /dev/null +++ b/internal/httpapi/library_storage.go @@ -0,0 +1,201 @@ +package httpapi + +import ( + "net/http" + "sort" + "strings" + "time" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/libraryretention" + "knowledge-governance/internal/librarysnapshot" +) + +// 存储管理接口:容量、保留策略、依赖保护与清理预览。 +// +// 全部只读:没有删除动作,自动清理恒为关闭。候选版本只是"按策略如果清理会考虑这些", +// 受保护版本(生产生效、每库最近封存、每次生产预备份、在飞作业引用)永不进入候选。 +type storageVersionView struct { + ID string `json:"id"` + Kind string `json:"kind"` + Scope string `json:"scope"` + CreatedAt time.Time `json:"created_at"` + Protected bool `json:"protected"` + ProtectedBy []string `json:"protected_by,omitempty"` + ExclusiveBytes int64 `json:"exclusive_bytes"` + SharedBytes int64 `json:"shared_bytes"` +} + +type libraryStorageResponse struct { + Available bool `json:"available"` + Reason string `json:"reason,omitempty"` + ArchiveRoot string `json:"archive_root,omitempty"` + Versions []storageVersionView `json:"versions"` + ContentBytes int64 `json:"content_bytes"` + BlobFileBytes int64 `json:"blob_file_bytes"` + BlobAllocatedBytes int64 `json:"blob_allocated_bytes"` + UnreferencedBlobs int `json:"unreferenced_blobs"` + UnreferencedBytes int64 `json:"unreferenced_bytes"` + ManifestFileBytes int64 `json:"manifest_file_bytes"` + Policy libraryretention.Policy `json:"policy"` + Plan *libraryretention.Plan `json:"plan,omitempty"` + Capacity libraryretention.Capacity `json:"capacity"` + AutomaticCleanup bool `json:"automatic_cleanup"` + Notes []string `json:"notes"` +} + +func libraryStorageHandler(w http.ResponseWriter, r *http.Request, config Config) { + response := libraryStorageResponse{Versions: []storageVersionView{}, Notes: []string{}, AutomaticCleanup: false, + Policy: libraryretention.Policy{KeepVersions: int(config.LibraryRetentionVersions), KeepDays: int(config.LibraryRetentionDays)}} + if strings.TrimSpace(config.LibraryArchiveRoot) == "" { + response.Reason = "未接线:LIBRARY_ARCHIVE_ROOT 未配置,没有可统计的归档" + writeJSON(w, http.StatusServiceUnavailable, response) + return + } + archive, err := librarysnapshot.Open(config.LibraryArchiveRoot, 256*1024*1024) + if err != nil { + response.Reason = "归档根不可用" + writeJSON(w, http.StatusServiceUnavailable, response) + return + } + defer archive.Close() + total, err := archive.ContentUsage() + if err != nil { + response.Reason = "归档用量不可读" + writeJSON(w, http.StatusServiceUnavailable, response) + return + } + response.Available = true + response.ArchiveRoot = config.LibraryArchiveRoot + response.ContentBytes = total.ContentBytes + response.BlobFileBytes = total.BlobFileBytes + response.BlobAllocatedBytes = total.BlobAllocatedBytes + response.UnreferencedBlobs = total.UnreferencedBlobs + response.UnreferencedBytes = total.UnreferencedBytes + response.ManifestFileBytes = total.ManifestFileBytes + + usage, err := archive.Usage() + if err != nil { + response.Reason = "归档逐版本用量不可读" + writeJSON(w, http.StatusServiceUnavailable, response) + return + } + usageByID := map[string]librarysnapshot.Usage{} + ids := make([]string, 0, len(usage)) + for _, item := range usage { + usageByID[item.VersionID] = item + ids = append(ids, item.VersionID) + } + sort.Strings(ids) + + // 版本类型与保护依据来自持久登记与在飞作业,不靠文件时间猜。 + kinds := map[string]governance.LibraryVersion{} + protectedBy := map[string][]string{} + store, storeOK := libraryStore(config) + if storeOK { + for _, scope := range []string{"internal", "external"} { + versions, listErr := store.LibraryVersions(r.Context(), scope, 100) + if listErr == nil { + for _, item := range versions { + kinds[item.SnapshotID] = item + if item.Kind == governance.LibraryVersionProductionEffective && item.SupersededAt == nil { + protectedBy[item.SnapshotID] = append(protectedBy[item.SnapshotID], "生产生效版本") + } + if item.Kind == governance.LibraryVersionProductionPrebackup { + protectedBy[item.SnapshotID] = append(protectedBy[item.SnapshotID], "生产预备份") + } + } + } + jobs, jobErr := store.ListLibraryJobs(r.Context(), scope, 20) + if jobErr == nil { + for _, job := range jobs { + if job.State != governance.LibraryJobPending && job.State != governance.LibraryJobRunning { + continue + } + for _, id := range []string{job.SnapshotID, job.TargetSnapshotID} { + if id != "" { + protectedBy[id] = append(protectedBy[id], "在飞作业引用") + } + } + } + } + } + } else { + response.Notes = append(response.Notes, "版本登记存储不可用:只按归档文件统计,无法识别受保护版本") + } + + versions := make([]libraryretention.Version, 0, len(ids)) + latestSealed := map[string]time.Time{} + var requiredBytes int64 + for _, id := range ids { + manifest, loadErr := archive.Load(id) + if loadErr != nil { + response.Reason = "归档快照校验失败" + writeJSON(w, http.StatusServiceUnavailable, response) + return + } + kind := "unregistered" + if record, ok := kinds[id]; ok { + kind = string(record.Kind) + } else if manifest.ValidationPolicy != "" { + kind = "test_sealed" + } + if kind == "test_sealed" { + // 每库最近一次封存受保护:它是最新可发布的测试版本。 + if current, seen := latestSealed[manifest.Scope]; !seen || manifest.CreatedAt.After(current) { + latestSealed[manifest.Scope] = manifest.CreatedAt + } + } + item := usageByID[id] + view := storageVersionView{ID: id, Kind: kind, Scope: manifest.Scope, CreatedAt: manifest.CreatedAt, + ExclusiveBytes: item.ExclusiveBytes, SharedBytes: item.SharedBytes} + versions = append(versions, libraryretention.Version{ID: id, Kind: kind, CreatedAt: manifest.CreatedAt, + ExclusiveBytes: item.ExclusiveBytes, SharedBytes: item.SharedBytes}) + response.Versions = append(response.Versions, view) + } + // 用与上面相同的排序再定位一次最新测试封存,避免把时间映射回 ID 时出错。 + for _, id := range ids { + manifest, loadErr := archive.Load(id) + if loadErr != nil { + continue + } + if kindOf := kinds[id].Kind; kindOf == governance.LibraryVersionTestSealed || + (kindOf == "" && manifest.ValidationPolicy != "") { + if manifest.CreatedAt.Equal(latestSealed[manifest.Scope]) { + protectedBy[id] = append(protectedBy[id], "最近测试封存("+manifest.Scope+")") + } + } + } + + for index := range versions { + if reasons := protectedBy[versions[index].ID]; len(reasons) > 0 { + versions[index].Protected = true + versions[index].ProtectedBy = reasons + } + } + for index := range response.Versions { + if reasons := protectedBy[response.Versions[index].ID]; len(reasons) > 0 { + response.Versions[index].Protected = true + response.Versions[index].ProtectedBy = reasons + } + } + + now := time.Now().UTC() + plan := libraryretention.Build(versions, total.ContentBytes, response.Policy, now) + response.Plan = &plan + response.Notes = append(response.Notes, "候选版本只是清理预览;共享 blob 不会因删除单个版本释放") + response.Notes = append(response.Notes, "自动清理关闭,页面不提供删除动作;实际回收需要单独授权") + if !plan.PolicyConfigured { + response.Notes = append(response.Notes, "保留数量/天数未设置(LIBRARY_RETENTION_VERSIONS / LIBRARY_RETENTION_DAYS)") + } + + for index := range response.Versions { + item := response.Versions[index] + if item.Kind == "test_sealed" && item.CreatedAt.Equal(latestSealed[item.Scope]) { + requiredBytes = item.ExclusiveBytes + item.SharedBytes + break + } + } + response.Capacity = libraryretention.CheckCapacity(total.ContentBytes, requiredBytes, config.LibraryCapacityBudgetBytes) + writeJSON(w, http.StatusOK, response) +} diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index f75846e..fff6336 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -132,7 +132,12 @@ type Config struct { // LibraryArchiveRoot 是整库封存产物的只读归档根;留空即未接线(页面降级)。 LibraryArchiveRoot string // LibraryAgentSocket 是主机侧封存 agent 的 unix socket;留空即页面不能发起封存。 - LibraryAgentSocket string + LibraryAgentSocket string + // LibraryCapacityBudgetBytes 是整库归档容量预算;0 = 未设置(容量门禁不放行)。 + LibraryCapacityBudgetBytes int64 + // LibraryRetentionVersions/Days 是保留策略;都为 0 = 未设置(不生成清理候选)。 + LibraryRetentionVersions int + LibraryRetentionDays int BackupSchedule BackupScheduleStore BackupHost BackupHost BackupRuns *BackupRunTracker @@ -409,6 +414,10 @@ func NewHandler(config Config) (http.Handler, error) { mux.HandleFunc("GET /api/v1/library/overview", func(w http.ResponseWriter, r *http.Request) { libraryOverviewHandler(w, r, config) }) + // 存储管理:容量、保留策略、依赖保护与清理预览(只读,没有删除动作)。 + mux.HandleFunc("GET /api/v1/library/storage", func(w http.ResponseWriter, r *http.Request) { + libraryStorageHandler(w, r, config) + }) mux.HandleFunc("GET /api/v1/library/jobs", func(w http.ResponseWriter, r *http.Request) { libraryJobsHandler(w, r, config) }) diff --git a/internal/libraryretention/capacity.go b/internal/libraryretention/capacity.go new file mode 100644 index 0000000..8755b9f --- /dev/null +++ b/internal/libraryretention/capacity.go @@ -0,0 +1,35 @@ +package libraryretention + +import "fmt" + +// Capacity 是生产写入前的容量门禁:预算未设置就不放行(无法证明"装得下"), +// 预算已知但不足也阻断。它不复用清理预览的回收量——清理未授权,不能拿它抵账。 +type Capacity struct { + BudgetBytes int64 `json:"budget_bytes"` + CurrentBytes int64 `json:"current_bytes"` + RequiredBytes int64 `json:"required_bytes"` + ProjectedByte int64 `json:"projected_bytes"` + Configured bool `json:"configured"` + OK bool `json:"ok"` + Reason string `json:"reason,omitempty"` +} + +func CheckCapacity(currentBytes, requiredBytes, budgetBytes int64) Capacity { + result := Capacity{BudgetBytes: budgetBytes, CurrentBytes: currentBytes, RequiredBytes: requiredBytes, + ProjectedByte: currentBytes + requiredBytes} + if budgetBytes <= 0 { + result.Reason = "容量预算未设置(LIBRARY_CAPACITY_BUDGET_BYTES),无法证明装得下" + return result + } + result.Configured = true + if requiredBytes < 0 || currentBytes < 0 { + result.Reason = "容量口径异常(负数),拒绝放行" + return result + } + if result.ProjectedByte > budgetBytes { + result.Reason = fmt.Sprintf("写入后预计占用 %d 字节,超过预算 %d 字节", result.ProjectedByte, budgetBytes) + return result + } + result.OK = true + return result +} diff --git a/internal/libraryretention/retention.go b/internal/libraryretention/retention.go new file mode 100644 index 0000000..45678c0 --- /dev/null +++ b/internal/libraryretention/retention.go @@ -0,0 +1,109 @@ +// Package libraryretention 计算整库归档的保留、依赖保护与清理预览。 +// +// 只做计算,不做删除:所有结论都是"如果按这个策略清理,哪些版本会被保留、 +// 哪些成为候选、大约能释放多少独占字节"。共享 blob 不计入回收量,因为仍有 +// 其它版本引用它;没有任何策略配置时不给候选,也不拿默认值替用户拍板。 +package libraryretention + +import ( + "fmt" + "sort" + "time" +) + +// Version 是参与保留判断的一个整库版本。 +type Version struct { + ID string `json:"id"` + Kind string `json:"kind"` + CreatedAt time.Time `json:"created_at"` + // Protected 由调用方依据真实引用计算(生产生效、最近封存、在飞作业), + // 这里不猜;ProtectedBy 写明是哪条依据,审计时能逐条核对。 + Protected bool `json:"protected"` + ProtectedBy []string `json:"protected_by,omitempty"` + // ExclusiveBytes 是只有这个版本引用的内容字节(来自归档用量)。 + ExclusiveBytes int64 `json:"exclusive_bytes"` + SharedBytes int64 `json:"shared_bytes"` +} + +// Policy 是保留策略。零值表示"未设置"——这时不给任何候选。 +type Policy struct { + KeepVersions int `json:"keep_versions"` + KeepDays int `json:"keep_days"` +} + +func (p Policy) Configured() bool { return p.KeepVersions > 0 || p.KeepDays > 0 } + +type Candidate struct { + ID string `json:"id"` + Kind string `json:"kind"` + Reason []string `json:"reason"` + // ExclusiveBytes 是上限口径:就算删掉,共享 blob 也不会释放。 + ExclusiveBytes int64 `json:"exclusive_bytes"` +} + +type Plan struct { + Policy Policy `json:"policy"` + PolicyConfigured bool `json:"policy_configured"` + AutomaticCleanup bool `json:"automatic_cleanup"` + VersionCount int `json:"version_count"` + TotalBytes int64 `json:"total_bytes"` + Protected []string `json:"protected"` + Keep []string `json:"keep"` + Candidates []Candidate `json:"candidates"` + // ReclaimPreviewBytes 只是候选版本独占字节之和,不是承诺。 + ReclaimPreviewBytes int64 `json:"reclaim_preview_bytes"` + // Blocked 说明为什么给不出安全预览(策略未配置、时间基准异常等)。 + Blocked []string `json:"blocked"` + Now time.Time `json:"now"` +} + +// Build 生成清理预览。now 由调用方给,便于测试;不给真实时钟依赖。 +func Build(versions []Version, totalBytes int64, policy Policy, now time.Time) Plan { + plan := Plan{Policy: policy, PolicyConfigured: policy.Configured(), AutomaticCleanup: false, + VersionCount: len(versions), TotalBytes: totalBytes, Protected: []string{}, Keep: []string{}, + Candidates: []Candidate{}, Blocked: []string{}, Now: now.UTC()} + + sorted := append([]Version(nil), versions...) + sort.Slice(sorted, func(i, j int) bool { + if sorted[i].CreatedAt.Equal(sorted[j].CreatedAt) { + return sorted[i].ID > sorted[j].ID + } + return sorted[i].CreatedAt.After(sorted[j].CreatedAt) + }) + + if !policy.Configured() { + plan.Blocked = append(plan.Blocked, "保留策略未设置(保留版本数与保留天数都没有),不生成清理候选") + } + if policy.KeepVersions < 0 || policy.KeepDays < 0 { + plan.Blocked = append(plan.Blocked, "保留策略取值非法,拒绝生成预览") + return plan + } + + for rank, version := range sorted { + if version.Protected { + plan.Protected = append(plan.Protected, version.ID) + plan.Keep = append(plan.Keep, version.ID) + continue + } + if !policy.Configured() { + // 没策略时按"全部保留"处理,绝不默认清理。 + plan.Keep = append(plan.Keep, version.ID) + continue + } + reasons := make([]string, 0, 2) + if policy.KeepVersions > 0 && rank >= policy.KeepVersions { + reasons = append(reasons, fmt.Sprintf("超出保留 %d 个版本", policy.KeepVersions)) + } + if policy.KeepDays > 0 && !version.CreatedAt.IsZero() && version.CreatedAt.Before(now.AddDate(0, 0, -policy.KeepDays)) { + reasons = append(reasons, fmt.Sprintf("超出保留 %d 天", policy.KeepDays)) + } + if len(reasons) == 0 { + plan.Keep = append(plan.Keep, version.ID) + continue + } + plan.Candidates = append(plan.Candidates, Candidate{ID: version.ID, Kind: version.Kind, + Reason: reasons, ExclusiveBytes: version.ExclusiveBytes}) + plan.ReclaimPreviewBytes += version.ExclusiveBytes + } + return plan +} diff --git a/internal/libraryretention/retention_test.go b/internal/libraryretention/retention_test.go new file mode 100644 index 0000000..a020636 --- /dev/null +++ b/internal/libraryretention/retention_test.go @@ -0,0 +1,95 @@ +package libraryretention + +import ( + "testing" + "time" +) + +func day(n int) time.Time { return time.Date(2026, 10, 20, 0, 0, 0, 0, time.UTC).AddDate(0, 0, n) } + +func fixture() []Version { + return []Version{ + {ID: "v-new", Kind: "test_sealed", CreatedAt: day(5), ExclusiveBytes: 100, SharedBytes: 50}, + {ID: "v-mid", Kind: "test_sealed", CreatedAt: day(3), ExclusiveBytes: 200}, + {ID: "v-old", Kind: "test_sealed", CreatedAt: day(1), ExclusiveBytes: 300}, + {ID: "v-prod", Kind: "production_effective", CreatedAt: day(0), Protected: true, ProtectedBy: []string{"生产生效版本"}}, + } +} + +func TestBuildWithoutPolicyKeepsEverything(t *testing.T) { + plan := Build(fixture(), 1000, Policy{}, day(6)) + if plan.PolicyConfigured { + t.Fatal("zero policy must not look configured") + } + if len(plan.Candidates) != 0 { + t.Fatalf("no policy must not produce candidates: %+v", plan.Candidates) + } + if len(plan.Blocked) == 0 { + t.Fatal("no policy must explain why no preview is available") + } + if plan.AutomaticCleanup { + t.Fatal("automatic cleanup must stay off") + } +} + +func TestBuildProtectsVersionRegardlessOfAge(t *testing.T) { + plan := Build(fixture(), 1000, Policy{KeepVersions: 1}, day(6)) + for _, candidate := range plan.Candidates { + if candidate.ID == "v-prod" { + t.Fatal("protected version must never be a candidate") + } + } + found := false + for _, id := range plan.Protected { + if id == "v-prod" { + found = true + } + } + if !found { + t.Fatalf("protected list must include v-prod: %+v", plan.Protected) + } + // 保留 1 个版本(最近)之后,除受保护版本外都应成为候选 + if len(plan.Candidates) != 2 { + t.Fatalf("candidates = %+v, want v-mid and v-old", plan.Candidates) + } +} + +func TestBuildKeepsRecentPlusProtected(t *testing.T) { + plan := Build(fixture(), 1000, Policy{KeepVersions: 2}, day(6)) + // 保留最近 2 个(v-new、v-mid)+ 受保护的 v-prod;只有 v-old 成为候选。 + if len(plan.Keep) != 3 { + t.Fatalf("keep = %+v, want 3 versions", plan.Keep) + } + if len(plan.Candidates) != 1 || plan.Candidates[0].ID != "v-old" { + t.Fatalf("candidates = %+v, want only v-old", plan.Candidates) + } +} + +func TestReclaimPreviewCountsOnlyExclusiveBytes(t *testing.T) { + plan := Build([]Version{ + {ID: "a", CreatedAt: day(0), ExclusiveBytes: 100, SharedBytes: 900}, + {ID: "b", CreatedAt: day(1), ExclusiveBytes: 20}, + }, 1020, Policy{KeepVersions: 1}, day(2)) + if plan.ReclaimPreviewBytes != 100 { + t.Fatalf("reclaim preview = %d, want 100 (shared bytes must not count)", plan.ReclaimPreviewBytes) + } +} + +func TestBuildRejectsNegativePolicy(t *testing.T) { + plan := Build(fixture(), 1, Policy{KeepVersions: -1}, day(6)) + if len(plan.Blocked) == 0 || len(plan.Candidates) != 0 { + t.Fatalf("invalid policy must block preview: %+v", plan) + } +} + +func TestCheckCapacityFailsClosed(t *testing.T) { + if result := CheckCapacity(100, 100, 0); result.OK || result.Configured { + t.Fatalf("unset budget must fail closed: %+v", result) + } + if result := CheckCapacity(100, 100, 150); result.OK { + t.Fatalf("over budget must fail: %+v", result) + } + if result := CheckCapacity(100, 20, 150); !result.OK || !result.Configured { + t.Fatalf("within budget must pass: %+v", result) + } +} diff --git a/web/src/LibraryStorageSection.tsx b/web/src/LibraryStorageSection.tsx index 9657515..d3a78e3 100644 --- a/web/src/LibraryStorageSection.tsx +++ b/web/src/LibraryStorageSection.tsx @@ -1,29 +1,33 @@ import { useEffect, useState } from 'react' -import { fetchLibrarySnapshots, formatBytes, type LibrarySnapshotList } from './librarySnapshots' +import { fetchLibraryStorage, formatBytes, type LibraryStorage } from './librarySnapshots' import './libraryStorage.css' // 系统设置 → 存储管理:只读展示整库归档的真实口径。 -// 保留策略、依赖保护、清理预览都没有实现,自动清理保持关闭——页面不能暗示可以删。 +// 保留策略、依赖保护、清理预览都只是"如果清理会怎样",没有任何删除动作; +// 自动清理恒为关闭,策略未设置时不生成候选。 export function LibraryStorageSection() { - const [page, setPage] = useState(null) + const [data, setData] = useState(null) const [error, setError] = useState(null) const [loading, setLoading] = useState(true) useEffect(() => { const controller = new AbortController() - fetchLibrarySnapshots(controller.signal) + fetchLibraryStorage(controller.signal) .then((value) => { - setPage(value) + setData(value) setError(null) }) .catch((loadError) => { if ((loadError as Error).name === 'AbortError') return - setError(loadError instanceof Error ? loadError.message : '读取归档用量失败') + setError(loadError instanceof Error ? loadError.message : '读取存储用量失败') }) .finally(() => setLoading(false)) return () => controller.abort() }, []) + const plan = data?.plan + const policyConfigured = Boolean(plan?.policy_configured) + return (
@@ -37,43 +41,128 @@ export function LibraryStorageSection() {

{error}

) : null} - {page && !page.available ?

{page.reason || '归档未接线'}

: null} - {page?.available ? ( -
-
-
版本数
-
{page.versions}
+ {data && !data.available ?

{data.reason || '归档未接线'}

: null} + + {data?.available ? ( + <> +
+
+
版本数
+
{data.versions.length}
+
+
+
被版本引用的去重内容
+
{formatBytes(data.content_bytes)}
+
+
+
blob 文件(表观)
+
{formatBytes(data.blob_file_bytes)}
+
+
+
blob 实际分配
+
{formatBytes(data.blob_allocated_bytes)}
+
+
+
未被任何版本引用
+
+ {data.unreferenced_blobs} 个 / {formatBytes(data.unreferenced_bytes)} +
+
+
+
清单文件
+
{formatBytes(data.manifest_file_bytes)}
+
+
+ +
+

容量门禁

+ {data.capacity.configured ? ( +

+ 预算 {formatBytes(data.capacity.budget_bytes)} · 当前 {formatBytes(data.capacity.current_bytes)} · + 目标版本约 {formatBytes(data.capacity.required_bytes)} →{' '} + {data.capacity.ok ? '可写入' : `阻断:${data.capacity.reason}`} +

+ ) : ( +

+ 容量预算未设置(LIBRARY_CAPACITY_BUDGET_BYTES):无法证明装得下,生产写入按阻断处理。 +

+ )}
-
-
被版本引用的去重内容
-
{formatBytes(page.content_bytes)}
+ +
+

保留与依赖保护

+

+ {policyConfigured + ? `策略:${[ + plan && plan.policy.keep_versions > 0 ? `保留最近 ${plan.policy.keep_versions} 个版本` : '', + plan && plan.policy.keep_days > 0 ? `保留 ${plan.policy.keep_days} 天` : '', + ] + .filter(Boolean) + .join(' + ')}` + : '策略:未设置(不生成清理候选)'} +

+

+ 受保护版本 {plan?.protected.length ?? 0} 个:生产生效、每库最近封存、每次生产预备份、在飞作业引用, + 不论多久都不会进入候选。 +

+ {data.versions.filter((item) => item.protected).length > 0 ? ( +
    + {data.versions + .filter((item) => item.protected) + .map((item) => ( +
  • + {item.id.slice(0, 12)} {item.kind} · {(item.protected_by ?? []).join('、')} +
  • + ))} +
+ ) : null}
-
-
blob 文件(表观)
-
{formatBytes(page.blob_file_bytes)}
+ +
+

清理预览

+ {policyConfigured ? ( + plan && plan.candidates.length > 0 ? ( + <> +

+ 按策略可考虑清理 {plan.candidates.length} 个版本,独占字节上限{' '} + {formatBytes(plan.reclaim_preview_bytes)}(共享 blob 不会因此释放,这不是可回收空间)。 +

+
    + {plan.candidates.map((item) => ( +
  • + {item.id.slice(0, 12)} {item.kind} · {item.reason.join(';')} ·{' '} + {formatBytes(item.exclusive_bytes)} +
  • + ))} +
+ + ) : ( +

按当前策略没有可清理的候选版本。

+ ) + ) : ( +

+ 保留数量与天数都未设置,按「全部保留」处理:不生成候选,也不提供默认值。 +

+ )} + {plan?.blocked.length ? ( +
    + {plan.blocked.map((item) => ( +
  • {item}
  • + ))} +
+ ) : null}
-
-
blob 实际分配
-
{formatBytes(page.blob_allocated_bytes)}
-
-
-
未被任何版本引用
-
- {page.unreferenced_blobs} 个 / {formatBytes(page.unreferenced_bytes)} -
-
-
-
清单文件
-
{formatBytes(page.manifest_file_bytes)}
-
-
+ +
    +
  • 自动清理:{data.automatic_cleanup ? '开启' : '保持关闭'}(页面不提供删除动作)
  • +
  • 实际删除需要单独授权,本页只给预览
  • +
  • 以上数字都不是「可回收空间」,不能用来估算清理收益
  • + {data.notes.map((note) => ( +
  • {note}
  • + ))} +
+ ) : null} -
    -
  • 保留策略:未接线(不提供保留几版/多少天的设置)
  • -
  • 依赖保护与清理预览:未接线
  • -
  • 自动清理:保持关闭,页面不提供删除动作
  • -
  • 以上数字都不是“可回收空间”,不能用来估算清理收益
  • -
) } diff --git a/web/src/librarySnapshots.ts b/web/src/librarySnapshots.ts index e0b2396..84d41f6 100644 --- a/web/src/librarySnapshots.ts +++ b/web/src/librarySnapshots.ts @@ -311,3 +311,79 @@ export async function fetchLibraryOverview(scope: string, signal?: AbortSignal): if (!record(value)) return null return value as unknown as LibraryOverview } + +// ---- 存储管理:容量、保留策略、依赖保护与清理预览(只读) ---- +export interface LibraryStorageVersion { + id: string + kind: string + scope: string + created_at: string + protected: boolean + protected_by?: string[] + exclusive_bytes: number + shared_bytes: number +} + +export interface LibraryRetentionPolicy { + keep_versions: number + keep_days: number +} + +export interface LibraryCleanupCandidate { + id: string + kind: string + reason: string[] + exclusive_bytes: number +} + +export interface LibraryRetentionPlan { + policy: LibraryRetentionPolicy + policy_configured: boolean + automatic_cleanup: boolean + version_count: number + total_bytes: number + protected: string[] + keep: string[] + candidates: LibraryCleanupCandidate[] + reclaim_preview_bytes: number + blocked: string[] + now: string +} + +export interface LibraryCapacity { + budget_bytes: number + current_bytes: number + required_bytes: number + projected_bytes: number + configured: boolean + ok: boolean + reason?: string +} + +export interface LibraryStorage { + available: boolean + reason?: string + archive_root?: string + versions: LibraryStorageVersion[] + content_bytes: number + blob_file_bytes: number + blob_allocated_bytes: number + unreferenced_blobs: number + unreferenced_bytes: number + manifest_file_bytes: number + policy: LibraryRetentionPolicy + plan?: LibraryRetentionPlan + capacity: LibraryCapacity + automatic_cleanup: boolean + notes: string[] +} + +export async function fetchLibraryStorage(signal?: AbortSignal): Promise { + const response = await fetch('/api/v1/library/storage', { + headers: { Accept: 'application/json' }, + signal, + }) + const value = (await response.json().catch(() => null)) as unknown + if (!record(value)) return null + return value as unknown as LibraryStorage +} diff --git a/web/src/libraryStorage.css b/web/src/libraryStorage.css index c426ca9..db2423f 100644 --- a/web/src/libraryStorage.css +++ b/web/src/libraryStorage.css @@ -64,3 +64,36 @@ font-size: 12px; color: #7c2d12; } + +.library-storage-panel { + border: 1px solid #e6edf2; + border-radius: 8px; + padding: 10px 12px; + margin-bottom: 10px; +} +.library-storage-panel h4 { + margin: 0 0 6px; + font-size: 13px; +} +.library-storage-panel p { + margin: 0 0 6px; + font-size: 12px; + line-height: 1.7; + color: #3f5566; +} +.library-storage-warn { + color: #986b24 !important; +} +.library-storage-versions { + margin: 4px 0 0; + padding-left: 18px; + font-size: 12px; + line-height: 1.8; + color: #3f5566; +} +.library-storage-blocked-list { + margin: 4px 0 0; + padding-left: 18px; + font-size: 12px; + color: #a03a1e; +}