You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/tests/CloudDeploymentSnapshotServ...

764 lines
32 KiB
PHP

<?php
namespace App\Services {
final class Config
{
public static string $dataKey = '';
public static function get($name, $default = null)
{
return $name === 'cloud_data_key' ? self::$dataKey : $default;
}
}
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\CloudInstanceBackup;
use App\Services\Config;
use App\Services\Cloud\CloudDeploymentSnapshotService;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudObjectStorageS3Client;
use App\Services\Cloud\CloudSecrets;
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);
}
};
$expect = static function (int $status, callable $callback) use (
$assert
): void {
try {
$callback();
} catch (CloudError $error) {
$assert($error->httpStatus === $status,
'Cloud snapshot failure returned the wrong status.');
return;
}
throw new RuntimeException('Expected cloud snapshot failure.');
};
$capsule = new Capsule();
$capsule->addConnection([
'driver' => 'sqlite', 'database' => ':memory:',
], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = $capsule->schema('default');
$schema->create('user', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('enable');
});
$schema->create('cloud_instances', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('user_id');
$table->string('name');
$table->string('status');
});
$schema->create('cloud_backup_subscriptions',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('instance_id');
$table->integer('user_id');
});
$schema->create('cloud_backup_period_entitlements',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('subscription_id');
$table->integer('instance_id');
$table->integer('user_id');
$table->integer('ends_at');
});
$schema->create('cloud_instance_backups',
static function (Blueprint $table): void {
$table->increments('id');
$table->string('backup_key')->unique();
$table->integer('storage_artifact_id')->nullable();
$table->integer('source_instance_id');
$table->integer('source_host_id');
$table->integer('user_id');
$table->string('source_uuid');
$table->string('name');
$table->string('purpose');
$table->string('source');
$table->integer('subscription_id')->nullable();
$table->integer('scheduled_for')->nullable();
$table->string('state');
$table->string('consistency');
$table->string('object_key')->unique();
$table->integer('object_size_bytes');
$table->integer('virtual_size_bytes');
$table->string('sha256');
$table->string('object_etag')->default('');
$table->string('object_version_id')->default('');
$table->text('spec_json');
$table->text('sealed_storage_runtime');
$table->text('sealed_credential')->nullable();
$table->integer('storage_revision');
$table->integer('active_job_id')->nullable();
$table->string('last_operation_id')->nullable();
$table->string('delete_operation_id')->nullable();
$table->integer('delete_generation')->default(0);
$table->integer('delete_cycle_attempts')->default(0);
$table->integer('delete_presence_confirmations')->default(0);
$table->integer('delete_requested_at')->nullable();
$table->integer('delete_last_checked_at')->nullable();
$table->integer('delete_next_check_at')->default(0);
$table->integer('delete_attention_at')->nullable();
$table->string('error_code');
$table->integer('ready_at')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_storage_artifacts',
static function (Blueprint $table): void {
$table->increments('id');
$table->string('artifact_key');
$table->string('kind');
$table->integer('maximum_size_bytes');
$table->integer('size_bytes');
$table->string('sha256', 64);
$table->string('durability_policy');
$table->integer('desired_copies');
$table->integer('required_copies');
$table->string('state');
$table->string('last_operation_id')->nullable();
$table->integer('verified_at');
$table->integer('created_at');
$table->integer('updated_at');
});
$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->integer('config_revision');
$table->integer('tested_revision');
$table->string('admin_state');
$table->string('health_state');
$table->integer('write_priority');
$table->integer('consecutive_failures')->default(0);
$table->integer('consecutive_successes')->default(0);
$table->string('last_error_code')->default('');
$table->integer('last_tested_at')->default(0);
$table->integer('last_healthy_at')->default(0);
$table->integer('next_probe_at')->default(0);
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_storage_replicas',
static function (Blueprint $table): void {
$table->increments('id');
$table->string('replica_key')->unique();
$table->integer('artifact_id');
$table->integer('backend_id');
$table->string('role');
$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('publish_operation_id')->nullable();
$table->string('delete_operation_id')->nullable();
$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->string('lease_token')->nullable();
$table->integer('lease_until')->default(0);
$table->string('error_code')->default('');
$table->integer('verified_at')->default(0);
$table->integer('created_at');
$table->integer('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->integer('artifact_id');
$table->integer('replica_id')->nullable();
$table->integer('source_backend_id')->nullable();
$table->integer('target_backend_id')->nullable();
$table->string('kind');
$table->string('phase');
$table->string('outcome')->nullable();
$table->string('effect_resolution');
$table->integer('effect_may_have_applied')->nullable();
$table->integer('safe_to_resubmit')->nullable();
$table->integer('attempts');
$table->string('lease_token')->nullable();
$table->integer('lease_until');
$table->integer('available_at');
$table->integer('next_check_at');
$table->string('error_code');
$table->text('result_json')->nullable();
$table->integer('terminal_at')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_storage_publications',
static function (Blueprint $table): void {
$table->increments('id');
$table->string('publication_key')->unique();
$table->integer('artifact_id');
$table->integer('backup_id')->nullable();
$table->string('template_import_intent_id')->nullable();
$table->string('rescue_template_id')->nullable();
$table->string('state');
$table->integer('attempts')->default(0);
$table->integer('available_at')->default(0);
$table->string('lease_token')->nullable();
$table->integer('lease_until')->default(0);
$table->string('last_error_code')->default('');
$table->integer('coverage_ready_at')->nullable();
$table->integer('finalized_at')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_deployment_snapshots',
static function (Blueprint $table): void {
$table->increments('id');
$table->string('snapshot_key')->unique();
$table->integer('user_id');
$table->integer('backup_id')->unique();
$table->integer('source_instance_id');
$table->string('name');
$table->string('state');
$table->string('idempotency_key');
$table->string('request_hash');
$table->string('error_code');
$table->integer('ready_at');
$table->integer('deleted_at')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
$table->unique(['user_id', 'idempotency_key']);
});
$schema->create('cloud_orders', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('user_id');
$table->integer('deployment_snapshot_id')->nullable();
$table->string('status');
});
$schema->create('cloud_backup_restores',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('backup_id');
$table->string('state');
});
$schema->create('cloud_backup_recoveries',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('backup_id');
$table->string('state');
});
$schema->create('cloud_jobs', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('backup_id')->nullable();
$table->string('phase');
$table->string('effect_resolution');
$table->integer('finalization_incident')->default(0);
});
$now = time();
$capsule->table('user')->insert([
['id' => 7, 'enable' => 1],
['id' => 8, 'enable' => 1],
]);
$capsule->table('cloud_instances')->insert([
'id' => 50, 'user_id' => 7, 'name' => 'source-vm',
'status' => 'active',
]);
foreach ([1, 2, 3, 4] as $subscriptionId) {
$capsule->table('cloud_backup_subscriptions')->insert([
'id' => $subscriptionId, 'instance_id' => 50, 'user_id' => 7,
]);
}
$capsule->table('cloud_backup_period_entitlements')->insert([
['subscription_id' => 1, 'instance_id' => 50, 'user_id' => 7,
'ends_at' => $now + 86400],
['subscription_id' => 2, 'instance_id' => 50, 'user_id' => 7,
'ends_at' => $now - 4 * 86400],
['subscription_id' => 3, 'instance_id' => 50, 'user_id' => 7,
'ends_at' => $now + 86400],
['subscription_id' => 4, 'instance_id' => 50, 'user_id' => 7,
'ends_at' => $now + 86400],
]);
Config::$dataKey = base64_encode(str_repeat('d', 32));
$sealedBackendCredentials = function_exists(
'sodium_crypto_aead_xchacha20poly1305_ietf_encrypt'
) ? CloudSecrets::encrypt([
'access_key_id' => 'SNAPSHOTACCESS',
'secret_access_key' => 'snapshot-secret-value',
], 'object-storage-backend-credentials') : 'sealed-test-double';
$capsule->table('cloud_storage_backends')->insert([
'id' => 1,
'backend_key' => str_repeat('b', 32),
'identity_sha256' => str_repeat('c', 64),
'name' => 'snapshot-primary',
'driver' => 's3',
'endpoint' => 'https://objects.example.com',
'region' => 'us-east-1',
'bucket' => 'backup-bucket',
'prefix' => 'virt',
'path_style' => 1,
'failure_domain' => 'snapshot-primary',
'sealed_credentials' => $sealedBackendCredentials,
'config_revision' => 1,
'tested_revision' => 1,
'admin_state' => 'active',
'health_state' => 'healthy',
'write_priority' => 1,
'consecutive_successes' => 1,
'last_tested_at' => $now,
'last_healthy_at' => $now,
'next_probe_at' => $now + 300,
'created_at' => $now,
'updated_at' => $now,
]);
$newBackup = static function (int $id, int $userId, int $subscriptionId,
string $state = 'ready') use ($capsule, $now): CloudInstanceBackup {
$backup = new CloudInstanceBackup();
$backup->id = $id;
$backup->backup_key = str_pad(dechex($id), 32, '0', STR_PAD_LEFT);
$backup->source_instance_id = 50;
$backup->source_host_id = 3;
$backup->user_id = $userId;
$backup->source_uuid = '11111111-1111-4111-8111-111111111111';
$backup->name = 'backup-' . $id;
$backup->purpose = 'portable';
$backup->source = 'automatic';
$backup->subscription_id = $subscriptionId;
$backup->scheduled_for = $now - 60;
$backup->state = $state;
$backup->consistency = 'filesystem';
$backup->object_key = 'virt/vm-backups/' . $id . '/system.qcow2';
$backup->object_size_bytes = 1024;
$backup->virtual_size_bytes = 2048;
$backup->sha256 = str_repeat(dechex(($id % 15) + 1), 64);
$backup->object_etag = '';
$backup->object_version_id = '';
$backup->spec_json = json_encode([
'managed' => true,
'os_source' => 'cloud_template',
'os_name' => 'Debian 13',
'login_name' => 'root',
'debian_12_network_fix' => false,
], JSON_THROW_ON_ERROR);
$backup->sealed_storage_runtime = '';
$backup->sealed_credential = 'sealed-credential';
$backup->storage_revision = 1;
$backup->active_job_id = null;
$backup->last_operation_id = null;
$backup->delete_generation = 0;
$backup->delete_cycle_attempts = 0;
$backup->delete_presence_confirmations = 0;
$backup->delete_next_check_at = 0;
$backup->error_code = '';
$backup->ready_at = $now;
$backup->created_at = $backup->updated_at = $now;
$backup->save();
$artifactId = 1000 + $id;
$capsule->table('cloud_storage_artifacts')->insert([
'id' => $artifactId,
'artifact_key' => str_pad(dechex($artifactId), 32, '0', STR_PAD_LEFT),
'kind' => 'backup',
'maximum_size_bytes' => 2048,
'size_bytes' => (int) $backup->object_size_bytes,
'sha256' => (string) $backup->sha256,
'durability_policy' => 'single',
'desired_copies' => 1,
'required_copies' => 1,
'state' => 'available',
'last_operation_id' => null,
'verified_at' => $now,
'created_at' => $now,
'updated_at' => $now,
]);
$capsule->table('cloud_storage_publications')->insert([
'publication_key' => str_pad(
dechex(2000 + $id), 32, '0', STR_PAD_LEFT
),
'artifact_id' => $artifactId,
'backup_id' => (int) $backup->id,
'state' => 'completed',
'coverage_ready_at' => $now,
'finalized_at' => $now,
'created_at' => $now,
'updated_at' => $now,
]);
$capsule->table('cloud_storage_replicas')->insert([
'replica_key' => str_pad(
dechex(3000 + $id), 32, '0', STR_PAD_LEFT
),
'artifact_id' => $artifactId,
'backend_id' => 1,
'role' => 'primary',
'object_key' => 'virt/vm-backups/' . $id . '/system.qcow2',
'object_version_id' => 'version-' . $id,
'object_etag' => '"etag-' . $id . '"',
'size_bytes' => (int) $backup->object_size_bytes,
'sha256' => (string) $backup->sha256,
'state' => 'ready',
'verified_at' => $now,
'created_at' => $now,
'updated_at' => $now,
]);
$backup->storage_artifact_id = $artifactId;
$backup->storage_revision = 0;
$backup->save();
return $backup;
};
$actor = ['user_id' => 7];
$good = $newBackup(11, 7, 1);
$good->sealed_credential = null;
$good->save();
$snapshot = CloudDeploymentSnapshotService::promote(11, [
'name' => '生产恢复点',
'idempotency_key' => 'snapshot-promote-0001',
], $actor);
$replayed = CloudDeploymentSnapshotService::promote(11, [
'name' => '生产恢复点',
'idempotency_key' => 'snapshot-promote-0001',
], $actor);
$assert((int) $snapshot->id === (int) $replayed->id
&& preg_match('/^[a-f0-9]{32}$/D',
(string) $snapshot->snapshot_key) === 1,
'Cloud backup promotion was not idempotent.');
$expect(409, static fn () =>
CloudDeploymentSnapshotService::promote(11, [
'name' => '不同名称',
'idempotency_key' => 'snapshot-promote-0001',
], $actor));
$library = CloudDeploymentSnapshotService::library($actor, [
'page' => 1, 'per_page' => 20,
]);
$item = $library['items'][0] ?? [];
$assert(($library['pagination']['total'] ?? 0) === 1
&& ($item['snapshot_key'] ?? '') === (string) $snapshot->snapshot_key
&& ($item['name'] ?? '') === '生产恢复点'
&& ($item['os_name'] ?? '') === 'Debian 13'
&& ($item['source_instance']['name'] ?? '') === 'source-vm'
&& !array_key_exists('backup_id', $item)
&& !array_key_exists('object_key', $item)
&& !array_key_exists('sha256', $item)
&& !array_key_exists('sealed_storage_runtime', $item),
'Cloud snapshot library leaked backing identity or omitted display data.');
$capsule->table('cloud_backup_period_entitlements')
->where('subscription_id', 1)->update(['ends_at' => $now - 5 * 86400]);
$resolved = CloudDeploymentSnapshotService::resolveForOrder(
(string) $snapshot->snapshot_key, 7
);
$assert((int) $resolved['backup']->id === (int) $good->id,
'A promoted cloud snapshot incorrectly followed later backup entitlement expiry.');
$deploymentSource = CloudDeploymentSnapshotService::deploymentSource(
(string) $snapshot->snapshot_key, $actor
);
$assert(($deploymentSource['snapshot_key'] ?? '')
=== (string) $snapshot->snapshot_key
&& ($deploymentSource['can_create_instance'] ?? false) === true
&& !array_key_exists('object_key', $deploymentSource),
'Deployment bootstrap did not resolve a safe owner snapshot projection.');
$capsule->table('cloud_instance_backups')->where('id', (int) $good->id)
->update(['state' => 'failed']);
foreach ([
static fn () => CloudDeploymentSnapshotService::resolveForOrder(
(string) $snapshot->snapshot_key, 7
),
static fn () => CloudDeploymentSnapshotService::deploymentSource(
(string) $snapshot->snapshot_key, $actor
),
] as $invalidDeploymentSource) {
try {
$invalidDeploymentSource();
throw new RuntimeException(
'Invalid backing unexpectedly remained deployable.'
);
} catch (CloudError $error) {
$assert($error->getMessage()
=== '云快照不存在或当前不可用于部署',
'Deployment used the backup-promotion error vocabulary.');
}
}
$capsule->table('cloud_instance_backups')->where('id', (int) $good->id)
->update(['state' => 'ready']);
$capsule->table('cloud_deployment_snapshots')
->where('id', (int) $snapshot->id)
->update(['source_instance_id' => 999]);
$expect(409, static fn () =>
CloudDeploymentSnapshotService::resolveForOrder(
(string) $snapshot->snapshot_key, 7
));
$expect(409, static fn () =>
CloudDeploymentSnapshotService::deploymentSource(
(string) $snapshot->snapshot_key, $actor
));
$capsule->table('cloud_deployment_snapshots')
->where('id', (int) $snapshot->id)
->update(['source_instance_id' => (int) $good->source_instance_id]);
$wrongOwner = $newBackup(12, 8, 3);
$expect(409, static fn () =>
CloudDeploymentSnapshotService::promote((int) $wrongOwner->id, [
'idempotency_key' => 'snapshot-promote-0002',
], $actor));
$failed = $newBackup(13, 7, 3, 'failed');
$expect(409, static fn () =>
CloudDeploymentSnapshotService::promote((int) $failed->id, [
'idempotency_key' => 'snapshot-promote-0003',
], $actor));
$expired = $newBackup(14, 7, 2);
$expect(409, static fn () =>
CloudDeploymentSnapshotService::promote((int) $expired->id, [
'idempotency_key' => 'snapshot-promote-0004',
], $actor));
$capsule->table('cloud_orders')->insert([
'id' => 91,
'user_id' => 7,
'deployment_snapshot_id' => (int) $snapshot->id,
'status' => 'awaiting_payment',
]);
$expect(409, static fn () => CloudDeploymentSnapshotService::delete(
(string) $snapshot->snapshot_key, $actor
));
$capsule->table('cloud_orders')->where('id', 91)
->update(['status' => 'expired']);
$capsule->table('cloud_jobs')->insert([
'id' => 81,
'backup_id' => (int) $good->id,
'phase' => 'accepted',
'effect_resolution' => 'not_applicable',
'finalization_incident' => 0,
]);
$expect(409, static fn () => CloudDeploymentSnapshotService::delete(
(string) $snapshot->snapshot_key, $actor
));
$capsule->table('cloud_jobs')->where('id', 81)->update([
'phase' => 'terminal',
'effect_resolution' => 'applied',
]);
$capsule->table('cloud_jobs')->insert([
'id' => 82,
'backup_id' => (int) $good->id,
'phase' => 'terminal',
'effect_resolution' => 'unknown',
'finalization_incident' => 0,
]);
$expect(409, static fn () => CloudDeploymentSnapshotService::delete(
(string) $snapshot->snapshot_key, $actor
));
$capsule->table('cloud_jobs')->where('id', 82)->update([
'effect_resolution' => 'not_applied',
]);
$capsule->table('cloud_jobs')->insert([
'id' => 83,
'backup_id' => (int) $good->id,
'phase' => 'terminal',
'effect_resolution' => 'applied',
'finalization_incident' => 1,
]);
$expect(409, static fn () => CloudDeploymentSnapshotService::delete(
(string) $snapshot->snapshot_key, $actor
));
$capsule->table('cloud_jobs')->where('id', 83)->update([
'finalization_incident' => 0,
]);
if (function_exists('sodium_crypto_aead_xchacha20poly1305_ietf_encrypt')) {
$client = static function (array $responses,
array &$history): CloudObjectStorageS3Client {
$stack = HandlerStack::create(new MockHandler($responses));
$stack->push(Middleware::history($history));
return new CloudObjectStorageS3Client(new Client([
'handler' => $stack,
]));
};
$history = [];
$deleted = CloudDeploymentSnapshotService::delete(
(string) $snapshot->snapshot_key,
$actor,
$client([
new Response(200, [
'Content-Length' => '1024',
'ETag' => '"etag-11"',
'x-amz-version-id' => 'version-11',
]),
new Response(204),
], $history)
);
$good->refresh();
$assert(($deleted['state'] ?? '') === 'deleted'
&& (string) $good->state === 'deleted'
&& count($history) === 2
&& $history[0]['request']->getMethod() === 'HEAD'
&& $history[1]['request']->getMethod() === 'DELETE',
'Cloud snapshot deletion did not converge its backing object.');
$uncertainBackup = $newBackup(15, 7, 3);
$uncertainSnapshot = CloudDeploymentSnapshotService::promote(15, [
'idempotency_key' => 'snapshot-promote-0005',
], $actor);
$uncertainHistory = [];
$uncertain = CloudDeploymentSnapshotService::delete(
(string) $uncertainSnapshot->snapshot_key,
$actor,
$client([
new Response(200, [
'Content-Length' => '1024',
'ETag' => '"etag-15"',
'x-amz-version-id' => 'version-15',
]),
new ConnectException(
'timeout', new Request('DELETE', 'https://objects.example.com')
),
], $uncertainHistory)
);
$assert(($uncertain['state'] ?? '') === 'delete_uncertain'
&& count($uncertainHistory) === 2
&& $uncertainHistory[1]['request']->getMethod() === 'DELETE',
'Unknown object deletion was not reflected by the cloud snapshot.');
$uncertainBackup->refresh();
$uncertainBackup->delete_next_check_at = 0;
$uncertainBackup->save();
$capsule->table('cloud_storage_operations')
->where('artifact_id', (int) $uncertainBackup->storage_artifact_id)
->where('kind', 'delete')->update(['next_check_at' => 0]);
$capsule->table('cloud_storage_replicas')
->where('artifact_id', (int) $uncertainBackup->storage_artifact_id)
->update(['delete_next_check_at' => 0]);
$reconcileHistory = [];
$reconciled = CloudDeploymentSnapshotService::delete(
(string) $uncertainSnapshot->snapshot_key,
$actor,
$client([new Response(404)], $reconcileHistory)
);
$assert(($reconciled['state'] ?? '') === 'deleted'
&& count($reconcileHistory) === 1
&& $reconcileHistory[0]['request']->getMethod() === 'HEAD',
'Cloud snapshot reconciliation replayed DeleteObject.');
} else {
$capsule->table('cloud_deployment_snapshots')
->where('id', (int) $snapshot->id)->update([
'state' => 'deleted', 'deleted_at' => $now,
]);
$capsule->table('cloud_instance_backups')
->where('id', (int) $good->id)->update(['state' => 'deleted']);
}
$second = $newBackup(16, 7, 3);
CloudDeploymentSnapshotService::promote((int) $second->id, [
'idempotency_key' => 'snapshot-promote-0006',
], $actor);
$third = $newBackup(17, 7, 4);
CloudDeploymentSnapshotService::promote((int) $third->id, [
'idempotency_key' => 'snapshot-promote-0007',
], $actor);
$fourth = $newBackup(18, 7, 4);
$expect(409, static fn () =>
CloudDeploymentSnapshotService::promote((int) $fourth->id, [
'idempotency_key' => 'snapshot-promote-0008',
], $actor));
$capsule->table('cloud_deployment_snapshots')
->where('backup_id', (int) $second->id)->update([
'state' => 'deleted', 'deleted_at' => $now,
]);
$artifactBackup = $newBackup(19, 7, 3);
$artifactBackup->storage_artifact_id = 901;
$artifactBackup->sealed_storage_runtime = '';
$artifactBackup->storage_revision = 0;
$artifactBackup->save();
$capsule->table('cloud_storage_artifacts')->insert([
'id' => 901,
'artifact_key' => str_repeat('9', 32),
'kind' => 'backup',
'maximum_size_bytes' => 2048,
'size_bytes' => (int) $artifactBackup->object_size_bytes,
'sha256' => (string) $artifactBackup->sha256,
'durability_policy' => 'mirror_async_2',
'desired_copies' => 2,
'required_copies' => 1,
'state' => 'available',
'last_operation_id' => str_repeat('8', 32),
'verified_at' => $now,
'created_at' => $now,
'updated_at' => $now,
]);
$capsule->table('cloud_storage_publications')->insert([
'id' => 902,
'publication_key' => str_repeat('9', 32),
'artifact_id' => 901,
'backup_id' => 18,
'state' => 'ready_to_finalize',
'attempts' => 0,
'available_at' => 0,
'lease_token' => null,
'lease_until' => 0,
'last_error_code' => '',
'coverage_ready_at' => $now,
'finalized_at' => null,
'created_at' => $now,
'updated_at' => $now,
]);
$snapshotRowsBeforeOwnerCheck =
$capsule->table('cloud_deployment_snapshots')->count();
$expect(409, static fn () => CloudDeploymentSnapshotService::promote(
(int) $artifactBackup->id,
['idempotency_key' => 'snapshot-promote-artifact-wrong-owner'],
$actor
));
$assert(
$capsule->table('cloud_deployment_snapshots')->count()
=== $snapshotRowsBeforeOwnerCheck
&& $capsule->table('cloud_storage_artifacts')
->where('id', 901)->value('state') === 'available'
&& $capsule->table('cloud_storage_publications')
->where('id', 902)->value('state') === 'ready_to_finalize'
&& (int) $capsule->table('cloud_storage_publications')
->where('id', 902)->value('backup_id') === 18,
'Cross-backup artifact binding granted a snapshot or changed state.'
);
$capsule->table('cloud_storage_publications')->where('id', 902)->update([
'backup_id' => (int) $artifactBackup->id,
'updated_at' => $now,
]);
$artifactSnapshot = CloudDeploymentSnapshotService::promote(
(int) $artifactBackup->id,
['idempotency_key' => 'snapshot-promote-artifact-0001'],
$actor
);
$assert((int) $artifactSnapshot->backup_id === (int) $artifactBackup->id,
'Artifact-backed automatic backup could not become a cloud snapshot.');
echo "Cloud deployment snapshot service tests passed.\n";
}