refactor(template): enforce unified import action policy

go
codex 3 weeks ago
parent 579be14f1a
commit 9d1c99d921

@ -34,19 +34,20 @@ final class CloudTemplateImportCancellation extends CloudTemplateImportModule
$candidate = CloudTemplateImportIntent::query()
->where('expires_at', '<=', $now)
->where(static function ($query): void {
$query->whereIn('state', [
'prepared', 'fetching', 'uploading', 'upload_failed',
'source_failed', 'cancel_pending',
])->orWhere(static function ($unknown): void {
$unknown->where('source_kind', 'upload')
->where('state', 'source_unknown')
->where(static function ($recoverable): void {
$recoverable->where('multipart_upload_id', '')
->orWhereIn('error_code', [
'multipart_abort_rejected',
'multipart_abort_not_applied',
]);
});
foreach ([CloudTemplateImportStateMachine::SOURCE_UPLOAD,
CloudTemplateImportStateMachine::SOURCE_REMOTE] as $source) {
$query->orWhere(static function ($eligible) use ($source): void {
$eligible->where('source_kind', $source)->whereIn('state',
CloudTemplateImportStateMachine::cleanupStates($source));
});
}
})
->where(static function ($safe): void {
$safe->where('state', '<>', 'source_unknown')
->orWhere(static function ($recoverable): void {
$recoverable->where('multipart_upload_id', '')
->orWhereIn('error_code',
CloudTemplateImportStateMachine::retryableAbortCodes());
});
})
->orderBy('expires_at')->orderBy('id')->first();
@ -84,15 +85,10 @@ final class CloudTemplateImportCancellation extends CloudTemplateImportModule
if ($state === 'ready') {
throw new CloudError('已发布的云镜像不能作为上传取消', 409);
}
CloudTemplateImportStateMachine::assertAction(
$intent, CloudTemplateImportStateMachine::ACTION_CANCEL
);
if ((string) $intent->source_kind === 'remote') {
if (!in_array($state, [
'prepared', 'fetching', 'source_failed',
], true)) {
throw new CloudError(
'远程云镜像已进入对象存储核对,不能直接取消',
409
);
}
CloudTemplateImportStateMachine::move(
$intent,
'cancelled'
@ -115,12 +111,6 @@ final class CloudTemplateImportCancellation extends CloudTemplateImportModule
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,
@ -145,18 +135,8 @@ final class CloudTemplateImportCancellation extends CloudTemplateImportModule
$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
);
if ($state === 'prepared') {
throw new CloudError('尚未开始的导入包含异常上传会话', 409);
}
$reconcileFirst = $state === 'cancel_pending';
if (!$reconcileFirst) {

@ -19,8 +19,7 @@ final class CloudTemplateImportPublication extends CloudTemplateImportModule
$now
): bool {
$locked = self::lockIntent($id);
if (!in_array((string) $locked->state,
['source_verifying', 'source_unknown'], true)) {
if (CloudTemplateImportStateMachine::resumeStep($locked) !== 'verify') {
throw new CloudError('上传完成状态已变化,请刷新页面', 409);
}
if ((int) ($identity['size_bytes'] ?? 0)
@ -72,8 +71,7 @@ final class CloudTemplateImportPublication extends CloudTemplateImportModule
$id
): array {
$intent = self::lockIntent($id);
if (in_array((string) $intent->state,
['distributing', 'ready', 'distribution_failed'], true)) {
if (CloudTemplateImportStateMachine::resumeStep($intent) === 'published') {
$job = $intent->active_job_id === null ? null
: CloudJob::query()
->where('id', (int) $intent->active_job_id)

@ -21,12 +21,13 @@ final class CloudTemplateImportStateMachine
* policies. Callers must not maintain parallel state lists.
*
* @var array<string,array{
* transitions:list<string>,sources:list<string>,
* resume_step:string,transitions:list<string>,sources:list<string>,
* actions:array<string,list<string>>,resumable:list<string>,
* cancellable:list<string>,cleanup:list<string>,terminal:bool}>
*/
private const DEFINITIONS = [
'prepared' => [
'resume_step' => 'acquire',
'transitions' => ['uploading', 'fetching', 'cancelled'],
'sources' => ['upload', 'remote'],
'actions' => [
@ -39,6 +40,7 @@ final class CloudTemplateImportStateMachine
'terminal' => false,
],
'uploading' => [
'resume_step' => 'acquire',
'transitions' => [
'source_verifying', 'upload_failed', 'source_unknown',
'cancel_pending',
@ -55,6 +57,7 @@ final class CloudTemplateImportStateMachine
'terminal' => false,
],
'fetching' => [
'resume_step' => 'acquire',
'transitions' => [
'source_verifying', 'source_failed', 'source_unknown',
'cancelled',
@ -67,6 +70,7 @@ final class CloudTemplateImportStateMachine
'terminal' => false,
],
'source_verifying' => [
'resume_step' => 'verify',
'transitions' => [
'source_ready', 'upload_failed', 'source_failed',
'source_unknown',
@ -82,6 +86,7 @@ final class CloudTemplateImportStateMachine
'terminal' => false,
],
'source_ready' => [
'resume_step' => 'publish',
'transitions' => ['distributing', 'cancel_pending'],
'sources' => ['upload', 'remote'],
'actions' => [
@ -94,6 +99,7 @@ final class CloudTemplateImportStateMachine
'terminal' => false,
],
'distributing' => [
'resume_step' => 'published',
'transitions' => ['ready', 'distribution_failed'],
'sources' => ['upload', 'remote'],
'actions' => [
@ -106,6 +112,7 @@ final class CloudTemplateImportStateMachine
'terminal' => false,
],
'ready' => [
'resume_step' => 'published',
'transitions' => [],
'sources' => ['upload', 'remote'],
'actions' => [
@ -118,6 +125,7 @@ final class CloudTemplateImportStateMachine
'terminal' => true,
],
'upload_failed' => [
'resume_step' => 'acquire',
'transitions' => ['uploading', 'cancel_pending', 'cancelled'],
'sources' => ['upload'],
'actions' => [
@ -129,6 +137,7 @@ final class CloudTemplateImportStateMachine
'terminal' => false,
],
'source_failed' => [
'resume_step' => 'acquire',
'transitions' => ['fetching', 'cancelled'],
'sources' => ['remote'],
'actions' => ['remote' => ['resume_remote', 'cancel']],
@ -138,6 +147,7 @@ final class CloudTemplateImportStateMachine
'terminal' => false,
],
'source_unknown' => [
'resume_step' => 'verify',
'transitions' => ['source_verifying', 'cancel_pending'],
'sources' => ['upload', 'remote'],
'actions' => [
@ -150,6 +160,7 @@ final class CloudTemplateImportStateMachine
'terminal' => false,
],
'distribution_failed' => [
'resume_step' => 'published',
'transitions' => ['distributing', 'cancel_pending'],
'sources' => ['upload', 'remote'],
'actions' => [
@ -162,6 +173,7 @@ final class CloudTemplateImportStateMachine
'terminal' => false,
],
'cancel_pending' => [
'resume_step' => 'cancel',
'transitions' => ['cancelled', 'source_unknown'],
'sources' => ['upload'],
'actions' => ['upload' => ['cancel']],
@ -171,6 +183,7 @@ final class CloudTemplateImportStateMachine
'terminal' => false,
],
'cancelled' => [
'resume_step' => 'cancel',
'transitions' => [],
'sources' => ['upload', 'remote'],
'actions' => [
@ -238,6 +251,22 @@ final class CloudTemplateImportStateMachine
if (!in_array($action, $actions, true)) {
throw new CloudError('当前导入状态不能执行该操作', 409);
}
if ($action === self::ACTION_CANCEL && $state === 'source_unknown'
&& !self::capabilities($intent)['can_cancel']) {
throw new CloudError('当前上传结果尚未确认,不能终止原分段上传', 409);
}
}
public static function resumeStep(CloudTemplateImportIntent $intent): string
{
self::assertSourceState((string) $intent->source_kind, (string) $intent->state);
return self::DEFINITIONS[(string) $intent->state]['resume_step'];
}
/** Provider proof that a previous abort was not applied. */
public static function retryableAbortCodes(): array
{
return ['multipart_abort_rejected', 'multipart_abort_not_applied'];
}
/** @return array{can_resume:bool,can_cancel:bool} */
@ -252,10 +281,8 @@ final class CloudTemplateImportStateMachine
if ($canCancel && $source === self::SOURCE_UPLOAD
&& $state === 'source_unknown') {
$canCancel = (string) $intent->multipart_upload_id === ''
|| in_array((string) $intent->error_code, [
'multipart_abort_rejected',
'multipart_abort_not_applied',
], true);
|| in_array((string) $intent->error_code,
self::retryableAbortCodes(), true);
}
return [
'can_resume' => in_array(
@ -304,7 +331,7 @@ final class CloudTemplateImportStateMachine
];
foreach ($definitions as $state => $definition) {
if ($state === '' || array_keys($definition) !== [
'transitions', 'sources', 'actions', 'resumable',
'resume_step', 'transitions', 'sources', 'actions', 'resumable',
'cancellable', 'cleanup', 'terminal',
]) {
throw new \LogicException(
@ -322,7 +349,9 @@ final class CloudTemplateImportStateMachine
);
}
}
if ($definition['sources'] === []
if (!in_array($definition['resume_step'],
['acquire', 'verify', 'publish', 'published', 'cancel'], true)
|| $definition['sources'] === []
|| array_diff($definition['sources'], $sources) !== []
|| array_diff($definition['resumable'],
$definition['sources']) !== []
@ -350,7 +379,7 @@ final class CloudTemplateImportStateMachine
}
foreach ($definition['sources'] as $source) {
$stateActions = $definition['actions'][$source] ?? null;
if (!is_array($stateActions)) {
if (!is_array($stateActions) || $stateActions === []) {
throw new \LogicException(
'Cloud-template import source has no action definition'
);

@ -4,6 +4,8 @@ namespace App\Services\Cloud;
use App\Models\CloudTemplateImportIntent;
use App\Models\CloudTemplateImportPart;
use App\Models\CloudTemplate;
use App\Models\CloudJob;
/** Owns browser multipart upload planning, receipts and source verification. */
final class CloudTemplateMultipartAcquisition extends CloudTemplateImportModule
@ -42,10 +44,9 @@ final class CloudTemplateMultipartAcquisition extends CloudTemplateImportModule
409
);
}
if (!in_array($state,
['prepared', 'uploading', 'upload_failed'], true)) {
throw new CloudError('当前导入状态不能继续上传', 409);
}
CloudTemplateImportStateMachine::assertAction(
$intent, CloudTemplateImportStateMachine::ACTION_START_UPLOAD
);
if ((string) $intent->multipart_upload_id !== '') {
if ($state === 'upload_failed') {
CloudTemplateImportStateMachine::move(
@ -158,8 +159,10 @@ final class CloudTemplateMultipartAcquisition extends CloudTemplateImportModule
$now
): array {
$intent = self::lockIntent($id);
if ((string) $intent->state !== 'uploading'
|| (string) $intent->multipart_upload_id === '') {
CloudTemplateImportStateMachine::assertAction(
$intent, CloudTemplateImportStateMachine::ACTION_RECORD_PART
);
if ((string) $intent->multipart_upload_id === '') {
throw new CloudError('上传会话当前不能记录分片', 409);
}
self::assertPartGeometry($intent, $partNumber, $size);
@ -430,13 +433,16 @@ final class CloudTemplateMultipartAcquisition extends CloudTemplateImportModule
if ((string) $intent->source_kind !== 'upload') {
throw new CloudError('该导入记录不是本地上传', 409);
}
CloudTemplateImportStateMachine::assertAction(
$intent, CloudTemplateImportStateMachine::ACTION_COMPLETE_UPLOAD
);
$storedDigest = (string) $intent->source_sha256;
if ($storedDigest !== '' && !hash_equals($storedDigest, $sha256)) {
throw new CloudError('云镜像 SHA-256 与原完成请求不一致', 409);
}
$state = (string) $intent->state;
if (in_array($state,
['distributing', 'ready', 'distribution_failed'], true)) {
$step = CloudTemplateImportStateMachine::resumeStep($intent);
if ($step === 'published') {
$jobId = (int) ($intent->active_job_id ?? 0);
$job = $jobId > 0 ? CloudJob::query()
->where('id', $jobId)->lockForUpdate()->first() : null;
@ -451,15 +457,9 @@ final class CloudTemplateMultipartAcquisition extends CloudTemplateImportModule
}
return ['ack' => CloudJobService::acknowledgement($job)];
}
if ($state === 'source_ready') {
if ($step === 'publish') {
return ['finalize' => true, 'intent' => $intent];
}
if (!in_array($state, [
'uploading', 'upload_failed', 'source_verifying',
'source_unknown',
], true)) {
throw new CloudError('当前导入状态不能完成上传', 409);
}
if ((string) $intent->multipart_upload_id === ''
|| (int) $intent->multipart_part_size_bytes < 1
|| (int) $intent->multipart_part_count < 1) {
@ -495,8 +495,7 @@ final class CloudTemplateMultipartAcquisition extends CloudTemplateImportModule
return [
'intent' => $intent,
'parts' => $parts,
'reconcile' => in_array($state,
['source_verifying', 'source_unknown'], true),
'reconcile' => $step === 'verify',
];
}, 3);
}

@ -199,15 +199,15 @@ final class CloudTemplateRemoteAcquisition extends CloudTemplateImportModule
if ((string) $intent->source_kind !== 'remote') {
throw new CloudError('该导入记录不是远程云镜像', 409);
}
CloudTemplateImportStateMachine::assertAction(
$intent, CloudTemplateImportStateMachine::ACTION_RESUME_REMOTE
);
$state = (string) $intent->state;
if (in_array($state, [
'source_ready', 'distributing', 'ready',
'distribution_failed',
], true)) {
$step = CloudTemplateImportStateMachine::resumeStep($intent);
if ($step === 'publish' || $step === 'published') {
return ['intent' => $intent, 'finalize' => true];
}
if (in_array($state,
['source_verifying', 'source_unknown'], true)) {
if ($step === 'verify') {
if ((int) $intent->source_size_bytes
< self::MIN_UPLOAD_BYTES
|| preg_match('/^[a-f0-9]{64}$/D',
@ -219,10 +219,6 @@ final class CloudTemplateRemoteAcquisition extends CloudTemplateImportModule
}
return ['intent' => $intent, 'reconcile' => true];
}
if (!in_array($state,
['prepared', 'fetching', 'source_failed'], true)) {
throw new CloudError('当前导入状态不能下载远程云镜像', 409);
}
if ($state === 'fetching'
&& (int) $intent->updated_at > $now - 3600) {
throw new CloudError(

@ -162,6 +162,48 @@ namespace {
CloudTemplateImportStateMachine::assertIntegrity();
$definitions = CloudTemplateImportStateMachine::definitions();
foreach ($definitions as $stateName => $definition) {
foreach ($definition['sources'] as $source) {
$probe = clone $stored;
$probe->state = $stateName;
$probe->source_kind = $source;
$probe->multipart_upload_id = '';
foreach (['start_upload', 'record_part', 'complete_upload',
'resume_remote', 'cancel'] as $action) {
$expected = in_array($action, $definition['actions'][$source], true);
try {
CloudTemplateImportStateMachine::assertAction($probe, $action);
$assert($expected, 'An unlisted import action was accepted.');
} catch (CloudError $error) {
$assert(!$expected && $error->httpStatus === 409,
'A listed import action was rejected.');
}
}
$missingOutlet = $definitions;
$missingOutlet[$stateName]['actions'][$source] = [];
try {
CloudTemplateImportStateMachine::assertDefinitions($missingOutlet);
throw new RuntimeException('An import state lost all executable outlets.');
} catch (LogicException) {
// A future state cannot silently lose its action policy.
}
}
}
$unknownUpload = clone $stored;
$unknownUpload->state = 'source_unknown';
$unknownUpload->source_kind = 'upload';
$unknownUpload->multipart_upload_id = 'pending-provider-upload';
$unknownUpload->error_code = 'multipart_complete_unknown';
$assert(!CloudTemplateImportStateMachine::capabilities($unknownUpload)['can_cancel'],
'An unknown upload completion was exposed as cancellable.');
try {
CloudTemplateImportStateMachine::assertAction($unknownUpload, 'cancel');
throw new RuntimeException('The cancellation endpoint disagrees with its projection.');
} catch (CloudError $error) {
$assert($error->httpStatus === 409, 'Unknown cancellation returned the wrong status.');
}
$unknownUpload->error_code = 'multipart_abort_not_applied';
CloudTemplateImportStateMachine::assertAction($unknownUpload, 'cancel');
$mutated = $definitions;
unset($mutated['prepared']['actions']['upload']);
try {

Loading…
Cancel
Save