@ -187,6 +187,7 @@ final class CloudTemplateImportWorkflow
self::markUploadFailure(
$id,
$error->publicCode,
$error->effectMayHaveApplied,
$now
);
}
@ -774,12 +775,14 @@ final class CloudTemplateImportWorkflow
private static function markUploadFailure(
string $id,
string $code,
bool $unknown,
int $now
): void {
$connection = (new CloudTemplateImportIntent())->getConnection();
$connection->transaction(static function () use (
$id,
$code,
$unknown,
$now
): void {
$intent = self::lockIntent($id);
@ -787,7 +790,10 @@ final class CloudTemplateImportWorkflow
|| (string) $intent->multipart_upload_id !== '') {
return;
}
CloudTemplateImportStateMachine::move($intent, 'upload_failed');
CloudTemplateImportStateMachine::move(
$intent,
$unknown ? 'source_unknown' : 'upload_failed'
);
$intent->error_code = substr($code, 0, 128);
$intent->updated_at = $now;
$intent->save();
@ -1004,6 +1010,290 @@ final class CloudTemplateImportWorkflow
return ['intent' => self::dto($intent)];
}
/**
* Cancel one local multipart upload. A persisted cancel_pending row is
* reconciled with read-only provider evidence before another Abort is
* allowed, so a lost DELETE response is never blindly replayed.
*
* @return array< string , mixed >
*/
public function cancel(
string $id,
array $actor,
?CloudObjectStorageS3Client $client = null
): array {
CloudAccess::manage($actor);
return $this->cancelIntent(
self::intentId($id),
$client ?? new CloudObjectStorageS3Client(),
false
);
}
/**
* Reap at most one expired local upload. Bucket lifecycle remains the
* final safety net when CreateMultipartUpload succeeded but its response
* was lost before PHP learned the provider upload ID.
*/
public function cleanupOneExpired(
?CloudObjectStorageS3Client $client = null
): bool {
$model = new CloudTemplateImportIntent();
$connection = $model->getConnection();
if (!$connection->getSchemaBuilder()->hasTable(
$model->getTable()
)) {
return false;
}
$now = ($this->clock)();
$candidate = CloudTemplateImportIntent::query()
->where('source_kind', 'upload')
->where('expires_at', '< =', $now)
->where(static function ($query): void {
$query->whereIn('state', [
'prepared', 'uploading', 'upload_failed',
'cancel_pending',
])->orWhere(static function ($unknown): void {
$unknown->where('state', 'source_unknown')
->where(static function ($recoverable): void {
$recoverable->where('multipart_upload_id', '')
->orWhereIn('error_code', [
'multipart_abort_rejected',
'multipart_abort_not_applied',
]);
});
});
})
->orderBy('expires_at')->orderBy('id')->first();
if ($candidate === null) {
return false;
}
$this->cancelIntent(
(string) $candidate->id,
$client ?? new CloudObjectStorageS3Client(),
true
);
return true;
}
/** @return array< string , mixed > */
private function cancelIntent(
string $id,
CloudObjectStorageS3Client $client,
bool $expiredOnly
): array {
$now = ($this->clock)();
$connection = (new CloudTemplateImportIntent())->getConnection();
$prepared = $connection->transaction(static function () use (
$id,
$expiredOnly,
$now
): array {
$intent = self::lockIntent($id);
if ((string) $intent->source_kind !== 'upload') {
throw new CloudError('该导入记录不是本地上传', 409);
}
if ($expiredOnly & & (int) $intent->expires_at > $now) {
return ['done' => true, 'intent' => $intent];
}
$state = (string) $intent->state;
if ($state === 'cancelled') {
return ['done' => true, 'intent' => $intent];
}
if ($state === 'ready') {
throw new CloudError('已发布的云镜像不能作为上传取消', 409);
}
$uploadId = (string) $intent->multipart_upload_id;
if ($uploadId === '') {
if ($state === 'uploading' & & !$expiredOnly
& & (int) $intent->updated_at > $now - 120) {
throw new CloudError(
'对象存储上传会话正在创建,请稍后再取消',
409
);
}
if (!in_array($state, [
'prepared', 'uploading', 'upload_failed',
'source_unknown', 'cancel_pending',
], true)) {
throw new CloudError('当前导入状态不能取消', 409);
}
if (in_array($state, ['prepared', 'upload_failed'], true)) {
CloudTemplateImportStateMachine::move(
$intent,
'cancelled'
);
$intent->error_code = '';
} else {
if ($state !== 'cancel_pending') {
CloudTemplateImportStateMachine::move(
$intent,
'cancel_pending'
);
}
CloudTemplateImportStateMachine::move(
$intent,
'cancelled'
);
$intent->error_code = 'multipart_abandoned_lifecycle';
}
$intent->completed_at = $now;
$intent->updated_at = $now;
$intent->save();
return ['done' => true, 'intent' => $intent];
}
$retryableUnknown = $state === 'source_unknown'
& & in_array((string) $intent->error_code, [
'multipart_abort_rejected',
'multipart_abort_not_applied',
], true);
if (!in_array($state,
['uploading', 'upload_failed', 'cancel_pending'], true)
& & !$retryableUnknown) {
throw new CloudError(
'当前上传结果尚未确认,不能终止原分段上传',
409
);
}
$reconcileFirst = $state === 'cancel_pending';
if (!$reconcileFirst) {
CloudTemplateImportStateMachine::move(
$intent,
'cancel_pending'
);
$intent->error_code = 'multipart_abort_pending';
// If PHP stops after this commit, the worker can immediately
// reconcile the pending cancellation from provider evidence.
$intent->expires_at = $now;
$intent->updated_at = $now;
$intent->save();
}
return [
'done' => false,
'intent' => $intent,
'reconcile_first' => $reconcileFirst,
];
}, 3);
/** @var CloudTemplateImportIntent $intent */
$intent = $prepared['intent'];
if (($prepared['done'] ?? false) === true) {
return self::dto($intent);
}
if (($prepared['reconcile_first'] ?? false) === true) {
$evidence = $this->cancellationEvidence($intent, $client);
if ($evidence === 'absent') {
return self::settleCancelled($id, $now);
}
if ($evidence !== 'active') {
self::settleCancelUnknown($id, $evidence, $now);
throw new CloudError(
'无法确认原分段上传是否已终止,请勿重复取消',
502
);
}
}
$runtime = self::runtime($intent);
try {
$client->abortMultipartUpload(
$runtime['config'],
$runtime['credentials'],
(string) $intent->object_key,
(string) $intent->multipart_upload_id
);
return self::settleCancelled($id, $now);
} catch (CloudObjectStorageTransferError $error) {
$evidence = $this->cancellationEvidence($intent, $client);
if ($evidence === 'absent') {
return self::settleCancelled($id, $now);
}
$code = $evidence === 'active'
? 'multipart_abort_not_applied' : $evidence;
self::settleCancelUnknown($id, $code, $now);
throw new CloudError(
$evidence === 'active'
? '对象存储尚未终止分段上传,可以稍后重新取消'
: '无法确认原分段上传是否已终止,请勿重复取消',
$evidence === 'active' ? 409 : 502
);
}
}
/** @return 'active'|'absent'|string */
private function cancellationEvidence(
CloudTemplateImportIntent $intent,
CloudObjectStorageS3Client $client
): string {
$runtime = self::runtime($intent);
try {
if ($client->inspectObject(
$runtime['config'],
$runtime['credentials'],
(string) $intent->object_key
) !== null) {
return 'multipart_abort_object_present';
}
} catch (CloudObjectStorageTransferError $error) {
return $error->publicCode;
}
try {
$client->listMultipartParts(
$runtime['config'],
$runtime['credentials'],
(string) $intent->object_key,
(string) $intent->multipart_upload_id
);
return 'active';
} catch (CloudObjectStorageTransferError $error) {
return $error->publicCode === 'multipart_upload_absent'
? 'absent' : $error->publicCode;
}
}
/** @return array< string , mixed > */
private static function settleCancelled(string $id, int $now): array
{
$connection = (new CloudTemplateImportIntent())->getConnection();
return $connection->transaction(static function () use (
$id,
$now
): array {
$intent = self::lockIntent($id);
if ((string) $intent->state !== 'cancelled') {
if ((string) $intent->state !== 'cancel_pending') {
throw new CloudError('上传取消状态已变化,请刷新页面', 409);
}
CloudTemplateImportStateMachine::move($intent, 'cancelled');
}
$intent->error_code = '';
$intent->completed_at = $now;
$intent->updated_at = $now;
$intent->save();
return self::dto($intent);
}, 3);
}
private static function settleCancelUnknown(
string $id,
string $code,
int $now
): void {
$connection = (new CloudTemplateImportIntent())->getConnection();
$connection->transaction(static function () use (
$id,
$code,
$now
): void {
$intent = self::lockIntent($id);
if ((string) $intent->state !== 'cancel_pending') {
return;
}
CloudTemplateImportStateMachine::move($intent, 'source_unknown');
$intent->error_code = substr($code, 0, 128);
$intent->updated_at = $now;
$intent->save();
}, 3);
}
/** @return array{created:bool,intent:array< string , mixed > } */
private function reserveUploadIntent(
array $actor,
@ -1108,10 +1398,16 @@ final class CloudTemplateImportWorkflow
/** @return array< string , mixed > */
public static function dto(CloudTemplateImportIntent $intent): array
{
$partQuery = CloudTemplateImportPart::query()
->where('intent_id', (string) $intent->id);
$uploadedParts = (int) (clone $partQuery)->count();
$uploadedBytes = (int) (clone $partQuery)->sum('size_bytes');
$parts = CloudTemplateImportPart::query()
->where('intent_id', (string) $intent->id)
->orderBy('part_number')->get()->map(
static fn (CloudTemplateImportPart $part): array => [
'part_number' => (int) $part->part_number,
'size_bytes' => (int) $part->size_bytes,
]
)->all();
$uploadedParts = count($parts);
$uploadedBytes = array_sum(array_column($parts, 'size_bytes'));
$state = (string) $intent->state;
return [
'id' => (string) $intent->id,
@ -1127,10 +1423,11 @@ final class CloudTemplateImportWorkflow
'state' => $state,
'uploaded_parts' => $uploadedParts,
'uploaded_bytes' => $uploadedBytes,
'parts' => $parts,
'part_count' => (int) $intent->multipart_part_count,
'part_size_bytes' => (int) $intent->multipart_part_size_bytes,
'can_resume' => CloudTemplateImportStateMachine::resumable($state),
'can_cancel' => !CloudTemplateImportStateMachine::terminal($state ),
'can_cancel' => self::cancellable($intent ),
'task_id' => $intent->active_job_id === null
? null : (int) $intent->active_job_id,
'error_code' => (string) $intent->error_code,
@ -1142,6 +1439,28 @@ final class CloudTemplateImportWorkflow
];
}
private static function cancellable(
CloudTemplateImportIntent $intent
): bool {
if ((string) $intent->source_kind !== 'upload') {
return false;
}
$state = (string) $intent->state;
if (in_array($state, [
'prepared', 'uploading', 'upload_failed',
], true)) {
return true;
}
if ($state !== 'source_unknown') {
return false;
}
return (string) $intent->multipart_upload_id === ''
|| in_array((string) $intent->error_code, [
'multipart_abort_rejected',
'multipart_abort_not_applied',
], true);
}
private static function assertAdministrator(array $actor): void
{
if (($actor['is_admin'] ?? false) !== true) {