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

195 lines
8.8 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudAgentCompletionEvent;
use App\Models\CloudJob;
/** Applies immutable Agent receipts without ever re-dispatching a mutation. */
final class CloudOperationCompletionService
{
public static function accept(array $input): array
{
$receipt = self::validate($input);
$hash = hash('sha256', json_encode($receipt,
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
| JSON_UNESCAPED_UNICODE));
$event = (new CloudAgentCompletionEvent())->getConnection()
->transaction(function () use ($receipt, $hash) {
// Serialize durable receipt publication with the deadline
// finalizer. If expiry owns the job row first, this receipt is
// necessarily late; if receipt ingestion owns it first, expiry
// cannot pass the event before the event commit becomes
// visible. This makes received_at a real durable boundary.
CloudJob::where('host_id', $receipt['host_id'])
->where('execution_mode', 'agent')
->where('operation_id', $receipt['operation_id'])
->lockForUpdate()->first();
$existing = CloudAgentCompletionEvent::where(
'event_id', $receipt['event_id']
)->lockForUpdate()->first();
if ($existing === null) {
$existing = CloudAgentCompletionEvent::where(
'host_id', $receipt['host_id']
)->where('operation_id', $receipt['operation_id'])
->lockForUpdate()->first();
}
if ($existing !== null) {
if (!hash_equals((string) $existing->payload_sha256,
$hash)) {
throw new CloudError(
'同一完成回执标识不能承载不同结果', 409
);
}
return $existing;
}
$event = new CloudAgentCompletionEvent();
$event->event_id = $receipt['event_id'];
$event->host_id = $receipt['host_id'];
$event->operation_id = $receipt['operation_id'];
$event->payload_sha256 = $hash;
$event->outcome = $receipt['status'];
$event->effect_may_have_applied =
$receipt['effect_may_have_applied'] ? 1 : 0;
$event->safe_to_resubmit = $receipt['safe_to_resubmit'] ? 1 : 0;
$event->error_code = $receipt['error_code'];
$event->result_json = $receipt['result'] === null ? null
: json_encode($receipt['result'], JSON_THROW_ON_ERROR
| JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$event->disposition = 'received';
$event->received_at = time();
$event->applied_at = null;
$event->save();
return $event;
}, 3);
$job = CloudJob::where('host_id', $receipt['host_id'])
->where('execution_mode', 'agent')
->where('operation_id', $receipt['operation_id'])->first();
if ($job === null) {
self::mark($event, 'rejected');
$event = self::reload($event);
return ['accepted' => true,
'disposition' => (string) $event->disposition];
}
if ((string) $job->phase === 'terminal') {
// finish() stores completion_event_id before mark(applied). If PHP
// crashed in that narrow window, an identical retransmission must
// repair the event disposition instead of misclassifying the
// receipt that actually settled the task as late.
self::mark($event,
hash_equals((string) ($job->completion_event_id ?? ''),
(string) $event->event_id)
? 'applied' : 'late');
$event = self::reload($event);
return ['accepted' => true,
'disposition' => (string) $event->disposition];
}
if ((int) $job->dispatch_attempts !== 1
|| !in_array((string) $job->phase,
['dispatching', 'awaiting_receipt'], true)) {
self::mark($event, 'rejected');
return ['accepted' => true, 'disposition' => 'rejected'];
}
if (in_array((string) $job->phase,
['dispatching', 'awaiting_receipt'], true)) {
(new CloudWorkerService())->settleCompletionReceipt(
(int) $job->id,
(string) $event->event_id
);
$event = self::reload($event);
}
return ['accepted' => true,
'disposition' => (string) $event->disposition];
}
public static function pendingForJob(CloudJob $job): ?CloudAgentCompletionEvent
{
return CloudAgentCompletionEvent::where('host_id', (int) $job->host_id)
->where('operation_id', (string) $job->operation_id)
->where('disposition', 'received')->first();
}
public static function operation(CloudAgentCompletionEvent $event): array
{
return [
'operation_id' => (string) $event->operation_id,
'status' => (string) $event->outcome,
'effect_may_have_applied' => (bool) $event->effect_may_have_applied,
'safe_to_resubmit' => (bool) $event->safe_to_resubmit,
'error_code' => (string) $event->error_code,
'result' => $event->result_json === null ? null
: json_decode((string) $event->result_json, true,
64, JSON_THROW_ON_ERROR),
];
}
public static function mark(CloudAgentCompletionEvent $event,
string $disposition): void
{
CloudAgentCompletionEvent::where('event_id', (string) $event->event_id)
->where('disposition', 'received')->update([
'disposition' => $disposition,
'applied_at' => $disposition === 'applied' ? time() : null,
]);
}
private static function reload(
CloudAgentCompletionEvent $event
): CloudAgentCompletionEvent {
return CloudAgentCompletionEvent::where(
'event_id', (string) $event->event_id
)->first() ?? $event;
}
private static function validate(array $input): array
{
$allowed = ['type', 'id', 'agent_id', 'operation_id', 'status',
'effect_may_have_applied', 'safe_to_resubmit', 'error_code',
'result'];
if (array_is_list($input)
|| array_diff(array_keys($input), $allowed) !== []
|| ($input['type'] ?? null) !== 'completion'
|| !is_string($input['id'] ?? null)
|| preg_match('/^[A-Za-z0-9_-]{16,80}$/D', $input['id']) !== 1
|| (!is_int($input['agent_id'] ?? null)
&& (!is_string($input['agent_id'] ?? null)
|| preg_match('/^[1-9][0-9]{0,18}$/D',
$input['agent_id']) !== 1))
|| (int) $input['agent_id'] < 1
|| !is_string($input['operation_id'] ?? null)
|| preg_match('/^[a-f0-9]{32}$/D', $input['operation_id']) !== 1
|| !in_array($input['status'] ?? null,
['succeeded', 'failed'], true)
|| !is_bool($input['effect_may_have_applied'] ?? null)
|| !is_bool($input['safe_to_resubmit'] ?? null)
|| !is_string($input['error_code'] ?? null)
|| (($input['error_code'] ?? '') !== ''
&& preg_match('/^[a-z][a-z0-9_]{0,63}$/D',
$input['error_code']) !== 1)
|| !array_key_exists('result', $input)
|| ($input['result'] !== null && !is_array($input['result']))
|| (($input['status'] ?? null) === 'succeeded'
&& (($input['effect_may_have_applied'] ?? null) !== false
|| ($input['safe_to_resubmit'] ?? null) !== false
|| ($input['error_code'] ?? null) !== ''))
|| (($input['status'] ?? null) === 'failed'
&& (($input['error_code'] ?? '') === ''
|| (($input['effect_may_have_applied'] ?? false) === true
&& ($input['safe_to_resubmit'] ?? false) === true)))) {
throw new CloudError('Agent 完成回执无效', 400);
}
return [
'event_id' => $input['id'],
'host_id' => (int) $input['agent_id'],
'operation_id' => $input['operation_id'],
'status' => $input['status'],
'effect_may_have_applied' => $input['effect_may_have_applied'],
'safe_to_resubmit' => $input['safe_to_resubmit'],
'error_code' => $input['error_code'],
'result' => $input['result'],
];
}
}