feat(template): publish through replicated storage ledger
parent
013d05f93c
commit
1cfe6a8866
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -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";
|
||||
|
||||
@ -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…
Reference in New Issue