feat(template): add durable import intents

go
codex 3 weeks ago
parent ff1ca4e558
commit a31f18ad35

@ -8,11 +8,12 @@ use App\Services\Config;
/** Initializes only the clean-break PHP business and Agent log schemas. */
final class CloudSetup
{
private const SCHEMA_VERSION = 'go-agent-wss-v18-rescue-catalog';
private const SCHEMA_VERSION = 'go-agent-wss-v19-template-import-intents';
private const MAIN_TABLES = [
'cloud_regions', 'cloud_network_lines', 'cloud_resource_pools',
'cloud_hosts', 'cloud_host_agents',
'cloud_host_storage_configurations', 'cloud_templates',
'cloud_template_import_intents', 'cloud_template_import_parts',
'cloud_template_artifacts', 'cloud_template_replicas',
'cloud_user_isos',
'cloud_user_iso_replicas', 'cloud_rescue_templates',
@ -49,6 +50,23 @@ final class CloudSetup
'engine_vm_traffic_checkpoints', 'engine_vm_traffic_totals',
];
private const REQUIRED_MAIN_COLUMNS = [
'cloud_template_import_intents' => [
'id', 'user_id', 'request_idempotency_key',
'request_fingerprint', 'source_kind', 'name', 'os_family',
'os_version', 'source_filename', 'source_size_bytes',
'source_last_modified', 'source_sha256', 'sealed_source',
'template_id', 'catalog_key', 'version_label',
'generation_token', 'storage_revision',
'sealed_storage_runtime', 'object_key', 'multipart_upload_id',
'multipart_part_size_bytes', 'multipart_part_count',
'object_version_id', 'object_etag', 'state', 'active_job_id',
'error_code', 'expires_at', 'completed_at', 'created_at',
'updated_at',
],
'cloud_template_import_parts' => [
'intent_id', 'part_number', 'size_bytes', 'etag',
'created_at', 'updated_at',
],
'cloud_template_artifacts' => [
'template_id', 'storage_revision', 'sealed_storage_runtime',
'object_key', 'object_version_id', 'object_etag', 'size_bytes',
@ -256,6 +274,14 @@ final class CloudSetup
],
];
private const REQUIRED_CHECKS = [
'cloud_template_import_intents' => [
'chk_cloud_template_import_source',
'chk_cloud_template_import_state',
'chk_cloud_template_import_completion',
],
'cloud_template_import_parts' => [
'chk_cloud_template_import_part',
],
'cloud_host_vpc_transports' => [
'chk_cloud_host_vpc_transport_prefix',
'chk_cloud_host_vpc_transport_mode',
@ -320,6 +346,16 @@ final class CloudSetup
],
];
private const REQUIRED_INDEXES = [
'cloud_template_import_intents' => [
'PRIMARY', 'cloud_template_import_request',
'cloud_template_import_template',
'cloud_template_import_generation',
'cloud_template_import_object', 'cloud_template_import_state',
'cloud_template_import_job',
],
'cloud_template_import_parts' => [
'PRIMARY', 'cloud_template_import_part_order',
],
'cloud_template_artifacts' => [
'PRIMARY', 'cloud_template_artifact_object',
'cloud_template_artifact_state',
@ -472,6 +508,12 @@ final class CloudSetup
],
];
private const REQUIRED_FOREIGN_KEYS = [
'cloud_template_import_intents' => [
'fk_cloud_template_import_user',
],
'cloud_template_import_parts' => [
'fk_cloud_template_import_part_intent',
],
'cloud_jobs' => ['fk_cloud_job_user'],
];

@ -16,6 +16,7 @@ use App\Services\Cloud\CloudRescueCatalogService;
use App\Services\Cloud\CloudRescueTemplateReplicaCoordinator;
use App\Services\Cloud\CloudRescueTemplateRetirementService;
use App\Services\Cloud\CloudTemplateCatalogService;
use App\Services\Cloud\CloudTemplateImportWorkflow;
use App\Services\Cloud\CloudTemplateReplicaCoordinator;
use App\Services\Cloud\CloudUserIsoFeature;
@ -406,6 +407,36 @@ final class CloudAdminController
}
}
public function cloudTemplateImportIntents($request, $response)
{
$write = $request->getMethod() === 'POST';
$actor = $this->actor($request, $write);
$workflow = new CloudTemplateImportWorkflow();
if (!$write) {
return $response->withJson($workflow->active($actor))
->withHeader('Cache-Control', 'no-store');
}
$result = $workflow->beginUpload(
CloudInput::object($request),
$actor
);
return $response->withJson(
$result['intent'],
$result['created'] ? 201 : 200
)->withHeader('Cache-Control', 'no-store');
}
public function cloudTemplateImportIntent($request, $response, $args)
{
$actor = $this->actor($request);
return $response->withJson(
(new CloudTemplateImportWorkflow())->one(
(string) ($args['id'] ?? ''),
$actor
)['intent']
)->withHeader('Cache-Control', 'no-store');
}
private static function catalogName($value): string
{
if (!is_string($value) || preg_match('//u', $value) !== 1) {

@ -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',
];
}

@ -295,6 +295,21 @@ final class CloudTemplateArtifactManager
return $runtime;
}
/** Freeze the one immutable object key before any remote side effect. */
public static function plannedObjectKey(
array $runtime,
string $templateId,
string $generationToken
): string {
self::assertRuntime($runtime);
self::assertIdentity($templateId, $generationToken);
return self::objectKey(
(string) $runtime['config']['prefix'],
$templateId,
$generationToken
);
}
private static function objectKey(string $prefix, string $templateId,
string $generationToken): string
{

@ -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;
}
}

@ -217,4 +217,7 @@ $app->group('/api/v1', function () {
);
$this->post('/admin/cloud-templates/import', 'App\Controllers\CloudAdminController:templates')->setArgument('kind', 'cloud');
$this->post('/admin/cloud-templates/upload', 'App\Controllers\CloudAdminController:cloudTemplateUpload');
$this->get('/admin/cloud-template-imports', 'App\Controllers\CloudAdminController:cloudTemplateImportIntents');
$this->post('/admin/cloud-template-imports', 'App\Controllers\CloudAdminController:cloudTemplateImportIntents');
$this->get('/admin/cloud-template-imports/{id}', 'App\Controllers\CloudAdminController:cloudTemplateImportIntent');
})->add(new \App\Middleware\CloudApi());

@ -329,6 +329,85 @@ CREATE TABLE cloud_templates (
KEY cloud_template_catalog (state, os_family, os_version, name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Every cloud-template import starts with one durable authority record before
-- object storage or host distribution is contacted. Reusing the same public
-- idempotency key can only resume this exact intent; it can never allocate a
-- second template generation or object key.
CREATE TABLE cloud_template_import_intents (
id CHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL PRIMARY KEY,
user_id INT NOT NULL,
request_idempotency_key VARCHAR(128) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
request_fingerprint CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
source_kind VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
name VARCHAR(64) NOT NULL,
os_family VARCHAR(32) NOT NULL,
os_version VARCHAR(32) NOT NULL,
source_filename VARCHAR(255) NOT NULL DEFAULT '',
source_size_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0,
source_last_modified BIGINT UNSIGNED NOT NULL DEFAULT 0,
source_sha256 CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT '',
sealed_source LONGTEXT NOT NULL,
template_id VARCHAR(80) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
catalog_key VARCHAR(80) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
version_label VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
generation_token CHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
storage_revision BIGINT UNSIGNED NOT NULL,
sealed_storage_runtime LONGTEXT NOT NULL,
object_key VARCHAR(512) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
multipart_upload_id VARCHAR(1024) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT '',
multipart_part_size_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0,
multipart_part_count INT UNSIGNED NOT NULL DEFAULT 0,
object_version_id VARCHAR(1024) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT '',
object_etag VARCHAR(256) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT '',
state VARCHAR(24) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'prepared',
active_job_id BIGINT UNSIGNED DEFAULT NULL,
error_code VARCHAR(128) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT '',
expires_at BIGINT UNSIGNED NOT NULL,
completed_at BIGINT UNSIGNED DEFAULT NULL,
created_at BIGINT UNSIGNED NOT NULL,
updated_at BIGINT UNSIGNED NOT NULL,
UNIQUE KEY cloud_template_import_request (user_id, request_idempotency_key),
UNIQUE KEY cloud_template_import_template (template_id),
UNIQUE KEY cloud_template_import_generation (generation_token),
UNIQUE KEY cloud_template_import_object (object_key),
KEY cloud_template_import_state (state, expires_at, id),
KEY cloud_template_import_job (active_job_id, id),
CONSTRAINT chk_cloud_template_import_source CHECK (
source_kind IN ('upload','remote')
),
CONSTRAINT chk_cloud_template_import_state CHECK (
state IN ('prepared','uploading','fetching','source_verifying',
'source_ready','distributing','ready','upload_failed','source_failed',
'source_unknown','distribution_failed','cancel_pending','cancelled')
),
CONSTRAINT chk_cloud_template_import_completion CHECK (
(state IN ('ready','cancelled') AND completed_at IS NOT NULL)
OR (state NOT IN ('ready','cancelled') AND completed_at IS NULL)
),
CONSTRAINT fk_cloud_template_import_user FOREIGN KEY (user_id)
REFERENCES `user` (id) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Browser multipart progress is durable server-side evidence. The browser
-- may report an ETag, but completion will still verify the provider's exact
-- part ledger before the immutable object is accepted.
CREATE TABLE cloud_template_import_parts (
intent_id CHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
part_number INT UNSIGNED NOT NULL,
size_bytes BIGINT UNSIGNED NOT NULL,
etag VARCHAR(256) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
created_at BIGINT UNSIGNED NOT NULL,
updated_at BIGINT UNSIGNED NOT NULL,
PRIMARY KEY (intent_id, part_number),
KEY cloud_template_import_part_order (intent_id, part_number, size_bytes),
CONSTRAINT chk_cloud_template_import_part CHECK (
part_number > 0 AND size_bytes > 0
),
CONSTRAINT fk_cloud_template_import_part_intent FOREIGN KEY (intent_id)
REFERENCES cloud_template_import_intents (id)
ON DELETE CASCADE ON UPDATE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Every immutable template generation owns one canonical object-storage
-- artifact. Host replicas are disposable caches; this frozen runtime keeps
-- an old generation readable even after the administrator changes the global

@ -22,7 +22,7 @@ $assert(stripos($schema, 'compatibility import') === false
$assert(!preg_match('/\bengine_[A-Za-z0-9_]*\b/', $schema),
'cloud.sql retained an engine-prefixed identifier.');
$assert(str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v18-rescue-catalog'")
"SCHEMA_VERSION = 'go-agent-wss-v19-template-import-intents'")
&& !str_contains($setup, "SCHEMA_VERSION = 'go-v1'"),
'Outbound Agent schema must reject the incompatible earlier Go database.');
$assert(str_contains($schema,
@ -33,7 +33,9 @@ $assert(str_contains($schema,
&& !str_contains($schema, 'America/Los_Angeles'),
'Fresh automatic-backup subscriptions must default to UTC with a state revision.');
foreach (['cloud_host_agents', 'cloud_templates', 'cloud_template_artifacts',
foreach (['cloud_host_agents', 'cloud_templates',
'cloud_template_import_intents', 'cloud_template_import_parts',
'cloud_template_artifacts',
'cloud_template_replicas', 'cloud_rescue_templates',
'cloud_rescue_template_artifacts', 'cloud_rescue_template_replicas',
'cloud_hosts', 'cloud_instances',

@ -56,7 +56,7 @@ $assert($replica !== ''
&& str_contains($replica, 'cleanup_resolved_at BIGINT UNSIGNED'),
'Rescue replica cannot prove exact identity or retain cleanup debt.');
$assert(str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v18-rescue-catalog'")
"SCHEMA_VERSION = 'go-agent-wss-v19-template-import-intents'")
&& str_contains($setup, "'cloud_rescue_artifact_delete_due'")
&& str_contains($setup, "'cloud_rescue_replica_cleanup'"),
'CloudSetup version or rescue catalog indexes are incomplete.');

@ -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";
}

@ -101,7 +101,7 @@ $assert(str_contains($jobs, 'vpc_id BIGINT UNSIGNED DEFAULT NULL')
'Cloud jobs cannot be correlated to VPC or VPC-port work.');
$assert(str_contains($setup,
"private const SCHEMA_VERSION = 'go-agent-wss-v18-rescue-catalog'")
"private const SCHEMA_VERSION = 'go-agent-wss-v19-template-import-intents'")
&& str_contains($setup, "'name' => 'cloud_vpc_enabled'")
&& str_contains($setup, "'value' => 'false'")
&& str_contains($setup,

Loading…
Cancel
Save