feat: project Go Agent VM operation history

go-agent
admin 1 month ago
parent c952b3723f
commit bb153a51b0

@ -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]
));
}

@ -0,0 +1,156 @@
<?php
namespace App\Services\Cloud;
use App\Models\CloudInstance;
/**
* Project fresh Go Agent journal rows into the VM operation-log DTO.
*
* The detail page deliberately has one read contract for both generations of
* the panel. During the cutover this service owns the new path: it reads
* only cloud_agent_operations, maps the currently migrated domain_power kind
* to the historical `action` vocabulary, and never invokes Python, SSH or
* the encrypted CloudJob store. Adding another Agent kind requires an
* explicit presentation mapping here instead of making every internal probe
* visible to a tenant.
*/
final class CloudAgentOperationHistoryService
{
/** @var list<string> */
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<array<string,mixed>>,pagination:array<string,int>}
*/
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<string,mixed> $record @return array<string,mixed> */
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;
}
}

@ -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<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,
): 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<string,mixed> $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)

@ -0,0 +1,68 @@
<?php
// Source-level contract for the VM operation-log cutover. PHP/Composer are
// optional in the development shell, so the test verifies the boundary and
// DTO shape without booting the application or a database.
$root = dirname(__DIR__);
$read = static function (string $path) use ($root): string {
$value = file_get_contents($root . '/' . $path);
if (!is_string($value) || $value === '') {
throw new RuntimeException('Missing Agent operation-history source: ' . $path);
}
return $value;
};
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$service = $read('app/Services/Cloud/CloudAgentOperationHistoryService.php');
$repository = $read('app/Services/Cloud/CloudAgentOperationRepository.php');
$controller = $read('app/Controllers/CloudApiController.php');
$routes = $read('config/routes_cloud.php');
$middleware = $read('app/Middleware/CloudApi.php');
$start = strpos($controller, 'public function operationLogs(');
$end = strpos($controller, '/** Database-only read', $start === false ? 0 : $start);
$method = $start === false
? ''
: substr($controller, $start, $end === false ? null : $end - $start);
$assert(str_contains($repository, 'function historyForInstance(')
&& str_contains($repository, 'where(\'instance_uuid\', $instanceUuid)')
&& str_contains($repository, 'whereIn(\'kind\', $normalizedKinds)')
&& str_contains($repository, 'self::publicRecord($row)'),
'Agent operation repository lost the validated per-instance history query.');
$assert(str_contains($repository, 'if ($page < 1 || $perPage < 1 || $perPage > 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");
Loading…
Cancel
Save