From fafe32a037eb0cbad968f272c09f917811347334 Mon Sep 17 00:00:00 2001 From: admin Date: Fri, 16 Oct 2026 02:51:17 +0800 Subject: [PATCH] feat: cut VM reads over typed Go Agent observations --- web/app/Controllers/CloudApiController.php | 209 ++++++++----- .../Cloud/CloudAgentObservationService.php | 291 ++++++++++++++++++ .../Cloud/CloudInstancePageService.php | 30 +- ...oudAgentObservationServiceContractTest.php | 38 +++ web/tests/CloudInstancePageServiceTest.php | 8 + .../CloudInstancePageSsrContractTest.php | 27 +- 6 files changed, 505 insertions(+), 98 deletions(-) create mode 100644 web/app/Services/Cloud/CloudAgentObservationService.php create mode 100644 web/tests/CloudAgentObservationServiceContractTest.php diff --git a/web/app/Controllers/CloudApiController.php b/web/app/Controllers/CloudApiController.php index 1dd2a27e..bbbd1d1e 100644 --- a/web/app/Controllers/CloudApiController.php +++ b/web/app/Controllers/CloudApiController.php @@ -12,12 +12,15 @@ use App\Services\Auth; use App\Services\AdminCsrf; use App\Services\Config; use App\Services\Cloud\CloudAccess; +use App\Services\Cloud\CloudAgentActionService; use App\Services\Cloud\CloudAgentHostClientResolverFactory; use App\Services\Cloud\CloudAgentObservationService; +use App\Services\Cloud\CloudAgentDispatchUncertain; use App\Services\Cloud\CloudAgentOperationException; use App\Services\Cloud\CloudAgentOperationHistoryService; use App\Services\Cloud\CloudAgentOperationRepository; use App\Services\Cloud\CloudAgentOperationStatusService; +use App\Services\Cloud\CloudAgentVmGateway; use App\Services\Cloud\CloudDeploymentPageService; use App\Services\Cloud\CloudEngineClient; use App\Services\Cloud\CloudError; @@ -76,6 +79,15 @@ final class CloudApiController ); } + /** Build the request-local mutating Agent gateway; no Python/SSH fallback. */ + private function agentActionService(): CloudAgentActionService + { + return new CloudAgentActionService(new CloudAgentVmGateway( + CloudAgentHostClientResolverFactory::fromConfig(), + new CloudAgentOperationRepository(), + )); + } + /** Build the fresh, database-only Agent operation-history projection. */ private function agentOperationHistoryService(): CloudAgentOperationHistoryService { @@ -799,55 +811,24 @@ final class CloudApiController private function vmMetadataRows(array $actor, array $ids): array { - $snapshots = CloudInstancePageService::forActorIds($actor, $ids); - $targets = $this->vmProbeTargets($actor, $ids); - $live = []; - $engine = new CloudEngineClient(); - foreach ($this->vmSnapshotsByHost($snapshots, $targets) as $hostId => $group) { - $allowed = []; - $hostLive = []; - foreach ($group as $snapshot) { - $uuid = strtolower((string) $snapshot['uuid']); - $allowed[$uuid] = true; - } - try { - $payload = $engine->host((int) $hostId, 'GET', 'vm-metadata?ids=' . - rawurlencode(implode(',', array_keys($allowed))), $actor); - foreach (is_array($payload['items'] ?? null) ? $payload['items'] : [] as $item) { - if (!is_array($item) || !is_string($item['uuid'] ?? null)) { - continue; - } - $uuid = strtolower(trim($item['uuid'])); - if (isset($allowed[$uuid])) { - $hostLive[$uuid] = $item; - $live[(int) $hostId . ':' . $uuid] = $item; - } - } - } catch (CloudError $error) { - // Static database fields stay usable when one host is offline; - // another host's metadata can still be returned and cached. - } - CloudInstanceMetadata::persistBatch($group, $hostLive); - } + // Go Agent v1 deliberately has no domain_metadata operation yet. Do + // not fall back to the retired Python vm-metadata endpoint or expose + // raw XML here: the PHP-owned spec snapshot is the only safe source + // until a typed, allowlisted metadata read-back contract is added. + $snapshots = CloudInstancePageService::forActorIds($actor, $ids, true); $rows = []; foreach ($snapshots as $snapshot) { - $uuid = strtolower((string) $snapshot['uuid']); - $target = $targets[(int) $snapshot['id']] ?? null; - $key = is_array($target) ? (int) $target['host_id'] . ':' . $uuid : ''; - // Return the actor-visible identity even while its host is - // offline. The browser keeps the SSR fields and can distinguish - // temporary metadata unavailability from a missing instance. - $rows[] = CloudInstanceMetadata::publicView( - $snapshot, $live[$key] ?? [] - ); + // publicView applies the same static allowlist used by SSR; an + // empty live row intentionally means "cached, not host-confirmed". + $rows[] = CloudInstanceMetadata::publicView($snapshot, []); } return $rows; } /** * Lightweight live state for the visible list page. Database ownership is - * resolved before any engine response is considered; each engine request - * contains only the already actor-scoped UUIDs and never lists a host. + * resolved before any Agent response is considered; each observation + * contains only an already actor-scoped UUID and never lists a host. */ public function vmStatuses($request, $response) { @@ -860,8 +841,8 @@ final class CloudApiController $ids = array_values(array_unique(array_map('intval', explode(',', (string) $raw)))); $snapshots = CloudInstancePageService::forActorIds($actor, $ids); // Normal list refreshes are cache-only and therefore return without - // waiting on any host. An explicit live=1 request retains the - // previous synchronous engine probe for diagnostics/manual refresh. + // waiting on any host. An explicit live=1 request opts into typed + // Agent observations for the already bounded UUID set. $liveRequested = ($request->getQueryParams()['live'] ?? '') === '1'; if (!$liveRequested) { $statuses = []; @@ -871,31 +852,22 @@ final class CloudApiController return $this->json($response, ['vms' => $statuses]); } $targets = $this->vmProbeTargets($actor, $ids); - $live = []; - $engine = new CloudEngineClient(); + $observationTargets = []; foreach ($this->vmSnapshotsByHost($snapshots, $targets) as $hostId => $group) { - $allowed = []; foreach ($group as $snapshot) { - $allowed[strtolower((string) $snapshot['uuid'])] = true; - } - try { - $query = rawurlencode(implode(',', array_keys($allowed))); - $payload = $engine->host((int) $hostId, 'GET', - 'vm-states?ids=' . $query, $actor); - foreach (is_array($payload['items'] ?? null) ? $payload['items'] : [] as $item) { - if (!is_array($item) || !is_string($item['uuid'] ?? null)) { - continue; - } - $uuid = strtolower(trim($item['uuid'])); - if (isset($allowed[$uuid])) { - $live[(int) $hostId . ':' . $uuid] = $item; - } - } - } catch (CloudError $error) { - // The database rows remain visible with an unknown state; one - // offline host must not hide instances from another host. + $uuid = strtolower((string) $snapshot['uuid']); + $observationTargets[(int) $hostId . ':' . $uuid] = [ + 'host_id' => (int) $hostId, + 'uuid' => $uuid, + ]; } } + // There is no batch vm-states endpoint in Agent v1. The observation + // service issues one explicit UUID read per actor-scoped target and + // drops failed/uncertain items, preserving the cached DTO below. + $live = $this->agentObservationService()->observeMany( + $observationTargets, $actor + ); $statuses = []; foreach ($snapshots as $snapshot) { $uuid = strtolower((string) $snapshot['uuid']); @@ -1211,7 +1183,10 @@ final class CloudApiController $instance = CloudAccess::instance($args['id'], $actor, true); $actor = CloudAccess::vmActor($instance, $actor); $body = CloudInput::object($request); - CloudInput::only($body, ['action']); + // These two fields are control-plane identity, not Agent payload + // fields. They are optional for the unchanged browser UI; when a + // caller supplies an idempotency key, retries derive the same UUID. + CloudInput::only($body, ['action', 'idempotency_key', 'operation_id']); $action = $body['action'] ?? null; if (!is_string($action) || !CloudOperationCatalog::isPowerAction($action)) { throw new CloudError('操作无效'); @@ -1219,19 +1194,97 @@ final class CloudApiController if (in_array($action, ['start', 'reboot', 'reset'], true)) { $this->requireService($instance, $actor); } - $job = CloudJobService::enqueue($instance, $actor, 'action', 'POST', '/actions', $body); - // The validated request already contains the non-sensitive action; - // use it directly instead of decrypting the freshly queued payload a - // second time merely to build the acknowledgement. - $labels = CloudOperationCatalog::labels((string) $job->kind, $action); - return $this->json($response, [ - 'job_id' => (string) $job->id, - 'status_url' => '/api/v1/jobs/' . $job->id, - 'kind' => (string) $job->kind, - 'action' => $action, - 'kind_label' => $labels['kind_label'], - 'action_label' => $labels['action_label'], - ], 202); + $headerIdempotency = $request->getHeaderLine('Idempotency-Key'); + $headerOperationId = $request->getHeaderLine('X-Cloud-Request-ID'); + $bodyIdempotency = array_key_exists('idempotency_key', $body) + ? $body['idempotency_key'] : null; + $bodyOperationId = array_key_exists('operation_id', $body) + ? $body['operation_id'] : null; + if ($bodyIdempotency !== null && !is_string($bodyIdempotency)) { + throw new CloudError('面板 Agent 幂等键无效', 422); + } + if ($bodyOperationId !== null && !is_string($bodyOperationId)) { + throw new CloudError('面板 Agent operation_id 无效', 422); + } + // A body/header disagreement is an ambiguous retry, not permission + // to choose whichever identity happens to be parsed first. Reject it + // before resolving an Agent or reserving a journal row. + if ($bodyIdempotency !== null && $headerIdempotency !== '' + && $bodyIdempotency !== $headerIdempotency) { + throw new CloudError('面板 Agent 幂等键在请求头和请求体中不一致', 422); + } + if ($bodyOperationId !== null && $headerOperationId !== '' + && $bodyOperationId !== $headerOperationId) { + throw new CloudError('面板 Agent operation_id 在请求头和请求体中不一致', 422); + } + $idempotency = $bodyIdempotency ?? ($headerIdempotency !== '' ? $headerIdempotency : null); + $operationId = $bodyOperationId ?? ($headerOperationId !== '' ? $headerOperationId : null); + if ($idempotency !== null && !is_string($idempotency)) { + throw new CloudError('面板 Agent 幂等键无效', 422); + } + if ($operationId !== null && !is_string($operationId)) { + throw new CloudError('面板 Agent operation_id 无效', 422); + } + try { + $dispatch = $this->agentActionService()->dispatch( + $instance, + $actor, + $action, + $idempotency === '' ? null : $idempotency, + $operationId === '' ? null : $operationId, + ); + return $this->json($response, array_merge( + CloudAgentActionService::acknowledgement( + (array) ($dispatch['record'] ?? []), + $instance, + $actor, + $action, + (string) ($dispatch['idempotency_key'] ?? ''), + ), + ['status_url' => '/api/v1/jobs/' . rawurlencode( + (string) ($dispatch['operation_id'] ?? '') + ), 'replayed' => (bool) ($dispatch['replayed'] ?? false)], + ), 202); + } catch (CloudAgentDispatchUncertain $uncertain) { + // The operation row is already fenced as uncertain. Return its + // UUID so the unchanged browser poller can show “结果待核对”; + // never silently retry a lifecycle mutation from this endpoint. + return $this->json($response, array_merge( + CloudAgentActionService::acknowledgement( + $uncertain->record, + $instance, + $actor, + $action, + is_string($idempotency) && $idempotency !== '' + ? $idempotency + : (string) ($uncertain->record['idempotency_key'] ?? ''), + ), + ['status_url' => '/api/v1/jobs/' . rawurlencode($uncertain->operationId), + 'replayed' => false], + ), 202); + } catch (CloudAgentOperationException $error) { + // Repository conflicts and instance mutex hits are deterministic + // control-plane outcomes. Keep their status (usually 409) and + // map the bounded error code to a stable public message instead + // of letting the middleware turn them into a misleading 503. + throw new CloudError( + self::publicAgentActionError($error->errorCode), + $error->httpStatus, + ); + } + } + + private static function publicAgentActionError(string $errorCode): string + { + return match ($errorCode) { + 'instance_busy' => '虚拟机已有 Agent 操作,请先核对结果', + 'conflict' => '面板 Agent 幂等身份冲突,请勿重复提交', + 'lease_busy', 'lease_lost', 'attempt_limit' => 'Agent 操作租约冲突,请按操作编号核对结果', + 'storage_unavailable', 'storage_corrupt' => 'Agent 操作记录暂时不可用', + 'not_found' => 'Agent 操作不存在', + 'invalid_request' => '面板 Agent 操作参数无效', + default => 'Agent 操作暂时不可用', + }; } public function reinstall($request, $response, $args) diff --git a/web/app/Services/Cloud/CloudAgentObservationService.php b/web/app/Services/Cloud/CloudAgentObservationService.php new file mode 100644 index 00000000..ab302a0e --- /dev/null +++ b/web/app/Services/Cloud/CloudAgentObservationService.php @@ -0,0 +1,291 @@ + 900) { + throw new \InvalidArgumentException('Agent observation lease is outside the supported range'); + } + $this->leaseOwnerFactory = \Closure::fromCallable( + $leaseOwnerFactory ?? static fn (): string => 'php-agent-observe-' . bin2hex(random_bytes(8)), + ); + } + + /** + * @param array $actor + * @return array{record:array,observation:array|null,replayed:bool} + */ + public function observe( + int $hostId, + string $uuid, + array $actor, + ?string $operationId = null, + ?string $idempotencyKey = null, + ): array { + $uuid = self::uuid($uuid); + $operationId ??= self::newUuid(); + $idempotencyKey ??= 'observe-' . bin2hex(random_bytes(16)); + self::assertOperationIdentity($operationId, $idempotencyKey); + $payload = ['uuid' => $uuid]; + $requestHash = self::requestHash($operationId, $idempotencyKey, $uuid, $payload); + + // A degraded registration is sufficient for a read-only observation; + // the resolver still requires a pinned endpoint, certificate and key. + $handle = $this->resolver->resolveReadOnly($hostId); + $reservation = $this->operations->reserve([ + 'operation_id' => $operationId, + 'idempotency_key' => $idempotencyKey, + 'agent_id' => $handle->agentId, + 'instance_uuid' => $uuid, + 'kind' => 'domain_observe', + 'target' => $uuid, + 'request_hash' => $requestHash, + 'desired' => ['uuid' => $uuid], + ]); + if (($reservation['replay'] ?? false) === true) { + $record = $reservation['record']; + return [ + 'record' => $record, + 'observation' => is_array($record['result'] ?? null) ? $record['result'] : null, + 'replayed' => true, + ]; + } + + $owner = ($this->leaseOwnerFactory)(); + if (!is_string($owner) + || preg_match('/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/D', $owner) !== 1) { + throw new CloudError('面板 Agent 观察租约身份无效', 503); + } + $claimResult = $this->operations->claim( + $operationId, + $owner, + $this->leaseSeconds, + ); + $claim = $claimResult['claim'] ?? null; + if (!$claim instanceof CloudAgentOperationClaim) { + throw new CloudError('面板 Agent 观察未能取得租约', 503); + } + + try { + $response = $handle->operation( + $operationId, + $idempotencyKey, + 'domain_observe', + $uuid, + $payload, + $actor, + ); + // CloudAgentClient returns a reduced envelope for a definitive + // HTTP rejection. Preserve that deterministic failure in the + // panel journal; only transport/unknown outcomes are uncertain. + if (self::isReducedFailure($response, $operationId)) { + $status = $response['status']; + $errorCode = is_string($response['error_code'] ?? null) + && $response['error_code'] !== '' + ? $response['error_code'] : 'agent_observation_rejected'; + if ($status === 'failed') { + $record = $this->operations->finalize( + $claim, 'failed', null, $errorCode, null, + ); + } else { + $record = $this->operations->markUncertain($claim, $errorCode); + } + } else { + $envelope = CloudAgentOperationEnvelope::fromResponse( + $response, + $operationId, + $idempotencyKey, + $requestHash, + 'domain_observe', + $uuid, + ); + if ($envelope->status === 'succeeded') { + $record = $this->operations->finalize( + $claim, + 'succeeded', + $envelope->result, + '', + $envelope->commitBoundary, + ); + } elseif ($envelope->status === 'failed') { + $record = $this->operations->finalize( + $claim, + 'failed', + $envelope->result, + $envelope->errorCode, + $envelope->commitBoundary, + ); + } else { + $record = $this->operations->markUncertain( + $claim, + $envelope->errorCode !== '' ? $envelope->errorCode : 'agent_observation_incomplete', + $envelope->commitBoundary, + ); + } + } + } catch (CloudAgentOperationException $error) { + throw $error; + } catch (CloudError $error) { + try { + $this->operations->markUncertain($claim, 'agent_observation_transport_uncertain'); + } catch (CloudAgentOperationException) { + throw $error; + } + throw new CloudError('宿主机 Agent 观察结果待核对,请按操作编号重试查询', 503); + } catch (\Throwable) { + try { + $this->operations->markUncertain($claim, 'agent_observation_response_invalid'); + } catch (CloudAgentOperationException) { + throw new CloudError('宿主机 Agent 观察结果待核对,请按操作编号重试查询', 503); + } + throw new CloudError('宿主机 Agent 观察结果待核对,请按操作编号重试查询', 503); + } + + return [ + 'record' => $record, + 'observation' => is_array($record['result'] ?? null) ? $record['result'] : null, + 'replayed' => false, + ]; + } + + /** + * Observe an already actor-scoped set of VMs through typed Agent calls. + * + * The v1 Agent intentionally exposes one explicit UUID per + * `domain_observe`; there is no host inventory or batch endpoint. This + * adapter keeps the old list DTO while validating every returned UUID and + * bounded power state. A failed or uncertain item is omitted so the + * caller can retain its database/runtime snapshot instead of fabricating + * a successful state. Keys are caller-provided host/UUID identities and + * are never taken from Agent response data. + * + * @param array $targets + * @param array $actor + * @return array> + */ + public function observeMany(array $targets, array $actor): array + { + $live = []; + foreach ($targets as $key => $target) { + if (!is_string($key) || !is_array($target) + || !is_int($target['host_id'] ?? null) + || $target['host_id'] < 1 + || !is_string($target['uuid'] ?? null)) { + continue; + } + $uuid = strtolower(trim($target['uuid'])); + if (preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/D', $uuid) !== 1) { + continue; + } + try { + $observed = $this->observe($target['host_id'], $uuid, $actor); + $record = is_array($observed['record'] ?? null) + ? $observed['record'] : []; + if (($record['status'] ?? null) !== 'succeeded') { + continue; + } + $candidate = is_array($observed['observation'] ?? null) + ? $observed['observation'] : []; + $candidateUuid = is_string($candidate['uuid'] ?? null) + ? strtolower(trim($candidate['uuid'])) : ''; + if ($candidateUuid === '' || !hash_equals($uuid, $candidateUuid)) { + continue; + } + $state = CloudInstanceMetadata::state($candidate['state'] ?? null); + if ($state === 'unknown') { + continue; + } + $candidate['uuid'] = $candidateUuid; + $candidate['state'] = $state; + $live[$key] = $candidate; + } catch (CloudError|CloudAgentOperationException) { + // A list refresh is best-effort per VM. The operation row is + // retained (including uncertain transport outcomes); the + // caller returns the previous cache for this item. + } catch (\Throwable) { + // Do not allow one malformed target/Agent response to turn a + // bounded list endpoint into a tenant-visible 500. + } + } + return $live; + } + + /** @param array $payload */ + public static function requestHash( + string $operationId, + string $idempotencyKey, + string $uuid, + array $payload, + ): string { + $body = json_encode([ + 'operation_id' => $operationId, + 'idempotency_key' => $idempotencyKey, + 'kind' => 'domain_observe', + 'target' => $uuid, + 'payload' => $payload === [] ? (object) [] : $payload, + ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + return hash('sha256', $body); + } + + private static function uuid(string $uuid): string + { + $uuid = strtolower(trim($uuid)); + if (preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/D', $uuid) !== 1) { + throw new CloudError('虚拟机标识无效', 422); + } + return $uuid; + } + + private static function newUuid(): string + { + $bytes = random_bytes(16); + $bytes[6] = chr((ord($bytes[6]) & 0x0f) | 0x40); + $bytes[8] = chr((ord($bytes[8]) & 0x3f) | 0x80); + return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($bytes), 4)); + } + + private static function assertOperationIdentity(string $operationId, string $idempotencyKey): 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', $operationId) !== 1 + || preg_match('/^[A-Za-z0-9][A-Za-z0-9_-]{7,63}$/D', $idempotencyKey) !== 1) { + throw new CloudError('面板 Agent 观察操作身份无效', 422); + } + } + + /** @param array $response */ + private static function isReducedFailure(array $response, string $operationId): bool + { + return ($response['operation_id'] ?? null) === $operationId + && is_string($response['status'] ?? null) + && in_array($response['status'], [ + 'pending', 'running', 'succeeded', 'failed', 'uncertain', + ], true) + && !array_key_exists('idempotency_key', $response) + && !array_key_exists('request_hash', $response) + && !array_key_exists('kind', $response) + && !array_key_exists('target', $response) + && !array_key_exists('commit_boundary', $response); + } +} diff --git a/web/app/Services/Cloud/CloudInstancePageService.php b/web/app/Services/Cloud/CloudInstancePageService.php index a380b9f1..feefec93 100644 --- a/web/app/Services/Cloud/CloudInstancePageService.php +++ b/web/app/Services/Cloud/CloudInstancePageService.php @@ -151,7 +151,11 @@ final class CloudInstancePageService * Ordinary users stay owner scoped; read-only administrators retain the * historical all-instance view without inheriting mutation permissions. */ - public static function forActorIds(array $actor, array $ids): array + public static function forActorIds( + array $actor, + array $ids, + bool $includeStaticMetadata = false, + ): array { $ordered = []; foreach ($ids as $id) { @@ -166,9 +170,16 @@ final class CloudInstancePageService if ($ordered === []) { return []; } + $columns = ['id', 'uuid', 'host_id', 'name']; + if ($includeStaticMetadata) { + // Static metadata is already a PHP-owned business snapshot. It + // is safe to project through the public allowlist, but the raw + // spec must never leave this method or be included in the DTO. + $columns[] = 'spec_json'; + } $records = self::visibleQuery($actor) ->whereIn('id', array_keys($ordered)) - ->get(['id', 'uuid', 'host_id', 'name']); + ->get($columns); $runtime = []; try { // Resolve the cache against the current authorized DB identity. @@ -191,7 +202,14 @@ final class CloudInstancePageService 'state_sync_status' => 'pending', 'state_label_hint' => '等待宿主机同步', ]; - $vms[] = [ + $static = []; + if ($includeStaticMetadata) { + $decoded = json_decode((string) $instance->spec_json, true); + $static = CloudInstanceMetadata::publicSpec( + is_array($decoded) && !array_is_list($decoded) ? $decoded : [] + ); + } + $vms[] = $static + [ 'id' => (string) $instance->id, 'api_id' => (string) $instance->id, 'uuid' => (string) $instance->uuid, @@ -208,7 +226,7 @@ final class CloudInstancePageService return $vms; } - /** A deliberately small mutable status view merged with live engine data. */ + /** A deliberately small mutable status view merged with live Agent data. */ public static function status(array $snapshot, array $live = []): array { $liveUuid = is_string($live['uuid'] ?? null) @@ -223,8 +241,8 @@ final class CloudInstancePageService && CloudInstanceMetadata::state($live['state'] ?? null) !== 'unknown'; // A malformed or unavailable live response must not erase a valid // cached observation. The runtime cache remains authoritative for - // ordinary polling; the optional live probe only wins when its state - // is in the bounded vocabulary. + // ordinary polling; the optional Agent observation only wins when its + // state is in the bounded vocabulary. $state = $liveStateAvailable ? CloudInstanceMetadata::state($live['state']) : CloudInstanceMetadata::state($snapshot['state'] ?? 'unknown'); diff --git a/web/tests/CloudAgentObservationServiceContractTest.php b/web/tests/CloudAgentObservationServiceContractTest.php new file mode 100644 index 00000000..5a88708f --- /dev/null +++ b/web/tests/CloudAgentObservationServiceContractTest.php @@ -0,0 +1,38 @@ +billingActor($request)') && !str_contains($pageApi, 'CloudEngineClient'), 'Paginated VM rows must not create an engine session or contact libvirt.'); $assert(str_contains($metadataApi, 'CloudInstancePageService::forActorIds') - && str_contains($metadataApi, '$this->vmProbeTargets($actor, $ids)') - && str_contains($metadataApi, "'GET', 'vm-metadata?ids='") - && str_contains($metadataApi, 'isset($allowed[$uuid])') - && str_contains($metadataApi, 'CloudInstanceMetadata::persistBatch($group, $hostLive)') - && str_contains($metadataApi, ". ':' . \$uuid") + && str_contains($metadataApi, 'CloudInstancePageService::forActorIds($actor, $ids, true)') && str_contains($metadataApi, 'CloudInstanceMetadata::publicView') - && !str_contains($metadataApi, "'GET', 'vms'"), - 'Static VM metadata refresh must be bounded, owner intersected and cached without full inventory.'); + && str_contains($metadataApi, 'domain_metadata operation yet') + && !str_contains($metadataApi, 'CloudEngineClient') + && !str_contains($metadataApi, 'vm-metadata?ids='), + 'Static VM metadata must use the actor-scoped PHP snapshot until a typed Agent read exists.'); $assert(str_contains($statusesApi, 'CloudInstancePageService::forActorIds') && str_contains($statusesApi, '$this->vmProbeTargets($actor, $ids)') + && str_contains($statusesApi, '$this->agentObservationService()->observeMany(') + && str_contains($statusesApi, '$observationTargets') && str_contains($statusesApi, 'CloudInstancePageService::powerStatus') - && str_contains($statusesApi, "'GET',\n 'vm-states?ids='") - && str_contains($statusesApi, 'isset($allowed[$uuid])') && str_contains($statusesApi, ". ':' . \$uuid") - && !str_contains($statusesApi, "'GET', 'vms'"), - 'Batch VM status must intersect owner UUIDs, preserve host identity and use only the lightweight engine resource.'); + && !str_contains($statusesApi, 'CloudEngineClient') + && !str_contains($statusesApi, 'vm-states?ids='), + 'Batch VM status must intersect owner UUIDs, preserve host identity and use typed Agent observations.'); $assert(str_contains($statusApi, 'CloudInstancePageService::statusForActor') && str_contains($statusApi, "['live'] ?? '') === '1'") - && str_contains($statusApi, 'new CloudEngineClient(null, 5.0)') - && str_contains($statusApi, ". '/state'") + && str_contains($statusApi, '$this->agentObservationService()->observe(') + && !str_contains($statusApi, 'CloudEngineClient') && str_contains($statusApi, 'hash_equals(') && str_contains($statusApi, 'CloudInstanceRuntimeService::beginCurrentObservation(') && str_contains($statusApi, 'CloudInstanceRuntimeService::normalizeState(') @@ -137,7 +136,7 @@ $assert(str_contains($statusApi, 'CloudInstancePageService::statusForActor') && str_contains($statusApi, '$runtimeRevision') && str_contains($statusApi, "\$observedState !== 'unknown'") && strpos($statusApi, 'CloudInstanceRuntimeService::beginCurrentObservation(') - < strpos($statusApi, 'new CloudEngineClient(null, 5.0)') + < strpos($statusApi, '$this->agentObservationService()->observe(') && strrpos($statusApi, 'hash_equals(') < strpos($statusApi, 'CloudInstanceRuntimeService::markObserved('), 'Single VM status must keep its cache fallback and bounded, UUID-checked, write-through live path.');