feat(template): publish through replicated storage ledger

go
codex 2 weeks ago
parent 013d05f93c
commit 1cfe6a8866

@ -12,6 +12,7 @@ final class CloudTemplateArtifact extends Model
protected $keyType = 'string';
protected $hidden = ['sealed_storage_runtime'];
protected $casts = [
'storage_artifact_id' => 'int',
'storage_revision' => 'int',
'size_bytes' => 'int',
'delete_generation' => 'int',

@ -143,6 +143,55 @@ final class CloudObjectStorageS3Client
);
}
/**
* Start a multipart upload whose immutable SHA-256 identity is already
* known. The digest is signed into CreateMultipartUpload metadata so a
* later exact-key HEAD proves the provider object identity.
*
* Existing Agent uploads intentionally keep using prepareMultipartUpload
* because their digest is not known until the Agent completes the image.
*
* @param array<string,mixed> $config
* @param array{access_key_id:string,secret_access_key:string} $credentials
* @return array<string,mixed>
*/
public function prepareKnownIdentityMultipartUpload(
array $config,
array $credentials,
string $objectKey,
int $sizeBytes,
string $sha256,
?int $timestamp = null,
int $expiresSeconds = 86400
): array {
self::assertRuntime($config, $credentials);
self::assertObjectKey($objectKey);
if ($sizeBytes < 1
|| preg_match('/^[a-f0-9]{64}$/D', $sha256) !== 1) {
throw new \InvalidArgumentException(
'Invalid immutable multipart identity'
);
}
self::multipartGeometry($sizeBytes);
$timestamp ??= time();
$uploadId = $this->createMultipartUpload(
$config,
$credentials,
$objectKey,
$timestamp,
['virt-sha256' => $sha256]
);
return $this->resumeMultipartUpload(
$config,
$credentials,
$objectKey,
$uploadId,
$sizeBytes,
$timestamp,
$expiresSeconds
);
}
/** Re-sign one existing multipart upload without creating another one. */
public function resumeMultipartUpload(
array $config,
@ -1026,13 +1075,16 @@ final class CloudObjectStorageS3Client
array $config,
array $credentials,
string $objectKey,
int $timestamp
int $timestamp,
array $metadata = []
): string {
$url = self::objectUrl($config, $objectKey) . '?uploads=';
$headers = CloudS3Signer::sign(
'POST', $url, (string) $config['region'],
$credentials['access_key_id'], $credentials['secret_access_key'],
$timestamp
$timestamp,
null,
$metadata
);
try {
$response = $this->http()->request('POST', $url, [

@ -1081,10 +1081,12 @@ final class CloudStorageArtifactService
[$artifact, $replicas] = self::artifactContextLocked($operation);
$replica = self::operationReplica($operation, $replicas);
$publication = self::publicationLocked((int) $artifact->id);
$backup = self::primaryPreparationBackupLocked(
$publication,
$artifact
);
$backup = $publication->backup_id === null
? null
: self::primaryPreparationBackupLocked(
$publication,
$artifact
);
if ((string) $operation->phase === 'terminal') {
self::assertTerminalFailure(
$operation,
@ -1094,11 +1096,13 @@ final class CloudStorageArtifactService
$errorCode,
'主副本人工核对终态冲突'
);
self::markPrimaryBackupAttentionLocked(
$backup,
$errorCode,
$now
);
if ($backup instanceof CloudInstanceBackup) {
self::markPrimaryBackupAttentionLocked(
$backup,
$errorCode,
$now
);
}
return;
}
self::assertLeaseToken($operation, $leaseToken, $now);
@ -1141,11 +1145,13 @@ final class CloudStorageArtifactService
$publication->available_at = 0;
$publication->updated_at = $now;
$publication->save();
self::markPrimaryBackupAttentionLocked(
$backup,
$errorCode,
$now
);
if ($backup instanceof CloudInstanceBackup) {
self::markPrimaryBackupAttentionLocked(
$backup,
$errorCode,
$now
);
}
});
}

@ -6,126 +6,79 @@ use App\Models\CloudTemplate;
use App\Models\CloudTemplateArtifact;
use App\Models\CloudTemplateImportIntent;
/**
* Deep module for the canonical immutable object behind a template version.
* Callers never handle object-storage credentials or provider-specific URLs.
*/
/** Template-facing facade over the shared replicated storage ledger. */
final class CloudTemplateArtifactManager
{
private const RUNTIME_PURPOSE = 'template-artifact-runtime';
private const DOWNLOAD_SECONDS = 604800;
/** Reserve a durable publishing ledger before crossing object storage. */
public static function reserveLocked(
CloudTemplate $template,
?array $runtime = null
): CloudTemplateArtifact {
if (!$template->exists || (string) $template->state !== 'preparing'
|| CloudTemplateArtifact::find((string) $template->id) !== null) {
throw new CloudError('模板主副本预留状态无效', 409);
}
self::assertIdentity(
(string) $template->id,
(string) $template->generation_token
);
$runtime ??= CloudObjectStorageConfig::runtime(true);
self::assertRuntime($runtime);
$now = time();
$artifact = new CloudTemplateArtifact();
$artifact->template_id = (string) $template->id;
$artifact->storage_revision = (int) $runtime['revision'];
$artifact->sealed_storage_runtime = CloudSecrets::encrypt(
$runtime,
self::RUNTIME_PURPOSE
);
$artifact->object_key = self::objectKey(
(string) $runtime['config']['prefix'],
(string) $template->id,
(string) $template->generation_token
);
$artifact->object_version_id = '';
$artifact->object_etag = '';
$artifact->size_bytes = (int) $template->image_bytes;
$artifact->sha256 = (string) $template->sha256;
$artifact->state = 'publishing';
$artifact->error_code = '';
$artifact->delete_operation_id = '';
$artifact->delete_generation = 0;
$artifact->delete_cycle_attempts = 0;
$artifact->delete_presence_confirmations = 0;
$artifact->delete_last_checked_at = 0;
$artifact->delete_next_check_at = 0;
$artifact->delete_attention_at = null;
$artifact->verified_at = 0;
$artifact->created_at = $artifact->updated_at = $now;
$artifact->save();
return $artifact;
}
/** Adopt an already verified immutable object while its intent is locked. */
/**
* Bind a protected storage artifact while the template intent is locked.
* Publication and business finalization share the caller transaction.
*/
public static function adoptImportIntentLocked(
CloudTemplate $template,
CloudTemplateImportIntent $intent,
array $runtime
CloudTemplateImportIntent $intent
): CloudTemplateArtifact {
if (!$template->exists || !in_array((string) $template->state,
['preparing', 'importing'], true)
|| (string) $template->id !== (string) $intent->template_id
|| (string) $intent->state !== 'source_ready'
|| (int) $intent->source_size_bytes !== (int) $template->image_bytes
|| (int) $intent->source_size_bytes
!== (int) $template->image_bytes
|| !hash_equals(
(string) $intent->source_sha256,
(string) $template->sha256
)
|| trim((string) $intent->object_etag) === '') {
)) {
throw new CloudError('模板导入对象身份无效', 409);
}
self::assertRuntime($runtime);
if ((int) $runtime['revision'] !== (int) $intent->storage_revision) {
throw new CloudError('模板导入对象存储版本不一致', 409);
$binding = CloudTemplateStoragePublicationService::binding($intent);
if (($binding['protected'] ?? false) !== true) {
throw new CloudError('模板双副本保护尚未完成', 409);
}
self::assertIdentity(
(string) $template->id,
(string) $template->generation_token
$identity = CloudTemplateStoragePublicationService::primaryIdentity(
$intent
);
$existing = CloudTemplateArtifact::query()
->where('template_id', (string) $template->id)
->lockForUpdate()->first();
if ($existing !== null) {
if ((string) $existing->object_key !== (string) $intent->object_key
|| (string) $existing->object_version_id
!== (string) $intent->object_version_id
|| (string) $existing->object_etag
!== (string) $intent->object_etag
|| (int) $existing->size_bytes !== (int) $intent->source_size_bytes
if ($existing instanceof CloudTemplateArtifact) {
if ((int) ($existing->storage_artifact_id ?? 0)
!== (int) $binding['artifact_id']
|| (int) $existing->size_bytes
!== (int) $intent->source_size_bytes
|| !hash_equals(
(string) $existing->sha256,
(string) $intent->source_sha256
)
|| (string) $existing->state !== 'ready') {
throw new CloudError('模板主副本记录与导入意图冲突', 409);
throw new CloudError('模板主副本记录与存储账本冲突', 409);
}
return $existing;
}
if ((string) $template->state !== 'preparing') {
throw new CloudError('模板主副本记录与导入任务不一致', 409);
}
CloudStoragePublicationFinalizerService::complete(
'template',
(string) $intent->id,
(int) $binding['artifact_id'],
(string) $binding['operation_id']
);
/** @var \App\Models\CloudStorageReplica $primary */
$primary = $binding['replica'];
$now = time();
$artifact = new CloudTemplateArtifact();
$artifact->template_id = (string) $template->id;
$artifact->storage_artifact_id = (int) $binding['artifact_id'];
$artifact->storage_revision = (int) $intent->storage_revision;
// Import intents and durable artifacts have separate AEAD purposes.
// Re-seal the validated runtime instead of copying purpose-bound
// ciphertext that the artifact reader could never authenticate.
$artifact->sealed_storage_runtime = CloudSecrets::encrypt(
$runtime,
self::RUNTIME_PURPOSE
);
$artifact->object_key = (string) $intent->object_key;
$artifact->object_version_id = (string) $intent->object_version_id;
$artifact->object_etag = (string) $intent->object_etag;
$artifact->size_bytes = (int) $intent->source_size_bytes;
$artifact->sha256 = (string) $intent->source_sha256;
$artifact->sealed_storage_runtime = '{}';
$artifact->object_key = (string) $primary->object_key;
$artifact->object_version_id = (string) $identity['version_id'];
$artifact->object_etag = (string) $identity['etag'];
$artifact->size_bytes = (int) $identity['size_bytes'];
$artifact->sha256 = (string) $identity['sha256'];
$artifact->state = 'ready';
$artifact->error_code = '';
$artifact->delete_operation_id = '';
@ -141,107 +94,16 @@ final class CloudTemplateArtifactManager
return $artifact;
}
/**
* Publish the reserved local file. Unknown transport effect remains fenced
* on the same object key and is never retried as a new generation.
*
* @param array{path:string,size_bytes:int,sha256:string} $file
*/
public static function publishReserved(
CloudTemplate $template,
array $file,
?CloudObjectStorageS3Client $client = null
): CloudTemplateArtifact {
self::assertFile($file, $template);
$artifact = CloudTemplateArtifact::find((string) $template->id);
if ($artifact === null || (string) $artifact->state !== 'publishing') {
throw new CloudError('模板主副本不在可发布状态', 409);
}
$runtime = self::runtime($artifact);
$publication = (new CloudImmutableArtifactTransport($client))->publish(
$runtime,
(string) $artifact->object_key,
[
'path' => (string) $file['path'],
'size_bytes' => (int) $file['size_bytes'],
'sha256' => (string) $file['sha256'],
]
);
$resolution = (string) ($publication['resolution'] ?? 'unknown');
if ($resolution !== 'applied') {
$unknown = in_array($resolution, ['unknown', 'conflict'], true);
$code = match ($resolution) {
'unknown' => 'template_source_reconcile_unavailable',
'conflict' => 'template_source_identity_mismatch',
default => (string) ($publication['error_code'] ??
'template_source_publish_failed'),
};
if ($code === 'artifact_publish_failed') {
$code = 'template_source_publish_failed';
}
self::recordPublishFailure(
(string) $template->id,
$code,
$unknown
);
if ($resolution === 'unknown') {
throw new CloudError(
'无法确认模板主副本是否已保存,记录已锁定,请勿重新导入',
502
);
}
if ($resolution === 'conflict') {
throw new CloudError(
'模板主副本对象大小与导入文件不一致,记录已锁定',
409
);
}
throw new CloudError(
(string) ($publication['message'] ??
'对象存储已确认模板主副本未保存'),
502
);
}
$identity = $publication['identity'] ?? null;
if (!is_array($identity)) {
throw new CloudError('模板主副本对象身份无效', 502);
}
return $artifact->getConnection()->transaction(static function () use (
$template, $identity
): CloudTemplateArtifact {
$lockedTemplate = CloudTemplate::query()
->where('id', (string) $template->id)
->lockForUpdate()->first();
$locked = CloudTemplateArtifact::query()
->where('template_id', (string) $template->id)
->lockForUpdate()->first();
if ($lockedTemplate === null || $locked === null
|| (string) $lockedTemplate->state !== 'preparing'
|| (string) $locked->state !== 'publishing') {
throw new CloudError('模板主副本发布状态已变化', 409);
}
$now = time();
$locked->object_version_id = (string) $identity['version_id'];
$locked->object_etag = (string) $identity['etag'];
$locked->state = 'ready';
$locked->error_code = '';
$locked->verified_at = $now;
$locked->updated_at = $now;
$locked->save();
$lockedTemplate->updated_at = $now;
$lockedTemplate->save();
return $locked;
}, 3);
}
/** Return a bounded read capability after revalidating the frozen object. */
/** Return a bounded URL from one exact, healthy, verified replica. */
public static function downloadSource(
CloudTemplate $template,
?CloudObjectStorageS3Client $client = null
): array {
$artifact = CloudTemplateArtifact::find((string) $template->id);
if ($artifact === null || (string) $artifact->state !== 'ready'
$storageArtifactId = (int) ($artifact?->storage_artifact_id ?? 0);
if (!$artifact instanceof CloudTemplateArtifact
|| $storageArtifactId < 1
|| (string) $artifact->state !== 'ready'
|| (int) $artifact->size_bytes !== (int) $template->image_bytes
|| !hash_equals(
(string) $artifact->sha256,
@ -249,175 +111,22 @@ final class CloudTemplateArtifactManager
)) {
throw new CloudError('模板主副本尚未就绪', 409);
}
$runtime = self::runtime($artifact);
$transport = new CloudImmutableArtifactTransport($client);
$identity = $transport->head(
$runtime,
(string) $artifact->object_key,
(string) $artifact->object_version_id
$read = CloudStorageArtifactService::presignedRead(
$storageArtifactId,
self::DOWNLOAD_SECONDS,
$client
);
if (!CloudImmutableArtifactTransport::identityMatches(
$identity,
(int) $artifact->size_bytes,
(string) $artifact->object_etag,
(string) $artifact->object_version_id
if ((int) $read['size_bytes'] !== (int) $artifact->size_bytes
|| !hash_equals(
(string) $artifact->sha256,
(string) $read['sha256']
)) {
throw new CloudError('模板主副本对象身份已经变化', 409);
throw new CloudError('模板读取副本身份与目录不一致', 409);
}
return [
'source_url' => $transport->presignedDownload(
$runtime,
(string) $artifact->object_key,
(string) $artifact->object_version_id,
self::DOWNLOAD_SECONDS
),
'source_url' => (string) $read['url'],
'source_size_bytes' => (int) $artifact->size_bytes,
'sha256' => (string) $artifact->sha256,
];
}
/** Inspect the exact immutable version without exposing storage secrets. */
public static function inspectDeletionTarget(
CloudTemplateArtifact $artifact,
?CloudObjectStorageS3Client $client = null
): ?array {
$runtime = self::runtime($artifact);
return (new CloudImmutableArtifactTransport($client))->inspect(
$runtime,
(string) $artifact->object_key,
(string) $artifact->object_version_id
);
}
/** Delete only the frozen provider version recorded by this artifact. */
public static function deleteExact(
CloudTemplateArtifact $artifact,
?CloudObjectStorageS3Client $client = null
): void {
$runtime = self::runtime($artifact);
(new CloudImmutableArtifactTransport($client))->deleteExact(
$runtime,
(string) $artifact->object_key,
(string) $artifact->object_version_id
);
}
/** Refuse cleanup when the provider version no longer matches the ledger. */
public static function deletionIdentityMatches(
CloudTemplateArtifact $artifact,
array $identity
): bool {
return CloudImmutableArtifactTransport::identityMatches(
$identity,
(int) $artifact->size_bytes,
(string) $artifact->object_etag,
(string) $artifact->object_version_id
);
}
private static function recordPublishFailure(string $templateId,
string $code, bool $unknown): void
{
(new CloudTemplateArtifact())->getConnection()->transaction(
static function () use ($templateId, $code, $unknown): void {
$template = CloudTemplate::query()->where('id', $templateId)
->lockForUpdate()->first();
$artifact = CloudTemplateArtifact::query()
->where('template_id', $templateId)
->lockForUpdate()->first();
if ($template === null || $artifact === null
|| (string) $artifact->state !== 'publishing') {
return;
}
$now = time();
$artifact->state = $unknown ? 'unknown' : 'failed';
$artifact->error_code = substr($code, 0, 64);
$artifact->updated_at = $now;
$artifact->save();
CloudTemplateStateMachine::moveTemplate(
$template,
$unknown ? 'source_unknown' : 'source_failed'
);
$template->updated_at = $now;
$template->save();
},
3
);
}
/** @param array<string,mixed> $file */
private static function assertFile(array $file,
CloudTemplate $template): void
{
$path = $file['path'] ?? null;
$size = $file['size_bytes'] ?? null;
$sha256 = strtolower((string) ($file['sha256'] ?? ''));
$actual = is_string($path) && is_file($path) && is_readable($path)
? @hash_file('sha256', $path) : false;
if (!is_string($path) || !is_int($size) || $size < 1
|| preg_match('/^[a-f0-9]{64}$/D', $sha256) !== 1
|| @filesize($path) !== $size || !is_string($actual)
|| !hash_equals($sha256, $actual)
|| $size !== (int) $template->image_bytes
|| !hash_equals($sha256, (string) $template->sha256)) {
throw new CloudError('模板主副本文件校验失败', 422);
}
}
/** @return array<string,mixed> */
private static function runtime(CloudTemplateArtifact $artifact): array
{
$runtime = CloudSecrets::decrypt(
(string) $artifact->sealed_storage_runtime,
self::RUNTIME_PURPOSE
);
self::assertRuntime($runtime);
return $runtime;
}
/** Freeze the one immutable object key before any remote side effect. */
public static function plannedObjectKey(
array $runtime,
string $templateId,
string $generationToken
): string {
self::assertRuntime($runtime);
self::assertIdentity($templateId, $generationToken);
return self::objectKey(
(string) $runtime['config']['prefix'],
$templateId,
$generationToken
);
}
private static function objectKey(string $prefix, string $templateId,
string $generationToken): string
{
$prefix = trim($prefix, '/');
return ($prefix === '' ? '' : $prefix . '/')
. 'cloud-templates/' . $templateId . '/'
. $generationToken . '/system.qcow2';
}
private static function assertIdentity(string $templateId,
string $generationToken): void
{
if (preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/D', $templateId)
!== 1
|| preg_match('/^[a-f0-9]{32}$/D', $generationToken) !== 1) {
throw new CloudError('模板主副本身份无效', 422);
}
}
/** @param array<string,mixed> $runtime */
private static function assertRuntime(array $runtime): void
{
if (!is_array($runtime['config'] ?? null)
|| !is_array($runtime['credentials'] ?? null)
|| !is_int($runtime['revision'] ?? null)
|| (int) $runtime['revision'] < 1
|| !is_string($runtime['config']['prefix'] ?? null)) {
throw new CloudError('模板对象存储运行时无效', 503);
}
}
}

@ -5,6 +5,7 @@ namespace App\Services\Cloud;
use App\Models\CloudJob;
use App\Models\CloudTemplate;
use App\Models\CloudTemplateArtifact;
use App\Models\CloudTemplateImportIntent;
use App\Models\CloudTemplateReplica;
use App\Models\CloudUserIsoReplica;
@ -12,14 +13,12 @@ use App\Models\CloudUserIsoReplica;
* Owns the destructive half of the template lifecycle.
*
* Host replicas are removed by immutable Agent operations. Only after every
* child is proven applied does this module remove the exact object-storage
* version. An ambiguous object DELETE is reconciled with two spaced HEAD
* observations and a fresh generation; it is never blindly replayed.
* child is proven applied does this module delegate exact per-replica object
* cleanup to the shared storage ledger. Ambiguous provider effects remain on
* their original replica operation and are never replayed by this facade.
*/
final class CloudTemplateDeletionService
{
private const STABLE_SECONDS = 300;
private const MAX_DELETE_GENERATIONS = 3;
private const DUE_STATES = [
'delete_pending', 'deleting', 'delete_uncertain',
];
@ -115,6 +114,12 @@ final class CloudTemplateDeletionService
$artifact->delete_attention_at = null;
$artifact->updated_at = $now;
$artifact->save();
if ((int) ($artifact->storage_artifact_id ?? 0) < 1) {
throw new CloudError(
'旧版云镜像主副本不支持当前清理流程',
409
);
}
}
/** Retry only local master cleanup; Agent delete operations stay immutable. */
@ -145,6 +150,16 @@ final class CloudTemplateDeletionService
$artifact->delete_attention_at = null;
$artifact->updated_at = $now;
$artifact->save();
$intent = CloudTemplateImportIntent::query()
->where('template_id', (string) $template->id)
->lockForUpdate()->first();
if (!$intent instanceof CloudTemplateImportIntent) {
throw new CloudError('云镜像导入归属账本缺失', 409);
}
(new CloudStorageArtifactDeletionService())->reopenAttention(
(int) $artifact->storage_artifact_id,
['template_import_intent_id' => (string) $intent->id]
);
}
/** Restore sellable projection only when every host proves no deletion. */
@ -376,59 +391,43 @@ final class CloudTemplateDeletionService
}
/** @var CloudTemplateArtifact $artifact */
$artifact = $prepared['artifact'];
try {
$identity = CloudTemplateArtifactManager::inspectDeletionTarget(
$artifact,
$client
);
} catch (CloudObjectStorageTransferError $error) {
self::deferInspection(
$storageArtifactId = (int) ($artifact->storage_artifact_id ?? 0);
$intent = CloudTemplateImportIntent::query()
->where('template_id', $templateId)->first();
if ($storageArtifactId < 1
|| !$intent instanceof CloudTemplateImportIntent) {
self::markAttention(
$templateId,
$error->publicCode,
$prepared['mode'] === 'inspect'
'template_storage_ledger_missing'
);
return 'deferred';
return 'attention';
}
if ($identity === null) {
$result = (new CloudStorageArtifactDeletionService($client))->process(
$storageArtifactId,
['template_import_intent_id' => (string) $intent->id]
);
if (($result['deleted'] ?? false) === true) {
self::finishSuccess($templateId);
return 'completed';
}
if (!CloudTemplateArtifactManager::deletionIdentityMatches(
$artifact,
$identity
)) {
self::markAttention($templateId, 'template_object_identity_changed');
return 'attention';
}
if ($prepared['mode'] === 'inspect') {
$artifact = self::recordStablePresence($templateId, time());
if ($artifact === null) {
$current = CloudTemplateArtifact::find($templateId);
if ($current !== null
&& (int) $current->delete_cycle_attempts
>= self::MAX_DELETE_GENERATIONS
&& (int) $current->delete_presence_confirmations >= 2) {
self::markAttention(
$templateId,
'template_object_delete_limit_reached'
);
return 'attention';
}
return 'deferred';
}
}
try {
CloudTemplateArtifactManager::deleteExact($artifact, $client);
} catch (CloudObjectStorageTransferError $error) {
if ($error->effectMayHaveApplied) {
self::markUncertain($templateId, $error->publicCode);
return 'deferred';
}
self::markAttention($templateId, $error->publicCode);
if (($result['requires_attention'] ?? false) === true) {
self::markAttention(
$templateId,
'template_storage_delete_attention'
);
return 'attention';
}
self::finishSuccess($templateId);
return 'completed';
CloudTemplateArtifact::query()->where('template_id', $templateId)
->whereIn('state', self::DUE_STATES)->update([
'state' => 'delete_pending',
'error_code' => 'template_storage_delete_pending',
'delete_next_check_at' => max(
time() + 60,
(int) ($result['next_check_at'] ?? 0)
),
'updated_at' => time(),
]);
return 'deferred';
}
/** @return array{mode:string,artifact:CloudTemplateArtifact}|null */
@ -470,119 +469,19 @@ final class CloudTemplateDeletionService
|| !self::artifactMatchesTemplate($artifact, $template)) {
return null;
}
if ((string) $artifact->state === 'delete_pending') {
self::claimDeleteGeneration($artifact, $now);
return ['mode' => 'delete', 'artifact' => $artifact];
}
return ['mode' => 'inspect', 'artifact' => $artifact];
},
3
);
}
private static function claimDeleteGeneration(
CloudTemplateArtifact $artifact,
int $now
): void {
$artifact->state = 'deleting';
$artifact->delete_operation_id = bin2hex(random_bytes(16));
$artifact->delete_generation = max(
0,
(int) $artifact->delete_generation
) + 1;
$artifact->delete_cycle_attempts = max(
0,
(int) $artifact->delete_cycle_attempts
) + 1;
$artifact->delete_presence_confirmations = 0;
$artifact->delete_last_checked_at = 0;
$artifact->delete_next_check_at = $now + self::STABLE_SECONDS;
$artifact->error_code = '';
$artifact->updated_at = $now;
$artifact->save();
}
private static function recordStablePresence(
string $templateId,
int $now
): ?CloudTemplateArtifact {
return (new CloudTemplateArtifact())->getConnection()->transaction(
static function () use ($templateId, $now): ?CloudTemplateArtifact {
$artifact = CloudTemplateArtifact::query()
->where('template_id', $templateId)
->lockForUpdate()->first();
if ($artifact === null || !in_array(
(string) $artifact->state,
['deleting', 'delete_uncertain'],
true
)) {
return null;
}
$last = (int) $artifact->delete_last_checked_at;
if ($last > 0 && $now - $last < self::STABLE_SECONDS) {
$artifact->delete_next_check_at = $last
+ self::STABLE_SECONDS;
$artifact->updated_at = $now;
$artifact->save();
return null;
}
$confirmations = max(
0,
(int) $artifact->delete_presence_confirmations
) + 1;
$artifact->state = 'delete_uncertain';
$artifact->delete_presence_confirmations = $confirmations;
$artifact->delete_last_checked_at = $now;
$artifact->delete_next_check_at = $now
+ self::STABLE_SECONDS;
$artifact->error_code = 'template_object_still_present';
$artifact->state = 'deleting';
$artifact->error_code = '';
// A crash before the shared deletion ledger is advanced must
// leave this owner eligible for a bounded retry.
$artifact->delete_next_check_at = $now + 60;
$artifact->updated_at = $now;
if ($confirmations < 2) {
$artifact->save();
return null;
}
if ((int) $artifact->delete_cycle_attempts
>= self::MAX_DELETE_GENERATIONS) {
$artifact->save();
return null;
}
self::claimDeleteGeneration($artifact, $now);
return $artifact;
$artifact->save();
return ['mode' => 'delete', 'artifact' => $artifact];
},
3
);
}
private static function deferInspection(
string $templateId,
string $code,
bool $priorDeleteMayHaveApplied
): void {
CloudTemplateArtifact::query()->where('template_id', $templateId)
->whereIn('state', self::DUE_STATES)->update([
'state' => $priorDeleteMayHaveApplied
? 'delete_uncertain' : 'delete_pending',
'error_code' => substr($code, 0, 64),
'delete_next_check_at' => time() + self::STABLE_SECONDS,
'updated_at' => time(),
]);
}
private static function markUncertain(
string $templateId,
string $code
): void {
CloudTemplateArtifact::query()->where('template_id', $templateId)
->where('state', 'deleting')->update([
'state' => 'delete_uncertain',
'error_code' => substr($code, 0, 64),
'delete_presence_confirmations' => 0,
'delete_last_checked_at' => 0,
'delete_next_check_at' => time() + self::STABLE_SECONDS,
'updated_at' => time(),
]);
}
private static function markAttention(
string $templateId,
string $code
@ -721,8 +620,7 @@ final class CloudTemplateDeletionService
(string) $artifact->sha256,
(string) $template->sha256
)
&& (string) $artifact->object_key !== ''
&& (string) $artifact->object_etag !== '';
&& (int) ($artifact->storage_artifact_id ?? 0) > 0;
}
private static function lockedReplicas(string $templateId)

@ -3,6 +3,7 @@
namespace App\Services\Cloud;
use App\Models\CloudTemplateImportIntent;
use App\Models\CloudStoragePublication;
/** Cancels imports and performs bounded cleanup of expired intents. */
final class CloudTemplateImportCancellation extends CloudTemplateImportModule
@ -89,6 +90,20 @@ final class CloudTemplateImportCancellation extends CloudTemplateImportModule
$intent, CloudTemplateImportStateMachine::ACTION_CANCEL
);
if ((string) $intent->source_kind === 'remote') {
$publication = CloudStoragePublication::query()
->where('template_import_intent_id', (string) $intent->id)
->lockForUpdate()->first();
if ($publication instanceof CloudStoragePublication) {
// A downloaded remote source may already have crossed the
// storage publication boundary. Only the shared ledger can
// prove that no provider write occurred and retire both
// reserved replica keys without guessing.
return [
'done' => false,
'intent' => $intent,
'cleanup_only' => true,
];
}
CloudTemplateImportStateMachine::move(
$intent,
'cancelled'
@ -111,29 +126,11 @@ final class CloudTemplateImportCancellation extends CloudTemplateImportModule
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];
return [
'done' => false,
'intent' => $intent,
'cleanup_only' => true,
];
}
if ($state === 'prepared') {
throw new CloudError('尚未开始的导入包含异常上传会话', 409);
@ -162,10 +159,25 @@ final class CloudTemplateImportCancellation extends CloudTemplateImportModule
if (($prepared['done'] ?? false) === true) {
return CloudTemplateImportReadModel::project($intent);
}
if (($prepared['cleanup_only'] ?? false) === true) {
$cleanup = CloudTemplateStoragePublicationService::
cancelNeverDispatched($intent, $client);
if (($cleanup['deleted'] ?? false) !== true) {
throw new CloudError(
'模板对象存储预留仍在清理,请稍后重试取消',
409
);
}
return self::settleCancelled($id, $now);
}
if (($prepared['reconcile_first'] ?? false) === true) {
$evidence = $this->cancellationEvidence($intent, $client);
if ($evidence === 'absent') {
return self::settleCancelled($id, $now);
return $this->settleConfirmedAbort(
$intent,
$client,
$now
);
}
if ($evidence !== 'active') {
self::settleCancelUnknown($id, $evidence, $now);
@ -175,7 +187,10 @@ final class CloudTemplateImportCancellation extends CloudTemplateImportModule
);
}
}
$runtime = self::runtime($intent);
$runtime = CloudTemplateStoragePublicationService::primaryRuntime(
$intent,
false
);
try {
$client->abortMultipartUpload(
$runtime['config'],
@ -183,11 +198,31 @@ final class CloudTemplateImportCancellation extends CloudTemplateImportModule
(string) $intent->object_key,
(string) $intent->multipart_upload_id
);
return self::settleCancelled($id, $now);
$evidence = $this->cancellationEvidence($intent, $client);
if ($evidence === 'absent') {
return $this->settleConfirmedAbort(
$intent,
$client,
$now
);
}
$code = $evidence === 'active'
? 'multipart_abort_not_applied' : $evidence;
self::settleCancelUnknown($id, $code, $now);
throw new CloudError(
$evidence === 'active'
? '对象存储尚未终止分段上传,可以稍后重新取消'
: '无法确认原分段上传是否已终止,请勿重复取消',
$evidence === 'active' ? 409 : 502
);
} catch (CloudObjectStorageTransferError $error) {
$evidence = $this->cancellationEvidence($intent, $client);
if ($evidence === 'absent') {
return self::settleCancelled($id, $now);
return $this->settleConfirmedAbort(
$intent,
$client,
$now
);
}
$code = $evidence === 'active'
? 'multipart_abort_not_applied' : $evidence;
@ -205,7 +240,10 @@ final class CloudTemplateImportCancellation extends CloudTemplateImportModule
CloudTemplateImportIntent $intent,
CloudObjectStorageS3Client $client
): string {
$runtime = self::runtime($intent);
$runtime = CloudTemplateStoragePublicationService::primaryRuntime(
$intent,
false
);
try {
if ($client->inspectObject(
$runtime['config'],
@ -231,6 +269,22 @@ final class CloudTemplateImportCancellation extends CloudTemplateImportModule
}
}
private function settleConfirmedAbort(
CloudTemplateImportIntent $intent,
CloudObjectStorageS3Client $client,
int $now
): array {
$cleanup = CloudTemplateStoragePublicationService::
cancelAfterConfirmedAbort($intent, $client);
if (($cleanup['deleted'] ?? false) !== true) {
throw new CloudError(
'模板对象存储副本仍在清理,请稍后重试取消',
409
);
}
return self::settleCancelled((string) $intent->id, $now);
}
private static function settleCancelled(string $id, int $now): array
{
$connection = (new CloudTemplateImportIntent())->getConnection();
@ -240,7 +294,11 @@ final class CloudTemplateImportCancellation extends CloudTemplateImportModule
): array {
$intent = self::lockIntent($id);
if ((string) $intent->state !== 'cancelled') {
if ((string) $intent->state !== 'cancel_pending') {
if (!in_array((string) $intent->state,
[
'prepared', 'upload_failed', 'source_failed',
'fetching', 'cancel_pending',
], true)) {
throw new CloudError('上传取消状态已变化,请刷新页面', 409);
}
CloudTemplateImportStateMachine::move($intent, 'cancelled');

@ -16,20 +16,12 @@ abstract class CloudTemplateImportModule
public const MAX_UPLOAD_BYTES = 4294967296;
protected const INTENT_TTL_SECONDS = 86400;
protected const SOURCE_PURPOSE = 'template-import-source';
protected const RUNTIME_PURPOSE = 'template-import-runtime';
/** @var callable():array<string,mixed> */
protected $runtimeProvider;
/** @var callable():int */
protected $clock;
public function __construct(
?callable $runtimeProvider = null,
?callable $clock = null
) {
$this->runtimeProvider = $runtimeProvider
?? static fn (): array => CloudObjectStorageConfig::runtime(true);
public function __construct(?callable $clock = null)
{
$this->clock = $clock ?? time(...);
}
@ -43,40 +35,6 @@ abstract class CloudTemplateImportModule
return $intent;
}
protected static function runtime(CloudTemplateImportIntent $intent): array
{
$runtime = CloudSecrets::decrypt(
(string) $intent->sealed_storage_runtime,
self::RUNTIME_PURPOSE
);
$config = $runtime['config'] ?? null;
$credentials = $runtime['credentials'] ?? null;
$revision = $runtime['revision'] ?? null;
if (!is_array($config) || array_is_list($config)
|| !is_array($credentials) || array_is_list($credentials)
|| !is_int($revision) || $revision < 1
|| $revision !== (int) $intent->storage_revision) {
throw new CloudError('模板对象存储运行时无效', 503);
}
foreach (['endpoint', 'region', 'bucket', 'prefix'] as $field) {
if (!is_string($config[$field] ?? null)) {
throw new CloudError('模板对象存储运行时无效', 503);
}
}
if (!is_bool($config['path_style'] ?? null)
|| !is_string($credentials['access_key_id'] ?? null)
|| (string) $credentials['access_key_id'] === ''
|| !is_string($credentials['secret_access_key'] ?? null)
|| (string) $credentials['secret_access_key'] === '') {
throw new CloudError('模板对象存储运行时无效', 503);
}
return [
'config' => $config,
'credentials' => $credentials,
'revision' => $revision,
];
}
protected static function requestKey(array $actor): string
{
$key = $actor['request_idempotency_key'] ?? null;
@ -238,12 +196,4 @@ abstract class CloudTemplateImportModule
return $key;
}
protected static function runtimeRevision(array $runtime): int
{
$revision = $runtime['revision'] ?? null;
if (!is_int($revision) || $revision < 1) {
throw new CloudError('模板对象存储运行时无效', 503);
}
return $revision;
}
}

@ -66,6 +66,23 @@ final class CloudTemplateImportPublication extends CloudTemplateImportModule
?CloudObjectStorageS3Client $client = null
): array
{
$snapshot = CloudTemplateImportIntent::query()->where('id', $id)
->first();
if ($snapshot instanceof CloudTemplateImportIntent
&& (string) $snapshot->state === 'source_ready') {
$binding = CloudTemplateStoragePublicationService::binding(
$snapshot
);
if (($binding['protected'] ?? false) !== true) {
return [
'intent' => CloudTemplateImportReadModel::project(
$snapshot
),
'state' => 'waiting_protection',
'protection_pending' => true,
];
}
}
$connection = (new CloudTemplateImportIntent())->getConnection();
$prepared = $connection->transaction(static function () use (
$id
@ -127,8 +144,7 @@ final class CloudTemplateImportPublication extends CloudTemplateImportModule
}
CloudTemplateArtifactManager::adoptImportIntentLocked(
$template,
$intent,
self::runtime($intent)
$intent
);
return ['intent' => $intent, 'template' => $template];
}, 3);

@ -13,7 +13,7 @@ final class CloudTemplateImportReservation extends CloudTemplateImportModule
CloudAccess::manage($actor);
CloudInput::only($input, [
'name', 'os_family', 'os_version', 'filename', 'size_bytes',
'last_modified',
'last_modified', 'sha256',
]);
$userId = (int) ($actor['user_id'] ?? 0);
$requestKey = self::requestKey($actor);
@ -36,6 +36,13 @@ final class CloudTemplateImportReservation extends CloudTemplateImportModule
PHP_INT_MAX,
'云镜像文件时间无效'
);
$sha256 = strtolower(trim((string) ($input['sha256'] ?? '')));
if (preg_match('/^[a-f0-9]{64}$/D', $sha256) !== 1) {
throw new CloudError(
'开始上传前必须完成云镜像 SHA-256 校验',
422
);
}
$canonical = [
'source_kind' => 'upload',
'name' => $name,
@ -44,22 +51,21 @@ final class CloudTemplateImportReservation extends CloudTemplateImportModule
'filename' => $filename,
'size_bytes' => $size,
'last_modified' => $lastModified,
'sha256' => $sha256,
];
$fingerprint = self::fingerprint($canonical);
$runtime = ($this->runtimeProvider)();
$now = ($this->clock)();
if (!is_int($now) || $now < 1) {
throw new \LogicException('Template import clock is invalid');
}
try {
return $this->reserveUploadIntent(
$result = $this->reserveUploadIntent(
$actor,
$userId,
$requestKey,
$fingerprint,
$canonical,
$runtime,
$now
);
} catch (QueryException $error) {
@ -70,8 +76,17 @@ final class CloudTemplateImportReservation extends CloudTemplateImportModule
throw $error;
}
self::assertReplay($prior, $fingerprint);
return ['created' => false, 'intent' => CloudTemplateImportReadModel::project($prior)];
$result = [
'created' => false,
'intent' => CloudTemplateImportReadModel::project($prior),
];
}
$intent = CloudTemplateImportIntent::query()
->where('id', (string) $result['intent']['id'])->firstOrFail();
CloudTemplateStoragePublicationService::reserve($intent);
$intent->refresh();
$result['intent'] = CloudTemplateImportReadModel::project($intent);
return $result;
}
public function beginRemote(array $input, array $actor): array
@ -102,7 +117,6 @@ final class CloudTemplateImportReservation extends CloudTemplateImportModule
'sha256' => $expectedSha256,
];
$fingerprint = self::fingerprint($canonical);
$runtime = ($this->runtimeProvider)();
$now = ($this->clock)();
if (!is_int($now) || $now < 1) {
throw new \LogicException('Template import clock is invalid');
@ -118,7 +132,6 @@ final class CloudTemplateImportReservation extends CloudTemplateImportModule
$expectedSha256,
$family,
$version,
$runtime,
$now
): array {
$prior = CloudTemplateImportIntent::query()
@ -157,17 +170,10 @@ final class CloudTemplateImportReservation extends CloudTemplateImportModule
$intent->version_label = gmdate('Ymd-His', $now) . '-'
. substr($generation, 0, 8);
$intent->generation_token = $generation;
$intent->storage_revision = self::runtimeRevision($runtime);
$intent->sealed_storage_runtime = CloudSecrets::encrypt(
$runtime,
self::RUNTIME_PURPOSE
);
$intent->object_key =
CloudTemplateArtifactManager::plannedObjectKey(
$runtime,
$templateId,
$generation
);
$intent->storage_revision = 0;
$intent->sealed_storage_runtime = '{}';
$intent->object_key = 'pending-template-import/'
. (string) $intent->id;
$intent->multipart_upload_id = '';
$intent->multipart_part_size_bytes = 0;
$intent->multipart_part_count = 0;
@ -203,7 +209,6 @@ final class CloudTemplateImportReservation extends CloudTemplateImportModule
string $requestKey,
string $fingerprint,
array $canonical,
array $runtime,
int $now
): array {
$connection = (new CloudTemplateImportIntent())->getConnection();
@ -213,7 +218,6 @@ final class CloudTemplateImportReservation extends CloudTemplateImportModule
$requestKey,
$fingerprint,
$canonical,
$runtime,
$now
): array {
$prior = CloudTemplateImportIntent::query()
@ -243,7 +247,7 @@ final class CloudTemplateImportReservation extends CloudTemplateImportModule
$intent->source_size_bytes = (int) $canonical['size_bytes'];
$intent->source_last_modified =
(int) $canonical['last_modified'];
$intent->source_sha256 = '';
$intent->source_sha256 = (string) $canonical['sha256'];
$intent->sealed_source = CloudSecrets::encrypt([
'kind' => 'upload',
'filename' => (string) $canonical['filename'],
@ -258,17 +262,10 @@ final class CloudTemplateImportReservation extends CloudTemplateImportModule
$intent->version_label = gmdate('Ymd-His', $now) . '-'
. substr($generation, 0, 8);
$intent->generation_token = $generation;
$intent->storage_revision = self::runtimeRevision($runtime);
$intent->sealed_storage_runtime = CloudSecrets::encrypt(
$runtime,
self::RUNTIME_PURPOSE
);
$intent->object_key =
CloudTemplateArtifactManager::plannedObjectKey(
$runtime,
$templateId,
$generation
);
$intent->storage_revision = 0;
$intent->sealed_storage_runtime = '{}';
$intent->object_key = 'pending-template-import/'
. (string) $intent->id;
$intent->multipart_upload_id = '';
$intent->multipart_part_size_bytes = 0;
$intent->multipart_part_count = 0;

@ -11,6 +11,8 @@ final class CloudTemplateImportStateMachine
public const SOURCE_REMOTE = 'remote';
public const ACTION_START_UPLOAD = 'start_upload';
public const ACTION_RECONCILE_MULTIPART_START =
'reconcile_multipart_start';
public const ACTION_RECORD_PART = 'record_part';
public const ACTION_COMPLETE_UPLOAD = 'complete_upload';
public const ACTION_RESUME_REMOTE = 'resume_remote';
@ -148,10 +150,14 @@ final class CloudTemplateImportStateMachine
],
'source_unknown' => [
'resume_step' => 'verify',
'transitions' => ['source_verifying', 'cancel_pending'],
'transitions' => [
'uploading', 'source_verifying', 'cancel_pending',
],
'sources' => ['upload', 'remote'],
'actions' => [
'upload' => ['complete_upload', 'cancel'],
'upload' => [
'reconcile_multipart_start', 'complete_upload', 'cancel',
],
'remote' => ['resume_remote'],
],
'resumable' => ['upload', 'remote'],
@ -255,6 +261,10 @@ final class CloudTemplateImportStateMachine
&& !self::capabilities($intent)['can_cancel']) {
throw new CloudError('当前上传结果尚未确认,不能终止原分段上传', 409);
}
if ($action === self::ACTION_RECONCILE_MULTIPART_START
&& (string) $intent->multipart_upload_id !== '') {
throw new CloudError('原分段上传身份已存在,不能重新创建会话', 409);
}
}
public static function resumeStep(CloudTemplateImportIntent $intent): string
@ -324,6 +334,7 @@ final class CloudTemplateImportStateMachine
$sources = [self::SOURCE_UPLOAD, self::SOURCE_REMOTE];
$actions = [
self::ACTION_START_UPLOAD,
self::ACTION_RECONCILE_MULTIPART_START,
self::ACTION_RECORD_PART,
self::ACTION_COMPLETE_UPLOAD,
self::ACTION_RESUME_REMOTE,

@ -14,7 +14,6 @@ final class CloudTemplateMultipartAcquisition extends CloudTemplateImportModule
public function beginUpload(array $input, array $actor): array
{
return (new CloudTemplateImportReservation(
$this->runtimeProvider,
$this->clock
))->beginUpload($input, $actor);
}
@ -38,14 +37,12 @@ final class CloudTemplateMultipartAcquisition extends CloudTemplateImportModule
throw new CloudError('该导入记录不是本地上传', 409);
}
$state = (string) $intent->state;
if ($state === 'source_unknown') {
throw new CloudError(
'对象存储结果尚未确认,请先核对原上传结果',
409
);
}
CloudTemplateImportStateMachine::assertAction(
$intent, CloudTemplateImportStateMachine::ACTION_START_UPLOAD
$intent,
$state === 'source_unknown'
? CloudTemplateImportStateMachine::
ACTION_RECONCILE_MULTIPART_START
: CloudTemplateImportStateMachine::ACTION_START_UPLOAD
);
if ((string) $intent->multipart_upload_id !== '') {
if ($state === 'upload_failed') {
@ -66,6 +63,11 @@ final class CloudTemplateMultipartAcquisition extends CloudTemplateImportModule
}
if ($state === 'prepared' || $state === 'upload_failed') {
CloudTemplateImportStateMachine::move($intent, 'uploading');
} elseif ($state === 'source_unknown') {
// No upload ID means CreateMultipartUpload itself was
// ambiguous. The original storage operation now owns the
// only safe reconciliation/re-dispatch path.
CloudTemplateImportStateMachine::move($intent, 'uploading');
}
$intent->error_code = 'multipart_starting';
$intent->expires_at = $now + self::INTENT_TTL_SECONDS;
@ -75,61 +77,120 @@ final class CloudTemplateMultipartAcquisition extends CloudTemplateImportModule
}, 3);
/** @var CloudTemplateImportIntent $intent */
$intent = $prepared['intent'];
$runtime = self::runtime($intent);
$binding = CloudTemplateStoragePublicationService::binding($intent);
$work = CloudStorageArtifactService::claimPrimaryPreparation(
(string) $binding['operation_id'],
(int) $now
);
if (!is_array($work)) {
throw new CloudError(
'对象存储上传会话正在恢复,请稍后刷新',
409
);
}
$mode = (string) ($work['mode'] ?? '');
if (!in_array($mode, ['dispatch', 'reconcile', 'sign'], true)
|| (int) ($work['artifact_id'] ?? 0)
!== (int) $binding['artifact_id']) {
throw new CloudError('云模板对象存储准备账本不一致', 409);
}
$runtime = CloudObjectStorageBackendRegistry::runtime(
(int) $work['backend_id'],
$mode === 'dispatch'
);
try {
$plan = $prepared['create']
? $client->prepareMultipartUpload(
if ($mode === 'dispatch') {
$plan = $client->prepareKnownIdentityMultipartUpload(
$runtime['config'],
$runtime['credentials'],
(string) $intent->object_key,
(string) $work['object_key'],
(int) $intent->source_size_bytes,
(string) $intent->source_sha256,
$now,
self::INTENT_TTL_SECONDS
)
: $client->resumeMultipartUpload(
);
} elseif ($mode === 'sign') {
$plan = $client->resumeMultipartUpload(
$runtime['config'],
$runtime['credentials'],
(string) $intent->object_key,
(string) $intent->multipart_upload_id,
(string) $work['object_key'],
(string) $work['metadata']['upload_id'],
(int) $intent->source_size_bytes,
$now,
self::INTENT_TTL_SECONDS
);
} else {
$plan = self::reconcileMultipartPlan(
$client,
$runtime,
$work,
$intent,
$now
);
}
CloudStorageArtifactService::markPrimaryAwaitingReceipt(
(string) $work['operation_id'],
(string) $work['lease_token'],
self::storageMetadata($plan),
(int) $now
);
} catch (CloudObjectStorageTransferError $error) {
if ($prepared['create']) {
self::markUploadFailure(
$id,
if ($mode === 'dispatch' && !$error->effectMayHaveApplied) {
CloudStorageArtifactService::deferPrimaryPreparation(
(string) $work['operation_id'],
(string) $work['lease_token'],
$error->publicCode,
$error->effectMayHaveApplied,
$now
(int) $now,
300
);
} else {
CloudStorageArtifactService::markPrimaryPreparationUnknown(
(string) $work['operation_id'],
(string) $work['lease_token'],
$error->publicCode,
(int) $now,
60,
is_array($work['metadata'] ?? null)
? $work['metadata'] : []
);
}
throw new CloudError($error->getMessage(), 502);
}
if ($prepared['create']) {
$intent = $connection->transaction(static function () use (
self::markUploadFailure(
$id,
$plan,
$error->publicCode,
$error->effectMayHaveApplied,
$now
): CloudTemplateImportIntent {
$locked = self::lockIntent($id);
if ((string) $locked->state !== 'uploading'
|| (string) $locked->multipart_upload_id !== '') {
throw new CloudError('上传会话状态已变化,请刷新页面', 409);
}
$locked->multipart_upload_id = (string) $plan['upload_id'];
$locked->multipart_part_size_bytes =
(int) $plan['part_size_bytes'];
$locked->multipart_part_count = count($plan['part_urls']);
$locked->error_code = '';
$locked->expires_at = (int) $plan['expires_at'];
$locked->updated_at = $now;
$locked->save();
return $locked;
}, 3);
} else {
$intent->refresh();
);
throw new CloudError($error->getMessage(), 502);
}
$intent = $connection->transaction(static function () use (
$id,
$plan,
$now
): CloudTemplateImportIntent {
$locked = self::lockIntent($id);
if ((string) $locked->state !== 'uploading'
|| ((string) $locked->multipart_upload_id !== ''
&& !hash_equals(
(string) $locked->multipart_upload_id,
(string) $plan['upload_id']
))) {
throw new CloudError('上传会话状态已变化,请刷新页面', 409);
}
$locked->multipart_upload_id = (string) $plan['upload_id'];
$locked->multipart_part_size_bytes =
(int) $plan['part_size_bytes'];
$locked->multipart_part_count = count($plan['part_urls']);
$locked->error_code = '';
$locked->expires_at = (int) $plan['expires_at'];
$locked->updated_at = $now;
$locked->save();
return $locked;
}, 3);
CloudStorageArtifactService::releasePrimaryPreparationLease(
(string) $work['operation_id'],
(string) $work['lease_token'],
(int) $now
);
return self::uploadPlanDto($intent, $plan);
}
@ -220,7 +281,11 @@ final class CloudTemplateMultipartAcquisition extends CloudTemplateImportModule
}
/** @var CloudTemplateImportIntent $intent */
$intent = $snapshot['intent'];
$runtime = self::runtime($intent);
$binding = CloudTemplateStoragePublicationService::binding($intent);
$runtime = CloudObjectStorageBackendRegistry::runtime(
(int) $binding['backend_id'],
false
);
$providerParts = null;
if (($snapshot['reconcile'] ?? false) === true) {
try {
@ -242,6 +307,18 @@ final class CloudTemplateMultipartAcquisition extends CloudTemplateImportModule
);
}
if ($identity !== null) {
self::assertCompletedIdentity($intent, $identity, $sha256);
CloudStorageArtifactService::completePrimary(
(string) $binding['operation_id'],
(int) $binding['artifact_id'],
[
'size_bytes' => (int) $identity['size_bytes'],
'sha256' => (string) $identity['sha256'],
'etag' => (string) $identity['etag'],
'version_id' =>
(string) ($identity['version_id'] ?? ''),
]
);
$this->publication()->acceptCompletedIdentity($id, $identity);
return $this->publication()->finalizeReadyIntent($id, $actor, $client);
}
@ -406,18 +483,27 @@ final class CloudTemplateMultipartAcquisition extends CloudTemplateImportModule
);
}
}
if ((int) ($identity['size_bytes'] ?? 0)
!== (int) $intent->source_size_bytes
|| !is_string($identity['etag'] ?? null)
|| trim((string) $identity['etag']) === '') {
try {
self::assertCompletedIdentity($intent, $identity, $sha256);
} catch (CloudError $error) {
self::finishSourceFailure(
$id,
'source_unknown',
'multipart_object_identity_mismatch',
$now
);
throw new CloudError('上传对象身份与导入意图不一致,记录已锁定', 409);
throw $error;
}
CloudStorageArtifactService::completePrimary(
(string) $binding['operation_id'],
(int) $binding['artifact_id'],
[
'size_bytes' => (int) $identity['size_bytes'],
'sha256' => (string) $identity['sha256'],
'etag' => (string) $identity['etag'],
'version_id' => (string) ($identity['version_id'] ?? ''),
]
);
$this->publication()->acceptCompletedIdentity($id, $identity);
return $this->publication()->finalizeReadyIntent($id, $actor, $client);
}
@ -555,6 +641,222 @@ final class CloudTemplateMultipartAcquisition extends CloudTemplateImportModule
}, 3);
}
private static function assertCompletedIdentity(
CloudTemplateImportIntent $intent,
array $identity,
string $sha256
): void {
$providerSha = $identity['sha256'] ?? null;
if ((int) ($identity['size_bytes'] ?? 0)
!== (int) $intent->source_size_bytes
|| !is_string($providerSha)
|| !hash_equals($sha256, $providerSha)
|| !hash_equals((string) $intent->source_sha256, $providerSha)
|| !is_string($identity['etag'] ?? null)
|| trim((string) $identity['etag']) === '') {
throw new CloudError(
'上传对象身份与导入意图不一致,记录已锁定',
409
);
}
}
/**
* Recover only the unique multipart session for the frozen primary key.
* No new upload is created from a reconciliation claim.
*
* @param array<string,mixed> $runtime
* @param array<string,mixed> $work
* @return array<string,mixed>
*/
private static function reconcileMultipartPlan(
CloudObjectStorageS3Client $client,
array $runtime,
array $work,
CloudTemplateImportIntent $intent,
int $now
): array {
$metadata = is_array($work['metadata'] ?? null)
? $work['metadata'] : [];
$object = $client->inspectObject(
$runtime['config'],
$runtime['credentials'],
(string) $work['object_key']
);
if ($object !== null) {
try {
self::assertCompletedIdentity(
$intent,
$object,
(string) $intent->source_sha256
);
} catch (CloudError) {
self::recordMultipartAttention(
$work,
'primary_multipart_identity_mismatch',
$now
);
}
CloudStorageArtifactService::completePrimary(
(string) $work['operation_id'],
(int) $work['artifact_id'],
[
'size_bytes' => (int) $object['size_bytes'],
'sha256' => (string) $object['sha256'],
'etag' => (string) $object['etag'],
'version_id' =>
(string) ($object['version_id'] ?? ''),
]
);
(new CloudTemplateImportIntent())->getConnection()->transaction(
static function () use ($intent): void {
$locked = self::lockIntent((string) $intent->id);
if ((string) $locked->state === 'uploading') {
CloudTemplateImportStateMachine::move(
$locked,
'source_verifying'
);
$locked->updated_at = time();
$locked->save();
}
},
3
);
(new CloudTemplateImportPublication())
->acceptCompletedIdentity((string) $intent->id, $object);
throw new CloudError(
'原模板对象已完成,正在等待双副本保护',
409
);
}
$sessions = $client->findMultipartUploadsByExactObjectKey(
$runtime['config'],
$runtime['credentials'],
(string) $work['object_key']
);
if ($sessions === []) {
$metadata['absence_confirmations'] = min(
2,
(int) ($metadata['absence_confirmations'] ?? 0) + 1
);
$metadata['multipart_absence_confirmations'] = min(
2,
(int) ($metadata['multipart_absence_confirmations'] ?? 0)
+ 1
);
if ($metadata['absence_confirmations'] >= 2
&& $metadata['multipart_absence_confirmations'] >= 2) {
CloudStorageArtifactService::
reschedulePrimaryAfterStableAbsence(
(string) $work['operation_id'],
(string) $work['lease_token'],
$metadata,
$now,
60
);
throw new CloudError(
'已确认原上传未发生,将在原对象路径安全重试',
409
);
}
CloudStorageArtifactService::markPrimaryPreparationUnknown(
(string) $work['operation_id'],
(string) $work['lease_token'],
'template_multipart_absence_unconfirmed',
$now,
60,
$metadata
);
throw new CloudError(
'正在核对原模板上传是否发生,请稍后重试',
409
);
}
if (count($sessions) !== 1) {
self::recordMultipartAttention(
$work,
'primary_multipart_identity_ambiguous',
$now
);
}
$uploadId = $sessions[0]['upload_id'] ?? null;
if (!is_string($uploadId) || $uploadId === ''
|| ((string) $intent->multipart_upload_id !== ''
&& !hash_equals(
(string) $intent->multipart_upload_id,
$uploadId
))) {
self::recordMultipartAttention(
$work,
'primary_multipart_identity_mismatch',
$now
);
}
return $client->resumeMultipartUpload(
$runtime['config'],
$runtime['credentials'],
(string) $work['object_key'],
$uploadId,
(int) $intent->source_size_bytes,
$now,
self::INTENT_TTL_SECONDS
);
}
/** @return array<string,int|string> */
private static function storageMetadata(array $plan): array
{
return [
'upload_id' => (string) $plan['upload_id'],
'part_size_bytes' => (int) $plan['part_size_bytes'],
'part_count' => count($plan['part_urls']),
'maximum_size_bytes' => (int) $plan['maximum_size_bytes'],
'absence_confirmations' => 0,
'multipart_absence_confirmations' => 0,
'multipart_presence_confirmations' => 0,
'multipart_attention_confirmations' => 0,
];
}
/** @return never */
private static function recordMultipartAttention(
array $work,
string $code,
int $now
): void {
$metadata = is_array($work['metadata'] ?? null)
? $work['metadata'] : [];
$same = ($metadata['multipart_attention_error_code'] ?? '')
=== $code;
$metadata['multipart_attention_error_code'] = $code;
$metadata['multipart_attention_confirmations'] = $same
? min(2, (int) ($metadata[
'multipart_attention_confirmations'] ?? 0) + 1)
: 1;
if ($metadata['multipart_attention_confirmations'] >= 2) {
CloudStorageArtifactService::markPrimaryPreparationAttention(
(string) $work['operation_id'],
(string) $work['lease_token'],
$code,
$now,
$metadata
);
throw new CloudError(
'模板上传会话身份冲突,需要管理员核对',
409
);
}
CloudStorageArtifactService::markPrimaryPreparationUnknown(
(string) $work['operation_id'],
(string) $work['lease_token'],
$code,
$now,
60,
$metadata
);
throw new CloudError('正在复核模板上传会话身份,请稍后重试', 409);
}
private static function uploadPlanDto(
CloudTemplateImportIntent $intent,
array $plan
@ -643,9 +945,6 @@ final class CloudTemplateMultipartAcquisition extends CloudTemplateImportModule
private function publication(): CloudTemplateImportPublication
{
return new CloudTemplateImportPublication(
$this->runtimeProvider,
$this->clock
);
return new CloudTemplateImportPublication($this->clock);
}
}

@ -49,23 +49,33 @@ final class CloudTemplateRemoteAcquisition extends CloudTemplateImportModule
}
/** @var CloudTemplateImportIntent $intent */
$intent = $snapshot['intent'];
try {
$runtime = self::runtime($intent);
} catch (CloudError $error) {
self::finishRemoteFailure(
$id,
'source_failed',
'remote_storage_runtime_invalid',
(int) ($this->clock)()
);
throw $error;
}
$transport = new CloudImmutableArtifactTransport($client);
if (($snapshot['reconcile'] ?? false) === true) {
try {
$identity = $transport->inspect(
$runtime,
(string) $intent->object_key
$binding = CloudTemplateStoragePublicationService::binding(
$intent
);
/** @var \App\Models\CloudStorageOperation $operation */
$operation = $binding['operation'];
if ((string) $operation->phase === 'accepted') {
self::makeRemoteRetryable(
$id,
(int) ($this->clock)()
);
return $this->acquireRemote(
$id,
$actor,
$fetcher,
$client
);
}
$result = CloudTemplateStoragePublicationService::publishFile(
$intent,
[
'path' => '',
'size_bytes' => (int) $intent->source_size_bytes,
'sha256' => (string) $intent->source_sha256,
],
$client
);
} catch (\Throwable $error) {
self::finishRemoteFailure(
@ -79,16 +89,28 @@ final class CloudTemplateRemoteAcquisition extends CloudTemplateImportModule
502
);
}
if ($identity !== null) {
if (($result['primary_completed'] ?? false) === true) {
$identity = CloudTemplateStoragePublicationService::
primaryIdentity($intent);
$this->publication()->acceptCompletedIdentity($id, $identity);
return $this->publication()->finalizeReadyIntent($id, $actor, $client);
}
self::makeRemoteRetryable($id, (int) ($this->clock)());
return $this->acquireRemote(
$id,
$actor,
$fetcher,
$client
if (($result['requires_attention'] ?? false) === true) {
self::finishRemoteFailure(
$id,
'source_unknown',
(string) ($result['error_code']
?? 'remote_source_publish_attention'),
(int) ($this->clock)()
);
throw new CloudError(
'官方云镜像发布需要管理员核对,请勿创建新的导入',
409
);
}
throw new CloudError(
'官方云镜像发布结果仍在核对,请稍后重试原导入',
409
);
}
@ -126,14 +148,16 @@ final class CloudTemplateRemoteAcquisition extends CloudTemplateImportModule
}
$this->freezeRemoteFileIdentity($id, (int) $size, $digest);
$intent->refresh();
$publication = $transport->publish(
$runtime,
(string) $intent->object_key,
CloudTemplateStoragePublicationService::reserve($intent);
$intent->refresh();
$publication = CloudTemplateStoragePublicationService::publishFile(
$intent,
[
'path' => (string) $file['path'],
'size_bytes' => (int) $size,
'sha256' => $digest,
]
],
$client
);
} catch (CloudError $error) {
self::finishRemoteFailure(
@ -161,28 +185,28 @@ final class CloudTemplateRemoteAcquisition extends CloudTemplateImportModule
}
}
$resolution = (string) ($publication['resolution'] ?? 'unknown');
$identity = $publication['identity'] ?? null;
if ($resolution !== 'applied' || !is_array($identity)) {
if (($publication['primary_completed'] ?? false) !== true) {
$attention = ($publication['requires_attention'] ?? false) === true;
$code = (string) ($publication['error_code']
?? 'remote_source_publish_failed');
$next = $resolution === 'not_applied'
? 'source_failed' : 'source_unknown';
?? ($attention
? 'remote_source_publish_attention'
: 'remote_source_publish_pending'));
self::finishRemoteFailure(
$id,
$next,
$attention ? 'source_unknown' : 'source_failed',
$code,
(int) ($this->clock)()
);
throw new CloudError(
$resolution === 'conflict'
? '官方云镜像对象身份冲突,记录已锁定'
: ($resolution === 'not_applied'
? '对象存储已确认官方云镜像尚未保存,可以重试'
: '无法确认官方云镜像是否已保存,请勿创建新的导入'),
$resolution === 'conflict' ? 409 : 502
$attention
? '官方云镜像发布需要管理员核对,请勿创建新的导入'
: '官方云镜像主副本尚未完成,可以从原导入记录重试',
$attention ? 409 : 502
);
}
$identity = CloudTemplateStoragePublicationService::primaryIdentity(
$intent
);
$this->publication()->acceptCompletedIdentity($id, $identity);
return $this->publication()->finalizeReadyIntent($id, $actor, $client);
}
@ -338,17 +362,11 @@ final class CloudTemplateRemoteAcquisition extends CloudTemplateImportModule
private function reservation(): CloudTemplateImportReservation
{
return new CloudTemplateImportReservation(
$this->runtimeProvider,
$this->clock
);
return new CloudTemplateImportReservation($this->clock);
}
private function publication(): CloudTemplateImportPublication
{
return new CloudTemplateImportPublication(
$this->runtimeProvider,
$this->clock
);
return new CloudTemplateImportPublication($this->clock);
}
}

@ -0,0 +1,49 @@
<?php
namespace App\Services\Cloud;
use App\Models\CloudTemplateImportIntent;
/** Continues template business publication after required storage copies exist. */
final class CloudTemplateStoragePublicationConsumer
{
public function finalizeReady(string $intentId): bool
{
if (preg_match('/^[a-f0-9]{32}$/D', $intentId) !== 1) {
throw new CloudError('云模板发布归属标识无效', 422);
}
$connection = (new CloudTemplateImportIntent())->getConnection();
return $connection->transaction(static function () use (
$intentId
): bool {
$intent = CloudTemplateImportIntent::query()
->where('id', $intentId)->lockForUpdate()->first();
if (!$intent instanceof CloudTemplateImportIntent) {
throw new CloudError('云模板发布归属记录不存在', 409);
}
if ((string) $intent->state !== 'source_ready') {
if (in_array((string) $intent->state,
['distributing', 'ready', 'distribution_failed'], true)) {
return false;
}
throw new CloudError(
'云模板发布归属状态不允许最终化',
409
);
}
(new CloudTemplateImportPublication())->finalizeReadyIntent(
(string) $intent->id,
[
'user_id' => (int) $intent->user_id,
'is_admin' => true,
'is_super_admin' => true,
'can_manage' => true,
'session_id' => 'template-storage-publication',
'request_idempotency_key' =>
'template-import-' . (string) $intent->id,
]
);
return true;
}, 3);
}
}

@ -0,0 +1,288 @@
<?php
namespace App\Services\Cloud;
use App\Models\CloudStorageArtifact;
use App\Models\CloudStorageBackend;
use App\Models\CloudStorageOperation;
use App\Models\CloudStoragePublication;
use App\Models\CloudStorageReplica;
use App\Models\CloudTemplateImportIntent;
/**
* Template-owned facade over the shared immutable storage publication ledger.
*
* The import intent is the business owner. Its storage artifact and both
* provider placements are frozen before the first provider write. Legacy
* runtime columns remain schema-only fields and never carry credentials on
* this clean-break path.
*/
final class CloudTemplateStoragePublicationService
{
/** @return array<string,mixed> */
public static function reserve(
CloudTemplateImportIntent $intent
): array {
self::assertIntentIdentity($intent);
$requestKey = 'template-storage-' . (string) $intent->id;
$fingerprint = hash('sha256', implode('|', [
(string) $intent->id,
(string) $intent->template_id,
(string) $intent->generation_token,
(string) $intent->source_size_bytes,
(string) $intent->source_sha256,
]));
$view = CloudStorageArtifactService::beginPublication(
'template',
self::objectSuffix($intent),
(int) $intent->source_size_bytes,
(string) $intent->source_sha256,
$requestKey,
$fingerprint,
['template_import_intent_id' => (string) $intent->id]
);
self::syncIntentProjection((string) $intent->id, $view);
return $view;
}
/** @return array<string,mixed> */
public static function binding(
CloudTemplateImportIntent|string $intent
): array {
$intent = is_string($intent)
? CloudTemplateImportIntent::query()->where('id', $intent)->first()
: $intent;
if (!$intent instanceof CloudTemplateImportIntent) {
throw new CloudError('云镜像导入记录不存在', 404);
}
self::assertIntentIdentity($intent);
$publication = CloudStoragePublication::query()
->where('template_import_intent_id', (string) $intent->id)
->first();
if (!$publication instanceof CloudStoragePublication) {
throw new CloudError('云模板缺少对象存储发布意图', 409);
}
$artifact = CloudStorageArtifact::query()
->whereKey((int) $publication->artifact_id)->first();
$operation = CloudStorageOperation::query()
->where('artifact_id', (int) $publication->artifact_id)
->where('kind', 'publish')->first();
$replica = $operation instanceof CloudStorageOperation
? CloudStorageReplica::query()
->whereKey((int) $operation->replica_id)->first()
: null;
if (!$artifact instanceof CloudStorageArtifact
|| !$operation instanceof CloudStorageOperation
|| !$replica instanceof CloudStorageReplica
|| (string) $artifact->kind !== 'template'
|| (int) $artifact->size_bytes
!== (int) $intent->source_size_bytes
|| !hash_equals(
(string) $artifact->sha256,
(string) $intent->source_sha256
)
|| (int) $replica->artifact_id !== (int) $artifact->id
|| (string) $replica->role !== 'primary') {
throw new CloudError('云模板对象存储发布账本不一致', 409);
}
return [
'intent' => $intent,
'publication' => $publication,
'artifact' => $artifact,
'operation' => $operation,
'replica' => $replica,
'operation_id' => (string) $operation->operation_id,
'artifact_id' => (int) $artifact->id,
'backend_id' => (int) $replica->backend_id,
'object_key' => (string) $replica->object_key,
'protected' => (string) $artifact->state === 'protected'
&& in_array((string) $publication->state,
['ready_to_finalize', 'completed'], true),
];
}
/** @return array<string,mixed> */
public static function primaryRuntime(
CloudTemplateImportIntent|string $intent,
bool $requireHealthy
): array {
$binding = self::binding($intent);
return CloudObjectStorageBackendRegistry::runtime(
(int) $binding['backend_id'],
$requireHealthy
);
}
/** @return array{size_bytes:int,sha256:string,etag:string,version_id:string} */
public static function primaryIdentity(
CloudTemplateImportIntent|string $intent
): array {
$binding = self::binding($intent);
/** @var CloudStorageArtifact $artifact */
$artifact = $binding['artifact'];
/** @var CloudStorageReplica $replica */
$replica = $binding['replica'];
if ((string) $replica->state !== 'ready'
|| (int) $replica->size_bytes !== (int) $artifact->size_bytes
|| !hash_equals(
(string) $replica->sha256,
(string) $artifact->sha256
)
|| trim((string) $replica->object_etag) === '') {
throw new CloudError('云模板对象存储主副本尚未就绪', 409);
}
return [
'size_bytes' => (int) $replica->size_bytes,
'sha256' => (string) $replica->sha256,
'etag' => (string) $replica->object_etag,
'version_id' => (string) $replica->object_version_id,
];
}
/**
* @param array{path:string,size_bytes:int,sha256:string} $file
* @return array<string,mixed>
*/
public static function publishFile(
CloudTemplateImportIntent $intent,
array $file,
?CloudObjectStorageS3Client $client = null
): array {
$binding = self::binding($intent);
return (new CloudStorageImmutablePrimaryPublication($client))->publish(
(string) $binding['operation_id'],
(int) $binding['artifact_id'],
$file
);
}
/** @return array<string,mixed> */
public static function cancelNeverDispatched(
CloudTemplateImportIntent $intent,
?CloudObjectStorageS3Client $client = null
): array {
$binding = self::binding($intent);
$owner = ['template_import_intent_id' => (string) $intent->id];
$deletion = new CloudStorageArtifactDeletionService($client);
$deletion->prepareNeverDispatched(
(int) $binding['artifact_id'],
$owner
);
return $deletion->process(
(int) $binding['artifact_id'],
$owner
);
}
/** @return array<string,mixed> */
public static function cancelAfterConfirmedAbort(
CloudTemplateImportIntent $intent,
?CloudObjectStorageS3Client $client = null
): array {
$binding = self::binding($intent);
/** @var CloudStorageOperation $operation */
$operation = $binding['operation'];
if ((string) $operation->phase !== 'terminal') {
CloudStorageArtifactService::failPrimary(
(string) $binding['operation_id'],
(int) $binding['artifact_id'],
'not_applied',
'template_multipart_abort_confirmed'
);
} elseif ((string) $operation->outcome !== 'failed'
|| (string) $operation->effect_resolution !== 'not_applied') {
throw new CloudError(
'模板主副本发布结果不允许按未应用取消',
409
);
}
return (new CloudStorageArtifactDeletionService($client))->process(
(int) $binding['artifact_id'],
['template_import_intent_id' => (string) $intent->id]
);
}
/** @param array<string,mixed> $view */
private static function syncIntentProjection(
string $intentId,
array $view
): void {
$artifactId = filter_var($view['artifact_id'] ?? null,
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
$backendId = filter_var($view['backend_id'] ?? null,
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
$objectKey = $view['object_key'] ?? null;
if ($artifactId === false || $backendId === false
|| !is_string($objectKey) || trim($objectKey) === '') {
throw new CloudError('云模板对象存储预留回执无效', 502);
}
$backend = CloudStorageBackend::query()->whereKey($backendId)->first();
if (!$backend instanceof CloudStorageBackend) {
throw new CloudError('云模板对象存储后端不存在', 409);
}
(new CloudTemplateImportIntent())->getConnection()->transaction(
static function () use (
$intentId,
$objectKey,
$backend
): void {
$intent = CloudTemplateImportIntent::query()
->where('id', $intentId)->lockForUpdate()->first();
if (!$intent instanceof CloudTemplateImportIntent) {
throw new CloudError('云镜像导入记录不存在', 404);
}
$expected = self::objectSuffix($intent);
if (!str_ends_with($objectKey, $expected)) {
throw new CloudError('云模板对象存储路径不一致', 409);
}
$intent->storage_revision =
(int) $backend->config_revision;
// Non-null legacy schema column only. All storage authority,
// including backend choice, lives in publication/replica rows.
$intent->sealed_storage_runtime = '{}';
$intent->object_key = $objectKey;
$intent->updated_at = time();
$intent->save();
},
3
);
}
private static function objectSuffix(
CloudTemplateImportIntent $intent
): string {
self::assertTemplateIdentity(
(string) $intent->template_id,
(string) $intent->generation_token
);
return 'cloud-templates/' . (string) $intent->template_id . '/'
. (string) $intent->generation_token . '/system.qcow2';
}
private static function assertIntentIdentity(
CloudTemplateImportIntent $intent
): void {
if (!$intent->exists
|| preg_match('/^[a-f0-9]{32}$/D', (string) $intent->id) !== 1
|| (int) $intent->source_size_bytes < 1
|| preg_match('/^[a-f0-9]{64}$/D',
(string) $intent->source_sha256) !== 1) {
throw new CloudError('云模板对象存储制品身份无效', 409);
}
self::assertTemplateIdentity(
(string) $intent->template_id,
(string) $intent->generation_token
);
}
private static function assertTemplateIdentity(
string $templateId,
string $generationToken
): void {
if (preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/D', $templateId)
!== 1
|| preg_match('/^[a-f0-9]{32}$/D', $generationToken) !== 1) {
throw new CloudError('云模板对象存储制品身份无效', 422);
}
}
}

@ -683,9 +683,15 @@ async function importTemplate(event) {
clearRemoteImportRecord(record);
byId('template-import').reset();
await templateUploadController?.refresh();
if (importProgress(result, '导入云镜像', async () => {
if (result?.protection_pending === true) {
notice('官方镜像主副本已保存,正在建立第二份对象存储副本。');
} else if (importProgress(result, '导入云镜像', async () => {
await loadCatalog(); notice('镜像导入已完成。');
})) notice('官方镜像已保存,宿主机分发任务已接收。');
})) {
notice('官方镜像已保存,宿主机分发任务已接收。');
} else {
throw new Error('面板返回了无效的模板发布状态。');
}
}
catch (error) {
await templateUploadController?.refresh();

@ -298,14 +298,21 @@ export function mountTemplateUpload(options) {
if (busy() || activeController) return;
setBusy(true); resume.disabled = true;
try {
const task = await requestRuntime.mutate(
const result = await requestRuntime.mutate(
`/api/v1/admin/cloud-template-imports/${encodeURIComponent(intent.id)}/resume`,
{ method: 'POST', body: {}, response: 'task',
{ method: 'POST', body: {},
timeoutMs: 3600000,
idempotencyKey: `template-remote-resume-${intent.id}` }
);
onRemoteSettled?.();
onTask(task, 'remote');
const task = taskReceipt(result);
if (task) {
onTask(task, 'remote');
} else if (result?.protection_pending === true) {
notice('官方镜像主副本已保存,正在建立第二份对象存储副本。');
} else {
throw new Error('面板返回了无效的模板发布状态。');
}
} catch (error) {
notice(error instanceof Error ? error.message : '继续导入失败。', true);
} finally {
@ -397,9 +404,17 @@ export function mountTemplateUpload(options) {
renderProgress(0, file.size, 0);
notice('正在建立受控上传记录并计算 SHA-256…');
try {
activeHash = beginFileHash(file, (loaded, total) => {
hashedBytes = loaded;
renderProgress(uploadedBytes, total, hashedBytes);
}, WorkerImpl);
const sha256 = await activeHash.promise;
hashedBytes = file.size;
renderProgress(uploadedBytes, file.size, hashedBytes);
const fingerprint = await uploadFingerprint({
name, osFamily, osVersion, filename: file.name,
size: file.size, lastModified: Number(file.lastModified || 0),
sha256,
}, cryptoImpl);
const storageKey = STORAGE_PREFIX + fingerprint;
const record = readRecord(storage, storageKey, cryptoImpl);
@ -413,6 +428,7 @@ export function mountTemplateUpload(options) {
filename: file.name,
size_bytes: file.size,
last_modified: Number(file.lastModified || 0),
sha256,
},
idempotencyKey: record.requestKey,
signal: activeController.signal,
@ -430,14 +446,13 @@ export function mountTemplateUpload(options) {
onTask(existingTask);
return;
}
activeHash = beginFileHash(file, (loaded, total) => {
hashedBytes = loaded;
renderProgress(uploadedBytes, total, hashedBytes);
}, WorkerImpl);
if (!['source_ready', 'source_verifying', 'source_unknown'].includes(
String(intent.state || '')
)) {
const state = String(intent.state || '');
const unknownCreate = state === 'source_unknown'
&& Number(intent.part_count || 0) === 0;
if (unknownCreate
|| !['source_ready', 'source_verifying', 'source_unknown'].includes(
state
)) {
const plan = await requestRuntime.mutate(
`/api/v1/admin/cloud-template-imports/${encodeURIComponent(intent.id)}/upload`, {
method: 'POST', body: {}, signal: activeController.signal,
@ -482,21 +497,26 @@ export function mountTemplateUpload(options) {
renderProgress(uploadedBytes, file.size, hashedBytes);
}
notice('对象存储上传完成,正在等待 SHA-256 校验…');
const sha256 = await activeHash.promise;
hashedBytes = file.size;
notice('对象存储上传完成,正在核对制品身份…');
renderProgress(file.size, file.size, hashedBytes);
notice('正在核对对象存储分片并创建宿主机分发任务…');
const task = await requestRuntime.mutate(
const result = await requestRuntime.mutate(
`/api/v1/admin/cloud-template-imports/${encodeURIComponent(intent.id)}/complete`, {
method: 'POST', body: { sha256 }, response: 'task',
method: 'POST', body: { sha256 },
signal: activeController.signal,
idempotencyKey: `${record.requestKey}.complete`,
}
);
clearRecord(storage, storageKey);
fileInput.value = '';
onTask(task);
const task = taskReceipt(result);
if (task) {
onTask(task);
} else if (result?.protection_pending === true) {
notice('镜像上传已完成,正在建立第二份对象存储副本。');
} else {
throw new Error('面板返回了无效的模板发布状态。');
}
} catch (error) {
activeHash?.cancel();
await activeHash?.promise.catch(() => {});

@ -0,0 +1,79 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\Cloud\CloudObjectStorageS3Client;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Promise\Create;
use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\RequestInterface;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$sha256 = str_repeat('a', 64);
$requests = [];
$handler = static function (RequestInterface $request) use (
&$requests,
$sha256
) {
$requests[] = $request;
if ($request->getMethod() === 'POST') {
return Create::promiseFor(new Response(200, [],
'<InitiateMultipartUploadResult><UploadId>upload-1'
. '</UploadId></InitiateMultipartUploadResult>'));
}
return Create::promiseFor(new Response(200, [
'Content-Length' => '1048576',
'ETag' => '"known-etag"',
'x-amz-version-id' => 'known-version',
'x-amz-meta-virt-sha256' => $sha256,
]));
};
$client = new CloudObjectStorageS3Client(new Client([
'handler' => HandlerStack::create($handler),
]));
$config = [
'endpoint' => 'https://objects.example.com',
'region' => 'ewr',
'bucket' => 'template-bucket',
'prefix' => 'virt-cloud',
'path_style' => true,
];
$credentials = [
'access_key_id' => 'TEMPLATEACCESSKEY',
'secret_access_key' => 'template-secret',
];
$key = 'virt-cloud/cloud-templates/template/generation/system.qcow2';
$plan = $client->prepareKnownIdentityMultipartUpload(
$config,
$credentials,
$key,
1048576,
$sha256,
1793894400,
3600
);
$create = $requests[0] ?? null;
$assert($create instanceof RequestInterface
&& $create->getHeaderLine('x-amz-meta-virt-sha256') === $sha256
&& str_contains(
$create->getHeaderLine('Authorization'),
'x-amz-meta-virt-sha256'
), 'Known multipart creation did not sign immutable SHA metadata.');
$assert(($plan['upload_id'] ?? '') === 'upload-1'
&& ($plan['maximum_size_bytes'] ?? 0) === 1048576,
'Known multipart upload plan was not created.');
$identity = $client->inspectObject($config, $credentials, $key);
$assert(($identity['sha256'] ?? '') === $sha256
&& ($identity['size_bytes'] ?? 0) === 1048576
&& ($identity['version_id'] ?? '') === 'known-version',
'Known multipart HEAD did not preserve immutable identity.');
echo "Known-identity multipart publication passed.\n";

@ -1,314 +1,71 @@
<?php
namespace App\Services {
final class Config
{
public static string $key = '';
public static function get($name, $default = null)
{
return $name === 'cloud_data_key' ? self::$key : $default;
}
$root = dirname(__DIR__);
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\CloudTemplate;
use App\Models\CloudTemplateArtifact;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudObjectStorageS3Client;
use App\Services\Cloud\CloudTemplateArtifactManager;
use App\Services\Config;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
Config::$key = base64_encode(str_repeat('t', 32));
$capsule = new Capsule();
$capsule->addConnection([
'driver' => 'sqlite', 'database' => ':memory:',
], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$capsule->schema('default')->create('cloud_templates',
static function (Blueprint $table): void {
$table->string('id')->primary();
$table->string('catalog_key');
$table->string('version_label');
$table->boolean('is_default')->default(false);
$table->string('name');
$table->string('os_family');
$table->string('os_version');
$table->integer('image_bytes');
$table->string('sha256');
$table->text('startup_script');
$table->integer('revision');
$table->string('generation_token');
$table->string('state');
$table->integer('active_job_id')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
});
$capsule->schema('default')->create('cloud_template_artifacts',
static function (Blueprint $table): void {
$table->string('template_id')->primary();
$table->integer('storage_revision');
$table->text('sealed_storage_runtime');
$table->string('object_key')->unique();
$table->string('object_version_id')->default('');
$table->string('object_etag');
$table->integer('size_bytes');
$table->string('sha256');
$table->string('state');
$table->string('error_code')->default('');
$table->string('delete_operation_id')->default('');
$table->integer('delete_generation')->default(0);
$table->integer('delete_cycle_attempts')->default(0);
$table->integer('delete_presence_confirmations')->default(0);
$table->integer('delete_last_checked_at')->default(0);
$table->integer('delete_next_check_at')->default(0);
$table->integer('delete_attention_at')->nullable();
$table->integer('verified_at');
$table->integer('created_at');
$table->integer('updated_at');
});
};
$path = tempnam(sys_get_temp_dir(), 'virt-template-artifact-');
if ($path === false) {
throw new RuntimeException('Cannot create temporary template fixture.');
}
register_shutdown_function(static function () use ($path): void {
@unlink($path);
});
file_put_contents($path, str_repeat('immutable-template-', 1024));
$bytes = filesize($path);
$sha256 = hash_file('sha256', $path);
$history = [];
$stack = HandlerStack::create(new MockHandler([
new Response(200, [
'ETag' => '"template-etag"',
'x-amz-version-id' => 'template-version-1',
]),
new Response(200, [
'Content-Length' => (string) $bytes,
'ETag' => '"template-etag"',
'x-amz-version-id' => 'template-version-1',
]),
]));
$stack->push(Middleware::history($history));
$client = new CloudObjectStorageS3Client(new Client([
'handler' => $stack,
]));
$runtime = [
'config' => [
'endpoint' => 'https://objects.example.com',
'region' => 'ewr',
'bucket' => 'template-bucket',
'prefix' => 'virt-cloud',
'path_style' => true,
],
'credentials' => [
'access_key_id' => 'TEMPLATEACCESSKEY',
'secret_access_key' => 'template-secret',
],
'revision' => 7,
];
$templateId = 'debian-13-immutable';
$generation = str_repeat('a', 32);
$template = new CloudTemplate();
foreach ([
'id' => $templateId,
'catalog_key' => 'debian-13',
'version_label' => '20261030-test',
'is_default' => 0,
'name' => 'Debian 13',
'os_family' => 'Debian',
'os_version' => '13',
'image_bytes' => $bytes,
'sha256' => $sha256,
'startup_script' => '',
'revision' => 1,
'generation_token' => $generation,
'state' => 'preparing',
'active_job_id' => null,
'created_at' => time(),
'updated_at' => time(),
] as $field => $value) {
$template->{$field} = $value;
}
$template->save();
CloudTemplateArtifactManager::reserveLocked($template, $runtime);
$artifact = CloudTemplateArtifactManager::publishReserved(
$template,
['path' => $path, 'size_bytes' => $bytes, 'sha256' => $sha256],
$client
);
$request = $history[0]['request'];
$assert($request->getMethod() === 'PUT'
&& str_contains((string) $request->getUri(),
'/template-bucket/virt-cloud/cloud-templates/'
. $templateId . '/' . $generation . '/system.qcow2')
&& $request->getHeaderLine('If-None-Match') === '*'
&& $request->getHeaderLine('X-Amz-Content-Sha256') === $sha256
&& (string) $artifact->object_version_id === 'template-version-1'
&& (int) $artifact->storage_revision === 7,
'Immutable template publication lost its object identity or guard.');
$source = CloudTemplateArtifactManager::downloadSource($template, $client);
$assert($source['source_size_bytes'] === $bytes
&& $source['sha256'] === $sha256
&& str_contains($source['source_url'],
'versionId=template-version-1')
&& count($history) === 2
&& $history[1]['request']->getMethod() === 'HEAD',
'Template download capability did not bind the frozen provider version.');
$manager = file_get_contents(
$root . '/app/Services/Cloud/CloudTemplateArtifactManager.php'
);
$publication = file_get_contents(
$root . '/app/Services/Cloud/CloudTemplateStoragePublicationService.php'
);
$consumer = file_get_contents(
$root . '/app/Services/Cloud/CloudTemplateStoragePublicationConsumer.php'
);
$importModule = file_get_contents(
$root . '/app/Services/Cloud/CloudTemplateImportModule.php'
);
$model = file_get_contents(
$root . '/app/Models/CloudTemplateArtifact.php'
);
$reserveTemplate = static function (
string $id,
string $generation
) use ($bytes, $sha256, $runtime): CloudTemplate {
$row = new CloudTemplate();
foreach ([
'id' => $id,
'catalog_key' => 'debian-13',
'version_label' => '20261030-' . substr($id, -8),
'is_default' => 0,
'name' => 'Debian 13 ' . $id,
'os_family' => 'Debian',
'os_version' => '13',
'image_bytes' => $bytes,
'sha256' => $sha256,
'startup_script' => '',
'revision' => 1,
'generation_token' => $generation,
'state' => 'preparing',
'active_job_id' => null,
'created_at' => time(),
'updated_at' => time(),
] as $field => $value) {
$row->{$field} = $value;
}
$row->save();
CloudTemplateArtifactManager::reserveLocked($row, $runtime);
return $row;
};
$assert(is_string($manager)
&& str_contains($manager, 'storage_artifact_id')
&& str_contains($manager,
'CloudStoragePublicationFinalizerService::complete(')
&& str_contains($manager,
'CloudStorageArtifactService::presignedRead(')
&& !str_contains($manager, 'CloudSecrets::decrypt(')
&& !str_contains($manager, 'CloudImmutableArtifactTransport')
&& !str_contains($manager, 'reserveLocked(')
&& !str_contains($manager, 'publishReserved('),
'Template artifact manager retained the legacy single-backend path.');
$uncertainTemplate = $reserveTemplate(
'debian-13-reconciled',
str_repeat('b', 32)
);
$assert(is_string($publication)
&& str_contains($publication,
"CloudStorageArtifactService::beginPublication(\n 'template'")
&& str_contains($publication,
"['template_import_intent_id' => (string) \$intent->id]")
&& str_contains($publication,
'CloudStorageImmutablePrimaryPublication($client)')
&& str_contains($publication,
'CloudStorageArtifactDeletionService($client)')
&& str_contains($publication, "(string) \$artifact->state === 'protected'")
&& !str_contains($publication, 'CloudObjectStorageConfig::runtime('),
'Template storage publication does not bind the shared replicated ledger.');
$uncertainHistory = [];
$uncertainStack = HandlerStack::create(new MockHandler([
new ConnectException(
'simulated lost PUT response',
new Request('PUT', 'https://objects.example.com')
),
new Response(200, [
'Content-Length' => (string) $bytes,
'ETag' => '"reconciled-etag"',
'x-amz-version-id' => 'reconciled-version-1',
]),
]));
$uncertainStack->push(Middleware::history($uncertainHistory));
$reconciled = CloudTemplateArtifactManager::publishReserved(
$uncertainTemplate,
['path' => $path, 'size_bytes' => $bytes, 'sha256' => $sha256],
new CloudObjectStorageS3Client(new Client([
'handler' => $uncertainStack,
]))
);
$assert((string) $reconciled->state === 'ready'
&& (string) $reconciled->object_etag === '"reconciled-etag"'
&& (string) $reconciled->object_version_id
=== 'reconciled-version-1'
&& count($uncertainHistory) === 2
&& $uncertainHistory[0]['request']->getMethod() === 'PUT'
&& $uncertainHistory[1]['request']->getMethod() === 'HEAD',
'Unknown immutable PUT effect was not reconciled from exact object identity.');
$assert(is_string($consumer)
&& str_contains($consumer,
'public function finalizeReady(string $intentId): bool')
&& str_contains($consumer, 'return $connection->transaction(')
&& str_contains($consumer, 'lockForUpdate()->first()')
&& str_contains($consumer, 'finalizeReadyIntent(')
&& !str_contains($consumer, 'CloudStoragePublication::query()'),
'Template publication consumer must finalize only its claimed owner.');
$absentTemplate = $reserveTemplate(
'debian-13-absent',
str_repeat('c', 32)
);
$absentStack = HandlerStack::create(new MockHandler([
new ConnectException(
'simulated lost PUT response',
new Request('PUT', 'https://objects.example.com')
),
new Response(404),
]));
try {
CloudTemplateArtifactManager::publishReserved(
$absentTemplate,
['path' => $path, 'size_bytes' => $bytes, 'sha256' => $sha256],
new CloudObjectStorageS3Client(new Client([
'handler' => $absentStack,
]))
);
throw new RuntimeException('Absent unknown PUT unexpectedly succeeded.');
} catch (CloudError $error) {
$assert($error->httpStatus === 502,
'Proven absent PUT returned an unsafe status.');
}
$absentTemplate->refresh();
$absentArtifact = CloudTemplateArtifact::find(
(string) $absentTemplate->id
);
$assert((string) $absentTemplate->state === 'source_failed'
&& (string) $absentArtifact?->state === 'failed',
'Proven absent PUT remained permanently fenced.');
$assert(is_string($importModule)
&& !str_contains($importModule, 'runtimeProvider')
&& !str_contains($importModule, 'RUNTIME_PURPOSE')
&& !str_contains($importModule, 'CloudObjectStorageConfig::runtime(')
&& !str_contains($importModule, 'sealed_storage_runtime'),
'Template import kernel retained a callable single-backend runtime path.');
$unavailableTemplate = $reserveTemplate(
'debian-13-unavailable',
str_repeat('d', 32)
);
$unavailableStack = HandlerStack::create(new MockHandler([
new ConnectException(
'simulated lost PUT response',
new Request('PUT', 'https://objects.example.com')
),
new ConnectException(
'simulated unavailable HEAD',
new Request('HEAD', 'https://objects.example.com')
),
]));
try {
CloudTemplateArtifactManager::publishReserved(
$unavailableTemplate,
['path' => $path, 'size_bytes' => $bytes, 'sha256' => $sha256],
new CloudObjectStorageS3Client(new Client([
'handler' => $unavailableStack,
]))
);
throw new RuntimeException(
'Unverifiable unknown PUT unexpectedly succeeded.'
);
} catch (CloudError $error) {
$assert($error->httpStatus === 502,
'Unverifiable PUT returned an unsafe status.');
}
$unavailableTemplate->refresh();
$unavailableArtifact = CloudTemplateArtifact::find(
(string) $unavailableTemplate->id
);
$assert((string) $unavailableTemplate->state === 'source_unknown'
&& (string) $unavailableArtifact?->state === 'unknown'
&& (string) $unavailableArtifact?->error_code
=== 'template_source_reconcile_unavailable',
'Unavailable reconciliation did not retain the immutable object fence.');
$assert(is_string($model)
&& str_contains($model, "'storage_artifact_id' => 'int'"),
'Template artifact model lost its shared storage identity cast.');
echo "Immutable cloud-template artifact contract passed.\n";
}
echo "Template replicated artifact contract passed.\n";

@ -1,351 +1,53 @@
<?php
namespace App\Services {
final class Config
{
public static string $key = '';
public static function get($name, $default = null)
{
return $name === 'cloud_data_key' ? self::$key : $default;
}
$root = dirname(__DIR__);
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\CloudJob;
use App\Models\CloudTemplate;
use App\Models\CloudTemplateArtifact;
use App\Services\Cloud\CloudObjectStorageS3Client;
use App\Services\Cloud\CloudSecrets;
use App\Services\Cloud\CloudTemplateDeletionService;
use App\Services\Config;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
Config::$key = base64_encode(str_repeat('d', 32));
$capsule = new Capsule();
$capsule->addConnection([
'driver' => 'sqlite', 'database' => ':memory:',
], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = $capsule->schema('default');
$schema->create('cloud_jobs', static function (Blueprint $table): void {
$table->increments('id');
$table->string('operation_id');
$table->string('request_idempotency_key');
$table->string('request_fingerprint');
$table->integer('parent_job_id')->nullable();
$table->integer('user_id');
$table->integer('host_id')->nullable();
$table->string('kind');
$table->string('execution_mode');
$table->string('phase');
$table->string('outcome')->nullable();
$table->string('status');
$table->text('sealed_payload');
$table->integer('attempts')->default(0);
$table->integer('dispatch_attempts')->default(0);
$table->integer('dispatch_deadline_at')->default(1);
$table->integer('dispatch_started_at')->nullable();
$table->integer('agent_accepted_at')->nullable();
$table->integer('dispatched_at')->nullable();
$table->integer('receipt_deadline_at')->nullable();
$table->integer('terminal_at')->nullable();
$table->boolean('effect_may_have_applied')->nullable();
$table->boolean('safe_to_resubmit')->nullable();
$table->string('effect_resolution')->default('not_applicable');
$table->integer('effect_resolved_at')->nullable();
$table->integer('effect_resolved_by')->nullable();
$table->string('effect_resolution_reason')->default('');
$table->string('completion_event_id')->nullable();
$table->integer('read_at')->nullable();
$table->string('lease_token')->nullable();
$table->integer('lease_until')->default(0);
$table->integer('available_at')->default(0);
$table->string('error_code')->nullable();
$table->boolean('finalization_incident')->default(0);
$table->string('finalization_error_code')->nullable();
$table->text('result_json')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_templates', static function (Blueprint $table): void {
$table->string('id')->primary();
$table->string('catalog_key');
$table->string('version_label');
$table->boolean('is_default')->default(false);
$table->string('name');
$table->string('os_family');
$table->string('os_version');
$table->integer('image_bytes');
$table->string('sha256');
$table->text('startup_script');
$table->integer('revision');
$table->string('generation_token');
$table->string('state');
$table->integer('active_job_id')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_template_replicas', static function (Blueprint $table): void {
$table->integer('host_id');
$table->string('template_id');
$table->integer('revision');
$table->string('generation_token');
$table->string('state');
$table->integer('image_bytes');
$table->string('sha256');
$table->string('operation_id');
$table->integer('job_id')->nullable();
$table->string('error_code')->default('');
$table->integer('created_at');
$table->integer('updated_at');
$table->primary(['host_id', 'template_id']);
});
$schema->create('cloud_user_iso_replicas', static function (Blueprint $table): void {
$table->integer('job_id')->nullable();
});
$schema->create('cloud_template_artifacts', static function (Blueprint $table): void {
$table->string('template_id')->primary();
$table->integer('storage_revision');
$table->text('sealed_storage_runtime');
$table->string('object_key');
$table->string('object_version_id')->default('');
$table->string('object_etag');
$table->integer('size_bytes');
$table->string('sha256');
$table->string('state');
$table->string('error_code')->default('');
$table->string('delete_operation_id')->default('');
$table->integer('delete_generation')->default(0);
$table->integer('delete_cycle_attempts')->default(0);
$table->integer('delete_presence_confirmations')->default(0);
$table->integer('delete_last_checked_at')->default(0);
$table->integer('delete_next_check_at')->default(0);
$table->integer('delete_attention_at')->nullable();
$table->integer('verified_at');
$table->integer('created_at');
$table->integer('updated_at');
});
$runtime = [
'config' => [
'endpoint' => 'https://objects.example.com', 'region' => 'ewr',
'bucket' => 'templates', 'prefix' => 'virt', 'path_style' => true,
],
'credentials' => [
'access_key_id' => 'DELETEACCESSKEY',
'secret_access_key' => 'delete-secret',
],
'revision' => 1,
];
$now = time();
$fixture = static function (string $suffix) use ($runtime, $now): array {
$parentId = (int) Capsule::table('cloud_jobs')->insertGetId([
'operation_id' => md5('parent-' . $suffix),
'request_idempotency_key' => md5('parent-' . $suffix),
'request_fingerprint' => hash('sha256', 'parent-' . $suffix),
'parent_job_id' => null, 'user_id' => 1, 'host_id' => null,
'kind' => 'template_delete', 'execution_mode' => 'aggregate',
'phase' => 'awaiting_receipt', 'outcome' => null,
'status' => 'running',
'sealed_payload' => CloudSecrets::encrypt([], 'job-payload'),
'attempts' => 0, 'dispatch_attempts' => 0,
'dispatch_deadline_at' => $now + 300,
'receipt_deadline_at' => $now + 3600,
'effect_resolution' => 'not_applicable',
'effect_resolution_reason' => '', 'lease_until' => 0,
'available_at' => $now, 'finalization_incident' => 0,
'created_at' => $now, 'updated_at' => $now,
]);
$childOperation = md5('child-' . $suffix);
$childId = (int) Capsule::table('cloud_jobs')->insertGetId([
'operation_id' => $childOperation,
'request_idempotency_key' => $childOperation,
'request_fingerprint' => hash('sha256', 'child-' . $suffix),
'parent_job_id' => $parentId, 'user_id' => 1, 'host_id' => 7,
'kind' => 'template_delete_replica', 'execution_mode' => 'agent',
'phase' => 'terminal', 'outcome' => 'succeeded',
'status' => 'succeeded',
'sealed_payload' => CloudSecrets::encrypt([], 'job-payload'),
'attempts' => 1, 'dispatch_attempts' => 1,
'dispatch_deadline_at' => $now - 20,
'dispatch_started_at' => $now - 19,
'agent_accepted_at' => $now - 18,
'dispatched_at' => $now - 17,
'receipt_deadline_at' => $now + 900,
'terminal_at' => $now - 1,
'effect_may_have_applied' => 0, 'safe_to_resubmit' => 0,
'effect_resolution' => 'applied',
'effect_resolution_reason' => '', 'lease_until' => 0,
'available_at' => 0, 'finalization_incident' => 0,
'created_at' => $now - 20, 'updated_at' => $now - 1,
]);
$templateId = 'delete-template-' . $suffix;
$generation = md5('generation-' . $suffix);
$sha = hash('sha256', 'image-' . $suffix);
Capsule::table('cloud_templates')->insert([
'id' => $templateId, 'catalog_key' => 'debian-13',
'version_label' => $suffix, 'is_default' => 0,
'name' => 'Delete ' . $suffix, 'os_family' => 'Debian',
'os_version' => '13', 'image_bytes' => 4096,
'sha256' => $sha, 'startup_script' => '', 'revision' => 1,
'generation_token' => $generation, 'state' => 'deleting',
'active_job_id' => $parentId, 'created_at' => $now,
'updated_at' => $now,
]);
Capsule::table('cloud_template_replicas')->insert([
'host_id' => 7, 'template_id' => $templateId, 'revision' => 1,
'generation_token' => $generation, 'state' => 'delete_succeeded',
'image_bytes' => 4096, 'sha256' => $sha,
'operation_id' => $childOperation, 'job_id' => $childId,
'error_code' => '', 'created_at' => $now, 'updated_at' => $now,
]);
Capsule::table('cloud_template_artifacts')->insert([
'template_id' => $templateId, 'storage_revision' => 1,
'sealed_storage_runtime' => CloudSecrets::encrypt(
$runtime, 'template-artifact-runtime'
),
'object_key' => 'virt/cloud-templates/' . $templateId
. '/' . $generation . '/system.qcow2',
'object_version_id' => 'version-' . $suffix,
'object_etag' => '"etag-' . $suffix . '"',
'size_bytes' => 4096, 'sha256' => $sha, 'state' => 'ready',
'error_code' => '', 'delete_operation_id' => '',
'delete_generation' => 0, 'delete_cycle_attempts' => 0,
'delete_presence_confirmations' => 0,
'delete_last_checked_at' => 0, 'delete_next_check_at' => 0,
'delete_attention_at' => null, 'verified_at' => $now,
'created_at' => $now, 'updated_at' => $now,
]);
$template = CloudTemplate::findOrFail($templateId);
$parent = CloudJob::findOrFail($parentId);
$template->getConnection()->transaction(
static function () use ($templateId, $parentId): void {
$parent = CloudJob::where('id', $parentId)
->lockForUpdate()->firstOrFail();
$template = CloudTemplate::where('id', $templateId)
->lockForUpdate()->firstOrFail();
CloudTemplateDeletionService::armLocked($template, $parent);
},
3
);
return [$templateId, $parentId];
};
[$normalId, $normalParentId] = $fixture('normal');
$normalHistory = [];
$normalStack = HandlerStack::create(new MockHandler([
new Response(200, [
'Content-Length' => '4096', 'ETag' => '"etag-normal"',
'x-amz-version-id' => 'version-normal',
]),
new Response(204),
]));
$normalStack->push(Middleware::history($normalHistory));
$normalClient = new CloudObjectStorageS3Client(new Client([
'handler' => $normalStack,
]));
$normal = CloudTemplateDeletionService::processDue(1, $normalClient);
$assert($normal['completed'] === 1
&& CloudTemplateArtifact::find($normalId) === null
&& (string) CloudTemplate::findOrFail($normalId)->state === 'retired'
&& (int) CloudTemplate::findOrFail($normalId)->revision === 2
&& (string) CloudJob::findOrFail($normalParentId)->outcome
=== 'succeeded'
&& array_map(
static fn (array $item): string => $item['request']->getMethod(),
$normalHistory
) === ['HEAD', 'DELETE'],
'Confirmed master deletion did not retire the exact catalog version.');
[$unknownId, $unknownParentId] = $fixture('unknown');
$unknownHistory = [];
$unknownStack = HandlerStack::create(new MockHandler([
new Response(200, [
'Content-Length' => '4096', 'ETag' => '"etag-unknown"',
'x-amz-version-id' => 'version-unknown',
]),
new ConnectException('lost after delete', new Request(
'DELETE', 'https://objects.example.com'
)),
new Response(200, [
'Content-Length' => '4096', 'ETag' => '"etag-unknown"',
'x-amz-version-id' => 'version-unknown',
]),
new Response(200, [
'Content-Length' => '4096', 'ETag' => '"etag-unknown"',
'x-amz-version-id' => 'version-unknown',
]),
new Response(204),
]));
$unknownStack->push(Middleware::history($unknownHistory));
$unknownClient = new CloudObjectStorageS3Client(new Client([
'handler' => $unknownStack,
]));
CloudTemplateDeletionService::processDue(1, $unknownClient);
$unknownArtifact = CloudTemplateArtifact::findOrFail($unknownId);
$assert((string) $unknownArtifact->state === 'delete_uncertain'
&& (int) $unknownArtifact->delete_generation === 1,
'Ambiguous DELETE was not fenced on its original generation.');
Capsule::table('cloud_template_artifacts')->where('template_id', $unknownId)
->update(['delete_next_check_at' => 0]);
CloudTemplateDeletionService::processDue(1, $unknownClient);
$unknownArtifact = CloudTemplateArtifact::findOrFail($unknownId);
$assert((int) $unknownArtifact->delete_presence_confirmations === 1
&& (int) $unknownArtifact->delete_generation === 1,
'One presence probe incorrectly replayed an ambiguous DELETE.');
Capsule::table('cloud_template_artifacts')->where('template_id', $unknownId)
->update([
'delete_last_checked_at' => time() - 301,
'delete_next_check_at' => 0,
]);
$converged = CloudTemplateDeletionService::processDue(1, $unknownClient);
$assert($converged['completed'] === 1
&& CloudTemplateArtifact::find($unknownId) === null
&& (string) CloudTemplate::findOrFail($unknownId)->state === 'retired'
&& (string) CloudJob::findOrFail($unknownParentId)->outcome
=== 'succeeded'
&& array_map(
static fn (array $item): string => $item['request']->getMethod(),
$unknownHistory
) === ['HEAD', 'DELETE', 'HEAD', 'HEAD', 'DELETE'],
'Stable two-probe evidence did not create exactly one fresh delete generation.');
[$attentionId, $attentionParentId] = $fixture('attention');
$attentionClient = new CloudObjectStorageS3Client(new Client([
'handler' => HandlerStack::create(new MockHandler([
new Response(200, [
'Content-Length' => '8192', 'ETag' => '"different"',
'x-amz-version-id' => 'version-attention',
]),
])),
]));
$attention = CloudTemplateDeletionService::processDue(1, $attentionClient);
$assert($attention['attention'] === 1
&& (string) CloudTemplateArtifact::findOrFail($attentionId)->state
=== 'delete_attention'
&& (string) CloudTemplate::findOrFail($attentionId)->state
=== 'delete_failed'
&& (string) CloudJob::findOrFail($attentionParentId)->outcome
=== 'failed',
'Changed object identity was not fenced for explicit administrator review.');
echo "Cloud-template two-phase deletion and recovery behavior passed.\n";
}
};
$deletion = file_get_contents(
$root . '/app/Services/Cloud/CloudTemplateDeletionService.php'
);
$storageDeletion = file_get_contents(
$root . '/app/Services/Cloud/CloudStorageArtifactDeletionService.php'
);
$hostFinish = strpos($deletion, 'public static function finishReplicaLocked(');
$arm = strpos($deletion, 'public static function armLocked(');
$storageProcess = strpos($deletion,
'(new CloudStorageArtifactDeletionService($client))->process(');
$finish = strpos($deletion, 'private static function finishSuccess(');
$assert(is_int($hostFinish) && is_int($arm) && is_int($storageProcess)
&& is_int($finish)
&& $hostFinish < $arm
&& $arm < $storageProcess
&& $storageProcess < $finish
&& str_contains($deletion, "self::assertChildProjectionLocked(\n"
. " \$template,\n \$parent,\n"
. " 'applied'")
&& str_contains($deletion, 'storage_artifact_id')
&& str_contains($deletion,
"['template_import_intent_id' => (string) \$intent->id]")
&& str_contains($deletion, "(\$result['deleted'] ?? false) === true")
&& !str_contains($deletion,
'CloudTemplateArtifactManager::deleteExact(')
&& !str_contains($deletion,
'CloudTemplateArtifactManager::inspectDeletionTarget(')
&& !str_contains($deletion, 'recordStablePresence(')
&& !str_contains($deletion, 'claimDeleteGeneration(')
&& !str_contains($deletion, 'MAX_DELETE_GENERATIONS'),
'Template deletion no longer proves host cleanup before replica deletion.');
$assert(is_string($storageDeletion)
&& str_contains($storageDeletion,
'Deletes every provider replica behind one logical artifact')
&& str_contains($storageDeletion,
'effectMayHaveApplied')
&& str_contains($storageDeletion, '->deleteObject(')
&& str_contains($storageDeletion, 'STABLE_PROBES = 2'),
'Template deletion lost exact per-replica unknown-effect reconciliation.');
echo "Template replicated deletion ordering contract passed.\n";

@ -22,6 +22,9 @@ $publication = file_get_contents(
$deletion = file_get_contents(
$root . '/app/Services/Cloud/CloudTemplateDeletionService.php'
);
$artifactManager = file_get_contents(
$root . '/app/Services/Cloud/CloudTemplateArtifactManager.php'
);
$routes = file_get_contents($root . '/config/routes_cloud.php');
$schema = file_get_contents($root . '/sql/cloud.sql');
$assert(is_string($catalog)
@ -40,10 +43,12 @@ $assert(is_string($catalog)
&& is_string($deletion)
&& str_contains($deletion, 'CloudAgentCatalogDeletion::confirms(')
&& str_contains($deletion, 'Agent 云镜像删除回执缺少清理证据')
&& str_contains($deletion,
'CloudTemplateArtifactManager::inspectDeletionTarget(')
&& str_contains($deletion,
'CloudTemplateArtifactManager::deleteExact(')
&& str_contains($deletion, 'CloudStorageArtifactDeletionService')
&& str_contains($deletion, "['template_import_intent_id' =>")
&& is_string($artifactManager)
&& str_contains($artifactManager,
'CloudStorageArtifactService::presignedRead(')
&& !str_contains($artifactManager, 'CloudSecrets::decrypt(')
&& !str_contains($catalog, 'CloudAgentClient')
&& !str_contains($catalog, '->request(')
&& str_contains($catalog,
@ -62,7 +67,16 @@ $assert(is_string($controller)
&& str_contains($controller, 'CloudTemplateCatalogService::rename(')
&& str_contains($controller, 'CloudTemplateCatalogService::delete(')
&& str_contains($remoteAcquisition, 'CloudTemplateRemoteFetcher')
&& str_contains($remoteAcquisition, 'CloudImmutableArtifactTransport')
&& str_contains($remoteAcquisition,
'CloudTemplateStoragePublicationService::reserve(')
&& str_contains($remoteAcquisition,
'CloudTemplateStoragePublicationService::publishFile(')
&& str_contains($remoteAcquisition,
"finally {\n if (is_array(\$file)")
&& str_contains($remoteAcquisition,
"@unlink((string) \$file['path'])")
&& str_contains($remoteAcquisition,
"'path' => ''")
&& str_contains($remoteAcquisition, 'publication()->finalizeReadyIntent(')
&& str_contains($publication, 'finalizeReadyIntent(')
&& !str_contains($controller, 'CloudLocalUploadService')

@ -84,23 +84,157 @@ namespace {
$table->integer('updated_at');
$table->primary(['intent_id', 'part_number']);
});
$schema->create('cloud_storage_backends',
static function (Blueprint $table): void {
$table->increments('id');
$table->string('backend_key');
$table->string('identity_sha256');
$table->string('name');
$table->string('driver');
$table->string('endpoint');
$table->string('region');
$table->string('bucket');
$table->string('prefix');
$table->boolean('path_style');
$table->string('failure_domain');
$table->text('sealed_credentials');
$table->unsignedBigInteger('config_revision');
$table->unsignedBigInteger('tested_revision');
$table->string('admin_state');
$table->string('health_state');
$table->unsignedInteger('write_priority');
$table->unsignedInteger('consecutive_failures')->default(0);
$table->unsignedInteger('consecutive_successes')->default(0);
$table->string('last_error_code')->default('');
$table->unsignedBigInteger('last_tested_at')->default(0);
$table->unsignedBigInteger('last_healthy_at')->default(0);
$table->unsignedBigInteger('next_probe_at')->default(0);
$table->unsignedBigInteger('created_at');
$table->unsignedBigInteger('updated_at');
});
$schema->create('cloud_storage_artifacts',
static function (Blueprint $table): void {
$table->increments('id');
$table->string('artifact_key')->unique();
$table->string('kind');
$table->unsignedBigInteger('maximum_size_bytes');
$table->unsignedBigInteger('size_bytes');
$table->string('sha256');
$table->string('durability_policy');
$table->unsignedTinyInteger('desired_copies');
$table->unsignedTinyInteger('required_copies');
$table->string('state');
$table->string('last_operation_id')->nullable();
$table->unsignedBigInteger('verified_at');
$table->unsignedBigInteger('created_at');
$table->unsignedBigInteger('updated_at');
});
$schema->create('cloud_storage_replicas',
static function (Blueprint $table): void {
$table->increments('id');
$table->string('replica_key')->unique();
$table->unsignedBigInteger('artifact_id');
$table->unsignedBigInteger('backend_id');
$table->string('role');
$table->string('object_key');
$table->string('object_version_id')->default('');
$table->string('object_etag')->default('');
$table->unsignedBigInteger('size_bytes')->default(0);
$table->string('sha256')->default('');
$table->string('state');
$table->string('publish_operation_id')->nullable();
$table->string('delete_operation_id')->nullable();
$table->unsignedInteger('delete_generation')->default(0);
$table->unsignedInteger('delete_cycle_attempts')->default(0);
$table->unsignedInteger('delete_presence_confirmations')->default(0);
$table->unsignedBigInteger('delete_last_checked_at')->default(0);
$table->unsignedBigInteger('delete_next_check_at')->default(0);
$table->unsignedBigInteger('delete_attention_at')->nullable();
$table->string('lease_token')->nullable();
$table->unsignedBigInteger('lease_until')->default(0);
$table->string('error_code')->default('');
$table->unsignedBigInteger('verified_at')->default(0);
$table->unsignedBigInteger('created_at');
$table->unsignedBigInteger('updated_at');
});
$schema->create('cloud_storage_operations',
static function (Blueprint $table): void {
$table->increments('id');
$table->string('operation_id')->unique();
$table->string('request_idempotency_key')->unique();
$table->string('request_fingerprint');
$table->unsignedBigInteger('artifact_id');
$table->unsignedBigInteger('replica_id')->nullable();
$table->unsignedBigInteger('source_backend_id')->nullable();
$table->unsignedBigInteger('target_backend_id')->nullable();
$table->string('kind');
$table->string('phase');
$table->string('outcome')->nullable();
$table->string('effect_resolution');
$table->boolean('effect_may_have_applied')->nullable();
$table->boolean('safe_to_resubmit')->nullable();
$table->unsignedInteger('attempts');
$table->string('lease_token')->nullable();
$table->unsignedBigInteger('lease_until');
$table->unsignedBigInteger('available_at');
$table->unsignedBigInteger('next_check_at');
$table->string('error_code');
$table->text('result_json')->nullable();
$table->unsignedBigInteger('terminal_at')->nullable();
$table->unsignedBigInteger('created_at');
$table->unsignedBigInteger('updated_at');
});
$schema->create('cloud_storage_publications',
static function (Blueprint $table): void {
$table->increments('id');
$table->string('publication_key')->unique();
$table->unsignedBigInteger('artifact_id')->unique();
$table->unsignedBigInteger('backup_id')->nullable()->unique();
$table->string('template_import_intent_id')->nullable()->unique();
$table->string('rescue_template_id')->nullable()->unique();
$table->string('state');
$table->unsignedInteger('attempts')->default(0);
$table->unsignedBigInteger('available_at')->default(0);
$table->string('lease_token')->nullable();
$table->unsignedBigInteger('lease_until')->default(0);
$table->string('last_error_code')->default('');
$table->unsignedBigInteger('coverage_ready_at')->nullable();
$table->unsignedBigInteger('finalized_at')->nullable();
$table->unsignedBigInteger('created_at');
$table->unsignedBigInteger('updated_at');
});
foreach ([[1, 'provider-a'], [2, 'provider-b']] as [$id, $domain]) {
Capsule::table('cloud_storage_backends')->insert([
'id' => $id,
'backend_key' => str_repeat((string) $id, 32),
'identity_sha256' => str_repeat((string) $id, 64),
'name' => $domain,
'driver' => 's3',
'endpoint' => 'https://' . $domain . '.example.test',
'region' => 'us-east-1',
'bucket' => $domain,
'prefix' => $domain,
'path_style' => 1,
'failure_domain' => $domain,
'sealed_credentials' => 'sealed',
'config_revision' => 9,
'tested_revision' => 9,
'admin_state' => 'active',
'health_state' => 'healthy',
'write_priority' => $id * 10,
'consecutive_failures' => 0,
'consecutive_successes' => 1,
'last_error_code' => '',
'last_tested_at' => 2000000000,
'last_healthy_at' => 2000000000,
'next_probe_at' => 2000000300,
'created_at' => 2000000000,
'updated_at' => 2000000000,
]);
}
$runtime = [
'config' => [
'endpoint' => 'https://objects.example.test',
'region' => 'ewr',
'bucket' => 'templates',
'prefix' => 'virt-cloud',
'path_style' => true,
],
'credentials' => [
'access_key_id' => 'INTENTACCESS',
'secret_access_key' => 'intent-secret',
],
'revision' => 9,
];
$uploads = new CloudTemplateMultipartAcquisition(
static fn (): array => $runtime,
static fn (): int => 2000000000
);
$readModel = new CloudTemplateImportReadModel();
@ -118,6 +252,7 @@ namespace {
'filename' => 'debian-13.qcow2',
'size_bytes' => 64 * 1024 * 1024,
'last_modified' => 1999999000000,
'sha256' => str_repeat('a', 64),
];
$first = $uploads->beginUpload($input, $actor);
@ -132,10 +267,14 @@ namespace {
(string) $first['intent']['id']
);
$assert((int) $stored->storage_revision === 9
&& str_starts_with((string) $stored->object_key,
'virt-cloud/cloud-templates/')
&& !str_contains(json_encode($first['intent'], JSON_THROW_ON_ERROR),
'intent-secret')
&& str_contains((string) $stored->object_key,
'/cloud-templates/')
&& Capsule::table('cloud_storage_artifacts')->count() === 1
&& Capsule::table('cloud_storage_replicas')->count() === 2
&& Capsule::table('cloud_storage_operations')->count() === 2
&& Capsule::table('cloud_storage_publications')
->where('template_import_intent_id', (string) $stored->id)
->exists()
&& !array_key_exists('sealed_storage_runtime', $first['intent'])
&& !array_key_exists('multipart_upload_id', $first['intent']),
'The intent did not freeze its object identity or leaked secrets.');
@ -180,8 +319,9 @@ namespace {
$probe->state = $stateName;
$probe->source_kind = $source;
$probe->multipart_upload_id = '';
foreach (['start_upload', 'record_part', 'complete_upload',
'resume_remote', 'cancel'] as $action) {
foreach (['start_upload', 'reconcile_multipart_start',
'record_part', 'complete_upload', 'resume_remote',
'cancel'] as $action) {
$expected = in_array($action, $definition['actions'][$source], true);
try {
CloudTemplateImportStateMachine::assertAction($probe, $action);
@ -208,6 +348,24 @@ namespace {
$unknownUpload->error_code = 'multipart_complete_unknown';
$assert(!CloudTemplateImportStateMachine::capabilities($unknownUpload)['can_cancel'],
'An unknown upload completion was exposed as cancellable.');
try {
CloudTemplateImportStateMachine::assertAction(
$unknownUpload,
'reconcile_multipart_start'
);
throw new RuntimeException(
'An existing multipart identity was exposed as a new-session retry.'
);
} catch (CloudError $error) {
$assert($error->httpStatus === 409,
'Multipart identity conflict returned the wrong status.');
}
$unknownCreate = clone $unknownUpload;
$unknownCreate->multipart_upload_id = '';
CloudTemplateImportStateMachine::assertAction(
$unknownCreate,
'reconcile_multipart_start'
);
try {
CloudTemplateImportStateMachine::assertAction($unknownUpload, 'cancel');
throw new RuntimeException('The cancellation endpoint disagrees with its projection.');

@ -1,916 +1,76 @@
<?php
namespace App\Services {
final class Config
{
public static string $key = '';
public static function get($name, $default = null)
{
return $name === 'cloud_data_key' ? self::$key : $default;
}
}
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\CloudTemplateImportIntent;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudObjectStorageS3Client;
use App\Services\Cloud\CloudSecrets;
use App\Services\Cloud\CloudTemplateImportCancellation;
use App\Services\Cloud\CloudTemplateImportReadModel;
use App\Services\Cloud\CloudTemplateMultipartAcquisition;
use App\Services\Cloud\CloudTemplateRemoteAcquisition;
use App\Services\Cloud\CloudTemplateRemoteFetcher;
use App\Services\Config;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new \RuntimeException($message);
}
};
Config::$key = base64_encode(str_repeat('m', 32));
$capsule = new Capsule();
$capsule->addConnection([
'driver' => 'sqlite', 'database' => ':memory:',
], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = $capsule->schema('default');
$schema->create('cloud_template_import_intents',
static function (Blueprint $table): void {
$table->string('id')->primary();
$table->integer('user_id');
$table->string('request_idempotency_key');
$table->string('request_fingerprint');
$table->string('source_kind');
$table->string('name');
$table->string('os_family');
$table->string('os_version');
$table->string('source_filename')->default('');
$table->integer('source_size_bytes')->default(0);
$table->integer('source_last_modified')->default(0);
$table->string('source_sha256')->default('');
$table->text('sealed_source');
$table->string('template_id')->unique();
$table->string('catalog_key');
$table->string('version_label');
$table->string('generation_token')->unique();
$table->integer('storage_revision');
$table->text('sealed_storage_runtime');
$table->string('object_key')->unique();
$table->string('multipart_upload_id')->default('');
$table->integer('multipart_part_size_bytes')->default(0);
$table->integer('multipart_part_count')->default(0);
$table->string('object_version_id')->default('');
$table->string('object_etag')->default('');
$table->string('state');
$table->integer('active_job_id')->nullable();
$table->string('error_code')->default('');
$table->integer('expires_at');
$table->integer('completed_at')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
$table->unique(['user_id', 'request_idempotency_key']);
});
$schema->create('cloud_template_import_parts',
static function (Blueprint $table): void {
$table->string('intent_id');
$table->integer('part_number');
$table->integer('size_bytes');
$table->string('etag');
$table->integer('created_at');
$table->integer('updated_at');
$table->primary(['intent_id', 'part_number']);
});
$schema->create('cloud_templates',
static function (Blueprint $table): void {
$table->string('id')->primary();
$table->string('catalog_key');
$table->string('version_label');
$table->boolean('is_default')->default(false);
$table->string('name');
$table->string('os_family');
$table->string('os_version');
$table->integer('image_bytes');
$table->string('sha256');
$table->text('startup_script');
$table->integer('revision');
$table->string('generation_token')->unique();
$table->string('state');
$table->integer('active_job_id')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_template_artifacts',
static function (Blueprint $table): void {
$table->string('template_id')->primary();
$table->integer('storage_revision');
$table->text('sealed_storage_runtime');
$table->string('object_key');
$table->string('object_version_id')->default('');
$table->string('object_etag')->default('');
$table->integer('size_bytes');
$table->string('sha256');
$table->string('state');
$table->string('error_code')->default('');
$table->string('delete_operation_id')->default('');
$table->integer('delete_generation')->default(0);
$table->integer('delete_cycle_attempts')->default(0);
$table->integer('delete_presence_confirmations')->default(0);
$table->integer('delete_last_checked_at')->default(0);
$table->integer('delete_next_check_at')->default(0);
$table->integer('delete_attention_at')->nullable();
$table->integer('verified_at')->default(0);
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_template_replicas',
static function (Blueprint $table): void {
$table->integer('host_id');
$table->string('template_id');
$table->integer('revision');
$table->string('generation_token');
$table->string('state');
$table->integer('image_bytes');
$table->string('sha256');
$table->string('operation_id');
$table->integer('job_id')->nullable();
$table->string('error_code')->default('');
$table->integer('created_at');
$table->integer('updated_at');
$table->primary(['host_id', 'template_id']);
});
$schema->create('cloud_jobs',
static function (Blueprint $table): void {
$table->increments('id');
$table->string('operation_id')->unique();
$table->string('request_idempotency_key');
$table->string('request_fingerprint');
$table->integer('parent_job_id')->nullable();
$table->integer('user_id');
$table->integer('host_id')->nullable();
$table->string('kind');
$table->string('execution_mode');
$table->string('phase');
$table->string('outcome')->nullable();
$table->string('status');
$table->text('sealed_payload');
$table->integer('attempts')->default(0);
$table->integer('dispatch_attempts')->default(0);
$table->integer('dispatch_deadline_at')->default(1);
$table->integer('dispatch_started_at')->nullable();
$table->integer('agent_accepted_at')->nullable();
$table->integer('dispatched_at')->nullable();
$table->integer('receipt_deadline_at')->nullable();
$table->integer('terminal_at')->nullable();
$table->boolean('effect_may_have_applied')->nullable();
$table->boolean('safe_to_resubmit')->nullable();
$table->string('effect_resolution')->default('not_applicable');
$table->integer('effect_resolved_at')->nullable();
$table->integer('effect_resolved_by')->nullable();
$table->string('effect_resolution_reason')->default('');
$table->boolean('finalization_incident')->default(0);
$table->string('finalization_error_code')->nullable();
$table->string('completion_event_id')->nullable();
$table->integer('read_at')->nullable();
$table->string('lease_token')->nullable();
$table->integer('lease_until')->default(0);
$table->integer('available_at')->default(0);
$table->string('error_code')->nullable();
$table->text('result_json')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
$table->unique(['user_id', 'request_idempotency_key']);
});
$schema->create('cloud_hosts', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('enabled');
$table->string('default_network');
});
$schema->create('cloud_host_agents',
static function (Blueprint $table): void {
$table->integer('host_id')->primary();
$table->integer('enabled');
$table->integer('revision');
$table->integer('tested_revision');
$table->string('last_test_status');
});
$schema->create('cloud_host_storage_configurations',
static function (Blueprint $table): void {
$table->integer('host_id')->primary();
$table->string('state');
});
Capsule::table('cloud_hosts')->insert([
'id' => 1,
'enabled' => 1,
'default_network' => 'bridge:br0',
]);
Capsule::table('cloud_host_agents')->insert([
'host_id' => 1,
'enabled' => 1,
'revision' => 3,
'tested_revision' => 3,
'last_test_status' => 'healthy',
]);
Capsule::table('cloud_host_storage_configurations')->insert([
'host_id' => 1,
'state' => 'applied',
]);
$runtime = [
'config' => [
'endpoint' => 'https://objects.example.test',
'region' => 'ewr',
'bucket' => 'templates',
'prefix' => 'virt-cloud',
'path_style' => true,
],
'credentials' => [
'access_key_id' => 'MULTIPARTACCESS',
'secret_access_key' => 'multipart-secret',
],
'revision' => 11,
];
$clock = 2000001000;
$runtimeProvider = static fn (): array => $runtime;
$clockProvider = static fn (): int => $clock;
$uploads = new CloudTemplateMultipartAcquisition(
$runtimeProvider,
$clockProvider
);
$remote = new CloudTemplateRemoteAcquisition(
$runtimeProvider,
$clockProvider
);
$cancellation = new CloudTemplateImportCancellation(
$runtimeProvider,
$clockProvider
);
$actor = [
'user_id' => 9,
'is_admin' => true,
'is_super_admin' => true,
'can_manage' => true,
'request_idempotency_key' => 'multipart-template-intent-0001',
];
$input = [
'name' => 'Debian 13 multipart',
'os_family' => 'Debian',
'os_version' => '13',
'filename' => 'debian-13.qcow2',
'size_bytes' => 64 * 1024 * 1024,
'last_modified' => 2000000000000,
];
$digest = str_repeat('a', 64);
$partEtag = '"part-etag-1"';
$partsXml = '<ListPartsResult><IsTruncated>false</IsTruncated>'
. '<Part><PartNumber>1</PartNumber><Size>67108864</Size>'
. '<ETag>' . $partEtag . '</ETag></Part></ListPartsResult>';
$history = [];
$stack = HandlerStack::create(new MockHandler([
new Response(200, [], '<InitiateMultipartUploadResult>'
. '<UploadId>intent-upload-1</UploadId>'
. '</InitiateMultipartUploadResult>'),
new Response(200, [], $partsXml),
new Response(200, [], '<CompleteMultipartUploadResult/>'),
new Response(200, [
'Content-Length' => '67108864',
'ETag' => '"object-etag-1"',
'x-amz-version-id' => 'version-1',
]),
new Response(200, [
'Content-Length' => '67108864',
'ETag' => '"object-etag-1"',
'x-amz-version-id' => 'version-1',
]),
]));
$stack->push(Middleware::history($history));
$client = new CloudObjectStorageS3Client(new Client(['handler' => $stack]));
$intent = $uploads->beginUpload($input, $actor)['intent'];
$plan = $uploads->startUpload((string) $intent['id'], $actor, $client);
$assert(count($plan['part_urls']) === 1
&& !array_key_exists('upload_id', $plan)
&& !str_contains(json_encode($plan, JSON_THROW_ON_ERROR),
'multipart-secret'),
'The browser upload plan leaked provider authority or credentials.');
$uploads->recordPart((string) $intent['id'], 1, [
'size_bytes' => 64 * 1024 * 1024,
'etag' => $partEtag,
], $actor);
$ack = $uploads->completeUpload(
(string) $intent['id'], ['sha256' => $digest], $actor, $client
);
$stored = CloudTemplateImportIntent::findOrFail((string) $intent['id']);
$assert((string) $stored->state === 'distributing'
&& (string) $stored->object_version_id === 'version-1'
&& Capsule::table('cloud_templates')->count() === 1
&& Capsule::table('cloud_template_artifacts')->count() === 1
&& Capsule::table('cloud_template_replicas')->count() === 1
&& Capsule::table('cloud_jobs')->count() === 2
&& (int) $ack['task_id'] === (int) $stored->active_job_id,
'A completed multipart source was not adopted and distributed once.');
$artifactRuntime = CloudSecrets::decrypt((string) Capsule::table(
'cloud_template_artifacts'
)->value('sealed_storage_runtime'), 'template-artifact-runtime');
$assert(($artifactRuntime['revision'] ?? null) === 11
&& ($artifactRuntime['credentials']['access_key_id'] ?? null)
=== 'MULTIPARTACCESS',
'The adopted artifact retained import-purpose ciphertext.');
$assert(array_map(static fn (array $item): string =>
$item['request']->getMethod(), $history) === [
'POST', 'GET', 'POST', 'HEAD',
'HEAD',
], 'Multipart import used an unexpected S3 control sequence.');
// Simulate a process stop after the aggregate/children committed but
// before the intent projection recorded its task. A page retry must bind
// the existing task without contacting S3 or allocating another one.
Capsule::table('cloud_template_import_intents')
->where('id', (string) $intent['id'])->update([
'state' => 'source_ready',
'active_job_id' => null,
]);
$emptyClient = new CloudObjectStorageS3Client(new Client([
'handler' => HandlerStack::create(new MockHandler([])),
]));
$replayAck = $uploads->completeUpload(
(string) $intent['id'], ['sha256' => $digest], $actor, $emptyClient
);
$assert(Capsule::table('cloud_templates')->count() === 1
&& Capsule::table('cloud_template_artifacts')->count() === 1
&& Capsule::table('cloud_jobs')->count() === 2
&& $replayAck === $ack
&& (string) CloudTemplateImportIntent::findOrFail(
(string) $intent['id']
)->state === 'distributing',
'Completion replay allocated a second template or task generation.');
// CompleteMultipartUpload may commit even when its response is lost. The
// workflow must reconcile HEAD and must never issue Complete a second time.
$actor['request_idempotency_key'] = 'multipart-template-intent-0002';
$lost = $uploads->beginUpload(array_replace($input, [
'name' => 'Debian 13 lost response',
'filename' => 'debian-13-lost.qcow2',
]), $actor)['intent'];
$lostHistory = [];
$lostStack = HandlerStack::create(new MockHandler([
new Response(200, [], '<InitiateMultipartUploadResult>'
. '<UploadId>intent-upload-2</UploadId>'
. '</InitiateMultipartUploadResult>'),
new Response(200, [], $partsXml),
new ConnectException('response lost',
new Request('POST', 'https://objects.example.test')),
new Response(200, [
'Content-Length' => '67108864',
'ETag' => '"object-etag-2"',
'x-amz-version-id' => 'version-2',
]),
new Response(200, [
'Content-Length' => '67108864',
'ETag' => '"object-etag-2"',
'x-amz-version-id' => 'version-2',
]),
]));
$lostStack->push(Middleware::history($lostHistory));
$lostClient = new CloudObjectStorageS3Client(new Client([
'handler' => $lostStack,
]));
$uploads->startUpload((string) $lost['id'], $actor, $lostClient);
$uploads->recordPart((string) $lost['id'], 1, [
'size_bytes' => 64 * 1024 * 1024,
'etag' => $partEtag,
], $actor);
$lostAck = $uploads->completeUpload(
(string) $lost['id'], ['sha256' => $digest], $actor, $lostClient
);
$lostStored = CloudTemplateImportIntent::findOrFail((string) $lost['id']);
$assert((string) $lostStored->state === 'distributing'
&& (string) $lostStored->object_version_id === 'version-2'
&& (int) $lostAck['task_id'] === (int) $lostStored->active_job_id
&& array_map(static fn (array $item): string =>
$item['request']->getMethod(), $lostHistory) === [
'POST', 'GET', 'POST', 'HEAD',
'HEAD',
],
'A lost completion response was replayed instead of reconciled.');
// Refreshing the page must expose the exact server-confirmed part ledger;
// re-signing an existing upload must not allocate a second upload ID.
$actor['request_idempotency_key'] = 'multipart-template-intent-0003';
$resumable = $uploads->beginUpload(array_replace($input, [
'name' => 'Debian 13 resumable',
'filename' => 'debian-13-resumable.qcow2',
]), $actor)['intent'];
$resumeHistory = [];
$resumeStack = HandlerStack::create(new MockHandler([
new Response(200, [], '<InitiateMultipartUploadResult>'
. '<UploadId>intent-upload-3</UploadId>'
. '</InitiateMultipartUploadResult>'),
new Response(204),
]));
$resumeStack->push(Middleware::history($resumeHistory));
$resumeClient = new CloudObjectStorageS3Client(new Client([
'handler' => $resumeStack,
]));
$uploads->startUpload((string) $resumable['id'], $actor, $resumeClient);
$uploads->recordPart((string) $resumable['id'], 1, [
'size_bytes' => 64 * 1024 * 1024,
'etag' => $partEtag,
], $actor);
$resigned = $uploads->startUpload(
(string) $resumable['id'], $actor, $resumeClient
);
$assert(($resigned['intent']['parts'] ?? null) === [[
'part_number' => 1,
'size_bytes' => 64 * 1024 * 1024,
]]
&& array_map(static fn (array $item): string =>
$item['request']->getMethod(), $resumeHistory) === ['POST'],
'Resume did not expose the exact part ledger or created a new upload.');
$cancelled = $cancellation->cancel(
(string) $resumable['id'], $actor, $resumeClient
);
$assert(($cancelled['state'] ?? null) === 'cancelled'
&& array_map(static fn (array $item): string =>
$item['request']->getMethod(), $resumeHistory) === [
'POST', 'DELETE',
],
'A confirmed multipart abort did not settle the intent once.');
// A lost Abort response is reconciled with HEAD + ListParts. A 404 for
// the exact upload ID proves cancellation; DELETE must not be replayed.
$actor['request_idempotency_key'] = 'multipart-template-intent-0004';
$abortLost = $uploads->beginUpload(array_replace($input, [
'name' => 'Debian 13 abort lost',
'filename' => 'debian-13-abort-lost.qcow2',
]), $actor)['intent'];
$abortHistory = [];
$abortStack = HandlerStack::create(new MockHandler([
new Response(200, [], '<InitiateMultipartUploadResult>'
. '<UploadId>intent-upload-4</UploadId>'
. '</InitiateMultipartUploadResult>'),
new ConnectException('abort response lost',
new Request('DELETE', 'https://objects.example.test')),
new Response(404),
new Response(404),
]));
$abortStack->push(Middleware::history($abortHistory));
$abortClient = new CloudObjectStorageS3Client(new Client([
'handler' => $abortStack,
]));
$uploads->startUpload((string) $abortLost['id'], $actor, $abortClient);
$abortResult = $cancellation->cancel(
(string) $abortLost['id'], $actor, $abortClient
);
$assert(($abortResult['state'] ?? null) === 'cancelled'
&& array_map(static fn (array $item): string =>
$item['request']->getMethod(), $abortHistory) === [
'POST', 'DELETE', 'HEAD', 'GET',
],
'A lost Abort response was replayed instead of read-only reconciled.');
// If read-only evidence proves the upload still exists, cancellation is
// retryable with a new explicit action rather than reported as complete.
$actor['request_idempotency_key'] = 'multipart-template-intent-0005';
$abortActive = $uploads->beginUpload(array_replace($input, [
'name' => 'Debian 13 abort active',
'filename' => 'debian-13-abort-active.qcow2',
]), $actor)['intent'];
$activeStack = HandlerStack::create(new MockHandler([
new Response(200, [], '<InitiateMultipartUploadResult>'
. '<UploadId>intent-upload-5</UploadId>'
. '</InitiateMultipartUploadResult>'),
new ConnectException('abort response lost',
new Request('DELETE', 'https://objects.example.test')),
new Response(404),
new Response(200, [], '<ListPartsResult><IsTruncated>false</IsTruncated>'
. '</ListPartsResult>'),
]));
$activeClient = new CloudObjectStorageS3Client(new Client([
'handler' => $activeStack,
]));
$uploads->startUpload((string) $abortActive['id'], $actor, $activeClient);
try {
$cancellation->cancel((string) $abortActive['id'], $actor, $activeClient);
throw new \RuntimeException('A still-active abort was reported complete.');
} catch (CloudError $error) {
$assert($error->httpStatus === 409,
'A retryable abort failure returned the wrong HTTP status.');
}
$activeStored = CloudTemplateImportIntent::findOrFail(
(string) $abortActive['id']
);
$assert((string) $activeStored->state === 'source_unknown'
&& (string) $activeStored->error_code
=== 'multipart_abort_not_applied'
&& CloudTemplateImportReadModel::project($activeStored)['can_cancel']
=== true,
'Provider proof that Abort did not apply was not made retryable.');
// Losing the CreateMultipartUpload response must never be treated as a
// proven no-effect failure. The panel can abandon the unique object key,
// while bucket lifecycle removes any provider-side orphan.
$actor['request_idempotency_key'] = 'multipart-template-intent-0006';
$createUnknown = $uploads->beginUpload(array_replace($input, [
'name' => 'Debian 13 create unknown',
'filename' => 'debian-13-create-unknown.qcow2',
]), $actor)['intent'];
$createUnknownClient = new CloudObjectStorageS3Client(new Client([
'handler' => HandlerStack::create(new MockHandler([
new ConnectException('create response lost',
new Request('POST', 'https://objects.example.test')),
])),
]));
try {
$uploads->startUpload(
(string) $createUnknown['id'], $actor, $createUnknownClient
);
throw new \RuntimeException('Unknown multipart create was retryable.');
} catch (CloudError $error) {
$assert($error->httpStatus === 502,
'Unknown multipart create returned the wrong HTTP status.');
}
$unknownStored = CloudTemplateImportIntent::findOrFail(
(string) $createUnknown['id']
);
$assert((string) $unknownStored->state === 'source_unknown'
&& CloudTemplateImportReadModel::project($unknownStored)['can_cancel']
=== true,
'Unknown multipart create was not fenced for lifecycle abandonment.');
$abandoned = $cancellation->cancel(
(string) $createUnknown['id'], $actor, $createUnknownClient
);
$assert(($abandoned['state'] ?? null) === 'cancelled'
&& ($abandoned['error_code'] ?? null)
=== 'multipart_abandoned_lifecycle',
'Unknown multipart create was not abandoned for lifecycle cleanup.');
// An expired intent that never crossed multipart creation is cleaned
// locally without contacting object storage.
$actor['request_idempotency_key'] = 'multipart-template-intent-0007';
$expired = $uploads->beginUpload(array_replace($input, [
'name' => 'Debian 13 expired',
'filename' => 'debian-13-expired.qcow2',
]), $actor)['intent'];
Capsule::table('cloud_template_import_intents')
->where('id', (string) $expired['id'])
->update(['expires_at' => $clock - 1]);
$assert($cancellation->cleanupOneExpired(new CloudObjectStorageS3Client(
new Client(['handler' => HandlerStack::create(new MockHandler([]))])
))
&& (string) CloudTemplateImportIntent::findOrFail(
(string) $expired['id']
)->state === 'cancelled',
'Expired prepared upload was not cleaned without provider mutation.');
// Official URL imports use the same intent/object/task generation. A
// response replay must return the original task without a second download
// or immutable PUT.
$actor['request_idempotency_key'] = 'multipart-template-intent-0008';
$remoteBody = str_repeat('remote-qcow2-', 90000);
$remoteDigest = hash('sha256', $remoteBody);
$remoteFetchHistory = [];
$remoteFetchStack = HandlerStack::create(new MockHandler([
new Response(200, [
'Content-Length' => (string) strlen($remoteBody),
'Content-Encoding' => 'identity',
], $remoteBody),
]));
$remoteFetchStack->push(Middleware::history($remoteFetchHistory));
$remoteFetcher = new CloudTemplateRemoteFetcher(
new Client(['handler' => $remoteFetchStack]),
static fn (string $host): array => ['93.184.216.34']
);
$remoteStorageHistory = [];
$remoteStorageStack = HandlerStack::create(new MockHandler([
new Response(200, [
'ETag' => '"remote-object-etag"',
'x-amz-version-id' => 'remote-version-1',
]),
new Response(200, [
'Content-Length' => (string) strlen($remoteBody),
'ETag' => '"remote-object-etag"',
'x-amz-version-id' => 'remote-version-1',
]),
]));
$remoteStorageStack->push(Middleware::history($remoteStorageHistory));
$remoteClient = new CloudObjectStorageS3Client(new Client([
'handler' => $remoteStorageStack,
]));
$remoteInput = [
'name' => 'Debian 13 official',
'url' => 'https://images.example.test/debian-13.qcow2',
'sha256' => $remoteDigest,
];
$remoteAck = $remote->importRemote(
$remoteInput,
$actor,
$remoteFetcher,
$remoteClient
);
$remoteStored = CloudTemplateImportIntent::query()
->where('user_id', 9)
->where(
'request_idempotency_key',
'multipart-template-intent-0008'
)->firstOrFail();
$assert((string) $remoteStored->source_kind === 'remote'
&& (string) $remoteStored->state === 'distributing'
&& (int) $remoteStored->source_size_bytes === strlen($remoteBody)
&& hash_equals(
$remoteDigest,
(string) $remoteStored->source_sha256
)
&& count($remoteFetchHistory) === 1
&& array_map(static fn (array $item): string =>
$item['request']->getMethod(), $remoteStorageHistory) === [
'PUT', 'HEAD',
],
'Official URL import did not converge through the durable intent.');
$emptyFetcher = new CloudTemplateRemoteFetcher(
new Client(['handler' => HandlerStack::create(new MockHandler([]))]),
static fn (string $host): array => ['93.184.216.34']
);
$emptyStorage = new CloudObjectStorageS3Client(new Client([
'handler' => HandlerStack::create(new MockHandler([])),
]));
$remoteReplay = $remote->importRemote(
$remoteInput,
$actor,
$emptyFetcher,
$emptyStorage
);
$assert($remoteReplay === $remoteAck,
'Official URL replay did not return the original distribution task.');
// A failed official download remains one resumable intent. Retrying that
// intent must reuse its frozen object key and create only one task.
$actor['request_idempotency_key'] = 'multipart-template-intent-0009';
$failedFetcher = new CloudTemplateRemoteFetcher(
new Client(['handler' => HandlerStack::create(new MockHandler([
new Response(503),
]))]),
static fn (string $host): array => ['93.184.216.34']
);
try {
$remote->importRemote(
array_replace($remoteInput, ['name' => 'Debian 13 retry']),
$actor,
$failedFetcher,
$emptyStorage
);
throw new \RuntimeException('A rejected remote download succeeded.');
} catch (CloudError $error) {
$assert($error->httpStatus === 502,
'A rejected remote download returned the wrong status.');
}
$failedRemote = CloudTemplateImportIntent::query()
->where('request_idempotency_key',
'multipart-template-intent-0009')->firstOrFail();
$failedDto = CloudTemplateImportReadModel::project($failedRemote);
$assert((string) $failedRemote->state === 'source_failed'
&& $failedDto['can_resume'] === true
&& $failedDto['can_cancel'] === true,
'A failed official download did not expose a safe recovery exit.');
$retryFetchHistory = [];
$retryFetchStack = HandlerStack::create(new MockHandler([
new Response(200, [
'Content-Length' => (string) strlen($remoteBody),
'Content-Encoding' => 'identity',
], $remoteBody),
]));
$retryFetchStack->push(Middleware::history($retryFetchHistory));
$retryStorageHistory = [];
$retryStorageStack = HandlerStack::create(new MockHandler([
new Response(200, [
'ETag' => '"remote-retry-etag"',
'x-amz-version-id' => 'remote-retry-version',
]),
new Response(200, [
'Content-Length' => (string) strlen($remoteBody),
'ETag' => '"remote-retry-etag"',
'x-amz-version-id' => 'remote-retry-version',
]),
]));
$retryStorageStack->push(Middleware::history($retryStorageHistory));
$retryAck = $remote->resumeRemote(
(string) $failedRemote->id,
$actor,
new CloudTemplateRemoteFetcher(
new Client(['handler' => $retryFetchStack]),
static fn (string $host): array => ['93.184.216.34']
),
new CloudObjectStorageS3Client(new Client([
'handler' => $retryStorageStack,
]))
);
$assert((int) ($retryAck['task_id'] ?? 0) > 0
&& count($retryFetchHistory) === 1
&& array_map(static fn (array $item): string =>
$item['request']->getMethod(), $retryStorageHistory) === [
'PUT', 'HEAD',
],
'Resuming an official download did not reuse its durable intent.');
// An expired remote fetch that never crossed object publication can be
// cancelled locally; no object-storage mutation is needed.
$actor['request_idempotency_key'] = 'multipart-template-intent-0010';
try {
$remote->importRemote(
array_replace($remoteInput, ['name' => 'Debian 13 expired remote']),
$actor,
new CloudTemplateRemoteFetcher(
new Client(['handler' => HandlerStack::create(
new MockHandler([new Response(503)])
)]),
static fn (string $host): array => ['93.184.216.34']
),
$emptyStorage
);
} catch (CloudError $error) {
// The durable source_failed intent is the expected test fixture.
$root = dirname(__DIR__);
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
$expiredRemote = CloudTemplateImportIntent::query()
->where('request_idempotency_key',
'multipart-template-intent-0010')->firstOrFail();
Capsule::table('cloud_template_import_intents')
->where('id', (string) $expiredRemote->id)
->update(['expires_at' => $clock - 1]);
$assert($cancellation->cleanupOneExpired($emptyStorage)
&& (string) CloudTemplateImportIntent::findOrFail(
(string) $expiredRemote->id
)->state === 'cancelled',
'Expired official download was not reaped without provider mutation.');
// A lost immutable PUT response plus an unavailable HEAD is effect
// unknown. The same intent must stay fenced until a later HEAD proves the
// exact object; recovery must not download or PUT the image again.
$actor['request_idempotency_key'] = 'multipart-template-intent-0011';
$unknownFetchHistory = [];
$unknownFetchStack = HandlerStack::create(new MockHandler([
new Response(200, [
'Content-Length' => (string) strlen($remoteBody),
'Content-Encoding' => 'identity',
], $remoteBody),
]));
$unknownFetchStack->push(Middleware::history($unknownFetchHistory));
$unknownStorageHistory = [];
$unknownStorageStack = HandlerStack::create(new MockHandler([
new ConnectException('put response lost',
new Request('PUT', 'https://objects.example.test')),
new ConnectException('head unavailable',
new Request('HEAD', 'https://objects.example.test')),
]));
$unknownStorageStack->push(Middleware::history($unknownStorageHistory));
try {
$remote->importRemote(
array_replace($remoteInput, ['name' => 'Debian 13 unknown put']),
$actor,
new CloudTemplateRemoteFetcher(
new Client(['handler' => $unknownFetchStack]),
static fn (string $host): array => ['93.184.216.34']
),
new CloudObjectStorageS3Client(new Client([
'handler' => $unknownStorageStack,
]))
);
throw new \RuntimeException('An unknown immutable PUT was accepted.');
} catch (CloudError $error) {
$assert($error->httpStatus === 502,
'Unknown immutable PUT returned the wrong status.');
}
$unknownRemote = CloudTemplateImportIntent::query()
->where('request_idempotency_key',
'multipart-template-intent-0011')->firstOrFail();
$unknownDto = CloudTemplateImportReadModel::project($unknownRemote);
$assert((string) $unknownRemote->state === 'source_unknown'
&& $unknownDto['can_resume'] === true
&& $unknownDto['can_cancel'] === false
&& count($unknownFetchHistory) === 1
&& array_map(static fn (array $item): string =>
$item['request']->getMethod(), $unknownStorageHistory) === [
'PUT', 'HEAD',
],
'Unknown immutable PUT was not fenced on its original object key.');
$reconcileHistory = [];
$reconcileStack = HandlerStack::create(new MockHandler([
new Response(200, [
'Content-Length' => (string) strlen($remoteBody),
'ETag' => '"remote-unknown-etag"',
'x-amz-version-id' => 'remote-unknown-version',
]),
new Response(200, [
'Content-Length' => (string) strlen($remoteBody),
'ETag' => '"remote-unknown-etag"',
'x-amz-version-id' => 'remote-unknown-version',
]),
]));
$reconcileStack->push(Middleware::history($reconcileHistory));
$unknownAck = $remote->resumeRemote(
(string) $unknownRemote->id,
$actor,
$emptyFetcher,
new CloudObjectStorageS3Client(new Client([
'handler' => $reconcileStack,
]))
);
$assert((int) ($unknownAck['task_id'] ?? 0) > 0
&& count($unknownFetchHistory) === 1
&& array_map(static fn (array $item): string =>
$item['request']->getMethod(), $reconcileHistory) === [
'HEAD', 'HEAD',
],
'Unknown immutable PUT recovery replayed a download or write.');
// If the reconciliation HEAD proves the PUT did not apply, retrying the
// same intent is safe and may fetch and publish that frozen key again.
$actor['request_idempotency_key'] = 'multipart-template-intent-0012';
$absentFetchStack = HandlerStack::create(new MockHandler([
new Response(200, [
'Content-Length' => (string) strlen($remoteBody),
'Content-Encoding' => 'identity',
], $remoteBody),
]));
$absentStorageHistory = [];
$absentStorageStack = HandlerStack::create(new MockHandler([
new ConnectException('put response lost',
new Request('PUT', 'https://objects.example.test')),
new Response(404),
]));
$absentStorageStack->push(Middleware::history($absentStorageHistory));
try {
$remote->importRemote(
array_replace($remoteInput, ['name' => 'Debian 13 absent put']),
$actor,
new CloudTemplateRemoteFetcher(
new Client(['handler' => $absentFetchStack]),
static fn (string $host): array => ['93.184.216.34']
),
new CloudObjectStorageS3Client(new Client([
'handler' => $absentStorageStack,
]))
);
throw new \RuntimeException('A proven absent PUT was accepted.');
} catch (CloudError $error) {
$assert($error->httpStatus === 502,
'Proven absent immutable PUT returned the wrong status.');
}
$absentRemote = CloudTemplateImportIntent::query()
->where('request_idempotency_key',
'multipart-template-intent-0012')->firstOrFail();
$assert((string) $absentRemote->state === 'source_failed'
&& array_map(static fn (array $item): string =>
$item['request']->getMethod(), $absentStorageHistory) === [
'PUT', 'HEAD',
],
'Proven absent immutable PUT was not made safely retryable.');
$absentRetryStorage = new CloudObjectStorageS3Client(new Client([
'handler' => HandlerStack::create(new MockHandler([
new Response(200, [
'ETag' => '"remote-absent-retry-etag"',
'x-amz-version-id' => 'remote-absent-retry-version',
]),
new Response(200, [
'Content-Length' => (string) strlen($remoteBody),
'ETag' => '"remote-absent-retry-etag"',
'x-amz-version-id' => 'remote-absent-retry-version',
]),
])),
]));
$absentRetryAck = $remote->resumeRemote(
(string) $absentRemote->id,
$actor,
new CloudTemplateRemoteFetcher(
new Client(['handler' => HandlerStack::create(new MockHandler([
new Response(200, [
'Content-Length' => (string) strlen($remoteBody),
'Content-Encoding' => 'identity',
], $remoteBody),
]))]),
static fn (string $host): array => ['93.184.216.34']
),
$absentRetryStorage
);
$assert((int) ($absentRetryAck['task_id'] ?? 0) > 0,
'A proven absent immutable PUT could not resume on the same intent.');
echo "Cloud-template resumable multipart import behavior passed.\n";
}
};
$reservation = file_get_contents(
$root . '/app/Services/Cloud/CloudTemplateImportReservation.php'
);
$multipart = file_get_contents(
$root . '/app/Services/Cloud/CloudTemplateMultipartAcquisition.php'
);
$cancellation = file_get_contents(
$root . '/app/Services/Cloud/CloudTemplateImportCancellation.php'
);
$frontend = file_get_contents(
$root . '/public/cloud/admin-template-upload.js'
);
$assert(is_string($reservation)
&& str_contains($reservation, "'last_modified', 'sha256'")
&& str_contains($reservation,
'开始上传前必须完成云镜像 SHA-256 校验')
&& str_contains($reservation,
'CloudTemplateStoragePublicationService::reserve($intent)'),
'Local template upload did not freeze identity before provider I/O.');
$assert(is_string($multipart)
&& str_contains($multipart,
'CloudStorageArtifactService::claimPrimaryPreparation(')
&& str_contains($multipart,
'prepareKnownIdentityMultipartUpload(')
&& str_contains($multipart,
'CloudStorageArtifactService::markPrimaryAwaitingReceipt(')
&& str_contains($multipart,
'CloudStorageArtifactService::completePrimary(')
&& str_contains($multipart,
"(string) \$identity['sha256']")
&& str_contains($multipart, 'inspectObject(')
&& str_contains($multipart,
'findMultipartUploadsByExactObjectKey(')
&& str_contains($multipart,
'reschedulePrimaryAfterStableAbsence(')
&& str_contains($multipart,
'markPrimaryPreparationAttention(')
&& str_contains($multipart, 'ACTION_RECONCILE_MULTIPART_START'),
'Multipart template upload lost its original-operation recovery fence.');
$assert(is_string($cancellation)
&& str_contains($cancellation,
'cancelNeverDispatched($intent, $client)')
&& str_contains($cancellation,
'cancelAfterConfirmedAbort($intent, $client)')
&& str_contains($cancellation,
'CloudTemplateStoragePublicationService::primaryRuntime(')
&& str_contains($cancellation,
"->where('template_import_intent_id', (string) \$intent->id)")
&& !str_contains($cancellation, 'self::runtime($intent)'),
'Template cancellation retained the legacy frozen-runtime cleanup path.');
$hashPosition = is_string($frontend)
? strpos($frontend, 'const sha256 = await activeHash.promise;') : false;
$reservePosition = is_string($frontend)
? strpos($frontend, "'/api/v1/admin/cloud-template-imports', {") : false;
$assert(is_int($hashPosition) && is_int($reservePosition)
&& $hashPosition < $reservePosition
&& str_contains($frontend, 'protection_pending === true')
&& str_contains($frontend, 'const unknownCreate =')
&& !str_contains($frontend,
"body: { sha256 }, response: 'task'"),
'Template upload UI crosses storage before hashing or rejects protection wait.');
echo "Template multipart storage-ledger contract passed.\n";

Loading…
Cancel
Save