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/CloudAgentOperationStatusSe...

168 lines
7.7 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudAgent;
use App\Models\CloudAgentOperation;
use App\Models\CloudInstance;
/**
* Project a fresh Agent journal record into the existing job-status DTO.
*
* The browser can keep polling `/api/v1/jobs/{id}` while the panel changes
* the backing store from encrypted legacy jobs to the plaintext, typed Agent
* journal. Numeric legacy IDs remain handled by CloudJobService; UUID IDs
* are resolved here and are authorized against the instance UUID in the
* journal before any status is returned.
*/
final class CloudAgentOperationStatusService
{
/** @param array<string,mixed> $actor @return array<string,mixed> */
public static function forActor(string $operationId, array $actor): array
{
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) {
throw new CloudError('任务编号无效', 400);
}
try {
$row = CloudAgentOperation::where('operation_id', $operationId)->first();
} catch (\Throwable) {
throw new CloudError('Agent 操作记录暂时不可用', 503);
}
if ($row === null || !is_string($row->instance_uuid ?? null)
|| preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/D', $row->instance_uuid) !== 1) {
throw new CloudError('任务不存在', 404);
}
$agentId = is_string($row->agent_id ?? null) ? trim($row->agent_id) : '';
$hostId = filter_var($row->host_id ?? null, FILTER_VALIDATE_INT,
['options' => ['min_range' => 1]]);
$rawInstanceId = $row->instance_id ?? null;
$instanceId = null;
if ($rawInstanceId !== null) {
$instanceId = filter_var($rawInstanceId, FILTER_VALIDATE_INT,
['options' => ['min_range' => 1]]);
if ($instanceId === false) {
throw new CloudError('任务不存在', 404);
}
}
if ($agentId === '' || $hostId === false) {
throw new CloudError('任务不存在', 404);
}
try {
// The operation stores an immutable host snapshot. The current
// registry must still point the Agent at that same host; a
// re-enrollment/rebind can never make an old UUID operation cross
// into a different host's instance.
$agent = CloudAgent::where('agent_id', $agentId)
->where('host_id', (int) $hostId)->first();
$instance = $agent === null
? null
: CloudInstance::where('host_id', (int) $hostId)
->when($instanceId !== null,
static fn ($query) => $query->where('id', (int) $instanceId))
->where('uuid', $row->instance_uuid)->first();
} catch (\Throwable) {
throw new CloudError('任务所属实例暂时不可用', 503);
}
if ($instance === null || (!($actor['is_admin'] ?? false)
&& (int) $instance->user_id !== (int) ($actor['user_id'] ?? 0))) {
throw new CloudError('任务不存在', 404);
}
// Re-read through the repository so stored JSON/identity invariants
// are checked before they become a browser DTO. This also avoids
// exposing hidden lease/error-detail columns from the Eloquent row.
try {
$record = (new CloudAgentOperationRepository())->get($operationId);
} catch (CloudAgentOperationException $error) {
if ($error->errorCode === 'not_found') {
throw new CloudError('任务不存在', 404);
}
throw new CloudError('Agent 操作记录暂时不可用', 503);
}
if ((int) ($record['host_id'] ?? 0) !== (int) $hostId
|| (($instanceId === null && ($record['instance_id'] ?? null) !== null)
|| ($instanceId !== null && (int) ($record['instance_id'] ?? 0) !== (int) $instanceId)) {
throw new CloudError('任务身份已变化,请重新查询', 409);
}
$kind = (string) ($record['kind'] ?? '');
$panelKind = self::panelKind($kind);
if ($panelKind === null) {
// Internal observations/plans are not tenant-visible jobs. A
// caller who knows a UUID still must not turn a capability probe
// into a browser DTO.
throw new CloudError('任务不存在', 404);
}
$status = CloudOperationErrorCatalog::userStatus($record['status'] ?? null);
if ($status === null) {
// The repository validates this invariant. Keep the adapter
// fail-closed if a future repository implementation returns an
// unrecognised state rather than copying it to the browser.
throw new CloudError('Agent 操作状态损坏', 503);
}
$desired = is_array($record['desired'] ?? null) ? $record['desired'] : [];
$agentAction = is_string($desired['action'] ?? null) ? $desired['action'] : null;
$panelAction = self::panelAction($agentAction);
$administrator = (bool) ($actor['is_admin'] ?? false);
$errorCode = CloudOperationErrorCatalog::publicCode($record['error_code'] ?? null);
$error = CloudOperationErrorCatalog::userMessage(
$panelKind, $status, $errorCode, false, $panelAction,
);
if ($administrator) {
$error = CloudOperationErrorCatalog::adminSummary(
$panelKind, $status, $record['error_code'] ?? null, false, $panelAction,
);
}
$rawResult = is_array($record['result'] ?? null) ? $record['result'] : null;
// Repository JSON validation protects the storage shape, but it is
// intentionally not a presentation allow-list. Apply the same
// result projection used by legacy job DTOs before exposing any
// Agent-produced fields to users or administrators.
$result = $rawResult === null ? null : CloudOperationErrorCatalog::result(
$rawResult,
$administrator,
$panelKind,
$status,
false,
$panelAction,
);
$phaseValue = is_array($result) ? ($result['phase'] ?? null) : null;
$phase = $administrator
? CloudOperationErrorCatalog::adminSummary(
$panelKind, $status, $phaseValue, false, $panelAction,
)
: CloudOperationErrorCatalog::userPhase($phaseValue, $status, $panelKind);
return [
'id' => $operationId,
'job_id' => $operationId,
'operation_id' => $operationId,
'instance_id' => (string) $instance->id,
'kind' => $panelKind,
'status' => $status,
'error' => $error,
'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' => $panelAction,
'kind_label' => CloudOperationCatalog::kindLabel($panelKind, $panelAction),
'action_label' => CloudOperationCatalog::actionLabel($panelAction),
'phase' => $phase,
'result' => $result,
];
}
private static function panelKind(string $agentKind): ?string
{
return $agentKind === 'domain_power' ? 'action' : null;
}
private static function panelAction(?string $agentAction): ?string
{
if ($agentAction === 'destroy') {
return 'poweroff';
}
return $agentAction !== null && CloudOperationCatalog::isPowerAction($agentAction)
? $agentAction : null;
}
}