feat: project Go Agent VM operation history
parent
c952b3723f
commit
bb153a51b0
@ -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;
|
||||
}
|
||||
}
|
||||
@ -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…
Reference in New Issue