package libraryretention import ( "fmt" "math" ) // 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"` } // addCapacity 安全相加:int64 溢出时必须拒绝,而不是绕回负数让门禁通过。 func addCapacity(current, required int64) (int64, bool) { if current < 0 || required < 0 { return 0, false } if current > math.MaxInt64-required { return 0, false } return current + required, true } func CheckCapacity(currentBytes, requiredBytes, budgetBytes int64) Capacity { result := Capacity{BudgetBytes: budgetBytes, CurrentBytes: currentBytes, RequiredBytes: requiredBytes} if budgetBytes <= 0 { result.Reason = "容量预算未设置(LIBRARY_CAPACITY_BUDGET_BYTES),无法证明装得下" return result } result.Configured = true if currentBytes < 0 || requiredBytes < 0 { result.Reason = "容量口径异常(负数),拒绝放行" return result } projected, ok := addCapacity(currentBytes, requiredBytes) if !ok { // 溢出说明真实需求已经大得离谱:不能算出一个负数后"通过"。 result.Reason = "容量相加溢出 int64,拒绝放行" return result } result.ProjectedByte = projected if projected > budgetBytes { result.Reason = fmt.Sprintf("写入后预计占用 %d 字节,超过预算 %d 字节", projected, budgetBytes) return result } result.OK = true return result }