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/app/Services/Cloud/CloudTemplateArtifactManage...

424 lines
17 KiB
PHP

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