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/CloudTemplateStoragePublica...

286 lines
11 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudStorageArtifact;
use App\Models\CloudStorageBackend;
use App\Models\CloudStorageOperation;
use App\Models\CloudStoragePublication;
use App\Models\CloudStorageReplica;
use App\Models\CloudTemplateImportIntent;
/**
* Template-owned facade over the shared immutable storage publication ledger.
*
* The import intent is the business owner. Its storage artifact and both
* provider placements are frozen before the first provider write. Legacy
* runtime columns remain schema-only fields and never carry credentials on
* this clean-break path.
*/
final class CloudTemplateStoragePublicationService
{
/** @return array<string,mixed> */
public static function reserve(
CloudTemplateImportIntent $intent
): array {
self::assertIntentIdentity($intent);
$requestKey = 'template-storage-' . (string) $intent->id;
$fingerprint = hash('sha256', implode('|', [
(string) $intent->id,
(string) $intent->template_id,
(string) $intent->generation_token,
(string) $intent->source_size_bytes,
(string) $intent->source_sha256,
]));
$view = CloudStorageArtifactService::beginPublication(
'template',
self::objectSuffix($intent),
(int) $intent->source_size_bytes,
(string) $intent->source_sha256,
$requestKey,
$fingerprint,
['template_import_intent_id' => (string) $intent->id]
);
self::syncIntentProjection((string) $intent->id, $view);
return $view;
}
/** @return array<string,mixed> */
public static function binding(
CloudTemplateImportIntent|string $intent
): array {
$intent = is_string($intent)
? CloudTemplateImportIntent::query()->where('id', $intent)->first()
: $intent;
if (!$intent instanceof CloudTemplateImportIntent) {
throw new CloudError('云镜像导入记录不存在', 404);
}
self::assertIntentIdentity($intent);
$publication = CloudStoragePublication::query()
->where('template_import_intent_id', (string) $intent->id)
->first();
if (!$publication instanceof CloudStoragePublication) {
throw new CloudError('云模板缺少对象存储发布意图', 409);
}
$artifact = CloudStorageArtifact::query()
->whereKey((int) $publication->artifact_id)->first();
$operation = CloudStorageOperation::query()
->where('artifact_id', (int) $publication->artifact_id)
->where('kind', 'publish')->first();
$replica = $operation instanceof CloudStorageOperation
? CloudStorageReplica::query()
->whereKey((int) $operation->replica_id)->first()
: null;
if (!$artifact instanceof CloudStorageArtifact
|| !$operation instanceof CloudStorageOperation
|| !$replica instanceof CloudStorageReplica
|| (string) $artifact->kind !== 'template'
|| (int) $artifact->size_bytes
!== (int) $intent->source_size_bytes
|| !hash_equals(
(string) $artifact->sha256,
(string) $intent->source_sha256
)
|| (int) $replica->artifact_id !== (int) $artifact->id
|| (string) $replica->role !== 'primary') {
throw new CloudError('云模板对象存储发布账本不一致', 409);
}
return [
'intent' => $intent,
'publication' => $publication,
'artifact' => $artifact,
'operation' => $operation,
'replica' => $replica,
'operation_id' => (string) $operation->operation_id,
'artifact_id' => (int) $artifact->id,
'backend_id' => (int) $replica->backend_id,
'object_key' => (string) $replica->object_key,
'protected' => (string) $artifact->state === 'protected'
&& in_array((string) $publication->state,
['ready_to_finalize', 'completed'], true),
];
}
/** @return array<string,mixed> */
public static function primaryRuntime(
CloudTemplateImportIntent|string $intent,
bool $requireHealthy
): array {
$binding = self::binding($intent);
return CloudObjectStorageBackendRegistry::runtime(
(int) $binding['backend_id'],
$requireHealthy
);
}
/** @return array{size_bytes:int,sha256:string,etag:string,version_id:string} */
public static function primaryIdentity(
CloudTemplateImportIntent|string $intent
): array {
$binding = self::binding($intent);
/** @var CloudStorageArtifact $artifact */
$artifact = $binding['artifact'];
/** @var CloudStorageReplica $replica */
$replica = $binding['replica'];
if ((string) $replica->state !== 'ready'
|| (int) $replica->size_bytes !== (int) $artifact->size_bytes
|| !hash_equals(
(string) $replica->sha256,
(string) $artifact->sha256
)
|| trim((string) $replica->object_etag) === '') {
throw new CloudError('云模板对象存储主副本尚未就绪', 409);
}
return [
'size_bytes' => (int) $replica->size_bytes,
'sha256' => (string) $replica->sha256,
'etag' => (string) $replica->object_etag,
'version_id' => (string) $replica->object_version_id,
];
}
/**
* @param array{path:string,size_bytes:int,sha256:string} $file
* @return array<string,mixed>
*/
public static function publishFile(
CloudTemplateImportIntent $intent,
array $file,
?CloudObjectStorageS3Client $client = null
): array {
$binding = self::binding($intent);
return (new CloudStorageImmutablePrimaryPublication($client))->publish(
(string) $binding['operation_id'],
(int) $binding['artifact_id'],
$file
);
}
/** @return array<string,mixed> */
public static function cancelNeverDispatched(
CloudTemplateImportIntent $intent,
?CloudObjectStorageS3Client $client = null
): array {
$binding = self::binding($intent);
$owner = ['template_import_intent_id' => (string) $intent->id];
$deletion = new CloudStorageArtifactDeletionService($client);
$deletion->prepareNeverDispatched(
(int) $binding['artifact_id'],
$owner
);
return $deletion->process(
(int) $binding['artifact_id'],
$owner
);
}
/** @return array<string,mixed> */
public static function cancelAfterConfirmedAbort(
CloudTemplateImportIntent $intent,
?CloudObjectStorageS3Client $client = null
): array {
$binding = self::binding($intent);
/** @var CloudStorageOperation $operation */
$operation = $binding['operation'];
if ((string) $operation->phase !== 'terminal') {
CloudStorageArtifactService::failPrimary(
(string) $binding['operation_id'],
(int) $binding['artifact_id'],
'not_applied',
'template_multipart_abort_confirmed'
);
} elseif ((string) $operation->outcome !== 'failed'
|| (string) $operation->effect_resolution !== 'not_applied') {
throw new CloudError(
'模板主副本发布结果不允许按未应用取消',
409
);
}
return (new CloudStorageArtifactDeletionService($client))->process(
(int) $binding['artifact_id'],
['template_import_intent_id' => (string) $intent->id]
);
}
/** @param array<string,mixed> $view */
private static function syncIntentProjection(
string $intentId,
array $view
): void {
$artifactId = filter_var($view['artifact_id'] ?? null,
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
$backendId = filter_var($view['backend_id'] ?? null,
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
$objectKey = $view['object_key'] ?? null;
if ($artifactId === false || $backendId === false
|| !is_string($objectKey) || trim($objectKey) === '') {
throw new CloudError('云模板对象存储预留回执无效', 502);
}
$backend = CloudStorageBackend::query()->whereKey($backendId)->first();
if (!$backend instanceof CloudStorageBackend) {
throw new CloudError('云模板对象存储后端不存在', 409);
}
(new CloudTemplateImportIntent())->getConnection()->transaction(
static function () use (
$intentId,
$objectKey,
$backend
): void {
$intent = CloudTemplateImportIntent::query()
->where('id', $intentId)->lockForUpdate()->first();
if (!$intent instanceof CloudTemplateImportIntent) {
throw new CloudError('云镜像导入记录不存在', 404);
}
$expected = self::objectSuffix($intent);
if (!str_ends_with($objectKey, $expected)) {
throw new CloudError('云模板对象存储路径不一致', 409);
}
$intent->storage_revision =
(int) $backend->config_revision;
$intent->object_key = $objectKey;
$intent->updated_at = time();
$intent->save();
},
3
);
}
private static function objectSuffix(
CloudTemplateImportIntent $intent
): string {
self::assertTemplateIdentity(
(string) $intent->template_id,
(string) $intent->generation_token
);
return 'cloud-templates/' . (string) $intent->template_id . '/'
. (string) $intent->generation_token . '/system.qcow2';
}
private static function assertIntentIdentity(
CloudTemplateImportIntent $intent
): void {
if (!$intent->exists
|| preg_match('/^[a-f0-9]{32}$/D', (string) $intent->id) !== 1
|| (int) $intent->source_size_bytes < 1
|| preg_match('/^[a-f0-9]{64}$/D',
(string) $intent->source_sha256) !== 1) {
throw new CloudError('云模板对象存储制品身份无效', 409);
}
self::assertTemplateIdentity(
(string) $intent->template_id,
(string) $intent->generation_token
);
}
private static function assertTemplateIdentity(
string $templateId,
string $generationToken
): void {
if (preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/D', $templateId)
!== 1
|| preg_match('/^[a-f0-9]{32}$/D', $generationToken) !== 1) {
throw new CloudError('云模板对象存储制品身份无效', 422);
}
}
}