From 92695dc332714ba84fd8e064593bdd88a3e33bc2 Mon Sep 17 00:00:00 2001 From: admin Date: Fri, 16 Oct 2026 01:24:38 +0800 Subject: [PATCH] feat: add panel operation CAS state machine --- agent/internal/api/server.go | 5 + agent/internal/operation/store.go | 12 +- agent/internal/operation/store_test.go | 45 + docs/GO_AGENT_PHP_OPERATION_CAS.md | 98 ++ web/app/Models/CloudAgentOperation.php | 34 + .../Cloud/CloudAgentOperationClaim.php | 54 + .../Cloud/CloudAgentOperationEnvelope.php | 46 +- .../Cloud/CloudAgentOperationException.php | 26 + .../Cloud/CloudAgentOperationRepository.php | 930 ++++++++++++++++++ ...loudAgentOperationEnvelopeContractTest.php | 61 ++ ...udAgentOperationRepositoryContractTest.php | 84 ++ 11 files changed, 1386 insertions(+), 9 deletions(-) create mode 100644 docs/GO_AGENT_PHP_OPERATION_CAS.md create mode 100644 web/app/Models/CloudAgentOperation.php create mode 100644 web/app/Services/Cloud/CloudAgentOperationClaim.php create mode 100644 web/app/Services/Cloud/CloudAgentOperationException.php create mode 100644 web/app/Services/Cloud/CloudAgentOperationRepository.php create mode 100644 web/tests/CloudAgentOperationRepositoryContractTest.php diff --git a/agent/internal/api/server.go b/agent/internal/api/server.go index 9a241ed9..2a4aa302 100644 --- a/agent/internal/api/server.go +++ b/agent/internal/api/server.go @@ -563,6 +563,11 @@ func (s *Server) completeCapabilityProbe(w http.ResponseWriter, record operation return } result, _ := json.Marshal(snapshot) + if _, boundaryErr := s.store.SetCommitBoundary(record.OperationID, "capability_readback_confirmed"); boundaryErr != nil { + _, _ = s.store.Update(record.OperationID, operation.StatusUncertain, result, "operation_journal_update_failed", "capability probe was confirmed but operation state could not be committed") + writeJSON(w, http.StatusServiceUnavailable, errorResponse{Error: "operation result could not be committed"}) + return + } updated, err := s.store.Update(record.OperationID, operation.StatusSucceeded, result, "", "") if err != nil { writeJSON(w, http.StatusServiceUnavailable, errorResponse{Error: "operation result could not be committed"}) diff --git a/agent/internal/operation/store.go b/agent/internal/operation/store.go index e79e55fe..8415fe96 100644 --- a/agent/internal/operation/store.go +++ b/agent/internal/operation/store.go @@ -753,6 +753,9 @@ func (s *Store) Update(operationID string, status Status, result json.RawMessage if !validErrorCode(errorCode) || !validErrorMessage(errorMessage) { return Record{}, fmt.Errorf("operation error metadata is invalid") } + if status == StatusSucceeded && (record.CommitBoundary == "" || record.CommitBoundary == "not_started" || record.CommitBoundary == "unknown") { + return Record{}, fmt.Errorf("successful operation requires a proven commit boundary") + } previous := record record.Status = status record.Version++ @@ -801,12 +804,19 @@ func (s *Store) RecoverInFlight() (int, error) { if record.Status != StatusPending && record.Status != StatusRunning { continue } + wasRunning := record.Status == StatusRunning record.Status = StatusUncertain record.Version++ record.UpdatedAt = now record.ErrorCode = "agent_restarted_before_readback" record.ErrorMessage = "operation was in flight when the agent restarted" - record.CommitBoundary = "unknown" + // A proven host boundary is durable evidence even when the process + // restarts before terminal read-back. Only an in-flight record with + // no prior boundary becomes unknown; do not erase seed/read-back + // evidence that reconciliation needs. + if wasRunning && (record.CommitBoundary == "" || record.CommitBoundary == "not_started") { + record.CommitBoundary = "unknown" + } s.records[id] = record changed++ } diff --git a/agent/internal/operation/store_test.go b/agent/internal/operation/store_test.go index dcb7cc33..7f3df9a6 100644 --- a/agent/internal/operation/store_test.go +++ b/agent/internal/operation/store_test.go @@ -81,6 +81,51 @@ func TestUpdateRollsBackOnInvalidStatus(t *testing.T) { } } +func TestRecoverInFlightPreservesProvenCommitBoundary(t *testing.T) { + store := NewMemory() + request := beginRequest() + if _, _, err := store.Begin(request); err != nil { + t.Fatal(err) + } + if _, err := store.Update(request.OperationID, StatusRunning, nil, "", ""); err != nil { + t.Fatal(err) + } + if _, err := store.SetCommitBoundary(request.OperationID, "seed_published"); err != nil { + t.Fatal(err) + } + if changed, err := store.RecoverInFlight(); err != nil || changed != 1 { + t.Fatalf("RecoverInFlight() changed=%d err=%v", changed, err) + } + recovered, err := store.Get(request.OperationID) + if err != nil { + t.Fatal(err) + } + if recovered.Status != StatusUncertain || recovered.CommitBoundary != "seed_published" { + t.Fatalf("recovery erased proven boundary: %+v", recovered) + } +} + +func TestRecoverInFlightMarksUnprovenRunningBoundaryUnknown(t *testing.T) { + store := NewMemory() + request := beginRequest() + if _, _, err := store.Begin(request); err != nil { + t.Fatal(err) + } + if _, err := store.Update(request.OperationID, StatusRunning, nil, "", ""); err != nil { + t.Fatal(err) + } + if _, err := store.RecoverInFlight(); err != nil { + t.Fatal(err) + } + recovered, err := store.Get(request.OperationID) + if err != nil { + t.Fatal(err) + } + if recovered.CommitBoundary != "unknown" { + t.Fatalf("unproven running boundary = %q, want unknown", recovered.CommitBoundary) + } +} + func TestNonceConsumptionSurvivesJournalReload(t *testing.T) { path := filepath.Join(t.TempDir(), "operations.json") store, err := Open(path) diff --git a/docs/GO_AGENT_PHP_OPERATION_CAS.md b/docs/GO_AGENT_PHP_OPERATION_CAS.md new file mode 100644 index 00000000..3c7dca14 --- /dev/null +++ b/docs/GO_AGENT_PHP_OPERATION_CAS.md @@ -0,0 +1,98 @@ +# Go Agent 面板 operation CAS 边界 + +状态:`go-agent` 分支的 greenfield 面板状态机基础层。该组件尚未接入旧 +PHP 用户/管理员路由,也不调用宿主机、SSH、Python Engine 或旧数据库。 + +## 责任边界 + +`CloudAgentOperationRepository` 是新表 `cloud_agent_operations` 的唯一写入 +入口。它只负责以下面板侧事实: + +- 以 `operation_id + agent_id + idempotency_key + request_hash` 保留一次新的 + typed operation;相同身份可安全重放读取,不同请求会返回冲突; +- 用 `version`、`lease_owner`、`lease_expires_at` 和 `attempt_count` 做跨 PHP + worker 的 CAS/租约 fencing; +- 保存有限的 desired/result JSON、状态、错误码和 commit boundary;不会保存 + Agent 错误详情、原始 XML、网络/启动脚本、宿主路径、URL、命令或凭据; +- 在网络结果未知时把状态保留为 `uncertain`,只允许显式 `reconcile` claim, + 不把原 destructive request 自动重放成新的 dispatch; +- 返回不携带 lease owner 的公开记录。`CloudAgentOperationClaim` 只在当前 + PHP 进程内使用,显式禁止队列序列化。 + +Agent HTTP 必须在事务外执行。正确顺序是: + +```text +reserve + -> claim(dispatch) + -> [HTTP Agent 请求;不持有数据库事务] + -> renew(长操作仍在执行且租约尚未过期时) + -> setCommitBoundary(如有宿主 read-back 证据) + -> finalize(succeeded|failed;省略 boundary 时保留当前证据) + -> 或 markUncertain / claim(reconcile) +``` + +### 状态转移 + +| 当前状态 | 允许动作 | 结果 | +| --- | --- | --- | +| `pending` | `claim(dispatch)` | `running`,版本与尝试次数递增 | +| `running` 且租约有效 | 同一 claim 的 boundary/finalize | CAS 成功才可写入 | +| `running` 且租约过期 | 任意新 claim | 先提交 `uncertain + lease_expired`,然后要求只读核对 | +| `uncertain` | `claim(reconcile)` | 继续 `uncertain`,不得变成 dispatch | +| `running/uncertain` | `finalize` | `succeeded`、`failed` 或再次 `uncertain` | +| 终态 | 任意 claim/finalize | 拒绝,不能覆盖既有证据 | + +过期 fencing 在同一数据库事务中写入,但异常在事务提交后才抛出;这样不会因 +“通知调用方必须核对”而把 fencing 回滚成陈旧的 `running`。所有更新都要求 +`operation_id + version + status + lease_owner`,终态还要求 lease 仍未过期, +因此迟到的 worker 不能覆盖新的核对结果。 + +`renew()` 也必须带同一个 fencing token,并且只接受仍未过期的租约。它只延长 +租约并递增版本,不会把 `uncertain` 变回 `running`;续租失败时应立即停止等待 +原请求并转入只读核对。租约过期 fencing 只会把尚未证明的 +`not_started` boundary 变为 `unknown`,已经由宿主 read-back 证明的 boundary +必须保留,供 reconcile 决定清理或继续观察。 + +## 数据和错误边界 + +- desired/result 只接受受限 JSON;根 desired 必须是非空对象,result 必须是非空 + 对象或 `null`(不接受 JSON list/空对象),嵌套深度和字节数有上限,字段名拒绝 + 控制字符、路径/XML/网络/启动脚本/凭据等敏感形态。非凭据摘要 + 字段(例如 `xml_hash`、`plan_hash`)可保留,但不代表原文已经进入数据库; + `password_hash`、`secret_hash`、`token_hash` 等凭据摘要也拒绝进入 operation + result,避免把认证材料的衍生物误当作普通资源身份。 +- `error_code` 是稳定的小写机器码;人类错误详情不进入 journal。数据库异常 + 对外统一映射为安全的 `storage_unavailable`,不泄露 SQL/连接细节。 +- `CloudAgentOperationException` 使用独立的 `errorCode` 属性,不重声明 PHP + 内置 `Exception::$code`;HTTP 状态仅由 API adapter 映射,不能作为业务错误码。 +- 新 schema 的 `version` 是独立 CAS token(marker v2),不能用秒级 + `updated_at` 代替;数据库仍是新库初始化,不执行旧表迁移、解密或回填。 +- `finalize()`/`markUncertain()` 未显式给出 boundary 时保留当前已证明值;只有 + `uncertain` 且仍为 `not_started` 的记录会被标为 `unknown`。它们不会把 + `seed_published`、`readback_confirmed` 等证据回退掉。 +- `succeeded` 终态必须带非 `not_started`/`unknown` 的宿主 commit boundary;没有 + read-back 证据的请求只能停在 `failed` 或 `uncertain`。 +- `reserve()` 接收的 `request_hash` 是调用方已经从 canonical request body + 计算出的值,不是授权或 hash 生成器;在接入 gateway 前必须先做 typed + normalizer、校验 `target`/`instance_uuid` 与 desired 的一致性,并绑定 actor、 + host/enrollment generation,再调用 reserve。不能让 HTTP 参数直接透传成 + trusted replay。 + +## 接入前必须完成的工作 + +这层完成后仍不能宣布生产切换。接 gateway 时必须再完成: + +1. 将 `agent_id` 与不可变的宿主/enrollment generation 绑定,防止重新注册后 + 旧 operation 被路由到错误宿主;当前 repository 只接受 registry 已验证的 + `agent_id`,不会自行推断 host 归属。 +2. 由唯一 gateway 在事务外构造 mTLS/HMAC client,校验完整响应 envelope,再 + 调用 `setCommitBoundary`/`finalize`;不能把任意 HTTP JSON 直接写进 result。 +3. 为不同 operation kind 定义 commit boundary 的合法顺序、清理清单和只读 + reconcile;当前 repository 只提供 CAS,不替业务宣称宿主动作已完成。 +4. 在 CI/部署环境执行 PHP 8.5、Eloquent、真实 MariaDB 并发测试。当前开发 + shell 没有 PHP/Composer,因此本轮只能提供源码契约检查;Go `race/vet` + 不能替代 PHP/数据库/真实宿主验收。 + +旧 `CloudJob`、Python Engine、SSH 和现有业务路由仍保留为独立回滚面,直到 +每个 typed Agent operation 完成 shadow、103 宿主只读验证、真实 read-back 和 +回滚窗口验收后,才允许另一个独立提交删除它们。 diff --git a/web/app/Models/CloudAgentOperation.php b/web/app/Models/CloudAgentOperation.php new file mode 100644 index 00000000..054fc511 --- /dev/null +++ b/web/app/Models/CloudAgentOperation.php @@ -0,0 +1,34 @@ + 'int', + 'version' => 'int', + 'attempt_count' => 'int', + 'lease_expires_at' => 'int', + 'created_at' => 'int', + 'updated_at' => 'int', + 'completed_at' => 'int', + ]; +} diff --git a/web/app/Services/Cloud/CloudAgentOperationClaim.php b/web/app/Services/Cloud/CloudAgentOperationClaim.php new file mode 100644 index 00000000..3303a776 --- /dev/null +++ b/web/app/Services/Cloud/CloudAgentOperationClaim.php @@ -0,0 +1,54 @@ +assertValid(); + } + + public function assertValid(): void + { + if (preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/D', $this->operationId) !== 1 + || $this->version < 1 + || preg_match('/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/D', $this->leaseOwner) !== 1) { + throw new \InvalidArgumentException('Agent operation claim identity is invalid'); + } + $validPair = ($this->mode === 'dispatch' && $this->status === 'running') + || ($this->mode === 'reconcile' && $this->status === 'uncertain'); + if (!$validPair) { + throw new \InvalidArgumentException('Agent operation claim mode/status is invalid'); + } + } + + public function next(int $version, string $status): self + { + return new self($this->operationId, $version, $this->leaseOwner, + $this->mode, $status); + } + + public function __serialize(): array + { + throw new \LogicException('Agent operation claims must not be serialized'); + } + + /** @param array $data */ + public function __unserialize(array $data): void + { + throw new \LogicException('Agent operation claims must not be unserialized'); + } +} diff --git a/web/app/Services/Cloud/CloudAgentOperationEnvelope.php b/web/app/Services/Cloud/CloudAgentOperationEnvelope.php index a4dce565..88b98a19 100644 --- a/web/app/Services/Cloud/CloudAgentOperationEnvelope.php +++ b/web/app/Services/Cloud/CloudAgentOperationEnvelope.php @@ -101,13 +101,15 @@ final class CloudAgentOperationEnvelope $result = null; if (array_key_exists('result', $response) && $response['result'] !== null) { - if (!is_array($response['result'])) { + if (!is_array($response['result']) + || array_is_list($response['result']) + || $response['result'] === []) { throw new CloudError('宿主机 Agent 操作结果格式无效', 502); } $result = self::projectResult($kind, $response['result']); self::assertSafeResult($result); } - self::assertStatusShape($status, $errorCode, $result); + self::assertStatusShape($status, $boundary, $errorCode, $result); return new self( $operationId, @@ -198,7 +200,14 @@ final class CloudAgentOperationEnvelope } if (is_string($key)) { $normalized = self::normalizeResultKey($key); - if (self::isSensitiveResultKey($normalized)) { + if (self::isDigestResultKey($normalized) + && (!self::isSafeDigestResultKey($normalized) + || !self::isDigestResultValue($item))) { + throw new CloudError('宿主机 Agent 操作摘要字段无效', 502); + } + if (self::isSensitiveResultKey($normalized) + && (!self::isSafeDigestResultKey($normalized) + || !self::isDigestResultValue($item))) { throw new CloudError('宿主机 Agent 操作结果包含敏感字段', 502); } } @@ -239,11 +248,8 @@ final class CloudAgentOperationEnvelope private static function isSensitiveResultKey(string $normalized): bool { - // A digest is metadata, not the underlying secret/XML/path. Keep the - // explicit suffix exception limited to an actual hash/digest field; - // ordinary secret_ref or diagnostic names still fail below. if (preg_match('/(?:^|_)(hash|digest|sha256)$/', $normalized) === 1) { - return false; + return true; } return preg_match( '/(?:^|_)(password|token|secret|secret_ref|private|private_key|credential|startup|startup_script|network|network_config|raw|raw_xml|normalized|normalized_xml|xml|path|url|directory|source|source_ref|endpoint|command|argv|stderr|error_message|error_detail|resolved_addresses|cipher)(?:_|$)/', @@ -251,8 +257,29 @@ final class CloudAgentOperationEnvelope ) === 1; } + private static function isDigestResultKey(string $normalized): bool + { + return preg_match('/(?:^|_)(hash|digest|sha256|fingerprint)$/', $normalized) === 1; + } + + private static function isSafeDigestResultKey(string $normalized): bool + { + return self::isDigestResultKey($normalized) + && preg_match('/(?:^|_)(password|passwd|token|secret|private|credential|api_key|access_key|signing_key|hmac_key)(?:_|$)/', $normalized) !== 1; + } + + private static function isDigestResultValue(mixed $value): bool + { + return is_string($value) && preg_match('/^[a-f0-9]{64}$/D', $value) === 1; + } + /** @param array|null $result */ - private static function assertStatusShape(string $status, string $errorCode, ?array $result): void + private static function assertStatusShape( + string $status, + string $boundary, + string $errorCode, + ?array $result, + ): void { if (in_array($status, ['pending', 'running'], true) && ($errorCode !== '' || $result !== null)) { @@ -261,6 +288,9 @@ final class CloudAgentOperationEnvelope if ($status === 'succeeded' && $errorCode !== '') { throw new CloudError('宿主机 Agent 成功操作携带了错误码', 502); } + if ($status === 'succeeded' && in_array($boundary, ['not_started', 'unknown'], true)) { + throw new CloudError('宿主机 Agent 成功操作缺少 commit boundary', 502); + } if (in_array($status, ['failed', 'uncertain'], true) && $errorCode === '') { throw new CloudError('宿主机 Agent 未成功操作缺少错误码', 502); } diff --git a/web/app/Services/Cloud/CloudAgentOperationException.php b/web/app/Services/Cloud/CloudAgentOperationException.php new file mode 100644 index 00000000..63211b03 --- /dev/null +++ b/web/app/Services/Cloud/CloudAgentOperationException.php @@ -0,0 +1,26 @@ + 599) { + throw new \InvalidArgumentException('Agent operation exception metadata is invalid'); + } + $this->errorCode = $errorCode; + $this->httpStatus = $httpStatus; + parent::__construct($message); + } +} diff --git a/web/app/Services/Cloud/CloudAgentOperationRepository.php b/web/app/Services/Cloud/CloudAgentOperationRepository.php new file mode 100644 index 00000000..c48dd9e0 --- /dev/null +++ b/web/app/Services/Cloud/CloudAgentOperationRepository.php @@ -0,0 +1,930 @@ + */ + private const KINDS = [ + 'capability_probe', + 'domain_read', + 'domain_power', + 'seed_prepare', + 'domain_preflight', + 'domain_create_plan', + 'domain_create_validate', + ]; + + /** @var object */ + private object $connection; + + /** + * @param object|null $connection Illuminate database connection; omitted + * in production so the new model selects the configured default. + */ + public function __construct(?object $connection = null) + { + $this->connection = $connection ?? (new CloudAgentOperation())->getConnection(); + } + + /** + * Reserve one operation idempotently. + * + * @param array $input + * @return array{record:array,replay:bool} + */ + public function reserve(array $input, ?int $now = null): array + { + $request = self::normalizeReservation($input); + $now = self::clock($now); + + // A unique-key race can occur between two PHP workers. Re-read once + // after the database rolls back the losing insert; never return a + // database exception or silently create a second operation. + for ($attempt = 0; $attempt < 2; $attempt++) { + try { + return $this->connection->transaction(function () use ($request, $now): array { + $table = $this->connection->table(self::TABLE); + $existing = $table->where('operation_id', $request['operation_id']) + ->lockForUpdate()->first(); + if ($existing !== null) { + return $this->replayOrConflict($existing, $request); + } + + $existing = $table->where('agent_id', $request['agent_id']) + ->where('idempotency_key', $request['idempotency_key']) + ->lockForUpdate()->first(); + if ($existing !== null) { + return $this->replayOrConflict($existing, $request); + } + + $table->insert([ + 'operation_id' => $request['operation_id'], + 'idempotency_key' => $request['idempotency_key'], + 'agent_id' => $request['agent_id'], + 'instance_uuid' => $request['instance_uuid'], + 'kind' => $request['kind'], + 'target' => $request['target'], + 'request_hash' => $request['request_hash'], + 'desired_json' => $request['desired_json'], + 'status' => 'pending', + 'version' => 1, + 'attempt_count' => 0, + 'lease_owner' => '', + 'lease_expires_at' => null, + 'commit_boundary' => 'not_started', + 'result_json' => null, + 'error_code' => '', + 'error_detail' => '', + 'created_at' => $now, + 'updated_at' => $now, + 'completed_at' => null, + ]); + $created = $table->where('operation_id', $request['operation_id']) + ->lockForUpdate()->first(); + if ($created === null) { + throw new CloudAgentOperationException( + 'storage_unavailable', 'Agent 操作记录未能读取', 503); + } + return [ + 'record' => self::publicRecord($created), + 'replay' => false, + ]; + }); + } catch (QueryException $error) { + if ($attempt === 0 && self::isUniqueViolation($error)) { + continue; + } + throw new CloudAgentOperationException( + 'storage_unavailable', 'Agent 操作记录暂时不可用', 503); + } catch (CloudAgentOperationException $error) { + throw $error; + } catch (\Throwable) { + throw new CloudAgentOperationException( + 'storage_unavailable', 'Agent 操作记录暂时不可用', 503); + } + } + + throw new CloudAgentOperationException( + 'storage_unavailable', 'Agent 操作记录暂时不可用', 503); + } + + /** + * Claim a pending dispatch or an uncertain read-only reconciliation. + * + * An expired running lease is first fenced to uncertain and never turned + * back into running by this method. Only an explicit `reconcile` claim + * may acquire a lease while status is uncertain. + */ + public function claim( + string $operationId, + string $leaseOwner, + int $leaseSeconds, + string $mode = 'dispatch', + ?int $now = null, + ): array { + $operationId = self::operationId($operationId); + $leaseOwner = self::leaseOwner($leaseOwner); + if ($leaseSeconds < 1 || $leaseSeconds > 900) { + throw new CloudAgentOperationException('invalid_request', 'Agent 租约时长无效', 422); + } + if (!in_array($mode, ['dispatch', 'reconcile'], true)) { + throw new CloudAgentOperationException('invalid_request', 'Agent 操作 claim 模式无效', 422); + } + $now = self::clock($now); + + try { + $result = $this->connection->transaction(function () use ( + $operationId, $leaseOwner, $leaseSeconds, $mode, $now + ): array { + $table = $this->connection->table(self::TABLE); + $row = $table->where('operation_id', $operationId)->lockForUpdate()->first(); + if ($row === null) { + throw new CloudAgentOperationException('not_found', 'Agent 操作不存在', 404); + } + $status = (string) ($row->status ?? ''); + $version = self::positiveInt($row->version ?? null); + $expiry = self::nullableInt($row->lease_expires_at ?? null); + $owner = (string) ($row->lease_owner ?? ''); + if ($version < 1 || !in_array($status, self::statuses(), true)) { + throw new CloudAgentOperationException('invalid_state', 'Agent 操作状态损坏', 409); + } + + if ($status === 'running') { + if ($expiry !== null && $expiry > $now) { + throw new CloudAgentOperationException('lease_busy', 'Agent 操作仍由其他 worker 持有', 409); + } + // A crashed worker cannot be safely replayed. Fence it + // before returning; the caller must reconcile by GET. + $boundary = (string) ($row->commit_boundary ?? ''); + $fencedBoundary = ($boundary === '' || $boundary === 'not_started') + ? 'unknown' : $boundary; + $fenced = $table->where('operation_id', $operationId) + ->where('version', $version) + ->where('status', 'running') + ->where('lease_owner', $owner) + ->update([ + 'status' => 'uncertain', + 'version' => $version + 1, + 'lease_owner' => '', + 'lease_expires_at' => null, + // Preserve a boundary already proven by the host; + // only an operation with no proven boundary is + // downgraded to unknown after lease expiry. + 'commit_boundary' => $fencedBoundary, + 'error_code' => 'lease_expired', + 'error_detail' => '', + 'updated_at' => $now, + ]); + if ((int) $fenced !== 1) { + throw new CloudAgentOperationException('lease_lost', 'Agent 操作租约已失效', 409); + } + // The transaction must commit the fence before the + // caller is told to reconcile; throwing here would roll + // the status change back and leave a stale running row. + return ['expired' => true]; + } + + if ($mode === 'dispatch') { + if ($status !== 'pending') { + throw new CloudAgentOperationException( + 'invalid_transition', '不确定操作禁止重新派发', 409); + } + } elseif ($status !== 'uncertain') { + throw new CloudAgentOperationException( + 'invalid_transition', '只有 uncertain 操作可以 reconcile', 409); + } + if ($expiry !== null && $expiry > $now) { + throw new CloudAgentOperationException('lease_busy', 'Agent 操作仍由其他 worker 持有', 409); + } + if ($status === 'uncertain' && $owner !== '' && $expiry !== null && $expiry <= $now) { + // The old reconcile lease is dead; this write clears it + // and advances the token before a new claimant proceeds. + $cleared = $table->where('operation_id', $operationId) + ->where('version', $version) + ->where('status', 'uncertain') + ->where('lease_owner', $owner) + ->update([ + 'version' => $version + 1, + 'lease_owner' => '', + 'lease_expires_at' => null, + 'updated_at' => $now, + ]); + if ((int) $cleared !== 1) { + throw new CloudAgentOperationException('lease_lost', 'Agent 操作租约已失效', 409); + } + $version++; + $owner = ''; + } + $attempts = self::nonNegativeInt($row->attempt_count ?? null); + if ($attempts >= 100) { + throw new CloudAgentOperationException('attempt_limit', 'Agent 操作尝试次数已达上限', 409); + } + $nextStatus = $mode === 'dispatch' ? 'running' : 'uncertain'; + $nextVersion = $version + 1; + $updated = $table->where('operation_id', $operationId) + ->where('version', $version) + ->where('status', $status) + ->where('lease_owner', $owner) + ->where(function ($query) use ($now): void { + $query->whereNull('lease_expires_at')->orWhere('lease_expires_at', '<=', $now); + }) + ->update([ + 'status' => $nextStatus, + 'version' => $nextVersion, + 'attempt_count' => $attempts + 1, + 'lease_owner' => $leaseOwner, + 'lease_expires_at' => $now + $leaseSeconds, + 'updated_at' => $now, + ]); + if ((int) $updated !== 1) { + throw new CloudAgentOperationException('lease_lost', 'Agent 操作 claim CAS 冲突', 409); + } + $fresh = $table->where('operation_id', $operationId)->first(); + if ($fresh === null) { + throw new CloudAgentOperationException('storage_unavailable', 'Agent 操作读取失败', 503); + } + $claim = new CloudAgentOperationClaim( + $operationId, $nextVersion, $leaseOwner, $mode, $nextStatus); + return [ + 'record' => self::publicRecord($fresh), + 'claim' => $claim, + ]; + }); + if (($result['expired'] ?? false) === true) { + throw new CloudAgentOperationException( + 'uncertain', 'Agent 操作租约已过期,必须先只读核对', 409); + } + return $result; + } catch (CloudAgentOperationException $error) { + throw $error; + } catch (\Throwable) { + throw new CloudAgentOperationException( + 'storage_unavailable', 'Agent 操作记录暂时不可用', 503); + } + } + + /** + * Finalize a claim. The version and lease owner are both required; a + * late worker cannot overwrite a newer reconcile or terminal result. + * + * @param array|null $result + * @return array + */ + public function finalize( + CloudAgentOperationClaim $claim, + string $status, + ?array $result = null, + string $errorCode = '', + ?string $commitBoundary = null, + ?int $now = null, + ): array { + self::assertClaim($claim); + $now = self::clock($now); + if (!in_array($status, ['succeeded', 'failed', 'uncertain'], true)) { + throw new CloudAgentOperationException('invalid_transition', 'Agent 终态无效', 422); + } + $errorCode = self::errorCode($errorCode, $status); + $requestedBoundary = $commitBoundary === null ? null : self::boundary($commitBoundary); + if ($result !== null && (array_is_list($result) || $result === [])) { + throw new CloudAgentOperationException('invalid_request', 'Agent 操作结果必须是对象', 422); + } + $resultJson = $result === null ? null : self::safeJson($result, self::MAX_RESULT_BYTES); + $completed = in_array($status, ['succeeded', 'failed'], true) ? $now : null; + + try { + return $this->connection->transaction(function () use ( + $claim, $status, $errorCode, $requestedBoundary, $resultJson, $completed, $now + ): array { + $table = $this->connection->table(self::TABLE); + $current = $table->where('operation_id', $claim->operationId) + ->lockForUpdate()->first(); + if ($current === null) { + throw new CloudAgentOperationException('not_found', 'Agent 操作不存在', 404); + } + $effectiveBoundary = self::resolveBoundary( + (string) ($current->commit_boundary ?? ''), $requestedBoundary, $status); + if ($status === 'succeeded' + && in_array($effectiveBoundary, ['not_started', 'unknown'], true)) { + throw new CloudAgentOperationException( + 'invalid_transition', '成功操作必须有宿主 commit boundary', 409); + } + $updated = $table->where('operation_id', $claim->operationId) + ->where('version', $claim->version) + ->where('status', $claim->status) + ->where('lease_owner', $claim->leaseOwner) + ->where('lease_expires_at', '>', $now) + ->update([ + 'status' => $status, + 'version' => $claim->version + 1, + 'lease_owner' => '', + 'lease_expires_at' => null, + 'commit_boundary' => $effectiveBoundary, + 'result_json' => $resultJson, + 'error_code' => $errorCode, + 'error_detail' => '', + 'updated_at' => $now, + 'completed_at' => $completed, + ]); + if ((int) $updated !== 1) { + throw new CloudAgentOperationException('lease_lost', 'Agent 操作 finalize CAS 冲突', 409); + } + $row = $table->where('operation_id', $claim->operationId)->first(); + if ($row === null) { + throw new CloudAgentOperationException('storage_unavailable', 'Agent 操作读取失败', 503); + } + return self::publicRecord($row); + }); + } catch (CloudAgentOperationException $error) { + throw $error; + } catch (\Throwable) { + throw new CloudAgentOperationException( + 'storage_unavailable', 'Agent 操作记录暂时不可用', 503); + } + } + + /** + * Advance a proven host commit boundary while retaining the lease. + * Returns an updated claim; the old claim is intentionally stale. + * + * @return array{record:array,claim:CloudAgentOperationClaim} + */ + public function setCommitBoundary( + CloudAgentOperationClaim $claim, + string $commitBoundary, + ?int $now = null, + ): array { + self::assertClaim($claim); + $now = self::clock($now); + $commitBoundary = self::boundary($commitBoundary); + try { + return $this->connection->transaction(function () use ($claim, $commitBoundary, $now): array { + $table = $this->connection->table(self::TABLE); + $current = $table->where('operation_id', $claim->operationId) + ->lockForUpdate()->first(); + if ($current === null) { + throw new CloudAgentOperationException('not_found', 'Agent 操作不存在', 404); + } + $effectiveBoundary = self::resolveBoundary( + (string) ($current->commit_boundary ?? ''), $commitBoundary, $claim->status); + $nextVersion = $claim->version + 1; + $updated = $table->where('operation_id', $claim->operationId) + ->where('version', $claim->version) + ->where('status', $claim->status) + ->where('lease_owner', $claim->leaseOwner) + ->where('lease_expires_at', '>', $now) + ->update([ + 'version' => $nextVersion, + 'commit_boundary' => $effectiveBoundary, + 'updated_at' => $now, + ]); + if ((int) $updated !== 1) { + throw new CloudAgentOperationException('lease_lost', 'Agent commit boundary CAS 冲突', 409); + } + $row = $table->where('operation_id', $claim->operationId)->first(); + if ($row === null) { + throw new CloudAgentOperationException('storage_unavailable', 'Agent 操作读取失败', 503); + } + return [ + 'record' => self::publicRecord($row), + 'claim' => $claim->next($nextVersion, $claim->status), + ]; + }); + } catch (CloudAgentOperationException $error) { + throw $error; + } catch (\Throwable) { + throw new CloudAgentOperationException( + 'storage_unavailable', 'Agent 操作记录暂时不可用', 503); + } + } + + /** + * Extend a live claim without changing its operation status. + * + * An expired claim cannot be renewed: the caller must let the row become + * uncertain and use a read-only reconcile path instead. + * + * @return array{record:array,claim:CloudAgentOperationClaim} + */ + public function renew( + CloudAgentOperationClaim $claim, + int $leaseSeconds, + ?int $now = null, + ): array { + self::assertClaim($claim); + if ($leaseSeconds < 1 || $leaseSeconds > 900) { + throw new CloudAgentOperationException('invalid_request', 'Agent 租约时长无效', 422); + } + $now = self::clock($now); + try { + return $this->connection->transaction(function () use ($claim, $leaseSeconds, $now): array { + $table = $this->connection->table(self::TABLE); + $nextVersion = $claim->version + 1; + $updated = $table->where('operation_id', $claim->operationId) + ->where('version', $claim->version) + ->where('status', $claim->status) + ->where('lease_owner', $claim->leaseOwner) + ->where('lease_expires_at', '>', $now) + ->update([ + 'version' => $nextVersion, + 'lease_expires_at' => $now + $leaseSeconds, + 'updated_at' => $now, + ]); + if ((int) $updated !== 1) { + throw new CloudAgentOperationException('lease_lost', 'Agent 操作 renew CAS 冲突', 409); + } + $row = $table->where('operation_id', $claim->operationId)->first(); + if ($row === null) { + throw new CloudAgentOperationException('storage_unavailable', 'Agent 操作读取失败', 503); + } + return [ + 'record' => self::publicRecord($row), + 'claim' => $claim->next($nextVersion, $claim->status), + ]; + }); + } catch (CloudAgentOperationException $error) { + throw $error; + } catch (\Throwable) { + throw new CloudAgentOperationException( + 'storage_unavailable', 'Agent 操作记录暂时不可用', 503); + } + } + + /** Mark a live claim uncertain without replaying the host request. */ + public function markUncertain( + CloudAgentOperationClaim $claim, + string $errorCode, + ?string $commitBoundary = null, + ?int $now = null, + ): array { + return $this->finalize($claim, 'uncertain', null, $errorCode, $commitBoundary, $now); + } + + /** @return array */ + public function get(string $operationId): array + { + $operationId = self::operationId($operationId); + try { + $row = $this->connection->table(self::TABLE) + ->where('operation_id', $operationId)->first(); + } catch (\Throwable) { + throw new CloudAgentOperationException( + 'storage_unavailable', 'Agent 操作记录暂时不可用', 503); + } + if ($row === null) { + throw new CloudAgentOperationException('not_found', 'Agent 操作不存在', 404); + } + return self::publicRecord($row); + } + + /** @param object $row @param array $request */ + private function replayOrConflict(object $row, array $request): array + { + $same = (string) ($row->operation_id ?? '') === $request['operation_id'] + && (string) ($row->idempotency_key ?? '') === $request['idempotency_key'] + && (string) ($row->agent_id ?? '') === $request['agent_id'] + && (string) ($row->request_hash ?? '') === $request['request_hash'] + && (string) ($row->kind ?? '') === $request['kind'] + && (string) ($row->target ?? '') === $request['target'] + && self::nullableString($row->instance_uuid ?? null) === $request['instance_uuid']; + if (!$same) { + throw new CloudAgentOperationException('conflict', 'Agent 幂等键或操作身份已被占用', 409); + } + return ['record' => self::publicRecord($row), 'replay' => true]; + } + + /** @param array $input @return array */ + private static function normalizeReservation(array $input): array + { + $operationId = self::operationId($input['operation_id'] ?? null); + $idempotencyKey = self::idempotencyKey($input['idempotency_key'] ?? null); + $agentId = self::agentId($input['agent_id'] ?? null); + $kind = self::kind($input['kind'] ?? null); + $target = self::target($input['target'] ?? ''); + $requestHash = self::hash($input['request_hash'] ?? null); + $instanceUuid = $input['instance_uuid'] ?? null; + if ($instanceUuid !== null) { + $instanceUuid = self::operationId($instanceUuid); + } + if (!array_key_exists('desired', $input) || !is_array($input['desired']) + || array_is_list($input['desired'])) { + throw new CloudAgentOperationException('invalid_request', 'Agent desired state 必须是对象', 422); + } + return [ + 'operation_id' => $operationId, + 'idempotency_key' => $idempotencyKey, + 'agent_id' => $agentId, + 'instance_uuid' => $instanceUuid, + 'kind' => $kind, + 'target' => $target, + 'request_hash' => $requestHash, + 'desired_json' => self::safeJson($input['desired'], self::MAX_DESIRED_BYTES), + ]; + } + + private static function operationId(mixed $value): string + { + if (!is_string($value) + || preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/D', $value) !== 1) { + throw new CloudAgentOperationException('invalid_request', 'Agent operation_id 无效', 422); + } + return $value; + } + + private static function idempotencyKey(mixed $value): string + { + if (!is_string($value) + || preg_match('/^[A-Za-z0-9][A-Za-z0-9_-]{7,63}$/D', $value) !== 1) { + throw new CloudAgentOperationException('invalid_request', 'Agent 幂等键无效', 422); + } + return $value; + } + + private static function agentId(mixed $value): string + { + if (!is_string($value) + || preg_match('/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/D', $value) !== 1) { + throw new CloudAgentOperationException('invalid_request', 'Agent 身份无效', 422); + } + return $value; + } + + private static function leaseOwner(mixed $value): string + { + if (!is_string($value) + || preg_match('/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/D', $value) !== 1) { + throw new CloudAgentOperationException('invalid_request', 'Agent lease owner 无效', 422); + } + return $value; + } + + private static function kind(mixed $value): string + { + if (!is_string($value) || !in_array($value, self::KINDS, true)) { + throw new CloudAgentOperationException('invalid_request', 'Agent operation kind 无效', 422); + } + return $value; + } + + private static function target(mixed $value): string + { + if (!is_string($value) || $value !== trim($value) || strlen($value) > 128 + || preg_match('/[\x00-\x1F\x7F]/', $value) === 1) { + throw new CloudAgentOperationException('invalid_request', 'Agent operation target 无效', 422); + } + return $value; + } + + private static function hash(mixed $value): string + { + if (!is_string($value) || preg_match('/^[a-f0-9]{64}$/D', $value) !== 1) { + throw new CloudAgentOperationException('invalid_request', 'Agent request_hash 无效', 422); + } + return $value; + } + + private static function boundary(mixed $value): string + { + if (!is_string($value) + || preg_match('/^[a-z][a-z0-9_.-]{0,31}$/D', $value) !== 1) { + throw new CloudAgentOperationException('invalid_request', 'Agent commit boundary 无效', 422); + } + return $value; + } + + private static function resolveBoundary( + string $current, + ?string $requested, + string $status, + ): string { + if ($current === '') { + $current = 'not_started'; + } elseif (self::boundary($current) !== $current) { + throw new CloudAgentOperationException('invalid_state', 'Agent commit boundary 损坏', 409); + } + if ($requested === null) { + return $status === 'uncertain' && $current === 'not_started' + ? 'unknown' : $current; + } + if (($requested === 'not_started' && $current !== 'not_started') + || ($requested === 'unknown' + && !in_array($current, ['not_started', 'unknown'], true))) { + throw new CloudAgentOperationException( + 'invalid_transition', 'Agent commit boundary 不能回退', 409); + } + return $requested; + } + + private static function errorCode(mixed $value, string $status): string + { + if (!is_string($value) + || ($value !== '' && preg_match('/^[a-z][a-z0-9_.-]{0,63}$/D', $value) !== 1)) { + throw new CloudAgentOperationException('invalid_request', 'Agent error code 无效', 422); + } + if ($status === 'succeeded' && $value !== '') { + throw new CloudAgentOperationException('invalid_transition', '成功操作不能带错误码', 409); + } + if (in_array($status, ['failed', 'uncertain'], true) && $value === '') { + throw new CloudAgentOperationException('invalid_transition', '失败或不确定操作必须带错误码', 409); + } + return $value; + } + + private static function assertClaim(CloudAgentOperationClaim $claim): void + { + try { + $claim->assertValid(); + } catch (\InvalidArgumentException) { + throw new CloudAgentOperationException( + 'invalid_request', 'Agent operation claim 无效', 422); + } + } + + /** @param array $value */ + private static function safeJson(array $value, int $limit): string + { + self::validateJsonValue($value, 0); + try { + $encoded = json_encode($value, + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + } catch (\Throwable) { + throw new CloudAgentOperationException('invalid_request', 'Agent JSON 结果无法编码', 422); + } + if (strlen($encoded) > $limit) { + throw new CloudAgentOperationException('invalid_request', 'Agent JSON 结果过大', 422); + } + return $encoded; + } + + /** @param mixed $value */ + private static function validateJsonValue(mixed $value, int $depth): void + { + if ($depth > self::MAX_DEPTH) { + throw new CloudAgentOperationException('invalid_request', 'Agent JSON 嵌套过深', 422); + } + if (is_array($value)) { + foreach ($value as $key => $child) { + if (!is_int($key) && (!is_string($key) || !self::validJsonKey($key) + || (self::isDigestKey($key) + && (!self::isSafeDigestKey($key) || !self::isDigestValue($child))) + || (self::sensitiveKey($key) + && (!self::isSafeDigestKey($key) || !self::isDigestValue($child))))) { + throw new CloudAgentOperationException('invalid_request', 'Agent JSON 字段无效', 422); + } + self::validateJsonValue($child, $depth + 1); + } + return; + } + if (is_string($value) && preg_match('/[\x00-\x1F\x7F]/', $value) === 1) { + throw new CloudAgentOperationException('invalid_request', 'Agent JSON 含控制字符', 422); + } + if (!is_null($value) && !is_scalar($value)) { + throw new CloudAgentOperationException('invalid_request', 'Agent JSON 类型无效', 422); + } + } + + private static function validJsonKey(string $key): bool + { + return strlen($key) >= 1 && strlen($key) <= 128 + && preg_match('/^[A-Za-z0-9]+(?:[_-][A-Za-z0-9]+)*$/D', $key) === 1; + } + + private static function sensitiveKey(string $key): bool + { + $normalized = strtolower((string) preg_replace('/([a-z0-9])([A-Z])/', '$1_$2', $key)); + $normalized = str_replace('-', '_', $normalized); + return preg_match('/(?:^|_)(password|passwd|token|secret|secret_ref|private|credential|startup|network|raw|normalized|xml|path|url|directory|source|endpoint|command|argv|stderr|error_detail|error_message|cipher)(?:_|$)/', $normalized) === 1; + } + + private static function isDigestKey(string $key): bool + { + $normalized = strtolower((string) preg_replace('/([a-z0-9])([A-Z])/', '$1_$2', $key)); + $normalized = str_replace('-', '_', $normalized); + return preg_match('/(?:^|_)(hash|digest|sha256|fingerprint)$/', $normalized) === 1; + } + + private static function isSafeDigestKey(string $key): bool + { + if (!self::isDigestKey($key)) { + return false; + } + $normalized = strtolower((string) preg_replace('/([a-z0-9])([A-Z])/', '$1_$2', $key)); + $normalized = str_replace('-', '_', $normalized); + return preg_match('/(?:^|_)(password|passwd|token|secret|private|credential|api_key|access_key|signing_key|hmac_key)(?:_|$)/', $normalized) !== 1; + } + + private static function isDigestValue(mixed $value): bool + { + return is_string($value) && preg_match('/^[a-f0-9]{64}$/D', $value) === 1; + } + + /** @return list */ + private static function statuses(): array + { + return ['pending', 'running', 'succeeded', 'failed', 'uncertain']; + } + + private static function clock(?int $now): int + { + $now ??= time(); + if ($now < 1) { + throw new CloudAgentOperationException('invalid_request', 'Agent 时间戳无效', 422); + } + return $now; + } + + private static function positiveInt(mixed $value): int + { + if (is_int($value)) { + return $value > 0 ? $value : 0; + } + return is_string($value) && preg_match('/^[1-9][0-9]*$/D', $value) === 1 + ? (int) $value : 0; + } + + private static function nonNegativeInt(mixed $value): int + { + if (is_int($value)) { + return $value >= 0 ? $value : 0; + } + return is_string($value) && preg_match('/^(?:0|[1-9][0-9]*)$/D', $value) === 1 + ? (int) $value : 0; + } + + private static function nullableInt(mixed $value): ?int + { + if ($value === null) { + return null; + } + if (is_int($value)) { + return $value; + } + return is_string($value) && preg_match('/^(?:0|[1-9][0-9]*)$/D', $value) === 1 + ? (int) $value : null; + } + + private static function nullableString(mixed $value): ?string + { + return $value === null ? null : (is_string($value) ? $value : null); + } + + private static function isUniqueViolation(QueryException $error): bool + { + return (string) $error->getCode() === '23000'; + } + + /** @param object $row @return array */ + private static function publicRecord(object $row): array + { + self::assertStoredRow($row); + $desired = self::decodeObject($row->desired_json ?? null); + $result = self::decodeNullableObject($row->result_json ?? null); + return [ + 'operation_id' => (string) ($row->operation_id ?? ''), + 'idempotency_key' => (string) ($row->idempotency_key ?? ''), + 'agent_id' => (string) ($row->agent_id ?? ''), + 'instance_uuid' => self::nullableString($row->instance_uuid ?? null), + 'kind' => (string) ($row->kind ?? ''), + 'target' => (string) ($row->target ?? ''), + 'request_hash' => (string) ($row->request_hash ?? ''), + 'desired' => $desired, + 'status' => (string) ($row->status ?? ''), + 'version' => self::positiveInt($row->version ?? null), + 'attempt_count' => self::nonNegativeInt($row->attempt_count ?? null), + 'lease_expires_at' => self::nullableInt($row->lease_expires_at ?? null), + 'commit_boundary' => (string) ($row->commit_boundary ?? ''), + 'result' => $result, + 'error_code' => (string) ($row->error_code ?? ''), + 'created_at' => self::nonNegativeInt($row->created_at ?? null), + 'updated_at' => self::nonNegativeInt($row->updated_at ?? null), + 'completed_at' => self::nullableInt($row->completed_at ?? null), + ]; + } + + /** @param object $row */ + private static function assertStoredRow(object $row): void + { + $operationId = $row->operation_id ?? null; + $idempotencyKey = $row->idempotency_key ?? null; + $agentId = $row->agent_id ?? null; + $kind = $row->kind ?? null; + $target = $row->target ?? null; + $requestHash = $row->request_hash ?? null; + if (!is_string($operationId) + || preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/D', $operationId) !== 1 + || !is_string($idempotencyKey) + || preg_match('/^[A-Za-z0-9][A-Za-z0-9_-]{7,63}$/D', $idempotencyKey) !== 1 + || !is_string($agentId) + || preg_match('/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/D', $agentId) !== 1 + || !is_string($kind) + || !in_array($kind, self::KINDS, true) + || !is_string($target) + || $target !== trim($target) + || strlen($target) > 128 + || preg_match('/[\x00-\x1F\x7F]/', $target) === 1 + || !is_string($requestHash) + || preg_match('/^[a-f0-9]{64}$/D', $requestHash) !== 1) { + throw new CloudAgentOperationException('storage_corrupt', 'Agent 操作身份已损坏', 503); + } + $instanceUuid = $row->instance_uuid ?? null; + if ($instanceUuid !== null + && (!is_string($instanceUuid) + || preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/D', $instanceUuid) !== 1)) { + throw new CloudAgentOperationException('storage_corrupt', 'Agent 实例身份已损坏', 503); + } + $status = $row->status ?? null; + if (!is_string($status) || !in_array($status, self::statuses(), true) + || self::positiveInt($row->version ?? null) < 1 + || self::nonNegativeInt($row->attempt_count ?? null) < 0) { + throw new CloudAgentOperationException('storage_corrupt', 'Agent 操作状态已损坏', 503); + } + $boundary = $row->commit_boundary ?? null; + if (!is_string($boundary) || preg_match('/^[a-z][a-z0-9_.-]{0,31}$/D', $boundary) !== 1) { + throw new CloudAgentOperationException('storage_corrupt', 'Agent commit boundary 已损坏', 503); + } + $errorCode = $row->error_code ?? null; + if (!is_string($errorCode) + || ($errorCode !== '' && preg_match('/^[a-z][a-z0-9_.-]{0,63}$/D', $errorCode) !== 1)) { + throw new CloudAgentOperationException('storage_corrupt', 'Agent 错误码已损坏', 503); + } + $owner = $row->lease_owner ?? null; + if (!is_string($owner) + || ($owner !== '' && preg_match('/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/D', $owner) !== 1)) { + throw new CloudAgentOperationException('storage_corrupt', 'Agent lease owner 已损坏', 503); + } + $expiry = self::nullableInt($row->lease_expires_at ?? null); + if (($owner !== '' && $expiry === null) || ($owner === '' && $expiry !== null)) { + throw new CloudAgentOperationException('storage_corrupt', 'Agent lease 状态已损坏', 503); + } + if (in_array($status, ['pending', 'running'], true) && $errorCode !== '') { + throw new CloudAgentOperationException('storage_corrupt', 'Agent 非终态错误码已损坏', 503); + } + if ($status === 'succeeded' && ($errorCode !== '' || in_array($boundary, ['not_started', 'unknown'], true))) { + throw new CloudAgentOperationException('storage_corrupt', 'Agent 成功状态证据已损坏', 503); + } + if (in_array($status, ['failed', 'uncertain'], true) && $errorCode === '') { + throw new CloudAgentOperationException('storage_corrupt', 'Agent 终态错误码已损坏', 503); + } + if (!is_string($row->desired_json ?? null)) { + throw new CloudAgentOperationException('storage_corrupt', 'Agent desired JSON 已损坏', 503); + } + self::decodeObject($row->desired_json); + if (($row->result_json ?? null) !== null) { + self::decodeNullableObject($row->result_json); + } + } + + /** @return array */ + private static function decodeObject(mixed $value): array + { + if (!is_string($value) || $value === '') { + throw new CloudAgentOperationException('storage_corrupt', 'Agent 操作 JSON 已损坏', 503); + } + $trimmed = ltrim($value); + if ($trimmed === '' || $trimmed[0] !== '{') { + throw new CloudAgentOperationException('storage_corrupt', 'Agent 操作 JSON 顶层类型已损坏', 503); + } + try { + $decoded = json_decode($value, true, self::MAX_DEPTH, + JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING); + } catch (\Throwable) { + throw new CloudAgentOperationException('storage_corrupt', 'Agent 操作 JSON 已损坏', 503); + } + if (!is_array($decoded) || $decoded === [] || array_is_list($decoded)) { + throw new CloudAgentOperationException('storage_corrupt', 'Agent 操作 JSON 顶层类型已损坏', 503); + } + try { + self::validateJsonValue($decoded, 0); + } catch (CloudAgentOperationException) { + throw new CloudAgentOperationException('storage_corrupt', 'Agent 操作 JSON 内容已损坏', 503); + } + return $decoded; + } + + /** @return array|null */ + private static function decodeNullableObject(mixed $value): ?array + { + if ($value === null) { + return null; + } + return self::decodeObject($value); + } +} diff --git a/web/tests/CloudAgentOperationEnvelopeContractTest.php b/web/tests/CloudAgentOperationEnvelopeContractTest.php index 588b99e6..58e3dfbf 100644 --- a/web/tests/CloudAgentOperationEnvelopeContractTest.php +++ b/web/tests/CloudAgentOperationEnvelopeContractTest.php @@ -108,6 +108,54 @@ $cases = [ '00000000-0000-4000-8000-000000000001', ); }, + 'secret hash with raw value' => static function () use ($response, $operationId, $idempotencyKey, $requestHash): void { + $invalid = $response; + $invalid['result'] = ['secret_hash' => 'raw-secret-not-a-digest']; + CloudAgentOperationEnvelope::fromResponse( + $invalid, + $operationId, + $idempotencyKey, + $requestHash, + 'domain_create_validate', + '00000000-0000-4000-8000-000000000001', + ); + }, + 'invalid digest shape' => static function () use ($response, $operationId, $idempotencyKey, $requestHash): void { + $invalid = $response; + $invalid['result'] = ['plan_hash' => 'not-a-sha256']; + CloudAgentOperationEnvelope::fromResponse( + $invalid, + $operationId, + $idempotencyKey, + $requestHash, + 'domain_create_validate', + '00000000-0000-4000-8000-000000000001', + ); + }, + 'list result' => static function () use ($response, $operationId, $idempotencyKey, $requestHash): void { + $invalid = $response; + $invalid['result'] = ['unexpected-list-item']; + CloudAgentOperationEnvelope::fromResponse( + $invalid, + $operationId, + $idempotencyKey, + $requestHash, + 'domain_create_validate', + '00000000-0000-4000-8000-000000000001', + ); + }, + 'empty result object' => static function () use ($response, $operationId, $idempotencyKey, $requestHash): void { + $invalid = $response; + $invalid['result'] = []; + CloudAgentOperationEnvelope::fromResponse( + $invalid, + $operationId, + $idempotencyKey, + $requestHash, + 'domain_create_validate', + '00000000-0000-4000-8000-000000000001', + ); + }, 'nested diagnostic result' => static function () use ($response, $operationId, $idempotencyKey, $requestHash): void { $invalid = $response; $invalid['result'] = ['details' => ['errorDetail' => 'host diagnostic']]; @@ -197,6 +245,18 @@ $cases = [ '00000000-0000-4000-8000-000000000001', ); }, + 'succeeded without proven boundary' => static function () use ($response, $operationId, $idempotencyKey, $requestHash): void { + $invalid = $response; + $invalid['commit_boundary'] = 'unknown'; + CloudAgentOperationEnvelope::fromResponse( + $invalid, + $operationId, + $idempotencyKey, + $requestHash, + 'domain_create_validate', + '00000000-0000-4000-8000-000000000001', + ); + }, ]; foreach ($cases as $name => $case) { try { @@ -225,6 +285,7 @@ $source = file_get_contents(dirname(__DIR__) . '/app/Services/Cloud/CloudAgentOp $assert($source !== false && str_contains($source, 'version') && str_contains($source, 'assertSafeResult') + && str_contains($source, 'array_is_list($response[\'result\'])') && !str_contains($source, 'CloudEngineClient') && !str_contains($source, 'CloudSecrets'), 'Operation envelope crossed the legacy engine or secret boundary.'); diff --git a/web/tests/CloudAgentOperationRepositoryContractTest.php b/web/tests/CloudAgentOperationRepositoryContractTest.php new file mode 100644 index 00000000..7d8deaae --- /dev/null +++ b/web/tests/CloudAgentOperationRepositoryContractTest.php @@ -0,0 +1,84 @@ + $repository, 'model' => $model, 'claim' => $claim, 'exception' => $exception, 'schema' => $schema] as $name => $source) { + $assert(is_string($source) && $source !== '', 'Missing Agent operation ' . $name . ' source.'); +} + +$assert(str_contains($model, "cloud_agent_operations") + && str_contains($model, "desired_json") + && str_contains($model, "lease_owner"), + 'CloudAgentOperation model lost the fresh journal mapping.'); +$assert(str_contains($repository, "private const TABLE = 'cloud_agent_operations'") + && str_contains($repository, "function reserve") + && str_contains($repository, "function claim") + && str_contains($repository, "function finalize") + && str_contains($repository, "function setCommitBoundary") + && str_contains($repository, "function renew") + && str_contains($repository, "function markUncertain") + && str_contains($repository, "function get"), + 'Agent operation repository is missing a required state transition.'); + +foreach ([ + "->where('version'", + "->where('status'", + "->where('lease_owner'", + "->where('lease_expires_at'", + "'attempt_count' =>", + "'version' =>", + "lockForUpdate()", + 'if ((int) $updated !== 1)', + "lease_lost", + "lease_expired", + "不确定操作禁止重新派发", +] as $required) { + $assert(str_contains($repository, $required), + 'Agent repository lost CAS/lease guard: ' . $required); +} + +$assert(str_contains($claim, 'must not be serialized') + && str_contains($claim, '__unserialize') + && str_contains($claim, 'dispatch\' && $this->status === \'running') + && str_contains($claim, 'reconcile\' && $this->status === \'uncertain'), + 'Agent operation claim can cross a queue serialization boundary.'); +$assert(str_contains($exception, 'public readonly string $errorCode') + && !str_contains($exception, 'public readonly string $code'), + 'Agent operation exception must not redeclare Exception::$code.'); +$assert(str_contains($repository, 'array_is_list($input[\'desired\'])') + && str_contains($repository, 'validJsonKey') + && str_contains($repository, 'isDigestValue') + && str_contains($repository, "\$trimmed[0] !== '{'") + && str_contains($repository, 'array_is_list($decoded)') + && str_contains($repository, 'array_is_list($result) || $result === []') + && str_contains($repository, 'if ($value === null)') + && str_contains($repository, "Agent 操作 JSON 内容已损坏") + && !str_contains($repository, "if (!is_string(\$value) || \$value === '') {\n return [];") + && str_contains($repository, '成功操作必须有宿主 commit boundary'), + 'Agent operation desired/result JSON needs an object and key-shape boundary.'); +$assert(str_contains($schema, 'version BIGINT UNSIGNED NOT NULL DEFAULT 1') + && str_contains($schema, 'attempt_count INT UNSIGNED') + && str_contains($schema, 'lease_owner VARCHAR(96)') + && str_contains($schema, 'lease_expires_at BIGINT UNSIGNED'), + 'Fresh schema lacks operation CAS/lease columns.'); + +foreach (['CloudJob', 'CloudEngineClient', 'ssh', 'curl_exec', 'shell_exec', 'CloudSecrets'] as $forbidden) { + $assert(!str_contains($repository, $forbidden), + 'Fresh Agent repository crossed a legacy/transport boundary: ' . $forbidden); +} + +echo "Cloud Agent operation repository contract checks passed.\n";