package governance import ( "crypto/sha256" "encoding/hex" "errors" "fmt" "strings" "time" ) // 发布执行身份:operation / attempt 与版本事件、current 指针的唯一约定。 // // 为什么必须把这几件事分开: // - operation 是**用户的一次明确意图**(发布到这个快照 / 恢复到这个快照)。它不该被 // "这个快照已经成功过"吞掉——用户再次要求同一个目标状态是一次新意图,必须真的执行并 // 留下自己的记录(F01)。 // - attempt 是这次意图的**执行代次**(epoch)。崩溃、接管只新增代次,不新造意图, // 否则维护窗口、预备份、写集合的谱系就断了(F15)。旧代次一旦失租就不能再写(F13)。 // - 版本事件是**不可变事实**,同一快照被两个 operation 引用是两条事件,谁也不能覆盖谁 // (F02/F09)。current 只是一个"现在生效的是哪条事件"的指针,用单调次序做条件更新, // 不反过来修改历史。 // ErrLibraryEpochStale:这次写入来自已经失租/被接管的执行代次。 // 调用方必须停止副作用并把控制权交给当前代次,不能用"重试"掩盖。 var ErrLibraryEpochStale = errors.New("library attempt epoch is stale: another attempt owns this operation") // ErrLibraryCurrentStale:这条事件不是当前该生效的事实(有更晚的真相已登记)。 var ErrLibraryCurrentStale = errors.New("library current pointer already advanced past this event") // ErrLibraryOperationConflict:同一 operation 键被用在了不同的请求内容上。 var ErrLibraryOperationConflict = errors.New("library operation key reused with a different request") // LibraryAttemptState 是一次执行代次的状态。 type LibraryAttemptState string const ( // LibraryAttemptClaimed:已被某个 worker 认领,尚未进入维护窗口。 LibraryAttemptClaimed LibraryAttemptState = "claimed" // LibraryAttemptRunning:正在执行(持有目标执行域)。 LibraryAttemptRunning LibraryAttemptState = "running" LibraryAttemptCompleted LibraryAttemptState = "completed" LibraryAttemptFailed LibraryAttemptState = "failed" LibraryAttemptAbandoned LibraryAttemptState = "abandoned" ) // LibraryOperation 是一次明确意图。字段一旦写入就不再改变(锚点另见 LibraryAnchors)。 type LibraryOperation struct { ID string `json:"id"` Scope string `json:"scope"` Kind LibraryJobKind `json:"kind"` TargetSnapshotID string `json:"target_snapshot_id"` RequestDigest string `json:"request_digest"` OperationKey string `json:"operation_key"` Actor string `json:"actor"` CreatedAt time.Time `json:"created_at"` } // LibraryAnchors 是 operation 的**不可变首次锚点**:预备份身份/字节、写集合摘要、 // 目标指纹。所有 attempt 继承它;接管不许"再拍一份",也不许用新值覆盖它(F07/F09)。 type LibraryAnchors struct { FirstBackupSnapshotID string `json:"first_backup_snapshot_id,omitempty"` FirstBackupBytes *int64 `json:"first_backup_bytes,omitempty"` FirstBackupAt *time.Time `json:"first_backup_at,omitempty"` WriteSetDigest string `json:"writeset_digest,omitempty"` WriteSetRows *int64 `json:"writeset_rows,omitempty"` TargetFingerprint string `json:"target_fingerprint,omitempty"` RecordedAt *time.Time `json:"recorded_at,omitempty"` } // LibraryAttempt 是 operation 的一次执行代次。 type LibraryAttempt struct { OperationID string `json:"operation_id"` Epoch int `json:"epoch"` JobID string `json:"job_id"` QueueJobID string `json:"queue_job_id"` Owner string `json:"owner"` State LibraryAttemptState `json:"state"` StartedAt time.Time `json:"started_at"` HeartbeatAt *time.Time `json:"heartbeat_at,omitempty"` LeaseUntil *time.Time `json:"lease_until,omitempty"` FinishedAt *time.Time `json:"finished_at,omitempty"` Outcome string `json:"outcome,omitempty"` } // LibraryOperationID 由 (scope, kind, operation 键) 决定:同一个客户端重放键永远得到 // 同一个 operation(幂等),换一个键就是一次新意图(不是"历史成功")。 func LibraryOperationID(scope string, kind LibraryJobKind, operationKey string) string { sum := sha256.Sum256([]byte(string(kind) + "|" + scope + "|" + operationKey)) return "libop-" + hex.EncodeToString(sum[:])[:24] } // LibraryVersionEventID 生成一条**不可变版本事件**的 ID:同一个 operation 对同一快照 // 同一类别只产生一条事件(重放幂等);不同 operation 即使引用同一快照也是不同事件, // 因此 `source_job_id`/`evidence`/`created_at` 不会被后来的执行覆盖(F02)。 // operationID 为空时退回旧形状,供历史行/旧调用方保持同一身份。 func LibraryVersionEventID(kind LibraryVersionKind, scope, snapshotID, operationID string) string { identity := string(kind) + "|" + scope + "|" + snapshotID if operationID != "" { identity += "|" + operationID } sum := sha256.Sum256([]byte(identity)) return "libver-" + hex.EncodeToString(sum[:])[:16] } // CurrentOrderKey 给"这条事实是什么时候被记录为真相的"一个**单调可比较**的键。 // // 用它做 current 指针的条件更新:后来登记的事实可以推进指针,更早的不能把指针拉回历史。 // 旧执行代次"迟到 finalize 反转 current"在写边界就被拦住了(epoch 守卫), // 所以这里不需要也不该再拿 operation 的创建时间当次序——恢复回滚必须能把指针指回更早发布的 // 快照,那个事件的**登记时间**是新的。 func CurrentOrderKey(recordedAt time.Time, operationID string, epoch int) string { return fmt.Sprintf("%020d|%s|%09d", recordedAt.UTC().UnixNano(), operationID, epoch) } // CanAdvanceCurrent 判断一条新事实能否推进 current 指针(纯函数,供写入路径与测试共用)。 // 返回 false 表示"这条事件只能确认自己的历史",调用方必须拒绝把它登记成当前状态。 func CanAdvanceCurrent(currentOrderKey, nextOrderKey string) bool { if nextOrderKey == "" { return false } if currentOrderKey == "" { return true } return nextOrderKey > currentOrderKey } // LibraryJobTypePrefix 是所有整库发布相关队列作业的类型前缀。 // // 这些类型的准入条件(生产闸口、精确授权、维护互斥、目标身份核验)只在发布管理专用 // 入口里判断,所以它们对通用 queue 入口是**保留类型**:通用入口的通用 engineer 角色 // 检查替代不了准入,允许它造一个 library.* 作业就是绕过整条准入链(F14)。 const LibraryJobTypePrefix = "library." // IsReservedLibraryJobType 按前缀整类判断,而不是逐个列举类型: // 以后新增一种 library 作业类型时不会漏掉准入。 func IsReservedLibraryJobType(jobType string) bool { return strings.HasPrefix(strings.TrimSpace(jobType), LibraryJobTypePrefix) } // ValidateLibraryOperation 只做结构校验:缺字段就拒绝,不猜默认值。 func ValidateLibraryOperation(op LibraryOperation) error { if op.ID == "" || op.OperationKey == "" || op.RequestDigest == "" || op.CreatedAt.IsZero() { return errors.New("library operation requires id, key, digest and created_at") } if op.Scope != "internal" && op.Scope != "external" { return errors.New("library operation requires internal or external scope") } switch op.Kind { case LibraryJobSeal, LibraryJobSync, LibraryJobRestore, LibraryJobBaseline, LibraryJobRecover: default: return fmt.Errorf("unsupported library operation kind %q", op.Kind) } return nil }