feat(template): add durable import intents
parent
ff1ca4e558
commit
a31f18ad35
@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
/** Durable authority for one cloud-template source acquisition. */
|
||||
final class CloudTemplateImportIntent extends Model
|
||||
{
|
||||
protected $connection = 'default';
|
||||
protected $table = 'cloud_template_import_intents';
|
||||
protected $primaryKey = 'id';
|
||||
public $incrementing = false;
|
||||
protected $keyType = 'string';
|
||||
protected $hidden = ['sealed_source', 'sealed_storage_runtime',
|
||||
'multipart_upload_id'];
|
||||
protected $casts = [
|
||||
'user_id' => 'int',
|
||||
'source_size_bytes' => 'int',
|
||||
'source_last_modified' => 'int',
|
||||
'storage_revision' => 'int',
|
||||
'multipart_part_size_bytes' => 'int',
|
||||
'multipart_part_count' => 'int',
|
||||
'active_job_id' => 'int',
|
||||
'expires_at' => 'int',
|
||||
'completed_at' => 'int',
|
||||
'created_at' => 'int',
|
||||
'updated_at' => 'int',
|
||||
];
|
||||
}
|
||||
@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
/** One provider-confirmed part belonging to a resumable template upload. */
|
||||
final class CloudTemplateImportPart extends Model
|
||||
{
|
||||
protected $connection = 'default';
|
||||
protected $table = 'cloud_template_import_parts';
|
||||
protected $primaryKey = null;
|
||||
public $incrementing = false;
|
||||
protected $casts = [
|
||||
'part_number' => 'int',
|
||||
'size_bytes' => 'int',
|
||||
'created_at' => 'int',
|
||||
'updated_at' => 'int',
|
||||
];
|
||||
}
|
||||
@ -0,0 +1,110 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
use App\Models\CloudTemplateImportIntent;
|
||||
|
||||
/** The one executable state definition for cloud-template import intents. */
|
||||
final class CloudTemplateImportStateMachine
|
||||
{
|
||||
/** @var array<string,list<string>> */
|
||||
private const TRANSITIONS = [
|
||||
'prepared' => ['uploading', 'fetching', 'cancelled'],
|
||||
'uploading' => [
|
||||
'source_verifying', 'upload_failed', 'source_unknown',
|
||||
'cancel_pending',
|
||||
],
|
||||
'fetching' => [
|
||||
'source_verifying', 'source_failed', 'source_unknown',
|
||||
'cancelled',
|
||||
],
|
||||
'source_verifying' => [
|
||||
'source_ready', 'source_failed', 'source_unknown',
|
||||
],
|
||||
'source_ready' => ['distributing', 'cancel_pending'],
|
||||
'distributing' => ['ready', 'distribution_failed'],
|
||||
'upload_failed' => ['uploading', 'cancelled'],
|
||||
'source_failed' => ['fetching', 'cancelled'],
|
||||
'source_unknown' => ['source_verifying', 'cancel_pending'],
|
||||
'distribution_failed' => ['distributing', 'cancel_pending'],
|
||||
'cancel_pending' => ['cancelled', 'source_unknown'],
|
||||
'ready' => [],
|
||||
'cancelled' => [],
|
||||
];
|
||||
|
||||
/** @return list<string> */
|
||||
public static function states(): array
|
||||
{
|
||||
self::assertIntegrity();
|
||||
return array_keys(self::TRANSITIONS);
|
||||
}
|
||||
|
||||
public static function move(
|
||||
CloudTemplateImportIntent $intent,
|
||||
string $next
|
||||
): void {
|
||||
self::assertTransition((string) $intent->state, $next);
|
||||
$intent->state = $next;
|
||||
if (in_array($next, ['ready', 'cancelled'], true)) {
|
||||
$intent->completed_at = time();
|
||||
} else {
|
||||
$intent->completed_at = null;
|
||||
}
|
||||
}
|
||||
|
||||
public static function assertTransition(string $current, string $next): void
|
||||
{
|
||||
self::assertIntegrity();
|
||||
if ($current === $next && array_key_exists($current,
|
||||
self::TRANSITIONS)) {
|
||||
return;
|
||||
}
|
||||
if (!array_key_exists($current, self::TRANSITIONS)
|
||||
|| !in_array($next, self::TRANSITIONS[$current], true)) {
|
||||
throw new CloudError(sprintf(
|
||||
'云镜像导入状态不能从 %s 变更为 %s',
|
||||
$current === '' ? '(empty)' : $current,
|
||||
$next === '' ? '(empty)' : $next
|
||||
), 409);
|
||||
}
|
||||
}
|
||||
|
||||
public static function resumable(string $state): bool
|
||||
{
|
||||
return in_array($state, [
|
||||
'prepared', 'uploading', 'upload_failed', 'source_unknown',
|
||||
], true);
|
||||
}
|
||||
|
||||
public static function terminal(string $state): bool
|
||||
{
|
||||
return in_array($state, ['ready', 'cancelled'], true);
|
||||
}
|
||||
|
||||
public static function assertIntegrity(): void
|
||||
{
|
||||
foreach (self::TRANSITIONS as $state => $targets) {
|
||||
if ($state === '' || count($targets) !== count(array_unique($targets))) {
|
||||
throw new \LogicException(
|
||||
'Cloud-template import transition registry is invalid'
|
||||
);
|
||||
}
|
||||
foreach ($targets as $target) {
|
||||
if (!array_key_exists($target, self::TRANSITIONS)) {
|
||||
throw new \LogicException(sprintf(
|
||||
'Cloud-template import state %s references unknown state %s',
|
||||
$state,
|
||||
$target
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach (['ready', 'cancelled'] as $terminal) {
|
||||
if ((self::TRANSITIONS[$terminal] ?? null) !== []) {
|
||||
throw new \LogicException(
|
||||
'Cloud-template import terminal state has outgoing transitions'
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,367 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
use App\Models\CloudTemplateImportIntent;
|
||||
use App\Models\CloudTemplateImportPart;
|
||||
use Illuminate\Database\QueryException;
|
||||
|
||||
/**
|
||||
* Deep module that owns one cloud-template import from intent to publication.
|
||||
*
|
||||
* Object-storage and host-distribution adapters may change without exposing
|
||||
* their credentials, ordering rules, or retry semantics to controllers.
|
||||
*/
|
||||
final class CloudTemplateImportWorkflow
|
||||
{
|
||||
public const MIN_UPLOAD_BYTES = 1048576;
|
||||
public const MAX_UPLOAD_BYTES = 4294967296;
|
||||
private const INTENT_TTL_SECONDS = 86400;
|
||||
private const SOURCE_PURPOSE = 'template-import-source';
|
||||
private const RUNTIME_PURPOSE = 'template-import-runtime';
|
||||
|
||||
/** @var callable():array<string,mixed> */
|
||||
private $runtimeProvider;
|
||||
|
||||
/** @var callable():int */
|
||||
private $clock;
|
||||
|
||||
public function __construct(
|
||||
?callable $runtimeProvider = null,
|
||||
?callable $clock = null
|
||||
) {
|
||||
$this->runtimeProvider = $runtimeProvider
|
||||
?? static fn (): array => CloudObjectStorageConfig::runtime(true);
|
||||
$this->clock = $clock ?? time(...);
|
||||
}
|
||||
|
||||
/** Reserve one resumable local-upload intent without crossing S3. */
|
||||
public function beginUpload(array $input, array $actor): array
|
||||
{
|
||||
CloudAccess::manage($actor);
|
||||
CloudInput::only($input, [
|
||||
'name', 'os_family', 'os_version', 'filename', 'size_bytes',
|
||||
'last_modified',
|
||||
]);
|
||||
$userId = (int) ($actor['user_id'] ?? 0);
|
||||
$requestKey = self::requestKey($actor);
|
||||
if ($userId < 1) {
|
||||
throw new CloudError('管理员身份无效', 403);
|
||||
}
|
||||
$name = self::label($input['name'] ?? null, '模板名称', 64);
|
||||
$family = self::label($input['os_family'] ?? null, '系统系列', 32);
|
||||
$version = self::label($input['os_version'] ?? null, '系统版本', 32);
|
||||
$filename = self::filename($input['filename'] ?? null);
|
||||
$size = self::integer(
|
||||
$input['size_bytes'] ?? null,
|
||||
self::MIN_UPLOAD_BYTES,
|
||||
self::MAX_UPLOAD_BYTES,
|
||||
'云镜像文件大小无效'
|
||||
);
|
||||
$lastModified = self::integer(
|
||||
$input['last_modified'] ?? 0,
|
||||
0,
|
||||
PHP_INT_MAX,
|
||||
'云镜像文件时间无效'
|
||||
);
|
||||
$canonical = [
|
||||
'source_kind' => 'upload',
|
||||
'name' => $name,
|
||||
'os_family' => $family,
|
||||
'os_version' => $version,
|
||||
'filename' => $filename,
|
||||
'size_bytes' => $size,
|
||||
'last_modified' => $lastModified,
|
||||
];
|
||||
$fingerprint = self::fingerprint($canonical);
|
||||
$runtime = ($this->runtimeProvider)();
|
||||
$now = ($this->clock)();
|
||||
if (!is_int($now) || $now < 1) {
|
||||
throw new \LogicException('Template import clock is invalid');
|
||||
}
|
||||
|
||||
try {
|
||||
return $this->reserveUploadIntent(
|
||||
$actor,
|
||||
$userId,
|
||||
$requestKey,
|
||||
$fingerprint,
|
||||
$canonical,
|
||||
$runtime,
|
||||
$now
|
||||
);
|
||||
} catch (QueryException $error) {
|
||||
$prior = CloudTemplateImportIntent::query()
|
||||
->where('user_id', $userId)
|
||||
->where('request_idempotency_key', $requestKey)->first();
|
||||
if ($prior === null) {
|
||||
throw $error;
|
||||
}
|
||||
self::assertReplay($prior, $fingerprint);
|
||||
return ['created' => false, 'intent' => self::dto($prior)];
|
||||
}
|
||||
}
|
||||
|
||||
/** Return recent non-terminal intents so a refreshed page can resume. */
|
||||
public function active(array $actor): array
|
||||
{
|
||||
self::assertAdministrator($actor);
|
||||
$rows = CloudTemplateImportIntent::query()
|
||||
->whereNotIn('state', ['ready', 'cancelled'])
|
||||
->orderByDesc('created_at')->limit(50)->get();
|
||||
return ['intents' => $rows->map(
|
||||
static fn (CloudTemplateImportIntent $row): array => self::dto($row)
|
||||
)->all()];
|
||||
}
|
||||
|
||||
public function one(string $id, array $actor): array
|
||||
{
|
||||
self::assertAdministrator($actor);
|
||||
$id = self::intentId($id);
|
||||
$intent = CloudTemplateImportIntent::find($id);
|
||||
if ($intent === null) {
|
||||
throw new CloudError('云镜像导入记录不存在', 404);
|
||||
}
|
||||
return ['intent' => self::dto($intent)];
|
||||
}
|
||||
|
||||
/** @return array{created:bool,intent:array<string,mixed>} */
|
||||
private function reserveUploadIntent(
|
||||
array $actor,
|
||||
int $userId,
|
||||
string $requestKey,
|
||||
string $fingerprint,
|
||||
array $canonical,
|
||||
array $runtime,
|
||||
int $now
|
||||
): array {
|
||||
$connection = (new CloudTemplateImportIntent())->getConnection();
|
||||
return $connection->transaction(static function () use (
|
||||
$actor,
|
||||
$userId,
|
||||
$requestKey,
|
||||
$fingerprint,
|
||||
$canonical,
|
||||
$runtime,
|
||||
$now
|
||||
): array {
|
||||
$prior = CloudTemplateImportIntent::query()
|
||||
->where('user_id', $userId)
|
||||
->where('request_idempotency_key', $requestKey)
|
||||
->lockForUpdate()->first();
|
||||
if ($prior !== null) {
|
||||
self::assertReplay($prior, $fingerprint);
|
||||
return ['created' => false, 'intent' => self::dto($prior)];
|
||||
}
|
||||
|
||||
$generation = bin2hex(random_bytes(16));
|
||||
$templateId = self::newTemplateId(
|
||||
(string) $canonical['os_family'],
|
||||
(string) $canonical['os_version']
|
||||
);
|
||||
$intent = new CloudTemplateImportIntent();
|
||||
$intent->id = bin2hex(random_bytes(16));
|
||||
$intent->user_id = $userId;
|
||||
$intent->request_idempotency_key = $requestKey;
|
||||
$intent->request_fingerprint = $fingerprint;
|
||||
$intent->source_kind = 'upload';
|
||||
$intent->name = (string) $canonical['name'];
|
||||
$intent->os_family = (string) $canonical['os_family'];
|
||||
$intent->os_version = (string) $canonical['os_version'];
|
||||
$intent->source_filename = (string) $canonical['filename'];
|
||||
$intent->source_size_bytes = (int) $canonical['size_bytes'];
|
||||
$intent->source_last_modified =
|
||||
(int) $canonical['last_modified'];
|
||||
$intent->source_sha256 = '';
|
||||
$intent->sealed_source = CloudSecrets::encrypt([
|
||||
'kind' => 'upload',
|
||||
'filename' => (string) $canonical['filename'],
|
||||
'size_bytes' => (int) $canonical['size_bytes'],
|
||||
'last_modified' => (int) $canonical['last_modified'],
|
||||
], self::SOURCE_PURPOSE);
|
||||
$intent->template_id = $templateId;
|
||||
$intent->catalog_key = self::catalogKey(
|
||||
(string) $canonical['os_family'],
|
||||
(string) $canonical['os_version']
|
||||
);
|
||||
$intent->version_label = gmdate('Ymd-His', $now) . '-'
|
||||
. substr($generation, 0, 8);
|
||||
$intent->generation_token = $generation;
|
||||
$intent->storage_revision = self::runtimeRevision($runtime);
|
||||
$intent->sealed_storage_runtime = CloudSecrets::encrypt(
|
||||
$runtime,
|
||||
self::RUNTIME_PURPOSE
|
||||
);
|
||||
$intent->object_key =
|
||||
CloudTemplateArtifactManager::plannedObjectKey(
|
||||
$runtime,
|
||||
$templateId,
|
||||
$generation
|
||||
);
|
||||
$intent->multipart_upload_id = '';
|
||||
$intent->multipart_part_size_bytes = 0;
|
||||
$intent->multipart_part_count = 0;
|
||||
$intent->object_version_id = '';
|
||||
$intent->object_etag = '';
|
||||
$intent->state = 'prepared';
|
||||
$intent->active_job_id = null;
|
||||
$intent->error_code = '';
|
||||
$intent->expires_at = $now + self::INTENT_TTL_SECONDS;
|
||||
$intent->completed_at = null;
|
||||
$intent->created_at = $intent->updated_at = $now;
|
||||
$intent->save();
|
||||
return ['created' => true, 'intent' => self::dto($intent)];
|
||||
}, 3);
|
||||
}
|
||||
|
||||
private static function assertReplay(
|
||||
CloudTemplateImportIntent $prior,
|
||||
string $fingerprint
|
||||
): void {
|
||||
if (!hash_equals((string) $prior->request_fingerprint, $fingerprint)) {
|
||||
throw new CloudError(
|
||||
'同一请求标识不能用于不同的云镜像导入',
|
||||
409
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public static function dto(CloudTemplateImportIntent $intent): array
|
||||
{
|
||||
$partQuery = CloudTemplateImportPart::query()
|
||||
->where('intent_id', (string) $intent->id);
|
||||
$uploadedParts = (int) (clone $partQuery)->count();
|
||||
$uploadedBytes = (int) (clone $partQuery)->sum('size_bytes');
|
||||
$state = (string) $intent->state;
|
||||
return [
|
||||
'id' => (string) $intent->id,
|
||||
'source_kind' => (string) $intent->source_kind,
|
||||
'name' => (string) $intent->name,
|
||||
'os_family' => (string) $intent->os_family,
|
||||
'os_version' => (string) $intent->os_version,
|
||||
'source_filename' => (string) $intent->source_filename,
|
||||
'source_size_bytes' => (int) $intent->source_size_bytes,
|
||||
'source_last_modified' => (int) $intent->source_last_modified,
|
||||
'source_sha256' => (string) $intent->source_sha256,
|
||||
'template_id' => (string) $intent->template_id,
|
||||
'state' => $state,
|
||||
'uploaded_parts' => $uploadedParts,
|
||||
'uploaded_bytes' => $uploadedBytes,
|
||||
'part_count' => (int) $intent->multipart_part_count,
|
||||
'part_size_bytes' => (int) $intent->multipart_part_size_bytes,
|
||||
'can_resume' => CloudTemplateImportStateMachine::resumable($state),
|
||||
'can_cancel' => !CloudTemplateImportStateMachine::terminal($state),
|
||||
'task_id' => $intent->active_job_id === null
|
||||
? null : (int) $intent->active_job_id,
|
||||
'error_code' => (string) $intent->error_code,
|
||||
'expires_at' => (int) $intent->expires_at,
|
||||
'completed_at' => $intent->completed_at === null
|
||||
? null : (int) $intent->completed_at,
|
||||
'created_at' => (int) $intent->created_at,
|
||||
'updated_at' => (int) $intent->updated_at,
|
||||
];
|
||||
}
|
||||
|
||||
private static function assertAdministrator(array $actor): void
|
||||
{
|
||||
if (($actor['is_admin'] ?? false) !== true) {
|
||||
throw new CloudError('需要管理员权限', 403);
|
||||
}
|
||||
}
|
||||
|
||||
private static function requestKey(array $actor): string
|
||||
{
|
||||
$key = $actor['request_idempotency_key'] ?? null;
|
||||
if (!is_string($key)
|
||||
|| preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $key) !== 1) {
|
||||
throw new CloudError('请求幂等标识无效', 400);
|
||||
}
|
||||
return $key;
|
||||
}
|
||||
|
||||
private static function intentId(string $id): string
|
||||
{
|
||||
if (preg_match('/^[a-f0-9]{32}$/D', $id) !== 1) {
|
||||
throw new CloudError('云镜像导入标识无效', 422);
|
||||
}
|
||||
return $id;
|
||||
}
|
||||
|
||||
private static function fingerprint(array $canonical): string
|
||||
{
|
||||
ksort($canonical, SORT_STRING);
|
||||
return hash('sha256', json_encode(
|
||||
$canonical,
|
||||
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
|
||||
| JSON_UNESCAPED_UNICODE
|
||||
));
|
||||
}
|
||||
|
||||
private static function filename($value): string
|
||||
{
|
||||
if (!is_string($value) || strlen($value) > 255
|
||||
|| str_contains($value, "\0")
|
||||
|| preg_match('/\.qcow2$/iD', $value) !== 1) {
|
||||
throw new CloudError('请选择扩展名为 .qcow2 的云镜像文件');
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
private static function label($value, string $label, int $maximum): string
|
||||
{
|
||||
if (!is_string($value) || preg_match('//u', $value) !== 1) {
|
||||
throw new CloudError($label . '无效');
|
||||
}
|
||||
$value = trim($value);
|
||||
if ($value === '' || mb_strlen($value, 'UTF-8') > $maximum
|
||||
|| preg_match('/[\x00-\x1f\x7f]/u', $value) === 1) {
|
||||
throw new CloudError($label . '无效');
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
private static function integer(
|
||||
$value,
|
||||
int $minimum,
|
||||
int $maximum,
|
||||
string $message
|
||||
): int {
|
||||
$integer = filter_var($value, FILTER_VALIDATE_INT, [
|
||||
'options' => ['min_range' => $minimum, 'max_range' => $maximum],
|
||||
]);
|
||||
if ($integer === false) {
|
||||
throw new CloudError($message, 422);
|
||||
}
|
||||
return (int) $integer;
|
||||
}
|
||||
|
||||
private static function newTemplateId(string $family,
|
||||
string $version): string
|
||||
{
|
||||
$prefix = strtolower(preg_replace('/[^A-Za-z0-9]+/', '-',
|
||||
$family . '-' . $version) ?? 'image');
|
||||
return substr(trim($prefix, '-'), 0, 55) . '-'
|
||||
. bin2hex(random_bytes(8));
|
||||
}
|
||||
|
||||
private static function catalogKey(string $family, string $version): string
|
||||
{
|
||||
$key = strtolower(preg_replace('/[^A-Za-z0-9]+/', '-',
|
||||
$family . '-' . $version) ?? 'image');
|
||||
$key = trim($key, '-');
|
||||
if ($key === '' || strlen($key) > 80) {
|
||||
throw new CloudError('云镜像目录标识无效', 422);
|
||||
}
|
||||
return $key;
|
||||
}
|
||||
|
||||
private static function runtimeRevision(array $runtime): int
|
||||
{
|
||||
$revision = $runtime['revision'] ?? null;
|
||||
if (!is_int($revision) || $revision < 1) {
|
||||
throw new CloudError('模板对象存储运行时无效', 503);
|
||||
}
|
||||
return $revision;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
$root = dirname(__DIR__);
|
||||
$schema = file_get_contents($root . '/sql/cloud.sql');
|
||||
$setup = file_get_contents($root . '/app/Command/CloudSetup.php');
|
||||
$routes = file_get_contents($root . '/config/routes_cloud.php');
|
||||
$controller = file_get_contents(
|
||||
$root . '/app/Controllers/CloudAdminController.php'
|
||||
);
|
||||
if (!is_string($schema) || !is_string($setup) || !is_string($routes)
|
||||
|| !is_string($controller)) {
|
||||
throw new RuntimeException('Template-import contract sources are unreadable.');
|
||||
}
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
foreach (['cloud_template_import_intents',
|
||||
'cloud_template_import_parts'] as $table) {
|
||||
$assert(str_contains($schema, 'CREATE TABLE ' . $table . ' ('),
|
||||
'Missing template-import table: ' . $table);
|
||||
$assert(str_contains($setup, "'" . $table . "'"),
|
||||
'CloudSetup does not require template-import table: ' . $table);
|
||||
}
|
||||
$assert(str_contains($schema,
|
||||
'UNIQUE KEY cloud_template_import_request (user_id, request_idempotency_key)')
|
||||
&& str_contains($schema,
|
||||
'UNIQUE KEY cloud_template_import_template (template_id)')
|
||||
&& str_contains($schema,
|
||||
'UNIQUE KEY cloud_template_import_object (object_key)')
|
||||
&& str_contains($schema,
|
||||
'CONSTRAINT chk_cloud_template_import_completion CHECK (')
|
||||
&& str_contains($setup,
|
||||
"SCHEMA_VERSION = 'go-agent-wss-v19-template-import-intents'"),
|
||||
'Template imports are missing durable identity or terminal-state constraints.');
|
||||
$assert(str_contains($routes, "'/admin/cloud-template-imports'")
|
||||
&& str_contains($routes, "'/admin/cloud-template-imports/{id}'")
|
||||
&& str_contains($controller, 'CloudTemplateImportWorkflow')
|
||||
&& str_contains($controller, 'beginUpload('),
|
||||
'Administrator template-import intent routes are not wired.');
|
||||
|
||||
echo "Cloud-template import intent schema and route contract passed.\n";
|
||||
@ -0,0 +1,176 @@
|
||||
<?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\CloudTemplateImportStateMachine;
|
||||
use App\Services\Cloud\CloudTemplateImportWorkflow;
|
||||
use App\Services\Config;
|
||||
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('i', 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']);
|
||||
});
|
||||
|
||||
$runtime = [
|
||||
'config' => [
|
||||
'endpoint' => 'https://objects.example.test',
|
||||
'region' => 'ewr',
|
||||
'bucket' => 'templates',
|
||||
'prefix' => 'virt-cloud',
|
||||
'path_style' => true,
|
||||
],
|
||||
'credentials' => [
|
||||
'access_key_id' => 'INTENTACCESS',
|
||||
'secret_access_key' => 'intent-secret',
|
||||
],
|
||||
'revision' => 9,
|
||||
];
|
||||
$workflow = new CloudTemplateImportWorkflow(
|
||||
static fn (): array => $runtime,
|
||||
static fn (): int => 2000000000
|
||||
);
|
||||
$actor = [
|
||||
'user_id' => 7,
|
||||
'is_admin' => true,
|
||||
'is_super_admin' => true,
|
||||
'can_manage' => true,
|
||||
'request_idempotency_key' => 'template-upload-intent-0001',
|
||||
];
|
||||
$input = [
|
||||
'name' => 'Debian 13 本地版',
|
||||
'os_family' => 'Debian',
|
||||
'os_version' => '13',
|
||||
'filename' => 'debian-13.qcow2',
|
||||
'size_bytes' => 64 * 1024 * 1024,
|
||||
'last_modified' => 1999999000000,
|
||||
];
|
||||
|
||||
$first = $workflow->beginUpload($input, $actor);
|
||||
$second = $workflow->beginUpload($input, $actor);
|
||||
$assert($first['created'] === true && $second['created'] === false
|
||||
&& $first['intent']['id'] === $second['intent']['id']
|
||||
&& $first['intent']['state'] === 'prepared'
|
||||
&& $first['intent']['can_resume'] === true
|
||||
&& $first['intent']['source_size_bytes'] === 64 * 1024 * 1024,
|
||||
'A same-key replay did not return the original template import intent.');
|
||||
$stored = CloudTemplateImportIntent::findOrFail(
|
||||
(string) $first['intent']['id']
|
||||
);
|
||||
$assert((int) $stored->storage_revision === 9
|
||||
&& str_starts_with((string) $stored->object_key,
|
||||
'virt-cloud/cloud-templates/')
|
||||
&& !str_contains(json_encode($first['intent'], JSON_THROW_ON_ERROR),
|
||||
'intent-secret')
|
||||
&& !array_key_exists('sealed_storage_runtime', $first['intent'])
|
||||
&& !array_key_exists('multipart_upload_id', $first['intent']),
|
||||
'The intent did not freeze its object identity or leaked secrets.');
|
||||
|
||||
try {
|
||||
$workflow->beginUpload(
|
||||
array_replace($input, ['name' => 'Different']),
|
||||
$actor
|
||||
);
|
||||
throw new RuntimeException('A same-key different request was accepted.');
|
||||
} catch (CloudError $error) {
|
||||
$assert($error->httpStatus === 409,
|
||||
'A same-key fingerprint conflict returned the wrong status.');
|
||||
}
|
||||
|
||||
$listed = $workflow->active($actor);
|
||||
$one = $workflow->one((string) $stored->id, $actor);
|
||||
$assert(count($listed['intents']) === 1
|
||||
&& $one['intent']['id'] === (string) $stored->id,
|
||||
'A refreshed administrator page cannot recover the active intent.');
|
||||
|
||||
CloudTemplateImportStateMachine::assertIntegrity();
|
||||
CloudTemplateImportStateMachine::move($stored, 'uploading');
|
||||
CloudTemplateImportStateMachine::move($stored, 'source_verifying');
|
||||
CloudTemplateImportStateMachine::move($stored, 'source_ready');
|
||||
CloudTemplateImportStateMachine::move($stored, 'distributing');
|
||||
CloudTemplateImportStateMachine::move($stored, 'ready');
|
||||
$assert($stored->completed_at !== null
|
||||
&& CloudTemplateImportStateMachine::terminal('ready'),
|
||||
'The import state machine did not mark a terminal intent.');
|
||||
try {
|
||||
CloudTemplateImportStateMachine::move($stored, 'uploading');
|
||||
throw new RuntimeException('A terminal import intent was reopened.');
|
||||
} catch (CloudError $error) {
|
||||
$assert($error->httpStatus === 409,
|
||||
'An invalid terminal transition returned the wrong status.');
|
||||
}
|
||||
|
||||
echo "Cloud-template import intent and state-machine behavior passed.\n";
|
||||
}
|
||||
Loading…
Reference in New Issue