feat: expose Go Agent operation status through job API
parent
703529eef4
commit
4055f91a4d
@ -0,0 +1,133 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
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);
|
||||
}
|
||||
try {
|
||||
// Keep the tombstone visible for the terminal delete operation.
|
||||
// Authorization still uses the owner on the retained instance
|
||||
// row; hiding `deleted` here would make a successful/uncertain
|
||||
// delete job impossible to poll after the worker marks it done.
|
||||
$instance = CloudInstance::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);
|
||||
}
|
||||
$kind = (string) ($record['kind'] ?? '');
|
||||
$panelKind = self::panelKind($kind);
|
||||
$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' : $agentKind;
|
||||
}
|
||||
|
||||
private static function panelAction(?string $agentAction): ?string
|
||||
{
|
||||
if ($agentAction === 'destroy') {
|
||||
return 'poweroff';
|
||||
}
|
||||
return $agentAction !== null && CloudOperationCatalog::isPowerAction($agentAction)
|
||||
? $agentAction : null;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
// Dependency-free contract for the UUID Agent-operation polling bridge. The
|
||||
// panel shell may not have PHP/Composer in the development environment, so
|
||||
// keep this test at source level and leave the full HTTP/model test to panel
|
||||
// CI.
|
||||
$root = dirname(__DIR__);
|
||||
$read = static function (string $path) use ($root): string {
|
||||
$value = file_get_contents($root . '/' . $path);
|
||||
if (!is_string($value)) {
|
||||
throw new RuntimeException('Missing Cloud Agent status contract source: ' . $path);
|
||||
}
|
||||
return $value;
|
||||
};
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
$service = $read('app/Services/Cloud/CloudAgentOperationStatusService.php');
|
||||
$controller = $read('app/Controllers/CloudApiController.php');
|
||||
$routes = $read('config/routes_cloud.php');
|
||||
$middleware = $read('app/Middleware/CloudApi.php');
|
||||
|
||||
$uuid = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';
|
||||
$jobRoute = "{id:{$uuid}}";
|
||||
$jobPath = '(?:jobs|reinstall-jobs|rescue-jobs)/' . $uuid;
|
||||
|
||||
$assert(str_contains($routes, $jobRoute)
|
||||
&& str_contains($routes, "'/' . $name . '/{id:[0-9]+}'"),
|
||||
'Agent UUID job routes were added without retaining numeric legacy routes.');
|
||||
$assert(str_contains($middleware, $jobPath)
|
||||
&& str_contains($middleware, '(?:jobs|reinstall-jobs|rescue-jobs)/[0-9]+'),
|
||||
'Cloud API middleware does not classify both Agent UUID and numeric jobs as database-only.');
|
||||
|
||||
$jobOffset = strpos($controller, 'public function job(');
|
||||
$agentOffset = strpos($controller, 'CloudAgentOperationStatusService::forActor', $jobOffset === false ? 0 : $jobOffset);
|
||||
$legacyOffset = strpos($controller, 'CloudJob::where', $jobOffset === false ? 0 : $jobOffset);
|
||||
$assert($jobOffset !== false && $agentOffset !== false && $legacyOffset !== false
|
||||
&& $agentOffset < $legacyOffset,
|
||||
'The job controller must dispatch UUIDs to the Agent projection before the numeric CloudJob query.');
|
||||
|
||||
$assert(str_contains($service, 'CloudAgentOperationRepository')
|
||||
&& str_contains($service, 'CloudInstance::where(\'uuid\', $row->instance_uuid)')
|
||||
&& str_contains($service, 'CloudOperationErrorCatalog::result(')
|
||||
&& str_contains($service, "'result' => $result"),
|
||||
'Agent status projection lost repository validation, owner lookup, or result redaction.');
|
||||
$assert(str_contains($service, "'job_id' => $operationId")
|
||||
&& str_contains($service, "'operation_id' => $operationId")
|
||||
&& str_contains($service, "'instance_id' => (string) $instance->id"),
|
||||
'Agent status DTO no longer preserves the browser job identity fields.');
|
||||
|
||||
foreach (['CloudEngineClient', 'CloudJobService', 'CloudWorkerService', 'ssh', 'SSH', 'shell_exec', 'curl_exec'] as $forbidden) {
|
||||
$assert(!str_contains($service, $forbidden),
|
||||
'Agent status projection crossed a legacy transport boundary: ' . $forbidden);
|
||||
}
|
||||
|
||||
fwrite(STDOUT, "Cloud Agent operation status contract passed.\n");
|
||||
Loading…
Reference in New Issue