You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/Cloud/CloudAgentOperationReposito...

1204 lines
53 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudAgentOperation;
use Illuminate\Database\QueryException;
/**
* CAS/lease repository for the greenfield Go Agent operation journal.
*
* Only this repository writes cloud_agent_operations. The transaction blocks
* contain row reads/writes only; callers must perform Agent HTTP outside the
* transaction and then use the returned claim as a fencing token.
*/
final class CloudAgentOperationRepository
{
private const TABLE = 'cloud_agent_operations';
private const MAX_DESIRED_BYTES = 512 * 1024;
private const MAX_RESULT_BYTES = 2 * 1024 * 1024;
private const MAX_DEPTH = 16;
private const READONLY_KINDS = [
'capability_probe',
'domain_read',
'domain_observe',
];
/** @var list<string> */
private const KINDS = [
'capability_probe',
'domain_read',
'domain_observe',
'domain_power',
'seed_prepare',
'domain_preflight',
'domain_create_plan',
'domain_create_validate',
];
/** Host/artifact mutations are serialized; capability/readback probes are not. */
private const MUTATING_KINDS = [
'domain_power',
'seed_prepare',
];
/** @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<string,mixed> $input
* @return array{record:array<string,mixed>,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);
}
// The fresh instance-state row is the durable mutex for
// mutating operations on one guest. Read-only probes may
// run beside a mutation, but a second lifecycle/create
// request must wait for a terminal record or explicit
// reconciliation instead of racing libvirt.
if ($request['instance_uuid'] !== null
&& in_array($request['kind'], self::MUTATING_KINDS, true)) {
$this->lockInstanceState(
$request['agent_id'], $request['host_id'], $request['instance_id'],
$request['instance_uuid'], $now,
);
$active = $table->where('agent_id', $request['agent_id'])
->where('host_id', $request['host_id'])
->where('instance_id', $request['instance_id'])
->where('instance_uuid', $request['instance_uuid'])
->where('operation_id', '<>', $request['operation_id'])
->whereIn('status', ['pending', 'running', 'uncertain'])
->lockForUpdate()->exists();
if ($active) {
throw new CloudAgentOperationException(
'instance_busy', '虚拟机已有 Agent 操作,请先核对结果', 409);
}
}
$table->insert([
'operation_id' => $request['operation_id'],
'idempotency_key' => $request['idempotency_key'],
'agent_id' => $request['agent_id'],
'host_id' => $request['host_id'],
'instance_uuid' => $request['instance_uuid'],
'instance_id' => $request['instance_id'],
'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);
}
if ($request['instance_uuid'] !== null
&& in_array($request['kind'], self::MUTATING_KINDS, true)) {
$this->connection->table('cloud_agent_instance_state')
->where('agent_id', $request['agent_id'])
->where('host_id', $request['host_id'])
->where('instance_id', $request['instance_id'])
->where('instance_uuid', $request['instance_uuid'])
->update([
'last_operation_id' => $request['operation_id'],
'updated_at' => $now,
]);
}
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<string,mixed>|null $result
* @return array<string,mixed>
*/
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<string,mixed>,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<string,mixed>,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<string,mixed> */
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);
}
/**
* Retain a bounded diagnostic window for high-frequency read-only
* observations. Terminal probe rows are not user-visible operations and
* may be pruned after the retention boundary; pending/running/uncertain
* rows are never removed because they may still require reconciliation.
*/
public function pruneReadOnly(int $before, int $limit = 2000): int
{
if ($before < 1 || $limit < 1 || $limit > 10000) {
return 0;
}
try {
$table = $this->connection->table(self::TABLE);
$ids = $table->whereIn('kind', self::READONLY_KINDS)
->whereIn('status', ['succeeded', 'failed'])
->where('created_at', '<', $before)
->orderBy('id')
->limit($limit)
->pluck('id')
->all();
if ($ids === []) {
return 0;
}
return (int) $table->whereIn('id', $ids)->delete();
} catch (\Throwable) {
// Journal pruning is maintenance, never a reason to fail a live
// observation tick or to alter its last-known runtime state.
return 0;
}
}
/**
* Read a bounded, validated operation history for one fresh-schema VM.
*
* This is intentionally a repository read rather than an Eloquent model
* dump: every row crosses the same identity/JSON invariants as a status
* poll, and lease/error-detail columns never leave this class. Callers
* must provide an explicit allow-list of Agent kinds so a future internal
* probe cannot silently become a user-facing operation-log entry.
*
* @param list<string> $kinds
* @return array{items:list<array<string,mixed>>,total:int,page:int,per_page:int,total_pages:int,from:int,to:int}
*/
public function historyForInstance(
string $instanceUuid,
array $kinds,
int $page = 1,
int $perPage = 10,
?string $agentId = null,
?int $hostId = null,
?int $instanceId = null,
): array {
$instanceUuid = self::instanceUuid($instanceUuid);
if ($agentId === null) {
throw new CloudAgentOperationException(
'invalid_request', 'Agent 操作历史必须绑定 Agent 身份', 422);
}
$agentId = self::agentId($agentId);
if ($hostId === null || $hostId < 1) {
throw new CloudAgentOperationException(
'invalid_request', 'Agent 操作历史必须绑定宿主身份', 422);
}
if ($instanceId === null || $instanceId < 1) {
throw new CloudAgentOperationException(
'invalid_request', 'Agent 操作历史必须绑定实例身份', 422);
}
if ($page < 1 || $perPage < 1 || $perPage > 50) {
throw new CloudAgentOperationException(
'invalid_request', 'Agent 操作历史分页参数无效', 422);
}
$normalizedKinds = [];
foreach ($kinds as $kind) {
if (!is_string($kind) || !in_array($kind, self::KINDS, true)) {
throw new CloudAgentOperationException(
'invalid_request', 'Agent 操作历史类型无效', 422);
}
if (!in_array($kind, $normalizedKinds, true)) {
$normalizedKinds[] = $kind;
}
}
if ($normalizedKinds === []) {
throw new CloudAgentOperationException(
'invalid_request', 'Agent 操作历史类型不能为空', 422);
}
try {
$query = $this->connection->table(self::TABLE)
->where('instance_uuid', $instanceUuid)
->where('agent_id', $agentId)
->where('host_id', $hostId)
->where('instance_id', $instanceId)
->whereIn('kind', $normalizedKinds)
// `id` is only a local tie-breaker. It is never exposed as
// the operation identity returned to the browser.
->orderByDesc('created_at')->orderByDesc('id');
$total = max(0, (int) (clone $query)->count('operation_id'));
$pages = max(1, (int) ceil($total / $perPage));
$page = min($page, $pages);
$offset = ($page - 1) * $perPage;
$rows = $query->offset($offset)->limit($perPage)->get();
$items = [];
foreach ($rows as $row) {
$items[] = self::publicRecord($row);
}
$from = $total === 0 ? 0 : $offset + 1;
return [
'items' => $items,
'total' => $total,
'page' => $page,
'per_page' => $perPage,
'total_pages' => $pages,
'from' => $from,
'to' => $from === 0 ? 0 : $from + count($items) - 1,
];
} catch (CloudAgentOperationException $error) {
throw $error;
} catch (\Throwable) {
throw new CloudAgentOperationException(
'storage_unavailable', 'Agent 操作历史暂时不可用', 503);
}
}
/** @param object $row @param array<string,mixed> $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']
&& self::positiveInt($row->host_id ?? null) === $request['host_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']
&& self::nullablePositiveInt($row->instance_id ?? null) === $request['instance_id'];
if (!$same) {
throw new CloudAgentOperationException('conflict', 'Agent 幂等键或操作身份已被占用', 409);
}
return ['record' => self::publicRecord($row), 'replay' => true];
}
/**
* Lock or create the fresh per-instance state row used as a mutation
* mutex. The caller is already inside the reservation transaction.
*/
private function lockInstanceState(
string $agentId,
int $hostId,
int $instanceId,
string $instanceUuid,
int $now,
): void {
$state = $this->connection->table('cloud_agent_instance_state')
->where('agent_id', $agentId)
->where('host_id', $hostId)
->where('instance_id', $instanceId)
->where('instance_uuid', $instanceUuid)
->lockForUpdate()->first();
if ($state !== null) {
return;
}
$this->connection->table('cloud_agent_instance_state')->insert([
'agent_id' => $agentId,
'host_id' => $hostId,
'instance_id' => $instanceId,
'instance_uuid' => $instanceUuid,
'desired_revision' => 1,
'desired_json' => '{"state":"unknown"}',
'observed_revision' => 0,
'observed_json' => null,
'convergence_status' => 'unknown',
'last_operation_id' => null,
'last_error_code' => '',
'created_at' => $now,
'updated_at' => $now,
]);
$state = $this->connection->table('cloud_agent_instance_state')
->where('agent_id', $agentId)
->where('host_id', $hostId)
->where('instance_id', $instanceId)
->where('instance_uuid', $instanceUuid)
->lockForUpdate()->first();
if ($state === null) {
throw new CloudAgentOperationException(
'storage_unavailable', 'Agent 实例状态锁不可用', 503);
}
}
/** @param array<string,mixed> $input @return array<string,mixed> */
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);
$hostId = self::positiveInt($input['host_id'] ?? null);
if ($hostId < 1) {
throw new CloudAgentOperationException('invalid_request', 'Agent 宿主身份无效', 422);
}
$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);
}
$instanceId = $input['instance_id'] ?? null;
if ($instanceId !== null) {
$instanceId = self::positiveInt($instanceId);
if ($instanceId < 1 || $instanceUuid === null) {
throw new CloudAgentOperationException('invalid_request', 'Agent 实例身份不完整', 422);
}
}
if (in_array($kind, self::MUTATING_KINDS, true)
&& ($instanceUuid === null || $instanceId === null)) {
throw new CloudAgentOperationException(
'invalid_request', 'Agent 变更操作必须绑定实例身份', 422);
}
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,
'host_id' => $hostId,
'instance_uuid' => $instanceUuid,
'instance_id' => $instanceId,
'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 instanceUuid(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 实例 UUID 无效', 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<mixed> $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<string> */
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 nullablePositiveInt(mixed $value): ?int
{
if ($value === null) {
return null;
}
$normalized = self::positiveInt($value);
return $normalized > 0 ? $normalized : 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<string,mixed> */
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 ?? ''),
'host_id' => self::positiveInt($row->host_id ?? null),
'instance_uuid' => self::nullableString($row->instance_uuid ?? null),
'instance_id' => self::nullablePositiveInt($row->instance_id ?? 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;
$hostId = self::positiveInt($row->host_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
|| $hostId < 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);
}
$instanceId = $row->instance_id ?? null;
if ($instanceId !== null && self::nullablePositiveInt($instanceId) === null) {
throw new CloudAgentOperationException('storage_corrupt', 'Agent 实例编号已损坏', 503);
}
if ($instanceId !== null && $instanceUuid === null) {
throw new CloudAgentOperationException('storage_corrupt', 'Agent 实例身份不完整', 503);
}
if (in_array($kind, self::MUTATING_KINDS, true)
&& ($instanceUuid === null || $instanceId === null)) {
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<string,mixed> */
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<string,mixed>|null */
private static function decodeNullableObject(mixed $value): ?array
{
if ($value === null) {
return null;
}
return self::decodeObject($value);
}
}