From bb153a51b097c387575e97dcae3178b75d5a885b Mon Sep 17 00:00:00 2001 From: admin Date: Fri, 16 Oct 2026 02:44:38 +0800 Subject: [PATCH] feat: project Go Agent VM operation history --- web/app/Controllers/CloudApiController.php | 15 +- .../CloudAgentOperationHistoryService.php | 156 ++++++++++++++++++ .../Cloud/CloudAgentOperationRepository.php | 81 +++++++++ ...CloudAgentOperationHistoryContractTest.php | 68 ++++++++ 4 files changed, 319 insertions(+), 1 deletion(-) create mode 100644 web/app/Services/Cloud/CloudAgentOperationHistoryService.php create mode 100644 web/tests/CloudAgentOperationHistoryContractTest.php diff --git a/web/app/Controllers/CloudApiController.php b/web/app/Controllers/CloudApiController.php index b830efb0..1dd2a27e 100644 --- a/web/app/Controllers/CloudApiController.php +++ b/web/app/Controllers/CloudApiController.php @@ -15,6 +15,7 @@ use App\Services\Cloud\CloudAccess; use App\Services\Cloud\CloudAgentHostClientResolverFactory; use App\Services\Cloud\CloudAgentObservationService; use App\Services\Cloud\CloudAgentOperationException; +use App\Services\Cloud\CloudAgentOperationHistoryService; use App\Services\Cloud\CloudAgentOperationRepository; use App\Services\Cloud\CloudAgentOperationStatusService; use App\Services\Cloud\CloudDeploymentPageService; @@ -75,6 +76,14 @@ final class CloudApiController ); } + /** Build the fresh, database-only Agent operation-history projection. */ + private function agentOperationHistoryService(): CloudAgentOperationHistoryService + { + return new CloudAgentOperationHistoryService( + new CloudAgentOperationRepository(), + ); + } + private function userIsoImportAllowed(array $actor, bool $throw = false): bool { $user = User::where('id', $actor['user_id'])->first(); @@ -1015,7 +1024,11 @@ final class CloudApiController throw new CloudError('操作日志页码无效', 400); } return $this->json($response, array_merge( - CloudJobService::operationLogs($instance, (int) $page, 10), + $this->agentOperationHistoryService()->forInstance( + $instance, + (int) $page, + 10, + ), ['instance_id' => (string) $instance->id] )); } diff --git a/web/app/Services/Cloud/CloudAgentOperationHistoryService.php b/web/app/Services/Cloud/CloudAgentOperationHistoryService.php new file mode 100644 index 00000000..87ff4bf8 --- /dev/null +++ b/web/app/Services/Cloud/CloudAgentOperationHistoryService.php @@ -0,0 +1,156 @@ + */ + private const HISTORY_KINDS = ['domain_power']; + + public function __construct( + private readonly CloudAgentOperationRepository $operations, + ) { + } + + /** + * Return the existing VM operation-log response shape. + * + * Authorization is intentionally performed by CloudAccess::instance in + * the controller before this service is called. That keeps the existing + * owner/admin visibility rule in one place while this service remains a + * database-only projection. + * + * @return array{items:list>,pagination:array} + */ + public function forInstance( + CloudInstance $instance, + int $page = 1, + int $perPage = 10, + ): array { + $uuid = strtolower(trim((string) ($instance->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('虚拟机标识无效', 503); + } + try { + $history = $this->operations->historyForInstance( + $uuid, + self::HISTORY_KINDS, + $page, + $perPage, + ); + } catch (CloudAgentOperationException $error) { + $status = in_array($error->httpStatus, [400, 422], true) + ? $error->httpStatus : 503; + throw new CloudError( + $status === 503 ? 'Agent 操作历史暂时不可用' : '操作日志分页参数无效', + $status, + ); + } + + $items = []; + foreach ($history['items'] as $record) { + $items[] = self::display($record); + } + return [ + 'items' => $items, + 'pagination' => [ + 'page' => $history['page'], + 'per_page' => $history['per_page'], + 'total' => $history['total'], + 'total_pages' => $history['total_pages'], + 'from' => $history['from'], + 'to' => $history['to'], + ], + ]; + } + + /** @param array $record @return array */ + private static function display(array $record): array + { + $kind = self::panelKind($record['kind'] ?? null); + if ($kind === null) { + // The repository allow-list should make this unreachable. Keep a + // second presentation boundary so a future mapping mistake does + // not turn an internal Agent kind into browser text. + throw new CloudError('Agent 操作类型无效', 503); + } + $status = CloudOperationErrorCatalog::userStatus($record['status'] ?? null); + if ($status === null) { + throw new CloudError('Agent 操作状态损坏', 503); + } + // Existing detail.js labels queued, not the fresh journal's pending. + $displayStatus = $status === 'pending' ? 'queued' : $status; + $desired = is_array($record['desired'] ?? null) ? $record['desired'] : []; + $action = self::panelAction($desired['action'] ?? null); + $errorCode = CloudOperationErrorCatalog::publicCode($record['error_code'] ?? null); + $rawResult = is_array($record['result'] ?? null) ? $record['result'] : null; + $result = $rawResult === null ? null : CloudOperationErrorCatalog::result( + $rawResult, + false, + $kind, + $displayStatus, + false, + $action, + ); + $phaseValue = is_array($result) ? ($result['phase'] ?? null) : null; + $phase = CloudOperationErrorCatalog::userPhase( + $phaseValue, + $displayStatus, + $kind, + ); + $labels = CloudOperationCatalog::labels($kind, $action); + + // Keep the legacy three-column list DTO. The UUID is intentionally + // used as `id` so a row can link to the same status endpoint without + // inventing a numeric CloudJob identity. + return [ + 'id' => (string) ($record['operation_id'] ?? ''), + 'kind' => $kind, + 'status' => $displayStatus, + 'error' => CloudOperationErrorCatalog::userMessage( + $kind, + $displayStatus, + $record['error_code'] ?? null, + false, + $action, + ), + 'error_code' => $errorCode, + 'attempts' => max(0, (int) ($record['attempt_count'] ?? 0)), + 'created_at' => max(0, (int) ($record['created_at'] ?? 0)), + 'updated_at' => max(0, (int) ($record['updated_at'] ?? 0)), + 'action' => $action, + 'kind_label' => $labels['kind_label'], + 'action_label' => $labels['action_label'], + 'phase' => is_string($phase) ? mb_substr($phase, 0, 120) : null, + ]; + } + + private static function panelKind(mixed $kind): ?string + { + return $kind === 'domain_power' ? 'action' : null; + } + + private static function panelAction(mixed $action): ?string + { + if (!is_string($action)) { + return null; + } + if ($action === 'destroy') { + return 'poweroff'; + } + return CloudOperationCatalog::isPowerAction($action) ? $action : null; + } +} diff --git a/web/app/Services/Cloud/CloudAgentOperationRepository.php b/web/app/Services/Cloud/CloudAgentOperationRepository.php index c48dd9e0..b79fa49e 100644 --- a/web/app/Services/Cloud/CloudAgentOperationRepository.php +++ b/web/app/Services/Cloud/CloudAgentOperationRepository.php @@ -495,6 +495,78 @@ final class CloudAgentOperationRepository return self::publicRecord($row); } + /** + * 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 $kinds + * @return array{items:list>,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, + ): array { + $instanceUuid = self::instanceUuid($instanceUuid); + 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) + ->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 $request */ private function replayOrConflict(object $row, array $request): array { @@ -549,6 +621,15 @@ final class CloudAgentOperationRepository 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) diff --git a/web/tests/CloudAgentOperationHistoryContractTest.php b/web/tests/CloudAgentOperationHistoryContractTest.php new file mode 100644 index 00000000..1dee4e6c --- /dev/null +++ b/web/tests/CloudAgentOperationHistoryContractTest.php @@ -0,0 +1,68 @@ + 50)') + && str_contains($repository, "->orderByDesc('created_at')->orderByDesc('id')"), + 'Agent history query is not bounded or deterministically ordered.'); + +$assert(str_contains($service, "private const HISTORY_KINDS = ['domain_power']") + && str_contains($service, 'historyForInstance(') + && str_contains($service, 'return $kind === \'domain_power\' ? \'action\' : null') + && str_contains($service, 'if ($action === \'destroy\')') + && str_contains($service, 'CloudOperationErrorCatalog::result(') + && str_contains($service, '\'kind_label\' => $labels[\'kind_label\']'), + 'Agent history projection lost explicit domain_power/action mapping or result redaction.'); + +$assert($start !== false && $method !== '' + && str_contains($method, 'CloudAccess::instance($args[\'id\'], $actor)') + && str_contains($method, 'agentOperationHistoryService()') + && !str_contains($method, 'CloudJobService::operationLogs') + && !str_contains($method, 'CloudEngineClient') + && !str_contains($method, 'shell_exec') + && !str_contains($method, 'curl_exec') + && !str_contains($method, 'ssh'), + 'VM operation-log route must use the fresh Agent projection after owner/admin lookup, without legacy transport.'); + +$assert(str_contains($routes, "'/vms/{id:[0-9]+}/operations'") + && str_contains($middleware, '/api/v1/vms/[0-9]+/operations$#D'), + 'The existing VM operation-log route or database-only middleware boundary changed.'); + +foreach (['CloudJobService::', 'CloudEngineClient', 'shell_exec', 'curl_exec'] as $forbidden) { + $assert(!str_contains($service, $forbidden), + 'Agent operation-history service crossed a legacy boundary: ' . $forbidden); +} + +fwrite(STDOUT, "Cloud Agent operation-history contract passed.\n");