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/CloudWorkerService.php

1956 lines
92 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudInstance;
use App\Models\CloudInvoice;
use App\Models\CloudJob;
use App\Models\CloudOrder;
use App\Models\CloudServicePeriod;
use App\Models\User;
use App\Services\Payment\PaymentOrderCreationException;
final class CloudWorkerService
{
private const AGENT_TIMEOUT_SECONDS = 900.0;
private const POLICY_AGENT_TIMEOUT_SECONDS = 120.0;
private const LEASE_SECONDS = 930;
private const POLICY_KINDS = ['service_suspend',
'network_suspend', 'network_resume'];
private const REINSTALL_REVIEW_CODES = [
'reinstall_cleanup_pending',
];
private bool $policyOnly;
private array $observedErrors = [];
public function observationErrors(): array
{
return array_values(array_unique($this->observedErrors));
}
public function __construct(private ?CloudAgentClient $agent = null,
bool $policyOnly = false)
{
$this->policyOnly = $policyOnly;
// A cloud-image clone can legitimately take minutes on remote storage.
// The layered deadlines are Agent API 840s, Agent WSS control 855s,
// Gateway 870s, PHP 900s and worker lease 930s. Each outer layer has
// time to persist the inner layer's structured result before expiry.
}
private function agentForJob(CloudJob $job): CloudAgentClient
{
if ($this->agent !== null) {
return $this->agent;
}
if ((string) $job->kind === 'host_storage_configure') {
return CloudAgentSettingsService::clientForConfiguration(
(int) $job->host_id,
self::POLICY_AGENT_TIMEOUT_SECONDS
);
}
return CloudAgentSettingsService::clientForHost(
(int) $job->host_id,
$this->policyOnly
? self::POLICY_AGENT_TIMEOUT_SECONDS
: self::AGENT_TIMEOUT_SECONDS
);
}
public static function disposition(array $operation, bool $creating,
?string $kind = null): string
{
$status = is_string($operation['status'] ?? null)
? strtolower(trim($operation['status'])) : 'failed';
return $status === 'succeeded' ? 'succeeded'
: ($status === 'failed' ? 'failed' : 'running');
}
/** A create may refund only after both the VM and all managed artifacts are absent. */
private static function createFailureConfirmedAbsent(array $operation): bool
{
$result = $operation['result'] ?? null;
return is_array($result)
&& ($result['creation_absent'] ?? false) === true
&& ($result['managed_artifacts_absent'] ?? false) === true;
}
/** Exact Agent evidence required before PHP releases a deleted VM's ledger. */
private static function deleteSuccessConfirmed(array $operation,
string $kind): bool
{
$result = $operation['result'] ?? null;
return is_array($result) && !array_is_list($result)
&& ($result['deleted'] ?? null) === true
&& ($result['managed_artifacts_absent'] ?? null) === true
&& ($kind === 'delete_force'
? ($result['forced'] ?? null) === true
: ($result['forced'] ?? null) === false);
}
/** Exact evidence for a create request proven not to have crossed dispatch. */
private static function createNotDispatchedFailure(): array
{
return [
'status' => 'failed',
'result' => [
'creation_absent' => true,
'managed_artifacts_absent' => true,
],
];
}
/** Treat unconfirmed reinstall cleanup as a failed receipt, never as active work. */
private static function reinstallNeedsReview(array $operation): bool
{
$code = is_string($operation['error_code'] ?? null)
? strtolower(trim($operation['error_code'])) : '';
if ($code === '' && is_array($operation['error'] ?? null)
&& is_string($operation['error']['code'] ?? null)) {
$code = strtolower(trim($operation['error']['code']));
}
if (in_array($code, self::REINSTALL_REVIEW_CODES, true)) {
return true;
}
$result = $operation['result'] ?? null;
return is_array($result)
&& ($result['cleanup_pending'] ?? false) === true;
}
public function tick(): bool
{
$this->observedErrors = [];
$expired = self::expireDueJobs();
return $this->tickJob() || $expired > 0;
}
/** Claim and advance at most one durable cloud job. */
private function tickJob(): bool
{
$job = (new CloudJob())->getConnection()->transaction(function () {
$now = time();
$query = self::dispatchableBeforeDeadline(
CloudJob::where('phase', 'accepted')
->whereIn('execution_mode', ['agent', 'local'])
->where('dispatch_attempts', 0),
$now
)->where('available_at', '<=', $now)
->where('lease_until', '<=', $now);
if ($this->policyOnly) {
$query->whereIn('kind', self::POLICY_KINDS);
} else {
// The regular worker remains a fail-safe policy consumer when
// the dedicated workers are not installed, but always claims
// target-state policy ahead of slow image/provisioning jobs.
$quoted = "'" . implode("','", self::POLICY_KINDS) . "'";
$query->orderByRaw("CASE WHEN kind IN (" . $quoted
. ") THEN 0 WHEN kind = 'expiry_delete' THEN 1 ELSE 2 END");
}
$job = $query->orderBy('id')->lockForUpdate()->first();
if ($job === null) {
return null;
}
$job->lease_token = bin2hex(random_bytes(16));
$job->lease_until = $now + (in_array($job->kind, self::POLICY_KINDS, true)
? 150 : self::LEASE_SECONDS);
$job->save();
return $job;
}, 3);
if ($job === null) {
return false;
}
$payload = [];
$dispatched = false;
try {
$payload = CloudSecrets::decrypt($job->sealed_payload, 'job-payload');
if ((string) $job->kind === 'payment_create') {
try {
$this->runPaymentCreate($job, $payload, $dispatched);
} catch (\Throwable $error) {
$this->observedErrors[] = 'payment_task_failed';
$crossed = $dispatched;
if (!$crossed) {
$fresh = CloudJob::find((int) $job->id);
$crossed = $fresh !== null
&& (int) $fresh->dispatch_attempts === 1;
}
self::forceTerminalFailure(
(int) $job->id,
(string) $job->lease_token,
$crossed,
!$crossed,
'payment_finalization_failed'
);
error_log('cloud payment task ' . (int) $job->id
. ' failed: ' . get_class($error));
}
return true;
}
if (!is_string($payload['method'] ?? null)
|| !in_array(strtoupper($payload['method']),
['POST', 'PUT', 'PATCH', 'DELETE'], true)
|| !is_string($payload['request_target'] ?? null)
|| !str_starts_with($payload['request_target'], '/v1/')
|| !is_array($payload['body'] ?? null)) {
throw new CloudError('Agent 任务请求格式无效', 409);
}
$policyKind = in_array($job->kind, self::POLICY_KINDS, true);
$systemPolicy = ($payload['system_policy'] ?? false) === true
&& $policyKind && self::validSystemPolicy($job, $payload);
$systemCleanup = $job->kind === 'expiry_delete'
&& ($payload['system_cleanup'] ?? false) === true
&& self::validSystemCleanup($job, $payload);
if (($policyKind && !$systemPolicy)
|| ($job->kind === 'expiry_delete' && !$systemCleanup)) {
throw new CloudError('系统策略任务与实例状态不匹配', 409);
}
$actor = ['user_id' => (int) $job->user_id, 'is_admin' => false, 'is_super_admin' => false,
'can_manage' => false, 'session_id' => '', 'operation_id' => $job->operation_id];
$user = User::find($job->user_id);
if (!$systemPolicy && !$systemCleanup
&& ($user === null || (int) $user->enable !== 1)) {
$operation = $job->kind === 'create'
? self::createNotDispatchedFailure()
: ['status' => 'failed'];
$operation['effect_may_have_applied'] = false;
$operation['safe_to_resubmit'] = true;
$this->finish($job, $operation, $payload);
return true;
}
if ($job->kind === 'create') {
$actor['can_provision'] = true;
$actor['can_manage'] = true;
} elseif ($systemPolicy || $systemCleanup) {
$actor['can_manage'] = true;
if ($systemCleanup) {
$actor['system_cleanup'] = true;
}
} elseif (($payload['can_manage'] ?? false) === true && $user !== null
&& (bool) $user->is_admin && in_array((int) $user->id,
array_map('intval', explode(',', (string) \App\Services\Config::get('super_admin'))), true)) {
$actor['is_admin'] = $actor['is_super_admin'] = $actor['can_manage'] = true;
} elseif ((int) ($payload['owner_id'] ?? 0) === (int) $job->user_id) {
$actor['can_manage'] = true;
}
if ($job->kind !== 'create' && !$actor['can_manage']) {
$this->finish($job, ['status' => 'failed',
'effect_may_have_applied' => false,
'safe_to_resubmit' => true], $payload);
return true;
}
if (!CloudFirewallService::assertJobRunnable($job, $payload)) {
// A confirmed instance deletion dominates an overlapping
// tenant firewall request. Close the obsolete job without
// touching the deleted policy or contacting the Agent.
$this->finish($job, [
'operation_id' => (string) $job->operation_id,
'status' => 'failed',
'error_code' => 'firewall_apply_superseded',
'error' => '实例已删除,防火墙请求不再适用',
], $payload);
return true;
}
if ($systemPolicy && $job->instance_id !== null) {
$instance = CloudInstance::find($job->instance_id);
$desired = self::policyDesired($instance, (string) $job->kind);
if (!$desired) {
$this->finish($job, ['status' => 'succeeded', 'result' => ['skipped' => true]], $payload);
return true;
}
}
if (!$systemPolicy && !$systemCleanup && $job->kind !== 'create'
&& $job->instance_id !== null) {
$instance = CloudInstance::find($job->instance_id);
$policyTransition = $instance !== null
&& (in_array((string) $instance->service_status,
['suspending_expired', 'resume_pending', 'resuming',
'suspend_failed', 'resume_failed', 'expired_grace',
'purge_stopping', 'purge_stop_failed',
'purge_force_required',
'purge_deleting', 'purge_failed'], true)
|| in_array((string) $instance->network_status,
['blocking', 'blocking_expired', 'blocked_expired',
'restore_pending', 'restoring', 'block_failed',
'restore_failed'], true));
$globalOverride = $actor['is_super_admin'] && $actor['can_manage'];
if ($instance === null || ($job->kind !== 'delete' && !$globalOverride
&& ($policyTransition || !$instance->serviceAvailable()))) {
$this->finish($job, ['status' => 'failed',
'error' => '实例服务已到期或正在执行策略,不能执行该操作'], $payload);
return true;
}
}
$now = time();
$dispatchClaim = self::dispatchableBeforeDeadline(
CloudJob::where('id', $job->id)
->where('lease_token', $job->lease_token)
->where('phase', 'accepted')
->where('dispatch_attempts', 0),
$now
);
$updated = $dispatchClaim->update([
'phase' => 'dispatching',
'status' => 'running',
'attempts' => 1,
'dispatch_attempts' => 1,
'dispatch_started_at' => $now,
'dispatched_at' => $now,
'receipt_deadline_at' => $now
+ CloudJobService::receiptDeadlineSeconds(
(string) $job->kind
),
'updated_at' => $now,
]);
if ($updated !== 1) {
return true;
}
CloudFirewallService::markJobRunning($job);
$dispatched = true;
$operation = self::operationForJob(
$job,
$this->agentForJob($job)->request(
$payload['method'],
$payload['request_target'],
$actor,
self::agentRequestBody((string) $job->kind,
$payload['body'])
)
);
$operation = self::normalizeAgentOperation($operation);
$agentStatus = strtolower((string) ($operation['status'] ?? ''));
if (in_array($agentStatus, ['succeeded', 'failed'], true)) {
$operation['effect_may_have_applied'] =
$operation['effect_may_have_applied'] ?? true;
$operation['safe_to_resubmit'] =
$operation['safe_to_resubmit'] ?? false;
$this->finish($job, $operation, $payload);
} elseif (in_array($agentStatus,
['accepted', 'reserved', 'dispatching', 'pending', 'running'],
true)) {
CloudJob::where('id', $job->id)
->where('lease_token', $job->lease_token)
->where('phase', 'dispatching')->update([
'phase' => 'awaiting_receipt',
'agent_accepted_at' => time(),
'lease_token' => null,
'lease_until' => 0,
'updated_at' => time(),
]);
$fresh = CloudJob::find((int) $job->id);
$event = $fresh === null ? null
: CloudOperationCompletionService::pendingForJob($fresh);
if ($event !== null) {
$this->settleCompletionReceipt((int) $job->id,
(string) $event->event_id);
}
} else {
throw new CloudError('Agent 返回了无效的任务状态', 502);
}
} catch (\Throwable $error) {
// Diagnostics deliberately contain no raw payloads, credentials or upstream tracebacks.
$this->observedErrors[] = 'worker_tick_failed';
$diagnostic = self::exceptionDiagnostic($error, $dispatched,
(string) $job->kind, $job->order_id !== null, self::payloadAction($payload));
$log = 'cloud worker job ' . $job->id . ' failed: ' . get_class($error);
if ($error instanceof CloudError) {
$log .= ' status=' . $error->httpStatus . ' message=' . $diagnostic;
}
error_log($log);
$safe = !$dispatched || ($error instanceof CloudAgentError
&& ($error->safeValidationFailure
|| $error->safePreDispatchFailure));
$operation = $safe && $job->kind === 'create'
? self::createNotDispatchedFailure() : ['status' => 'failed'];
$operation['operation_id'] = (string) $job->operation_id;
$operation['error_code'] = $error instanceof CloudAgentError
? $error->agentCode : 'dispatch_failed';
$operation['effect_may_have_applied'] = !$safe;
$operation['safe_to_resubmit'] = $safe;
try {
$this->finish($job, $operation, $payload);
} catch (\Throwable $finishError) {
self::forceTerminalFailure((int) $job->id,
(string) $job->lease_token, !$safe,
$safe, 'local_finalization_failed');
}
}
return true;
}
/**
* Keep both the queue claim and the accepted-to-dispatching CAS behind the
* same absolute deadline. The second check closes the boundary race where
* an old storage task was scanned just before created_at+60 but would
* otherwise cross dispatch using its former persisted 300-second value.
*/
private static function dispatchableBeforeDeadline($query, int $now)
{
$storageWindow = CloudJobService::dispatchDeadlineSeconds(
'host_storage_configure'
);
return $query->where('dispatch_deadline_at', '>', $now)
->where(static function ($eligible) use (
$now, $storageWindow
): void {
$eligible->where('kind', '!=', 'host_storage_configure')
->orWhere('created_at', '>', $now - $storageWindow);
});
}
private function runPaymentCreate(CloudJob $job, array $payload,
bool &$dispatched): void
{
$input = $payload['input'] ?? null;
if ($job->invoice_id === null || !is_array($input)
|| !is_string($input['idempotency_key'] ?? null)
|| !is_string($input['method'] ?? null)) {
$this->finishPaymentCreate($job, false, null, false, true,
'payment_request_invalid');
return;
}
$now = time();
$dispatchClaim = self::dispatchableBeforeDeadline(
CloudJob::where('id', (int) $job->id)
->where('lease_token', (string) $job->lease_token)
->where('phase', 'accepted')
->where('dispatch_attempts', 0),
$now
);
$claimed = $dispatchClaim->update([
'phase' => 'dispatching', 'status' => 'running',
'attempts' => 1, 'dispatch_attempts' => 1,
'dispatch_started_at' => $now, 'dispatched_at' => $now,
'receipt_deadline_at' => $now
+ CloudJobService::receiptDeadlineSeconds(
(string) $job->kind
),
'updated_at' => $now,
]);
if ($claimed !== 1) {
return;
}
$dispatched = true;
try {
$invoice = CloudInvoice::where('id', (int) $job->invoice_id)
->where('user_id', (int) $job->user_id)->first();
$user = User::find((int) $job->user_id);
if ($invoice === null || $user === null) {
throw new CloudError('账单或账户不存在', 404);
}
$payment = CloudInvoicePaymentService::create(
$invoice,
$user,
$input,
(string) ($payload['client_ip'] ?? ''),
(string) ($payload['user_agent'] ?? '')
);
$this->finishPaymentCreate($job, true, $payment, false, false, '');
} catch (\Throwable $error) {
$attempt = \App\Models\CloudInvoicePayment::where(
'user_id', (int) $job->user_id
)->where('idempotency_key', (string) $input['idempotency_key'])
->first();
if ($error instanceof PaymentOrderCreationException) {
$effect = $error->effectMayHaveApplied;
$safe = $error->safeToResubmit;
$code = $error->failureCode;
} elseif ((string) $input['method'] === 'usdt') {
// USDT order creation is one local database transaction; it
// does not submit a non-idempotent provider mutation here.
$effect = false;
$safe = true;
$code = 'payment_creation_failed';
} else {
$status = (string) ($attempt?->status ?? '');
$effect = $attempt !== null
&& $status !== 'not_created';
$safe = !$effect;
$code = $effect ? 'payment_creation_unknown'
: 'payment_creation_failed';
}
$this->finishPaymentCreate($job, false, null, $effect,
$safe, $code);
}
}
private function finishPaymentCreate(CloudJob $job, bool $success,
?array $result, bool $effect, bool $safe, string $code): void
{
CloudJob::where('id', (int) $job->id)
->where('lease_token', (string) $job->lease_token)
->where('phase', '<>', 'terminal')->update([
'phase' => 'terminal',
'outcome' => $success ? 'succeeded' : 'failed',
'status' => $success ? 'succeeded' : 'failed',
'terminal_at' => time(),
'effect_may_have_applied' => $effect ? 1 : 0,
'safe_to_resubmit' => $safe ? 1 : 0,
'effect_resolution' => $success ? 'applied'
: ($effect ? 'unknown' : 'not_applied'),
'error_code' => $success ? null : $code,
'result_json' => $result === null ? null
: json_encode(['payment_id' => (string) ($result['id'] ?? '')], JSON_THROW_ON_ERROR
| JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
'sealed_payload' => CloudSecrets::encrypt([], 'job-payload'),
'lease_token' => null, 'lease_until' => 0,
'available_at' => 0, 'updated_at' => time(),
]);
if (!$success) {
$this->observedErrors[] = 'task_failed';
}
}
/** Expire accepted or dispatched work into a local terminal failure. */
public static function expireDueJobs(int $limit = 100): int
{
return self::expireDueJobsMatching(null, null, $limit);
}
/**
* Close only one owner's public tasks when the worker daemon is absent.
* This path consumes durable receipts and performs local finalization; it
* never opens an Agent connection or dispatches a mutation.
*/
public static function expireDueTasksForOwner(int $userId,
?int $taskId = null, int $limit = 100): int
{
if ($userId < 1 || ($taskId !== null && $taskId < 1)) {
return 0;
}
return self::expireDueJobsMatching($userId, $taskId, $limit);
}
/**
* Close one already-due task from an administrator read path.
* This never contacts an Agent and never dispatches a mutation.
*/
public static function expireDueTaskForAdmin(int $taskId): int
{
if ($taskId < 1) {
return 0;
}
return self::expireDueJobsMatching(null, $taskId, 1);
}
private static function expireDueJobsMatching(?int $userId,
?int $taskId, int $limit): int
{
$now = time();
$storageDispatchWindow = CloudJobService::dispatchDeadlineSeconds(
'host_storage_configure'
);
$storageWindow = CloudJobService::receiptDeadlineSeconds(
'host_storage_configure'
);
$query = CloudJob::where(static function ($query) use (
$now, $storageDispatchWindow, $storageWindow
): void {
$query->where(static function ($accepted) use (
$now, $storageDispatchWindow
): void {
$accepted->where('phase', 'accepted')
->where(static function ($deadline) use (
$now, $storageDispatchWindow
): void {
$deadline->where('dispatch_deadline_at', '<=', $now)
->orWhere(static function ($storage) use (
$now, $storageDispatchWindow
): void {
$storage->where(
'kind', 'host_storage_configure'
)->where('created_at', '<=',
$now - $storageDispatchWindow);
});
});
})->orWhere(static function ($sent) use (
$now, $storageWindow
): void {
$sent->whereIn('phase', ['dispatching', 'awaiting_receipt'])
->whereNotNull('receipt_deadline_at')
->where(static function ($deadline) use (
$now, $storageWindow
): void {
$deadline->where('receipt_deadline_at', '<=', $now)
->orWhere(static function ($storage) use (
$now, $storageWindow
): void {
$storage->where(
'kind', 'host_storage_configure'
)->whereNotNull('dispatched_at')
->where('dispatched_at', '<=',
$now - $storageWindow);
});
});
});
});
if ($userId !== null) {
// Child jobs are not publicly listed, but the owner-scoped
// daemon-loss fallback must still terminalize them before their
// aggregate parent can close.
$query->where('user_id', $userId);
}
if ($taskId !== null) {
$query->where('id', $taskId);
}
$rows = $query
->orderByRaw('CASE WHEN parent_job_id IS NULL THEN 1 ELSE 0 END')
->orderBy('id')
->limit(max(1, min(100, $limit)))->get();
$expired = 0;
foreach ($rows as $row) {
$effect = (int) $row->dispatch_attempts === 1;
$token = bin2hex(random_bytes(16));
$claim = CloudJob::where('id', (int) $row->id)
->where('phase', (string) $row->phase)
->where('dispatch_attempts', (int) $row->dispatch_attempts);
if ($row->lease_token === null) {
$claim->whereNull('lease_token');
} else {
$claim->where('lease_token', (string) $row->lease_token);
}
// An absolute deadline wins over a stale worker lease. The CAS on
// phase/attempt/token prevents two local expiry paths from owning
// the same finalization.
$updated = $claim->update([
'lease_token' => $token,
'lease_until' => $now + self::LEASE_SECONDS,
'updated_at' => $now,
]);
if ($updated !== 1) {
continue;
}
$expired++;
$claimed = CloudJob::find((int) $row->id);
try {
if ($claimed !== null && $claimed->host_id !== null
&& (int) $claimed->dispatch_attempts === 1) {
$event = CloudOperationCompletionService::pendingForJob(
$claimed
);
if ($event !== null) {
(new self())->settleCompletionReceipt(
(int) $claimed->id,
(string) $event->event_id
);
continue;
}
}
if ($claimed !== null
&& (string) $claimed->execution_mode === 'local'
&& (string) $claimed->kind === 'payment_create') {
$payload = CloudSecrets::decrypt(
(string) $claimed->sealed_payload, 'job-payload'
);
[$success, $result, $effect, $safe, $code]
= self::expiredPaymentResult($claimed, $payload);
(new self())->finishPaymentCreate(
$claimed, $success, $result, $effect, $safe, $code
);
continue;
}
if ($claimed !== null && $claimed->host_id === null
&& $claimed->parent_job_id === null
&& (string) $claimed->execution_mode === 'aggregate') {
self::expireAggregate($claimed, $token);
continue;
}
$payload = CloudSecrets::decrypt(
(string) $claimed->sealed_payload, 'job-payload'
);
$operation = !$effect && (string) $claimed->kind === 'create'
? self::createNotDispatchedFailure()
: ['status' => 'failed'];
$operation['operation_id'] = (string) $claimed->operation_id;
$operation['error_code'] = $effect
? 'completion_deadline_exceeded'
: 'dispatch_deadline_exceeded';
$operation['effect_may_have_applied'] = $effect;
$operation['safe_to_resubmit'] = !$effect;
(new self())->finish($claimed, $operation, $payload);
} catch (\Throwable $error) {
self::forceTerminalFailure((int) $row->id, $token,
$effect, !$effect, $effect
? 'completion_deadline_exceeded'
: 'dispatch_deadline_exceeded');
}
}
return $expired;
}
/**
* Derive a local payment task's deadline result from its durable attempt.
* Claiming the worker is not proof that the provider POST was sent.
* This read never creates or retransmits a provider order.
*
* @return array{0:bool,1:?array,2:bool,3:bool,4:string}
*/
private static function expiredPaymentResult(CloudJob $job,
array $payload): array
{
$key = $payload['input']['idempotency_key'] ?? null;
if (!is_string($key)
|| preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $key) !== 1) {
return [false, null, true, false, 'payment_creation_unknown'];
}
$attempt = \App\Models\CloudInvoicePayment::where(
'user_id', (int) $job->user_id
)->where('invoice_id', (int) $job->invoice_id)
->where('idempotency_key', $key)->first();
if ($attempt === null) {
return [false, null, false, true,
'payment_order_not_dispatched'];
}
$status = (string) $attempt->status;
if (in_array($status,
['pending', 'paid_invoice', 'credited_balance'], true)) {
return [true, ['id' => (string) $attempt->id], false, false, ''];
}
if ($status === 'not_created') {
return [false, null, false, true, 'payment_order_rejected'];
}
return [false, null, true, false, 'payment_creation_unknown'];
}
public function settleCompletionReceipt(int $jobId,
string $eventId): CloudJob
{
$event = \App\Models\CloudAgentCompletionEvent::where(
'event_id', $eventId
)->first();
if ($event === null) {
throw new CloudError('完成回执不存在', 404);
}
$source = CloudJob::find($jobId);
if ($source === null) {
throw new CloudError('任务不存在', 404);
}
if ((string) $source->execution_mode !== 'agent'
|| $source->host_id === null
|| (int) $event->host_id !== (int) $source->host_id
|| !hash_equals((string) $source->operation_id,
(string) $event->operation_id)) {
CloudOperationCompletionService::mark($event, 'rejected');
throw new CloudError('完成回执与任务不匹配', 409);
}
if ((string) $source->phase === 'terminal') {
CloudOperationCompletionService::mark($event,
self::completionDisposition($source, $eventId));
return $source;
}
if ((string) $event->disposition !== 'received') {
throw new CloudError('完成回执已经处理', 409);
}
$receiptDeadline = CloudJobService::effectiveReceiptDeadline($source);
if ($receiptDeadline < 1
|| (int) $event->received_at >= $receiptDeadline) {
// The durable receive timestamp, rather than PHP processing time,
// decides the boundary. A receipt persisted before the absolute
// deadline can still settle later; one received after it is audit
// evidence only and can never revive or succeed the generation.
$token = bin2hex(random_bytes(16));
$claim = CloudJob::where('id', $jobId)
->whereIn('phase', ['dispatching', 'awaiting_receipt'])
->where('dispatch_attempts', 1);
if ($source->lease_token === null) {
$claim->whereNull('lease_token');
} else {
$claim->where('lease_token', (string) $source->lease_token);
}
$claimed = $claim->update([
'lease_token' => $token,
'lease_until' => time() + self::LEASE_SECONDS,
'updated_at' => time(),
]);
if ($claimed === 1) {
self::forceTerminalFailure(
$jobId,
$token,
true,
false,
'completion_deadline_exceeded'
);
}
$current = CloudJob::find($jobId) ?? $source;
if ((string) $current->phase === 'terminal') {
CloudOperationCompletionService::mark($event, 'late');
}
return $current;
}
$operation = CloudOperationCompletionService::operation($event);
$payload = CloudSecrets::decrypt((string) $source->sealed_payload,
'job-payload');
$token = bin2hex(random_bytes(16));
$claim = CloudJob::where('id', $jobId)
->whereIn('phase', ['dispatching', 'awaiting_receipt'])
->where('dispatch_attempts', 1);
if ($source->lease_token === null) {
$claim->whereNull('lease_token');
} else {
$claim->where('lease_token', (string) $source->lease_token);
}
$claimed = $claim->update([
'lease_token' => $token,
'lease_until' => time() + self::LEASE_SECONDS,
'completion_event_id' => $eventId,
'updated_at' => time(),
]);
if ($claimed !== 1) {
$current = CloudJob::find($jobId) ?? $source;
if ((string) $current->phase === 'terminal') {
CloudOperationCompletionService::mark($event,
self::completionDisposition($current, $eventId));
}
return $current;
}
$job = CloudJob::find($jobId);
$normalized = self::normalizeAgentOperation(
self::operationForJob($job, $operation)
);
try {
$this->finish($job, $normalized, $payload);
} catch (\Throwable $error) {
$createNotApplied = (string) $job->kind === 'create'
&& strtolower((string) ($normalized['status'] ?? ''))
=== 'failed'
&& self::createFailureConfirmedAbsent($normalized);
$safeToResubmit = $createNotApplied
&& ($normalized['safe_to_resubmit'] ?? false) === true;
self::forceTerminalFailure(
$jobId,
$token,
!$createNotApplied,
$safeToResubmit,
'completion_finalization_failed'
);
}
$current = CloudJob::find($jobId) ?? $source;
if ((string) $current->phase === 'terminal'
&& hash_equals((string) $current->completion_event_id, $eventId)) {
CloudOperationCompletionService::mark($event, 'applied');
} elseif ((string) $current->phase === 'terminal') {
CloudOperationCompletionService::mark($event, 'late');
}
return $current;
}
private static function completionDisposition(CloudJob $job,
string $eventId): string
{
return hash_equals((string) ($job->completion_event_id ?? ''), $eventId)
? 'applied' : 'late';
}
private static function forceTerminalFailure(int $jobId, string $token,
bool $effect, bool $safe, string $code): void
{
$claimed = CloudJob::where('id', $jobId)
->where('lease_token', $token)->where('phase', '<>', 'terminal')
->first();
if ($claimed !== null) {
try {
if ((string) $claimed->execution_mode === 'aggregate') {
if (!self::forceAggregateFailure($claimed, $token)) {
return;
}
} elseif ((string) $claimed->kind === 'payment_create') {
[$success, $result, $paymentEffect, $paymentSafe,
$paymentCode] = self::expiredPaymentResult(
$claimed,
['input' => ['idempotency_key' =>
(string) $claimed->request_idempotency_key]]
);
(new self())->finishPaymentCreate(
$claimed,
$success,
$result,
$paymentEffect,
$paymentSafe,
$paymentCode
);
} else {
$payload = CloudSecrets::decrypt(
(string) $claimed->sealed_payload, 'job-payload'
);
(new self())->finish($claimed, [
'operation_id' => (string) $claimed->operation_id,
'status' => 'failed',
'error_code' => $code,
'effect_may_have_applied' => $effect,
'safe_to_resubmit' => $safe,
], $payload);
}
$terminal = CloudJob::where('id', $jobId)
->where('phase', 'terminal')->exists();
if ($terminal) {
return;
}
} catch (\Throwable $finalizationError) {
error_log(sprintf(
'cloud task ledger finalization failed job_id=%d kind=%s error=%s',
$jobId,
(string) $claimed->kind,
get_class($finalizationError)
));
}
}
if ($claimed !== null
&& (string) $claimed->execution_mode === 'aggregate'
&& self::releaseAggregateParentWhenChildrenActive(
(int) $claimed->id,
$token
)) {
// A child can win the lease CAS between our snapshot and claim.
// Never hide still-active child work behind a terminal parent;
// a later bounded deadline pass will finish children first.
return;
}
// An order-backed create must never fall through to a job-only write:
// its wallet, invoice, stock and placement ledgers are one atomic
// finalization unit. Ambiguous effects retain a durable placement
// fence; proven no-effect failures refund and release exactly once.
if ($claimed !== null && (string) $claimed->kind === 'create'
&& $claimed->order_id !== null) {
try {
CloudCreateFailureFinalizer::forceTerminalFailure(
$jobId,
$token,
$effect,
$safe,
$code
);
if (CloudJob::where('id', $jobId)
->where('phase', 'terminal')->exists()) {
return;
}
} catch (\Throwable $finalizationError) {
error_log(sprintf(
'cloud create ledger finalization incident job_id=%d error=%s',
$jobId,
get_class($finalizationError)
));
}
}
if ($claimed !== null) {
// Best-effort resource latches make the incident visible in the
// affected catalog. Their own failure must never keep the public
// task active; the durable finalization_incident below remains the
// authoritative operator alert.
try {
CloudSnapshotService::markJobUncertain($claimed);
} catch (\Throwable $ignored) {
}
try {
CloudFirewallService::markJobUncertain($claimed);
} catch (\Throwable $ignored) {
}
}
// Last-resort terminalization is deliberately business-conservative:
// never refund, release or claim success after a ledger finalizer
// failed. Redact the encrypted request, retain every resource fence,
// and publish an explicit durable incident for operators.
CloudJob::where('id', $jobId)->where('lease_token', $token)
->where('phase', '<>', 'terminal')->update([
'phase' => 'terminal', 'outcome' => 'failed',
'status' => 'failed', 'terminal_at' => time(),
'effect_may_have_applied' => 1,
'safe_to_resubmit' => 0,
'effect_resolution' => 'unknown',
'error_code' => 'local_finalization_failed',
'finalization_incident' => 1,
'finalization_error_code' => substr($code, 0, 128),
'sealed_payload' => '', 'lease_token' => null,
'lease_until' => 0, 'available_at' => 0,
'updated_at' => time(),
]);
}
/** Close aggregate children first, then atomically converge its catalog. */
private static function forceAggregateFailure(CloudJob $parent,
string $token): bool
{
$children = CloudJob::where('parent_job_id', (int) $parent->id)
->where('phase', '<>', 'terminal')->orderBy('id')->get();
foreach ($children as $child) {
$childToken = bin2hex(random_bytes(16));
$claim = CloudJob::where('id', (int) $child->id)
->where('phase', (string) $child->phase)
->where('dispatch_attempts', (int) $child->dispatch_attempts);
if ($child->lease_token === null) {
$claim->whereNull('lease_token');
} else {
$claim->where('lease_token', (string) $child->lease_token);
}
if ($claim->update([
'lease_token' => $childToken,
'lease_until' => time() + self::LEASE_SECONDS,
'updated_at' => time(),
]) === 1) {
$crossed = (int) $child->dispatch_attempts === 1;
self::forceTerminalFailure(
(int) $child->id,
$childToken,
$crossed,
!$crossed,
'aggregate_finalization_failed'
);
}
}
if (self::releaseAggregateParentWhenChildrenActive(
(int) $parent->id,
$token
)) {
return false;
}
(new CloudJob())->getConnection()->transaction(
static function () use ($parent, $token): void {
$fresh = CloudJob::where('id', (int) $parent->id)
->where('lease_token', $token)
->lockForUpdate()->first();
if ($fresh === null
|| (string) $fresh->phase === 'terminal') {
return;
}
CloudUserIsoService::expireAggregateLocked($fresh);
CloudTemplateCatalogService::expireAggregateLocked($fresh);
$fresh = CloudJob::where('id', (int) $parent->id)
->where('lease_token', $token)->lockForUpdate()->first();
if ($fresh !== null
&& (string) $fresh->phase !== 'terminal') {
CloudJobService::completeAggregateLocked(
$fresh,
'failed',
true,
false,
'aggregate_finalization_failed'
);
}
},
3
);
return true;
}
/** Release the parent lease while any child can still execute. */
private static function releaseAggregateParentWhenChildrenActive(
int $parentId,
string $token
): bool {
if (!CloudJob::where('parent_job_id', $parentId)
->where('phase', '<>', 'terminal')->exists()) {
return false;
}
CloudJob::where('id', $parentId)
->where('lease_token', $token)
->where('phase', '<>', 'terminal')->update([
'lease_token' => null,
'lease_until' => 0,
'updated_at' => time(),
]);
return true;
}
/**
* A parent deadline is an absolute local boundary. Close every remaining
* child without contacting the Agent, let resource finalizers consume
* those failures, then close any aggregate that still has no result.
*/
private static function expireAggregate(CloudJob $parent,
string $token): void
{
$children = CloudJob::where('parent_job_id', (int) $parent->id)
->where('phase', '<>', 'terminal')->orderBy('id')->get();
foreach ($children as $child) {
if ($child->host_id !== null
&& (int) $child->dispatch_attempts === 1) {
$event = CloudOperationCompletionService::pendingForJob(
$child
);
if ($event !== null) {
try {
(new self())->settleCompletionReceipt(
(int) $child->id,
(string) $event->event_id
);
} catch (\Throwable $ignored) {
// A malformed/unapplicable receipt cannot keep the
// public parent active past its absolute deadline.
}
$child = CloudJob::find((int) $child->id) ?? $child;
if ((string) $child->phase === 'terminal') {
continue;
}
}
}
$childToken = bin2hex(random_bytes(16));
$claim = CloudJob::where('id', (int) $child->id)
->where('phase', (string) $child->phase)
->where('dispatch_attempts', (int) $child->dispatch_attempts);
if ($child->lease_token === null) {
$claim->whereNull('lease_token');
} else {
$claim->where('lease_token', (string) $child->lease_token);
}
$claimed = $claim->update([
'lease_token' => $childToken,
'lease_until' => time() + self::LEASE_SECONDS,
'updated_at' => time(),
]);
if ($claimed !== 1) {
continue;
}
$crossed = (int) $child->dispatch_attempts === 1;
self::forceTerminalFailure((int) $child->id, $childToken,
$crossed, !$crossed, 'aggregate_deadline_exceeded');
}
if (CloudJob::where('parent_job_id', (int) $parent->id)
->where('phase', '<>', 'terminal')->exists()) {
// A child changed concurrently after our snapshot. Keep the parent
// active and release this local lease; a later bounded fallback
// pass will close the child first. Never hide active child work
// behind a terminal parent.
CloudJob::where('id', (int) $parent->id)
->where('lease_token', $token)
->where('phase', '<>', 'terminal')->update([
'lease_token' => null,
'lease_until' => 0,
'updated_at' => time(),
]);
return;
}
(new CloudJob())->getConnection()->transaction(
static function () use ($parent, $token): void {
$fresh = CloudJob::where('id', (int) $parent->id)
->where('lease_token', $token)
->lockForUpdate()->first();
if ($fresh === null
|| (string) $fresh->phase === 'terminal') {
return;
}
CloudUserIsoService::expireAggregateLocked($fresh);
CloudTemplateCatalogService::expireAggregateLocked($fresh);
$fresh = CloudJob::where('id', (int) $parent->id)
->where('lease_token', $token)->lockForUpdate()->first();
if ($fresh !== null
&& (string) $fresh->phase !== 'terminal') {
CloudJobService::completeAggregateLocked(
$fresh, 'failed', true, false,
'aggregate_deadline_exceeded'
);
}
}, 3
);
}
private static function policyDesired(?CloudInstance $instance, string $kind): bool
{
if ($instance === null) {
return false;
}
$status = (string) $instance->status;
return match ($kind) {
'service_suspend' => in_array($status, ['active', 'deleting'], true)
&& (string) $instance->service_status === 'purge_stopping',
'network_suspend' => $status === 'active'
&& in_array((string) $instance->network_status,
['blocking', 'blocking_expired'], true),
'network_resume' => $status === 'active'
&& in_array((string) $instance->network_status,
['restore_pending', 'restoring'], true),
default => false,
};
}
private static function operationErrorCode(array $operation): string
{
$code = is_string($operation['error_code'] ?? null)
? strtolower(trim($operation['error_code'])) : '';
if ($code === '' && is_array($operation['error'] ?? null)
&& is_string($operation['error']['code'] ?? null)) {
$code = strtolower(trim($operation['error']['code']));
}
return preg_match('/^[a-z][a-z0-9_]{0,63}$/D', $code) === 1
? $code : '';
}
private function finish(CloudJob $claimed, array $operation, array $payload): void
{
$operation['operation_id'] = $operation['operation_id']
?? (string) $claimed->operation_id;
$status = self::disposition($operation, $claimed->kind === 'create',
(string) $claimed->kind);
if (!in_array($status, ['succeeded', 'failed'], true)) {
throw new CloudError('任务尚未取得终态回执', 409);
}
if ($status === 'succeeded'
&& in_array((string) $claimed->kind,
['delete', 'expiry_delete', 'delete_force'], true)
&& !self::deleteSuccessConfirmed($operation,
(string) $claimed->kind)) {
throw new CloudError('Agent 删除回执缺少资源已清理证据', 502);
}
if ((string) $claimed->kind === 'reinstall'
&& self::reinstallNeedsReview($operation)) {
throw new CloudError('Agent 重装回执未确认清理完成', 502);
}
if ($status === 'failed') {
$this->observedErrors[] = 'task_failed';
}
$forceRequired = $status === 'failed'
&& in_array((string) $claimed->kind,
['delete', 'expiry_delete', 'service_suspend'], true)
&& self::operationErrorCode($operation) === 'force_required';
$effectMayHaveApplied = $status === 'failed'
&& ($operation['effect_may_have_applied'] ?? false) === true;
$safeToResubmit = $status === 'failed'
&& ($operation['safe_to_resubmit'] ?? false) === true;
if ($forceRequired) {
$effectMayHaveApplied = false;
$safeToResubmit = false;
}
if ($effectMayHaveApplied) {
$safeToResubmit = false;
}
if ($status === 'failed' && (string) $claimed->kind === 'create') {
if (self::createFailureConfirmedAbsent($operation)) {
// Exact absence evidence is the authority for financial and
// placement rollback. safe_to_resubmit is informational only;
// this generation is never dispatched again.
$effectMayHaveApplied = false;
} else {
// Boolean transport hints alone cannot release a paid order.
// Keep every resource fenced until a fresh read-only host
// inspection proves both the guest and artifacts are absent.
$effectMayHaveApplied = true;
$safeToResubmit = false;
}
}
// Downstream error classification must use the validated PHP safety
// decision, never the Agent's original booleans. In particular an
// ambiguous create must not be labelled as refunded.
$operation['effect_may_have_applied'] = $effectMayHaveApplied;
$operation['safe_to_resubmit'] = $safeToResubmit;
$resourceStatus = $status === 'failed' && $effectMayHaveApplied
? 'uncertain' : $status;
$result = $operation['result'] ?? null;
(new CloudJob())->getConnection()->transaction(function () use ($claimed, $payload, $status, $resourceStatus, $effectMayHaveApplied, $safeToResubmit, $forceRequired, $result, $operation) {
// All financial transactions acquire the wallet first, avoiding wallet/order deadlocks.
$user = User::where('id', $claimed->user_id)->lockForUpdate()->first();
$order = $claimed->order_id === null ? null : CloudOrder::where('id', $claimed->order_id)->lockForUpdate()->first();
$job = CloudJob::where('id', $claimed->id)->lockForUpdate()->first();
if ($job === null || $job->lease_token !== $claimed->lease_token
|| (string) $job->phase === 'terminal') {
return;
}
$safe = is_array($result)
? CloudOperationErrorCatalog::workerResult($result) : null;
$causeCode = CloudOperationErrorCatalog::agentCauseCode(
$operation['cause_code'] ?? null
);
if ($causeCode !== null) {
$durableResult = is_array($result) && !array_is_list($result)
? $result : [];
// Keep the stable cause beside the sanitized operation
// evidence. It is never copied into the public error_code or
// ordinary user DTOs.
$durableResult['cause_code'] = $causeCode;
$safe = CloudOperationErrorCatalog::workerResult($durableResult);
}
$catalogStatus = $resourceStatus;
// Catalog/configuration mutations use the public terminal status,
// never the legacy resource-level "uncertain" label. Their
// replica rows and aggregate parent are settled in this same
// transaction as the child job.
CloudTemplateCatalogService::finishJobLocked(
$job, $status, $result, $payload, $operation
);
CloudUserIsoService::finishJobLocked(
$job, $status, $result, $payload, $operation
);
CloudRescueTemplateImportService::finishJobLocked(
$job, $status, $result, $operation
);
CloudRescueTemplateDeletionService::finishJobLocked(
$job, $status, $result, $operation
);
CloudHostStorageConfigurationService::finishJobLocked(
$job, $status, $result, $operation
);
CloudSnapshotService::finishJobLocked(
$job, $catalogStatus, $result, $payload
);
CloudSnapshotService::finishInstanceDeleteLocked(
$job, $catalogStatus
);
CloudFirewallService::finishJobLocked(
$job, $catalogStatus, $result, $payload, $operation
);
CloudFirewallService::finishInstanceDeleteLocked(
$job, $catalogStatus
);
if ($job->kind === 'network_change'
&& in_array($catalogStatus,
['succeeded', 'failed', 'uncertain'], true)) {
$instance = $job->instance_id === null ? null
: CloudInstance::where('id', $job->instance_id)
->lockForUpdate()->first();
$sourceIpId = filter_var($payload['source_public_ip_id'] ?? null,
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
$targetIpId = filter_var($payload['target_public_ip_id'] ?? null,
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
$networkAttachmentId = filter_var(
$payload['network_attachment_id'] ?? null,
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]
);
$sourcePoolId = filter_var(
$payload['source_public_ip_pool_id'] ?? null,
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]
);
$targetPoolId = filter_var(
$payload['target_public_ip_pool_id'] ?? null,
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]
);
if ($instance === null || $sourceIpId === false
|| $targetIpId === false || $networkAttachmentId === false
|| $sourcePoolId === false || $targetPoolId === false) {
throw new CloudError('公网 IP 变更任务缺少账本关联', 409);
}
if ($catalogStatus === 'succeeded') {
$requested = is_array($payload['body'] ?? null)
? ($payload['body']['public_ip_cidr'] ?? null) : null;
$requestedPoolKey = is_array($payload['body'] ?? null)
? ($payload['body']['public_pool_key'] ?? null) : null;
$confirmed = is_array($result)
? ($result['public_ip_cidr'] ?? null) : null;
$confirmedPoolKey = is_array($result)
? ($result['public_pool_key'] ?? null) : null;
if (!is_string($requested) || !is_string($confirmed)
|| !is_string($requestedPoolKey)
|| !is_string($confirmedPoolKey)
|| $requested !== $confirmed
|| !hash_equals($requestedPoolKey, $confirmedPoolKey)) {
throw new CloudError(
'Agent 成功结果缺少已确认的公网 IP 或地址池', 502
);
}
$decoded = json_decode((string) $instance->spec_json, true);
if (!is_array($decoded) || array_is_list($decoded)) {
throw new CloudError('虚拟机配置记录损坏,无法保存新的公网 IP', 409);
}
CloudPlacementService::finishNetworkChange($instance,
(string) $job->operation_id, (int) $sourceIpId,
(int) $targetIpId, (int) $networkAttachmentId,
(int) $sourcePoolId, (int) $targetPoolId, 'succeeded');
$decoded['public_ip_cidr'] = $confirmed;
$instance->spec_json = json_encode($decoded,
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
| JSON_UNESCAPED_UNICODE);
self::recordRuntime($instance, is_array($result) ? $result : [],
(string) $job->kind, $payload);
$instance->updated_at = time();
$instance->save();
} else {
CloudPlacementService::finishNetworkChange($instance,
(string) $job->operation_id, (int) $sourceIpId,
(int) $targetIpId, (int) $networkAttachmentId,
(int) $sourcePoolId, (int) $targetPoolId,
$catalogStatus);
}
} elseif ($status === 'succeeded' && $job->kind === 'create') {
$vm = is_array($result) ? ($result['vm'] ?? $result) : [];
$uuid = $vm['uuid'] ?? '';
if ($order === null || !is_string($uuid)
|| preg_match('/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iD', $uuid) !== 1) {
throw new CloudError('Agent 成功结果缺少虚拟机标识', 502);
}
$requestedPublicIpCidr = is_array($payload['body'] ?? null)
? ($payload['body']['public_ip_cidr'] ?? null) : null;
$requestedPublicPoolKey = is_array($payload['body'] ?? null)
? ($payload['body']['public_pool_key'] ?? null) : null;
$confirmedPublicIpCidr = $vm['public_ip_cidr'] ?? null;
$confirmedPublicPoolKey = $vm['public_pool_key'] ?? null;
if (!is_string($requestedPublicIpCidr)
|| !is_string($confirmedPublicIpCidr)
|| !hash_equals($requestedPublicIpCidr,
$confirmedPublicIpCidr)
|| !is_string($requestedPublicPoolKey)
|| !is_string($confirmedPublicPoolKey)
|| preg_match('/^[a-f0-9]{32}$/D',
$requestedPublicPoolKey) !== 1
|| !hash_equals($requestedPublicPoolKey,
$confirmedPublicPoolKey)) {
// A completion result may describe a VM whose network was
// changed out of band after dispatch. Never commit the
// original address in that case. Finalization converts the
// task to a terminal failure and retains the resource lock.
throw new CloudError(
'Agent 成功结果与预留公网 IP 不一致,必须人工核查', 502
);
}
$instance = CloudInstance::where('order_id', $order->id)->first();
$newInstance = $instance === null;
$instance ??= new CloudInstance();
$instance->uuid = $uuid;
$instance->host_id = $order->host_id;
$instance->user_id = $order->user_id;
$instance->order_id = $order->id;
$instance->offer_id = $order->offer_id;
$instance->resource_pool_id = $order->resource_pool_id;
$instance->reservation_id = $order->reservation_id;
$spec = json_decode((string) $order->spec_json, true) ?: [];
$templateMetadata = self::trustedTemplateMetadata($payload);
$spec = array_replace($spec, $templateMetadata);
$now = time();
$days = filter_var($spec['validity_days'] ?? null,
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
$traffic = filter_var($spec['traffic_quota_bytes'] ?? null,
FILTER_VALIDATE_INT, ['options' => ['min_range' => 0]]);
if ($days === false || $traffic === false) {
throw new CloudError('订单缺少不可变的计费周期快照', 409);
}
$instance->plan_id = $order->plan_id;
// A duplicate completion result must not overwrite a display
// name the owner changed after the first success committed.
if ($newInstance) {
$instance->name = $payload['body']['name'];
}
$instance->status = 'active';
$instance->service_status = 'active';
$instance->network_status = 'active';
$instance->expires_at = $now + $days * 86400;
$instance->renewal_price = $order->amount;
$instance->renewal_days = $days;
$instance->renewal_traffic_bytes = $traffic;
$instance->traffic_quota_bytes = $traffic;
$instance->traffic_download_bytes = 0;
$instance->traffic_upload_bytes = 0;
$instance->lifetime_download_bytes = 0;
$instance->lifetime_upload_bytes = 0;
$instance->traffic_synced_at = 0;
// Persist only the Agent's slow-changing public metadata.
// SSR pages can then render IP, operating system, login name
// and actual capacity without issuing a host read
// on every request. Billing/order fields remain authoritative
// because the allowlist cannot overwrite them.
$instanceSpec = CloudInstanceMetadata::merge($spec, $vm);
if ($templateMetadata !== null) {
// Agent observations cannot replace PHP's catalog
// snapshot, even if an older Agent happens to return
// similarly named fields.
$instanceSpec = array_replace(
$instanceSpec,
$templateMetadata
);
unset($instanceSpec['install_iso']);
}
// A VM is panel-managed only after the Agent's exact create
// operation has returned the validated success above.
$instanceSpec['managed'] = true;
$instance->spec_json = json_encode(
$instanceSpec,
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
| JSON_UNESCAPED_UNICODE
);
$instance->sealed_credential = isset($payload['credential'])
? CloudSecrets::encrypt(
$payload['credential'], 'instance-credential'
) : null;
// The paid service begins when provisioning actually succeeds,
// not while an opening invoice is waiting for payment. A
// duplicate success must retain the original value.
if (!$instance->exists) {
$instance->created_at = $now;
}
$instance->updated_at = time();
$instance->save();
CloudPlacementService::commit(
$order, (int) $instance->id, $confirmedPublicIpCidr
);
// Seed the independent runtime observation immediately after
// provisioning. If the Agent returned a trusted power
// state, promote it now; otherwise the background host batch
// will provide the first observation without showing "未知".
self::recordRuntime($instance, $vm, 'create', []);
$period = CloudServicePeriod::where('order_id', $order->id)->first()
?? new CloudServicePeriod();
$period->instance_id = $instance->id;
$period->user_id = $order->user_id;
$period->plan_id = $order->plan_id;
$period->order_id = $order->id;
$period->starts_at = $now;
$period->ends_at = $instance->expires_at;
$period->traffic_quota_bytes = $traffic;
$period->download_base_bytes = 0;
$period->upload_base_bytes = 0;
$period->download_used_bytes = 0;
$period->upload_used_bytes = 0;
$period->status = 'active';
$period->activated_at = $now;
$period->created_at = $period->created_at ?: $now;
$period->updated_at = $now;
$period->save();
$instance->current_period_id = $period->id;
$instance->save();
$job->instance_id = $order->instance_id = $instance->id;
$provisionInvoice = CloudInvoice::where('order_id', $order->id)
->lockForUpdate()->first();
if ($provisionInvoice !== null
&& (string) $provisionInvoice->purpose === 'provision') {
$provisionInvoice->instance_id = $instance->id;
$provisionInvoice->updated_at = time();
$provisionInvoice->save();
CloudInvoiceService::queueProvisionSucceeded(
$provisionInvoice, $now
);
}
$safe = $safe ?? [];
$safe['id'] = (string) $instance->id;
$safe['uuid'] = $uuid;
} elseif ($job->kind === 'reinstall'
&& $job->instance_id !== null
&& $status === 'succeeded') {
$instance = CloudInstance::where('id', $job->instance_id)
->lockForUpdate()->first();
if ($instance !== null) {
if (isset($payload['credential'])
&& is_array($payload['credential'])) {
$instance->sealed_credential = CloudSecrets::encrypt(
$payload['credential'], 'instance-credential'
);
}
// Once the Agent proves the replacement guest committed,
// its credential and template snapshot supersede the old
// guest even if deletion of the old volume still requires
// operator review. The task still ends as failed.
$decoded = json_decode((string) $instance->spec_json, true);
if (is_array($decoded) && !array_is_list($decoded)) {
$templateMetadata =
self::trustedTemplateMetadata($payload);
$templateId = is_array($payload['body'] ?? null)
? ($payload['body']['template_id'] ?? null) : null;
if (is_string($templateId)
&& preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/D',
$templateId) === 1) {
$decoded['template_id'] = $templateId;
}
$decoded = array_replace(
$decoded,
$templateMetadata
);
unset($decoded['install_iso']);
$decoded['managed'] = true;
// Force one fresh capacity/IP observation while the
// trusted PHP presentation snapshot remains usable.
unset($decoded['agent_metadata_version']);
$instance->spec_json = json_encode($decoded,
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
| JSON_UNESCAPED_UNICODE);
}
self::recordRuntime($instance,
is_array($result) ? $result : [],
(string) $job->kind, $payload);
$instance->updated_at = time();
$instance->save();
}
} elseif ($status === 'failed' && !$effectMayHaveApplied
&& $job->kind === 'create' && $order !== null) {
if ($user === null) {
throw new CloudError('退款账户不存在', 409);
}
CloudCreateFailureFinalizer::refundAndReleaseLocked(
$job,
$user,
$order,
'create_failed'
);
} elseif ($forceRequired && $job->instance_id !== null) {
$instance = CloudInstance::where('id', $job->instance_id)
->lockForUpdate()->first();
if ($instance !== null
&& (string) $instance->status === 'deleting') {
$instance->service_status = 'purge_force_required';
$instance->updated_at = time();
$instance->save();
}
} elseif ($status === 'failed' && $job->kind === 'expiry_delete'
&& $job->instance_id !== null) {
$instance = CloudInstance::where('id', $job->instance_id)
->lockForUpdate()->first();
if ($instance !== null && (string) $instance->status !== 'deleted') {
$instance->status = 'delete_failed';
$instance->service_status = 'purge_failed';
$instance->updated_at = time();
$instance->save();
}
} elseif ($status === 'failed' && $job->instance_id !== null
&& in_array($job->kind,
['service_suspend', 'network_suspend', 'network_resume'], true)) {
// Latch a visible policy failure. This generation is never
// queued again automatically.
$instance = CloudInstance::where('id', $job->instance_id)->lockForUpdate()->first();
if ($instance !== null) {
$expected = [
'service_suspend' => ['suspending_expired', 'purge_stopping'],
'network_suspend' => ['blocking', 'blocking_expired'],
'network_resume' => ['restore_pending', 'restoring'],
][$job->kind];
if ($job->kind === 'service_suspend'
&& in_array((string) $instance->service_status, $expected, true)) {
if ((string) $instance->status === 'deleting'
&& (string) $instance->service_status === 'purge_stopping') {
// Preserve the irreversible deletion latch, but do
// not enqueue this failed generation again.
$instance->service_status = 'purge_stop_failed';
} else {
$instance->service_status = 'suspend_failed';
}
} elseif ($job->kind === 'network_suspend'
&& in_array((string) $instance->network_status, $expected, true)) {
$instance->network_status = 'block_failed';
} elseif ($job->kind === 'network_resume'
&& in_array((string) $instance->network_status, $expected, true)) {
$instance->network_status = 'restore_failed';
}
$instance->updated_at = time();
$instance->save();
}
} elseif ($status === 'succeeded' && $job->instance_id !== null) {
$instance = CloudInstance::where('id', $job->instance_id)->lockForUpdate()->first();
if ($instance !== null) {
if (in_array((string) $job->kind,
['delete', 'expiry_delete', 'delete_force'], true)) {
$instance->status = 'deleted';
$instance->sealed_credential = null;
if ($instance->order_id !== null) {
$provisionOrder = CloudOrder::where('id', $instance->order_id)
->lockForUpdate()->first();
if ($provisionOrder !== null) {
CloudPlacementService::release(
$provisionOrder, 'instance_deleted', true
);
}
}
} elseif ($job->kind === 'instance_settings') {
// The Agent must acknowledge the controlled seed
// replacement before PHP changes any cached metadata.
// Passwords and public keys are intentionally never
// copied into spec_json or result_json.
if (!is_array($result) || ($result['settings_changed'] ?? false) !== true) {
throw new CloudError('Agent 成功结果缺少已确认的实例设置', 502);
}
if (isset($payload['credential'])
&& is_array($payload['credential'])) {
$instance->sealed_credential = CloudSecrets::encrypt(
$payload['credential'], 'instance-credential'
);
}
$requested = is_array($payload['body'] ?? null)
? $payload['body'] : [];
$decoded = json_decode((string) $instance->spec_json, true);
if (!is_array($decoded) || array_is_list($decoded)) {
throw new CloudError('虚拟机配置记录损坏,无法保存实例设置', 409);
}
if (array_key_exists('hostname', $requested)) {
$confirmed = $result['hostname'] ?? null;
if (!is_string($confirmed)
|| $confirmed !== $requested['hostname']
|| preg_match('/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/D', $confirmed) !== 1
|| strlen($confirmed) > 253) {
throw new CloudError('Agent 成功结果缺少已确认的主机名', 502);
}
$decoded['guest_hostname'] = $confirmed;
}
$instance->spec_json = json_encode($decoded,
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
| JSON_UNESCAPED_UNICODE);
} elseif ($job->kind === 'service_suspend'
&& in_array((string) $instance->service_status,
['purge_stopping', 'purge_force_required'], true)) {
if ((string) $instance->status === 'deleting'
&& in_array((string) $instance->service_status,
['purge_stopping', 'purge_force_required'], true)) {
// Only the Agent's active terminal receipt can
// advance expiry cleanup; read-only inspection
// never settles or reopens a timed-out task.
$instance->service_status = 'purge_deleting';
}
} elseif ($job->kind === 'network_suspend'
&& in_array((string) $instance->network_status,
['blocking', 'blocking_expired'], true)) {
$instance->network_status = ($payload['suspend_reason'] ?? '') === 'expired'
? 'blocked_expired' : 'blocked_traffic';
$instance->network_suspended_at = time();
} elseif ($job->kind === 'network_resume'
&& in_array((string) $instance->network_status, ['restoring', 'restore_pending'], true)) {
$instance->network_status = 'active';
$instance->network_suspended_at = null;
}
// Successful power/reinstall/policy operations often
// include the resulting VM state. Persist that bounded
// observation so the next page render is immediate;
// missing state is deliberately left for vm-states.
self::recordRuntime($instance, is_array($result) ? $result : [],
(string) $job->kind, $payload);
$instance->updated_at = time();
$instance->save();
}
}
$job->status = $status;
$job->phase = 'terminal';
$job->outcome = $status;
$job->terminal_at = time();
$job->effect_may_have_applied = $effectMayHaveApplied ? 1 : 0;
$job->safe_to_resubmit = $safeToResubmit ? 1 : 0;
$job->effect_resolution = $status === 'succeeded' ? 'applied'
: ($effectMayHaveApplied ? 'unknown' : 'not_applied');
if (in_array($status, ['succeeded', 'failed'], true)) {
// Terminal jobs never need credentials again. Preserve only
// a sanitized audit payload so the terminal row cannot remain
// a second recoverable copy of the root password.
$job->sealed_payload = CloudSecrets::encrypt(
CloudInput::safeResult($payload), 'job-payload'
);
}
$job->result_json = $safe === null ? null : json_encode($safe, JSON_THROW_ON_ERROR);
$job->error_code = CloudOperationErrorCatalog::workerSummary(
(string) $job->kind, $status, $operation, $order !== null,
self::payloadAction($payload)
);
$job->lease_token = null;
$job->lease_until = 0;
$job->available_at = 0;
$job->updated_at = time();
$job->save();
if ($order !== null) {
if ($job->kind === 'create' && $effectMayHaveApplied) {
CloudPlacementService::markUncertain($order);
}
$order->status = $status;
$order->updated_at = time();
$order->save();
}
}, 3);
}
private static function validSystemCleanup(CloudJob $job, array $payload): bool
{
if ($job->instance_id === null
|| ($payload['body'] ?? null) !== ['remove_managed_disks' => true]) {
return false;
}
$instance = CloudInstance::find($job->instance_id);
if ($instance === null || (string) $instance->status !== 'deleting'
|| (string) $instance->service_status !== 'purge_deleting'
|| (int) $job->user_id !== (int) $instance->user_id
|| (int) $job->host_id !== (int) $instance->host_id
|| (int) ($payload['owner_id'] ?? 0) !== (int) $instance->user_id) {
return false;
}
return ($payload['method'] ?? null) === 'DELETE'
&& ($payload['request_target'] ?? null) === '/v1/vms/'
. rawurlencode((string) $instance->uuid);
}
private static function validSystemPolicy(CloudJob $job, array $payload): bool
{
if ($job->instance_id === null || !is_array($payload['body'] ?? null)) {
return false;
}
$instance = CloudInstance::find($job->instance_id);
if ($instance === null || (int) $job->user_id !== (int) $instance->user_id
|| (int) $job->host_id !== (int) $instance->host_id
|| (int) ($payload['owner_id'] ?? 0) !== (int) $instance->user_id) {
return false;
}
$suffix = [
'service_suspend' => 'service/suspend',
'network_suspend' => 'network/suspend',
'network_resume' => 'network/resume',
][$job->kind] ?? null;
$expectedBody = match ((string) $job->kind) {
'service_suspend' => ['reason' => 'purge'],
'network_suspend' => ['reason' => (string) (
$payload['suspend_reason'] ?? ''
)],
'network_resume' => [],
default => null,
};
return $suffix !== null && $expectedBody !== null
&& ($payload['method'] ?? null) === 'POST'
&& ($payload['body'] ?? null) === $expectedBody
&& ($payload['request_target'] ?? null) === '/v1/vms/'
. rawurlencode((string) $instance->uuid) . '/' . $suffix;
}
private static function payloadAction(array $payload): ?string
{
$body = $payload['body'] ?? null;
$action = is_array($body) && is_string($body['action'] ?? null)
? $body['action'] : null;
return CloudOperationCatalog::isPowerAction($action ?? '') ? $action : null;
}
/**
* Validate the mandatory PHP-owned template snapshot without forwarding
* it to the Agent. This is a clean-break schema: create/reinstall work
* without the snapshot is invalid and finalizes as a local failure.
*/
private static function trustedTemplateMetadata(array $payload): array
{
if (!array_key_exists('template_metadata', $payload)) {
throw new CloudError(
'任务缺少云镜像展示快照,必须终止并人工核查', 409
);
}
$metadata = $payload['template_metadata'];
$body = $payload['body'] ?? null;
if (!is_array($metadata) || array_is_list($metadata)
|| !is_array($body) || array_is_list($body)
|| !is_string($metadata['template_id'] ?? null)
|| !is_string($body['template_id'] ?? null)
|| preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/D',
$metadata['template_id']) !== 1
|| !hash_equals($body['template_id'],
$metadata['template_id'])) {
throw new CloudError(
'任务中的云镜像展示快照与 Agent 请求不匹配,必须人工核查',
409
);
}
$public = CloudInstanceMetadata::publicSpec($metadata);
if (($public['os_source'] ?? null) !== 'cloud_template'
|| !is_string($public['os_name'] ?? null)
|| ($public['login_name'] ?? null) !== 'root') {
throw new CloudError('任务中的云镜像展示快照无效,必须人工核查',
409);
}
return [
'template_id' => $metadata['template_id'],
'os_source' => 'cloud_template',
'os_name' => $public['os_name'],
'login_name' => 'root',
];
}
/**
* Translate panel vocabulary only at the Agent wire boundary. The PHP job
* keeps "poweroff" so its audit label and user-facing history remain
* stable, while the Go protocol uses libvirt's explicit "destroy" action.
*/
private static function agentRequestBody(string $kind, array $body): array
{
if ($kind === 'action' && ($body['action'] ?? null) === 'poweroff') {
$body['action'] = 'destroy';
}
return $body;
}
/**
* Bind every journal-backed Agent response to the claimed PHP job before
* its status or result can influence durable panel state. Missing IDs and
* cross-operation responses are ambiguous, never legacy success shortcuts.
*/
private static function operationForJob(CloudJob $job,
array $operation): array
{
$expected = (string) $job->operation_id;
$actual = $operation['operation_id'] ?? null;
if (!is_string($actual) || $expected === ''
|| !hash_equals($expected, $actual)) {
throw new CloudError(
'Agent 操作标识与当前任务不匹配,必须人工核查',
502
);
}
return $operation;
}
private static function normalizeAgentOperation(array $operation): array
{
$causeCode = CloudOperationErrorCatalog::agentCauseCode(
$operation['cause_code'] ?? null
);
if ($causeCode === null) {
unset($operation['cause_code']);
} else {
$operation['cause_code'] = $causeCode;
}
$error = $operation['error'] ?? null;
if (is_array($error) && is_string($error['code'] ?? null)
&& preg_match('/^[a-z][a-z0-9_]{0,63}$/D', $error['code']) === 1) {
$operation['error_code'] = $error['code'];
}
// Never persist or expose free-form Agent error messages. The local
// catalog maps the bounded code and operation kind to reviewed text.
if (is_array($error)) {
unset($operation['error']);
}
return $operation;
}
/**
* Persist only a successful, allow-listed power observation. Runtime
* cache failures are isolated from the durable job outcome: the Agent
* result and billing state remain authoritative even during a rolling
* schema upgrade where the cache table may not exist yet.
*/
private static function recordRuntime(CloudInstance $instance, array $result,
string $kind, array $payload): void
{
try {
if (in_array($kind,
['delete', 'expiry_delete', 'delete_force'], true)) {
CloudInstanceRuntimeService::forget((int) $instance->id);
return;
}
$source = is_array($result['vm'] ?? null) ? $result['vm'] : $result;
$state = $source['status']
?? ($source['state'] ?? ($source['power_state'] ?? null));
$action = $kind === 'action' ? self::payloadAction($payload) : null;
$normalized = CloudInstanceRuntimeService::normalizeState($state);
if ($kind === 'action') {
// A successful graceful-shutdown job only confirms that the
// request was accepted. libvirt may still report running (or
// omit the state) until the guest completes ACPI shutdown.
// Preserve that distinction instead of publishing either a
// new fresh-running observation or a fabricated stopped one.
$state = CloudInstanceRuntimeService::stateAfterSuccessfulAction(
$state, $action
);
}
$instanceId = (int) $instance->id;
$hostId = (int) $instance->host_id;
$uuid = (string) $instance->uuid;
if ($kind === 'create') {
CloudInstanceRuntimeService::seed($instanceId, $hostId, $uuid);
}
if (CloudInstanceRuntimeService::normalizeState($state) !== 'unknown') {
CloudInstanceRuntimeService::markObserved(
$instanceId, $hostId, $uuid, $state
);
}
} catch (\Throwable $error) {
error_log('cloud runtime observation write unavailable: ' . get_class($error));
}
}
private static function exceptionDiagnostic(\Throwable $error, bool $dispatched,
?string $kind, bool $hasOrder, ?string $action): string
{
$operation = [];
if ($error instanceof CloudError) {
// CloudError text is Agent-/host-controlled too. The catalog
// keeps only exact reviewed details and otherwise returns a
// stable generic code for the durable job row.
$operation['error'] = $error->getMessage();
} elseif ($error instanceof \GuzzleHttp\Exception\TransferException) {
$operation['error'] = 'Agent 连接中断或操作超时';
}
$status = 'failed';
return CloudOperationErrorCatalog::workerSummary($kind, $status,
$operation, $hasOrder, $action)
?? CloudOperationErrorCatalog::userMessage($kind, $status, null,
$hasOrder, $action)
?? '虚拟机操作失败,请稍后重试';
}
}