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

2497 lines
101 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudJob;
use App\Models\CloudHost;
use App\Models\CloudOrder;
use App\Models\CloudTemplate;
use App\Models\CloudTemplateArtifact;
use App\Models\CloudTemplateImportIntent;
use App\Models\CloudTemplateReplica;
use App\Models\CloudUserIsoReplica;
/** PHP authority for the global template catalog and its durable replicas. */
final class CloudTemplateCatalogService
{
public const STARTUP_SCRIPT_MAX_BYTES = 32768;
public static function adminCatalog(): array
{
$templates = CloudTemplate::query()
->where('state', '<>', 'retired')->orderBy('os_family')
->orderBy('os_version')->orderBy('catalog_key')
->orderByDesc('created_at')->get();
$templateIds = $templates->map(
static fn (CloudTemplate $template): string =>
(string) $template->id
)->all();
$replicas = $templateIds === [] ? collect()
: CloudTemplateReplica::query()->whereIn(
'template_id',
$templateIds
)->orderBy('template_id')->orderBy('host_id')->get();
$artifacts = $templateIds === [] ? collect()
: CloudTemplateArtifact::query()->whereIn(
'template_id',
$templateIds
)->get()->keyBy('template_id');
$eligibleHostIds = array_fill_keys(array_map(
'intval',
CloudAgentSettingsService::enabledHostIds()
), true);
$hosts = [];
foreach (CloudHost::query()->orderBy('id')->get() as $host) {
$hostId = (int) $host->id;
$name = trim((string) ($host->name ?? ''));
$hosts[$hostId] = [
'id' => $hostId,
'name' => $name !== '' ? $name : '宿主机 #' . $hostId,
'region' => trim((string) ($host->region ?? '')),
'enabled' => (bool) $host->enabled,
'eligible' => isset($eligibleHostIds[$hostId]),
'record_present' => true,
];
}
foreach ($replicas as $replica) {
$hostId = (int) $replica->host_id;
if (!isset($hosts[$hostId])) {
$hosts[$hostId] = [
'id' => $hostId,
'name' => '宿主机 #' . $hostId,
'region' => '',
'enabled' => false,
'eligible' => false,
'record_present' => false,
];
}
}
ksort($hosts, SORT_NUMERIC);
$replicasByTemplate = [];
foreach ($replicas as $replica) {
$replicasByTemplate[(string) $replica->template_id][] = $replica;
}
return [
'hosts' => array_values($hosts),
'templates' => $templates->map(
static fn (CloudTemplate $row): array => self::adminDto(
$row,
$replicasByTemplate[(string) $row->id] ?? [],
$hosts,
$artifacts->get((string) $row->id)
)
)->all(),
];
}
public static function publicCatalog(): array
{
$templates = CloudTemplate::query()->whereIn('state', [
'active', 'degraded',
])
->where('is_default', 1)
->orderBy('os_family')->orderBy('os_version')->orderBy('name')
->get()->filter(static fn (CloudTemplate $row): bool =>
self::activeJobSafelySettled($row)
)->values();
$availability = CloudTemplateAvailabilityService::
deploymentAvailability($templates);
return ['templates' => $templates->filter(
static fn (CloudTemplate $row): bool =>
($availability[(string) $row->id]['offer_ids'] ?? []) !== []
)->values()->map(static fn (CloudTemplate $row): array => [
'id' => (string) $row->id,
'name' => (string) $row->name,
'os_family' => (string) $row->os_family,
'os_version' => (string) $row->os_version,
'offer_ids' => $availability[(string) $row->id]['offer_ids'],
'region_ids' =>
$availability[(string) $row->id]['region_ids'],
])->all()];
}
/** Host-scoped catalog for reinstall; sales topology is irrelevant here. */
public static function publicCatalogForHost(int $hostId): array
{
if ($hostId < 1) {
throw new CloudError('宿主机标识无效', 422);
}
return ['templates' => CloudTemplate::query()->whereIn('state', [
'active', 'degraded',
])->where('is_default', 1)
->orderBy('os_family')->orderBy('os_version')->orderBy('name')
->get()->filter(static fn (CloudTemplate $row): bool =>
self::activeJobSafelySettled($row)
&& CloudTemplateAvailabilityService::hostHasExactReplica(
$row,
$hostId
)
)->values()->map(static fn (CloudTemplate $row): array => [
'id' => (string) $row->id,
'name' => (string) $row->name,
'os_family' => (string) $row->os_family,
'os_version' => (string) $row->os_version,
])->all()];
}
/**
* Reserve host distribution only after an import intent froze its object.
*/
public static function distributePublishedImport(
CloudTemplateImportIntent $intent,
array $actor,
?CloudObjectStorageS3Client $client = null
): array {
if ((string) $intent->state !== 'source_ready') {
throw new CloudError('云镜像导入源尚未就绪', 409);
}
$template = CloudTemplate::find((string) $intent->template_id);
if ($template === null || (string) $template->generation_token
!== (string) $intent->generation_token) {
throw new CloudError('云镜像导入目录状态不一致', 409);
}
if ((string) $template->state === 'importing'
&& (int) ($template->active_job_id ?? 0) > 0) {
$job = CloudJob::find((int) $template->active_job_id);
if ($job === null || (string) $job->kind !== 'template_import'
|| (int) $job->user_id !== (int) $intent->user_id
|| (string) $job->request_idempotency_key
!== 'template-import-' . (string) $intent->id) {
throw new CloudError('云镜像导入任务账本不完整', 409);
}
return CloudJobService::acknowledgement($job);
}
if ((string) $template->state !== 'preparing') {
throw new CloudError('云镜像导入目录状态不一致', 409);
}
$hosts = array_values(array_unique(array_map('intval',
CloudAgentSettingsService::enabledHostIds())));
sort($hosts, SORT_NUMERIC);
if ($hosts === []) {
throw new CloudError('没有已启用且已配置 Agent 的宿主机', 409);
}
return self::reserveImport(
$actor,
$template,
$hosts,
CloudTemplateArtifactManager::downloadSource($template, $client)
);
}
/**
* @param list<int> $hosts
* @param array{source_url:string,source_size_bytes:int,sha256:string} $source
*/
private static function reserveImport(array $actor, CloudTemplate $template,
array $hosts, array $source): array
{
$connection = $template->getConnection();
$parent = $connection->transaction(static function () use (
$actor, $template, $hosts, $source
): CloudJob {
$locked = CloudTemplate::query()
->where('id', (string) $template->id)
->lockForUpdate()->first();
if ($locked === null || (string) $locked->state !== 'preparing') {
throw new CloudError('云镜像主副本状态不允许开始分发', 409);
}
[$parent, $created] = CloudJobService::reserveAggregate(
$actor, 'template_import', [
'template_id' => (string) $locked->id,
'name' => (string) $locked->name,
'family' => (string) $locked->os_family,
'version' => (string) $locked->os_version,
'generation_token' =>
(string) $locked->generation_token,
'size_bytes' => (int) $locked->image_bytes,
'sha256' => (string) $locked->sha256,
'host_ids' => $hosts,
]
);
if (!$created) {
return $parent;
}
$now = time();
CloudTemplateStateMachine::moveTemplate($locked, 'importing');
$locked->active_job_id = (int) $parent->id;
$locked->updated_at = $now;
$locked->save();
foreach ($hosts as $hostId) {
$body = [
'id' => (string) $locked->id,
'name' => (string) $locked->name,
'source_url' => $source['source_url'],
'os_family' => (string) $locked->os_family,
'version' => (string) $locked->os_version,
'architecture' => 'x86_64',
'sha256' => $source['sha256'],
'revision' => 1,
'generation_token' =>
(string) $locked->generation_token,
'source_size_bytes' =>
(int) $source['source_size_bytes'],
];
$operationId = bin2hex(random_bytes(16));
$child = CloudJobService::reserveAgentMutation(
$actor, $hostId, 'template_import_replica', 'POST',
'/v1/templates', $body, [
'can_manage' => true,
'template_id' => (string) $locked->id,
], (int) $parent->id, $operationId
);
$replica = new CloudTemplateReplica();
$replica->host_id = $hostId;
$replica->template_id = (string) $locked->id;
$replica->revision = 1;
$replica->generation_token =
(string) $locked->generation_token;
$replica->state = 'pending';
CloudTemplateStateMachine::moveReplica(
$replica,
'importing'
);
$replica->image_bytes = 0;
$replica->sha256 = (string) $locked->sha256;
$replica->operation_id = $operationId;
$replica->job_id = (int) $child->id;
$replica->error_code = '';
$replica->created_at = $replica->updated_at = $now;
$replica->save();
}
return $parent;
}, 3);
return CloudJobService::acknowledgement($parent);
}
/** Rename and reserve every metadata sync in one database transaction. */
public static function rename(string $id, $name, $expectedRevision,
$generationToken, array $actor): array
{
CloudAccess::manage($actor);
$id = self::templateId($id);
$name = self::name($name);
self::validateVersion($expectedRevision, $generationToken);
$connection = (new CloudTemplate())->getConnection();
$parent = $connection->transaction(static function () use (
$id, $name, $expectedRevision, $generationToken, $actor
): CloudJob {
$template = self::lockTemplateForMutation($id);
if ($template === null || (string) $template->state === 'retired') {
throw new CloudError('云镜像模板不存在', 404);
}
if ((string) $template->state !== 'active') {
throw new CloudError('云镜像当前状态不允许修改元数据', 409);
}
if ((int) $template->revision !== $expectedRevision
|| !hash_equals((string) $template->generation_token,
(string) $generationToken)) {
throw new CloudError('云镜像版本已变化,请刷新后重试', 409);
}
[$parent, $created] = CloudJobService::reserveAggregate(
$actor, 'template_metadata_sync', [
'template_id' => $id,
'name' => $name,
'expected_revision' => $expectedRevision,
'generation_token' => $generationToken,
]
);
if (!$created) {
return $parent;
}
$template->name = $name;
$template->revision = (int) $template->revision + 1;
$template->active_job_id = (int) $parent->id;
$template->updated_at = time();
$template->save();
$replicas = CloudTemplateReplica::query()
->where('template_id', $id)->whereIn('state', ['active', 'stale'])
->orderBy('host_id')->lockForUpdate()->get();
if ($replicas->isEmpty()) {
throw new CloudError('云镜像没有可同步的宿主机副本', 409);
}
foreach ($replicas as $replica) {
$operationId = bin2hex(random_bytes(16));
$child = CloudJobService::reserveAgentMutation(
$actor, (int) $replica->host_id,
'template_metadata_replica', 'PATCH',
'/v1/templates/' . rawurlencode($id), [
'name' => $name,
'revision' => (int) $template->revision,
'generation_token' =>
(string) $template->generation_token,
], [
'can_manage' => true,
'template_id' => $id,
], (int) $parent->id, $operationId
);
CloudTemplateStateMachine::moveReplica($replica, 'syncing');
$replica->operation_id = $operationId;
$replica->job_id = (int) $child->id;
$replica->error_code = '';
$replica->updated_at = time();
$replica->save();
}
return $parent;
}, 3);
return CloudJobService::acknowledgement($parent);
}
public static function delete(string $id, $expectedRevision,
$generationToken, array $actor): array
{
CloudAccess::manage($actor);
$id = self::templateId($id);
self::validateVersion($expectedRevision, $generationToken);
$connection = (new CloudTemplate())->getConnection();
$reserved = $connection->transaction(static function () use (
$id, $expectedRevision, $generationToken, $actor
): array {
// Payment already owns its order before it snapshots a template.
// Take the same order -> aggregate parent -> template sequence so
// template deletion cannot deadlock with invoice settlement.
self::assertNoOrderReferencesLocked($id);
$template = self::lockTemplateForMutation($id);
if ($template === null || (string) $template->state === 'retired') {
throw new CloudError('云镜像模板不存在', 404);
}
$partialCleanupKind = self::settledMixedCleanupParentKind(
$template
);
$partialCleanup = ($partialCleanupKind === 'template_import'
&& (string) $template->state === 'degraded')
|| ($partialCleanupKind === 'template_delete'
&& (string) $template->state === 'delete_failed');
if ((int) $template->revision !== $expectedRevision
|| !hash_equals((string) $template->generation_token,
(string) $generationToken)) {
throw new CloudError('云镜像版本已变化,请刷新后重试', 409);
}
$artifact = CloudTemplateArtifact::query()
->where('template_id', $id)->lockForUpdate()->first();
if ((string) $template->state === 'delete_failed'
&& $artifact !== null
&& (string) $artifact->state === 'delete_attention') {
$activeParent = CloudJob::query()
->where('id', (int) $template->active_job_id)
->where('kind', 'template_delete')
->where('execution_mode', 'aggregate')
->lockForUpdate()->first();
if ($activeParent === null) {
throw new CloudError('云镜像删除任务账本不完整', 409);
}
CloudTemplateDeletionService::retryAttentionLocked(
$template,
$activeParent
);
return ['job' => $activeParent, 'restarted' => true];
}
if ((string) $template->state !== 'active' && !$partialCleanup) {
throw new CloudError('云镜像存在未完成或失败任务,禁止删除', 409);
}
self::assertNoJobReferencesLocked($id);
$replicas = CloudTemplateReplica::query()
->where('template_id', $id)->orderBy('host_id')
->lockForUpdate()->get();
$allowedReplicaStates = match ($partialCleanupKind) {
'template_import' => ['active', 'failed'],
'template_delete' => ['delete_succeeded', 'delete_failed'],
default => ['active', 'stale'],
};
if ($replicas->isEmpty() || $replicas->contains(
static fn ($row): bool => !in_array(
(string) $row->state,
$allowedReplicaStates,
true
)
)) {
throw new CloudError('云镜像副本账本不完整,禁止删除', 409);
}
[$parent, $created] = CloudJobService::reserveAggregate(
$actor, 'template_delete', [
'template_id' => $id,
'revision' => $expectedRevision,
'generation_token' => $generationToken,
]
);
if (!$created) {
return ['job' => $parent, 'restarted' => false];
}
if ($partialCleanupKind === 'template_import') {
// A failed import replica is proven absent. Drop that catalog
// placeholder and delete only the hosts that proved the image
// exists, using fresh child operation identifiers below.
CloudTemplateReplica::query()->where('template_id', $id)
->where('state', 'failed')->delete();
} elseif ($partialCleanupKind === 'template_delete') {
// A successful old delete is already absent. Keep only the
// hosts that proved the image survived and normalize those
// rows before reserving a brand-new cleanup operation.
CloudTemplateReplica::query()->where('template_id', $id)
->where('state', 'delete_succeeded')->delete();
foreach (CloudTemplateReplica::query()
->where('template_id', $id)
->where('state', 'delete_failed')
->lockForUpdate()->get() as $survivor) {
CloudTemplateStateMachine::moveReplica(
$survivor,
(int) $survivor->revision === (int) $template->revision
? 'active' : 'stale'
);
$survivor->error_code = '';
$survivor->updated_at = time();
$survivor->save();
}
}
if ($partialCleanup) {
$replicas = CloudTemplateReplica::query()
->where('template_id', $id)->orderBy('host_id')
->lockForUpdate()->get();
if ($replicas->isEmpty() || $replicas->contains(
static fn ($row): bool => !in_array(
(string) $row->state,
['active', 'stale'],
true
)
)) {
throw new CloudError('云镜像部分结果账本不完整,禁止删除', 409);
}
}
CloudTemplateStateMachine::moveTemplate($template, 'deleting');
$template->active_job_id = (int) $parent->id;
$template->updated_at = time();
$template->save();
foreach ($replicas as $replica) {
$operationId = bin2hex(random_bytes(16));
$child = CloudJobService::reserveAgentMutation(
$actor, (int) $replica->host_id,
'template_delete_replica', 'DELETE',
'/v1/templates/' . rawurlencode($id), [], [
'can_manage' => true,
'template_id' => $id,
], (int) $parent->id, $operationId
);
CloudTemplateStateMachine::moveReplica($replica, 'deleting');
$replica->operation_id = $operationId;
$replica->job_id = (int) $child->id;
$replica->error_code = '';
$replica->updated_at = time();
$replica->save();
}
return ['job' => $parent, 'restarted' => false];
}, 3);
return CloudJobService::acknowledgement($reserved['job']) + [
'recovery_restarted' => (bool) $reserved['restarted'],
];
}
public static function finishJobLocked(CloudJob $job, string $status,
$result, array $payload, array $operation,
bool $recovery = false): void
{
if (!in_array((string) $job->kind, [
'template_import_replica', 'template_metadata_replica',
'template_delete_replica',
], true)) {
return;
}
$id = is_string($payload['template_id'] ?? null)
? $payload['template_id'] : '';
$template = CloudTemplate::query()->where('id', $id)
->lockForUpdate()->first();
$replica = CloudTemplateReplica::query()
->where('host_id', (int) $job->host_id)
->where('template_id', $id)->where('job_id', (int) $job->id)
->lockForUpdate()->first();
if ($template === null || $replica === null) {
throw new CloudError('云镜像任务账本不存在', 409);
}
// Project the leaf first. Aggregate children are published only by the
// parent reconciler; standalone repair jobs publish availability here
// only after a definitive result and keep unknown effects fenced.
if ((string) $job->kind === 'template_import_replica') {
self::finishImportReplica($template, $replica, $status, $result,
$operation, $recovery);
if ($job->parent_job_id === null) {
CloudTemplateReplicaCoordinator::settleStandaloneLocked(
$template,
$replica,
$job,
$status,
$operation
);
}
} elseif ((string) $job->kind === 'template_metadata_replica') {
self::finishMetadataReplica($template, $replica, $status, $result,
$operation, $recovery);
if ($job->parent_job_id === null) {
CloudTemplateReplicaCoordinator::settleStandaloneLocked(
$template,
$replica,
$job,
$status,
$operation
);
}
} else {
CloudTemplateDeletionService::finishReplicaLocked(
$template,
$replica,
$status,
$operation, $recovery);
}
}
/**
* Lock the catalog projection immediately after its aggregate parent.
* Every caller must do this before locking any child or replica row.
*/
public static function lockAggregateCatalogLocked(CloudJob $parent): void
{
if (!in_array((string) $parent->kind, [
'template_import', 'template_metadata_sync', 'template_delete',
], true)) {
return;
}
self::templateBoundToParentLocked($parent);
}
/**
* Publish an aggregate catalog result only after every recovered child
* has committed its final effect resolution. prepareRecoveredEffect()
* may update the replica first, but must never make the public parent look
* complete before the Agent fence is released.
*/
public static function settleRecoveredParentLocked(
CloudJob $parent,
string $resolution
): void {
if (!in_array((string) $parent->kind, [
'template_import', 'template_metadata_sync', 'template_delete',
], true) || (string) $parent->execution_mode !== 'aggregate'
|| ((string) $parent->phase === 'terminal'
&& ((string) $parent->outcome !== 'failed'
|| (string) $parent->effect_resolution !== 'unknown'))) {
return;
}
$template = self::templateBoundToParentLocked($parent);
if (!in_array(
$resolution,
['applied', 'not_applied', 'mixed'],
true
)) {
throw new CloudRecoveryAggregateStateConflict(
'云镜像汇总任务的子任务效果状态无效',
409
);
}
self::assertRecoveredReplicaProjectionLocked(
$template,
$parent,
$resolution
);
if ($resolution === 'not_applied') {
self::restoreNotAppliedProjectionLocked($template, $parent);
return;
}
$operation = ['effect_may_have_applied' => true];
if ((string) $parent->kind === 'template_import') {
self::settleImportParent(
$template,
(int) $parent->id,
$operation
);
} elseif ((string) $parent->kind === 'template_metadata_sync') {
self::settleMetadataParent(
$template,
(int) $parent->id,
$operation
);
} else {
if ($resolution === 'mixed') {
CloudTemplateDeletionService::settleMixedLocked(
$template,
$parent
);
} else {
CloudTemplateDeletionService::armLocked($template, $parent);
}
}
if ($resolution === 'mixed'
&& (string) $parent->kind !== 'template_metadata_sync') {
// The immutable parent/children retain the partial-failure audit.
// Release only the catalog's active-operation pointer so a new,
// independently identified cleanup operation can be considered.
$template->active_job_id = null;
$template->updated_at = time();
$template->save();
}
}
/**
* Verify an already-published aggregate without mutating its immutable
* task audit or catalog projection. This intentionally differs from the
* pre-settlement assertion below: successful deletes and no-effect imports
* have already removed their replica rows, while no-effect deletes have
* restored the surviving replicas to active/stale.
*/
public static function assertSettledParentProjectionLocked(
CloudJob $parent,
string $resolution
): void {
$kind = (string) $parent->kind;
if (!in_array($kind, [
'template_import', 'template_metadata_sync', 'template_delete',
], true) || (string) $parent->execution_mode !== 'aggregate'
|| !in_array($resolution, [
'applied', 'not_applied', 'mixed',
], true)) {
throw new CloudRecoveryAggregateStateConflict(
'云镜像汇总任务的已结算效果状态无效',
409
);
}
$template = self::templateBoundToParentLocked($parent);
$children = CloudJob::where('parent_job_id', (int) $parent->id)
->orderBy('id')->lockForUpdate()->get();
if ($children->isEmpty()) {
throw new CloudRecoveryAggregateStateConflict(
'云镜像汇总任务缺少子任务账本',
409
);
}
$settledChildIds = $children->map(
static fn (CloudJob $child): int => (int) $child->id
)->all();
if (CloudUserIsoReplica::query()->whereIn(
'job_id',
$settledChildIds
)->exists()) {
throw new CloudRecoveryOperationIdentityConflict(
'云镜像汇总子任务被 ISO 副本账本重复引用',
409
);
}
$expectedChildKind = match ($kind) {
'template_import' => 'template_import_replica',
'template_metadata_sync' => 'template_metadata_replica',
'template_delete' => 'template_delete_replica',
};
$childResolutions = [];
foreach ($children as $child) {
$childResolution = (string) $child->effect_resolution;
if ((int) ($child->parent_job_id ?? 0) !== (int) $parent->id
|| (int) $child->user_id !== (int) $parent->user_id
|| (string) $child->execution_mode !== 'agent'
|| (string) $child->kind !== $expectedChildKind
|| !in_array(
$childResolution,
['applied', 'not_applied'],
true
)) {
throw new CloudRecoveryAggregateStateConflict(
'云镜像汇总任务与子任务账本关系异常',
409
);
}
$childResolutions[$childResolution] = true;
}
$actualResolution = count($childResolutions) === 1
? (string) array_key_first($childResolutions) : 'mixed';
if ($actualResolution !== $resolution) {
throw new CloudRecoveryAggregateStateConflict(
'云镜像汇总任务与已结算效果不一致',
409
);
}
if ($kind === 'template_delete' && $resolution === 'applied') {
CloudTemplateDeletionService::assertSettledProjectionLocked(
$template,
$parent,
$resolution
);
return;
}
if ($resolution === 'mixed'
&& $kind !== 'template_metadata_sync') {
$expectedState = $kind === 'template_import'
? 'degraded' : 'delete_failed';
if ((string) $template->state !== $expectedState) {
throw new CloudRecoveryInstanceStateConflict(
'云镜像汇总任务的部分成功目录状态不一致',
409
);
}
self::assertRecoveredReplicaProjectionLocked(
$template,
$parent,
'mixed'
);
// Missing-pointer recovery temporarily restores this binding so
// the complete immutable projection can be checked under lock.
// A valid partial is intentionally released again afterwards.
$template->active_job_id = null;
$template->updated_at = time();
$template->save();
return;
}
$replicas = self::lockedReplicas((string) $template->id);
if (($kind === 'template_import' && $resolution === 'not_applied')
|| ($kind === 'template_delete' && $resolution === 'applied')) {
if ((string) $template->state !== 'retired'
|| !$replicas->isEmpty()) {
throw new CloudRecoveryInstanceStateConflict(
'云镜像汇总任务的已结算清理投影不一致',
409
);
}
return;
}
if ((string) $template->state !== 'active') {
throw new CloudRecoveryInstanceStateConflict(
'云镜像汇总任务的已结算主记录状态不一致',
409
);
}
if ($replicas->count() !== $children->count()) {
throw new CloudRecoveryAggregateStateConflict(
'云镜像汇总任务的已结算子任务与副本数量不一致',
409
);
}
foreach ($children as $child) {
$matches = $replicas->filter(
static fn (CloudTemplateReplica $replica): bool =>
(int) ($replica->job_id ?? 0) === (int) $child->id
);
$replica = $matches->count() === 1 ? $matches->first() : null;
if ($replica === null
|| (int) $replica->host_id !== (int) $child->host_id
|| !hash_equals(
(string) $child->operation_id,
(string) $replica->operation_id
)) {
throw new CloudRecoveryOperationIdentityConflict(
'云镜像汇总任务的已结算子任务与副本身份不一致',
409
);
}
$childResolution = (string) $child->effect_resolution;
$replicaRevision = (int) $replica->revision;
$templateRevision = (int) $template->revision;
$expectedState = match ($kind) {
'template_import' => 'active',
'template_metadata_sync' => $childResolution === 'applied'
? 'active' : 'stale',
'template_delete' => $replicaRevision === $templateRevision
? 'active' : 'stale',
};
$revisionInvalid = match ($kind) {
'template_import' => $replicaRevision !== $templateRevision,
'template_metadata_sync' => $childResolution === 'applied'
? $replicaRevision !== $templateRevision
: $replicaRevision >= $templateRevision,
'template_delete' => $replicaRevision > $templateRevision,
};
if (!hash_equals(
(string) $template->generation_token,
(string) $replica->generation_token
)
|| (string) $replica->state !== $expectedState
|| $revisionInvalid
|| (int) $replica->image_bytes
!== (int) $template->image_bytes
|| !hash_equals(
(string) $template->sha256,
(string) $replica->sha256
)) {
throw new CloudRecoveryInstanceStateConflict(
'云镜像汇总任务的已结算副本状态或内容不一致',
409
);
}
}
}
/** Do not publish aggregate applied until local master cleanup is durable. */
public static function aggregateEffectProjectionReadyLocked(
CloudJob $parent,
string $resolution
): bool {
if ((string) $parent->kind !== 'template_delete'
|| $resolution !== 'applied') {
return true;
}
$template = self::templateBoundToParentLocked($parent);
return (string) $template->state === 'retired'
&& !CloudTemplateReplica::query()->where(
'template_id',
(string) $template->id
)->lockForUpdate()->exists()
&& !CloudTemplateArtifact::query()->where(
'template_id',
(string) $template->id
)->lockForUpdate()->exists();
}
/**
* A recovered aggregate is stricter than ordinary incremental completion:
* every child must own exactly one replica with the same host, operation
* and final state. Empty, pending, extra or cross-wired ledgers stay fenced.
*/
private static function assertRecoveredReplicaProjectionLocked(
CloudTemplate $template,
CloudJob $parent,
string $resolution
): void {
if ((string) $parent->kind === 'template_delete') {
CloudTemplateDeletionService::assertChildProjectionLocked(
$template,
$parent,
$resolution
);
return;
}
$children = CloudJob::where('parent_job_id', (int) $parent->id)
->orderBy('id')->lockForUpdate()->get();
$replicas = self::lockedReplicas((string) $template->id);
if ($children->isEmpty() || $replicas->count() !== $children->count()) {
throw new CloudRecoveryAggregateStateConflict(
'云镜像汇总任务的子任务与副本数量不一致',
409
);
}
if (CloudUserIsoReplica::query()->whereIn(
'job_id',
$children->map(
static fn (CloudJob $child): int => (int) $child->id
)->all()
)->exists()) {
throw new CloudRecoveryOperationIdentityConflict(
'云镜像汇总子任务被 ISO 副本账本重复引用',
409
);
}
foreach ($children as $child) {
$childResolution = $resolution === 'mixed'
? (string) $child->effect_resolution : $resolution;
$expectedState = match ((string) $parent->kind) {
'template_import' => $childResolution === 'applied'
? 'active' : 'failed',
'template_metadata_sync' => $childResolution === 'applied'
? 'active' : 'stale',
'template_delete' => $childResolution === 'applied'
? 'delete_succeeded' : 'delete_failed',
default => '',
};
$matches = $replicas->filter(
static fn (CloudTemplateReplica $replica): bool =>
(int) ($replica->job_id ?? 0) === (int) $child->id
);
$replica = $matches->count() === 1 ? $matches->first() : null;
if ($replica === null
|| (int) $replica->host_id !== (int) $child->host_id
|| !hash_equals(
(string) $child->operation_id,
(string) $replica->operation_id
)) {
throw new CloudRecoveryOperationIdentityConflict(
'云镜像汇总任务的子任务与副本身份不一致',
409
);
}
if (!hash_equals(
(string) $template->generation_token,
(string) $replica->generation_token
)
|| (string) $replica->state !== $expectedState
|| ((string) $parent->kind !== 'template_import'
&& ((int) $replica->image_bytes
!== (int) $template->image_bytes
|| !hash_equals(
(string) $template->sha256,
(string) $replica->sha256
)))
|| ((string) $parent->kind === 'template_metadata_sync'
&& (($childResolution === 'applied'
&& (int) $replica->revision
!== (int) $template->revision)
|| ($childResolution === 'not_applied'
&& (int) $replica->revision
>= (int) $template->revision)))
|| ((string) $parent->kind === 'template_import'
&& $childResolution === 'applied'
&& ((int) $replica->revision
!== (int) $template->revision
|| (int) $replica->image_bytes
!== (int) $template->image_bytes
|| !hash_equals(
(string) $template->sha256,
(string) $replica->sha256
)))
|| ((string) $parent->kind === 'template_import'
&& $childResolution === 'not_applied'
&& ((int) $replica->image_bytes !== 0
|| ((string) $replica->sha256 !== ''
&& !hash_equals(
(string) $template->sha256,
(string) $replica->sha256
))))) {
throw new CloudRecoveryInstanceStateConflict(
'云镜像汇总任务的副本状态或内容不一致',
409
);
}
}
}
/** Restore the resource boundary only when every host proves no effect. */
private static function restoreNotAppliedProjectionLocked(
CloudTemplate $template,
CloudJob $parent
): void {
if ((string) $parent->kind === 'template_import') {
CloudTemplateReplica::query()->where(
'template_id',
(string) $template->id
)->delete();
CloudTemplateStateMachine::moveTemplate($template, 'retired');
$template->updated_at = time();
$template->save();
CloudTemplateImportPublication::settleDistributionLocked(
$template,
$parent,
false
);
CloudJobService::completeAggregateLocked(
$parent,
'failed',
false,
true,
'template_import_not_applied'
);
return;
}
if ((string) $parent->kind === 'template_delete') {
CloudTemplateDeletionService::restoreNotAppliedLocked(
$template,
$parent
);
return;
}
CloudTemplateStateMachine::assertReplicaTransition(
'syncing',
'stale'
);
CloudTemplateReplica::query()->where(
'template_id',
(string) $template->id
)->update([
'state' => 'stale',
'updated_at' => time(),
]);
CloudTemplateStateMachine::moveTemplate($template, 'active');
$template->updated_at = time();
$template->save();
CloudJobService::completeAggregateLocked(
$parent,
'failed',
false,
true,
'template_metadata_not_applied'
);
}
private static function finishImportReplica(CloudTemplate $template,
CloudTemplateReplica $replica, string $status, $result,
array $operation, bool $recovery): void
{
if ((string) $replica->state !== 'importing'
&& !($recovery && (string) $replica->state === 'failed')) {
throw new CloudError(
'云镜像副本状态与导入任务恢复证据不一致',
409
);
}
if ($status === 'succeeded') {
$digest = is_array($result)
? strtolower((string) ($result['sha256'] ?? '')) : '';
$bytes = is_array($result) ? filter_var(
$result['size_bytes'] ?? null,
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]
) : false;
if (!is_array($result) || array_is_list($result)
|| ($result['id'] ?? null) !== (string) $template->id
|| (int) ($result['revision'] ?? 0) !== (int) $template->revision
|| ($result['generation_token'] ?? null)
!== (string) $template->generation_token
|| $bytes === false
|| preg_match('/^[a-f0-9]{64}$/D', $digest) !== 1
|| ((string) $template->sha256 !== ''
&& !hash_equals((string) $template->sha256, $digest))
|| ((int) $template->image_bytes > 0
&& (int) $template->image_bytes !== (int) $bytes)) {
throw new CloudError('Agent 云镜像成功回执与请求不匹配', 502);
}
if ((string) $template->sha256 === '') {
$template->sha256 = $digest;
$template->image_bytes = (int) $bytes;
$template->updated_at = time();
$template->save();
}
CloudTemplateStateMachine::moveReplica($replica, 'active');
$replica->revision = (int) $template->revision;
$replica->image_bytes = (int) $bytes;
$replica->sha256 = $digest;
$replica->error_code = '';
} else {
CloudTemplateStateMachine::moveReplica($replica, 'failed');
$replica->error_code = self::errorCode(
$operation, 'template_import_failed'
);
}
CloudTemplateReplica::query()
->where('host_id', (int) $replica->host_id)
->where('template_id', (string) $replica->template_id)
->where('job_id', (int) $replica->job_id)->update([
'state' => (string) $replica->state,
'revision' => (int) $replica->revision,
'image_bytes' => (int) $replica->image_bytes,
'sha256' => (string) $replica->sha256,
'error_code' => (string) $replica->error_code,
'updated_at' => time(),
]);
}
private static function settleImportParent(CloudTemplate $template,
int $parentId, array $operation,
?int $completingChildId = null): void
{
$replicas = self::lockedReplicas((string) $template->id);
if ($replicas->isEmpty() || $replicas->contains(static fn ($row): bool =>
(string) $row->state === 'importing')) {
return;
}
$parent = self::parent($parentId, 'template_import');
self::assertTemplateParentBindingLocked($template, $parent);
if (CloudJobService::aggregateParentRecoveryPending(
$parent,
$completingChildId,
true
)) {
return;
}
$success = !$replicas->contains(static fn ($row): bool =>
(string) $row->state !== 'active');
$hostIds = $replicas->map(
static fn (CloudTemplateReplica $replica): int =>
(int) $replica->host_id
)->all();
$availability = CloudTemplateStateMachine::availability(
$template,
$replicas,
$hostIds
);
if ($availability !== 'error') {
CloudTemplate::query()
->where('catalog_key', (string) $template->catalog_key)
->where('id', '<>', (string) $template->id)
->where('is_default', 1)
->update(['is_default' => 0, 'updated_at' => time()]);
CloudTemplateStateMachine::moveTemplate(
$template,
$availability
);
$template->is_default = 1;
$template->updated_at = time();
$template->save();
} else {
CloudTemplateStateMachine::moveTemplate($template, 'error');
$template->updated_at = time();
$template->save();
}
if ($success) {
CloudTemplateImportPublication::settleDistributionLocked(
$template,
$parent,
true
);
CloudJobService::completeAggregateLocked($parent, 'succeeded',
true, false, '', ['template_id' => (string) $template->id]);
return;
}
CloudTemplateImportPublication::settleDistributionLocked(
$template,
$parent,
false
);
$effect = $replicas->contains(static fn ($row): bool =>
(string) $row->state === 'active')
|| ($operation['effect_may_have_applied'] ?? false) === true
|| CloudJob::where('parent_job_id', $parentId)
->where('effect_may_have_applied', 1)->exists();
CloudJobService::completeAggregateLocked($parent, 'failed', $effect,
false, 'template_import_failed');
}
private static function finishMetadataReplica(CloudTemplate $template,
CloudTemplateReplica $replica, string $status, $result,
array $operation, bool $recovery): void
{
if ((string) $replica->state !== 'syncing'
&& !($recovery && (string) $replica->state === 'stale')) {
throw new CloudError(
'云镜像副本状态与元数据任务恢复证据不一致',
409
);
}
if ($status === 'succeeded') {
if (!is_array($result) || array_is_list($result)
|| ($result['id'] ?? null) !== (string) $template->id
|| ($result['name'] ?? null) !== (string) $template->name
|| (int) ($result['revision'] ?? 0) !== (int) $template->revision
|| ($result['generation_token'] ?? null)
!== (string) $template->generation_token) {
throw new CloudError('Agent 元数据同步回执与请求不匹配', 502);
}
CloudTemplateStateMachine::moveReplica($replica, 'active');
$replica->revision = (int) $template->revision;
$replica->error_code = '';
} else {
CloudTemplateStateMachine::moveReplica($replica, 'stale');
$replica->error_code = self::errorCode(
$operation, 'template_metadata_sync_failed'
);
}
CloudTemplateReplica::query()
->where('host_id', (int) $replica->host_id)
->where('template_id', (string) $replica->template_id)
->where('job_id', (int) $replica->job_id)->update([
'state' => (string) $replica->state,
'revision' => (int) $replica->revision,
'error_code' => (string) $replica->error_code,
'updated_at' => time(),
]);
}
private static function settleMetadataParent(CloudTemplate $template,
int $parentId, array $operation,
?int $completingChildId = null): void
{
$replicas = self::lockedReplicas((string) $template->id);
if ($replicas->isEmpty() || $replicas->contains(static fn ($row): bool =>
(string) $row->state === 'syncing')) {
return;
}
$parent = self::parent($parentId, 'template_metadata_sync');
self::assertTemplateParentBindingLocked($template, $parent);
if (CloudJobService::aggregateParentRecoveryPending(
$parent,
$completingChildId,
true
)) {
return;
}
$success = !$replicas->contains(static fn ($row): bool =>
(string) $row->state !== 'active'
|| (int) $row->revision !== (int) $template->revision);
if ($success) {
CloudJobService::completeAggregateLocked($parent, 'succeeded',
true, false, '', ['template_id' => (string) $template->id]);
return;
}
$effect = $replicas->contains(static fn ($row): bool =>
(string) $row->state === 'active'
&& (int) $row->revision === (int) $template->revision)
|| ($operation['effect_may_have_applied'] ?? false) === true
|| CloudJob::where('parent_job_id', $parentId)
->where('effect_may_have_applied', 1)->exists();
CloudJobService::completeAggregateLocked($parent, 'failed', $effect,
false, 'template_metadata_sync_failed');
}
public static function expireAggregateLocked(CloudJob $parent): void
{
if (!in_array((string) $parent->kind, [
'template_import', 'template_metadata_sync', 'template_delete',
], true) || (string) $parent->phase === 'terminal') {
return;
}
$template = CloudTemplate::query()
->where('active_job_id', (int) $parent->id)
->lockForUpdate()->first();
if ($template === null) {
CloudJobService::completeAggregateLocked($parent, 'failed', true,
false, 'aggregate_ledger_missing');
return;
}
$children = CloudJob::where('parent_job_id', (int) $parent->id)
->lockForUpdate()->get();
$effect = $children->contains(static fn ($child): bool =>
CloudDispatchLedger::mayHaveDispatched($child)
|| (bool) $child->effect_may_have_applied);
$from = match ((string) $parent->kind) {
'template_import' => 'importing',
'template_metadata_sync' => 'syncing',
default => 'deleting',
};
$to = match ((string) $parent->kind) {
'template_import' => 'failed',
'template_metadata_sync' => 'stale',
default => 'delete_failed',
};
CloudTemplateStateMachine::assertReplicaTransition($from, $to);
CloudTemplateReplica::query()
->where('template_id', (string) $template->id)
->where('state', $from)->update([
'state' => $to,
'error_code' => 'aggregate_deadline_exceeded',
'updated_at' => time(),
]);
if ((string) $parent->kind === 'template_import') {
$replicas = self::lockedReplicas((string) $template->id);
$availability = CloudTemplateStateMachine::availability(
$template,
$replicas,
$replicas->map(
static fn (CloudTemplateReplica $replica): int =>
(int) $replica->host_id
)->all()
);
CloudTemplateStateMachine::moveTemplate(
$template,
$availability
);
} elseif ((string) $parent->kind === 'template_delete') {
CloudTemplateStateMachine::moveTemplate(
$template,
'delete_failed'
);
}
$template->updated_at = time();
$template->save();
if ((string) $parent->kind === 'template_import') {
CloudTemplateImportPublication::settleDistributionLocked(
$template,
$parent,
false
);
}
CloudJobService::completeAggregateLocked($parent, 'failed', $effect,
!$effect, 'aggregate_deadline_exceeded');
}
public static function startupScript(string $id): array
{
return self::scriptDto(self::find($id));
}
public static function applyProvisioningSnapshot(array $body,
bool $includeStartupScript = true): array
{
return self::applyProvisioningSnapshotForTarget(
$body,
$includeStartupScript,
null,
null
);
}
public static function applyProvisioningSnapshotForPool(
array $body,
int $poolId,
bool $includeStartupScript = true
): array {
return self::applyProvisioningSnapshotForTarget(
$body,
$includeStartupScript,
$poolId,
null
);
}
public static function applyProvisioningSnapshotForHost(
array $body,
int $hostId,
bool $includeStartupScript = true
): array {
return self::applyProvisioningSnapshotForTarget(
$body,
$includeStartupScript,
null,
$hostId
);
}
private static function applyProvisioningSnapshotForTarget(
array $body,
bool $includeStartupScript,
?int $poolId,
?int $hostId
): array {
$template = self::lockTemplateForMutation(
self::templateId($body['template_id'] ?? '')
);
$scoped = $poolId !== null || $hostId !== null;
if ($template === null || !in_array((string) $template->state,
$scoped ? ['active', 'degraded'] : ['active'], true)) {
throw new CloudError('云镜像模板不存在或暂不可用', 409);
}
if ($poolId !== null
&& !CloudTemplateAvailabilityService::poolHasExactReplica(
$template,
$poolId
)) {
throw new CloudError('所选销售地区暂未准备该云镜像', 409);
}
if ($hostId !== null
&& !CloudTemplateAvailabilityService::hostHasExactReplica(
$template,
$hostId
)) {
throw new CloudError('当前宿主机暂未准备该云镜像', 409);
}
if (!$scoped) {
self::assertCurrentActiveReplica($template, true);
}
unset($body['startup_script'], $body['template_revision'],
$body['template_generation_token']);
$body['template_id'] = (string) $template->id;
$body['template_revision'] = (int) $template->revision;
$body['template_generation_token'] =
(string) $template->generation_token;
if ($includeStartupScript) {
$body['startup_script'] = (string) $template->startup_script;
}
return $body;
}
public static function templateMetadataSnapshot(array $body): array
{
$id = self::templateId($body['template_id'] ?? '');
$revision = filter_var($body['template_revision'] ?? null,
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
$generation = $body['template_generation_token'] ?? null;
$template = self::lockTemplateForMutation($id);
if ($template === null || !in_array((string) $template->state,
['active', 'degraded'], true)
|| $revision === false
|| !is_string($generation)
|| !hash_equals((string) $template->generation_token, $generation)
|| (int) $template->revision !== (int) $revision) {
throw new CloudError('云镜像模板版本已变化,请重新提交', 409);
}
self::assertCurrentActiveReplica($template, true);
return ['template_id' => $id, 'os_source' => 'cloud_template',
'os_name' => self::name((string) $template->name),
'login_name' => 'root',
'debian_12_network_fix' =>
strcasecmp(trim((string) $template->os_family), 'debian') === 0
&& trim((string) $template->os_version) === '12'];
}
public static function assertProvisionable(string $id): void
{
$template = CloudTemplate::query()
->where('id', self::templateId($id))
->where('state', 'active')->first();
if ($template === null) {
throw new CloudError('云镜像模板不存在或暂不可用', 409);
}
if (!self::activeJobSafelySettled($template, false)) {
throw new CloudError(
'云镜像上一任务尚未安全收敛,禁止提交新的修改', 409
);
}
self::assertCurrentActiveReplica($template);
}
public static function assertProvisionableForPool(
string $id,
int $poolId
): void {
$template = self::scopedProvisionableTemplate($id);
if (!CloudTemplateAvailabilityService::poolHasExactReplica(
$template,
$poolId
)) {
throw new CloudError('所选销售地区暂未准备该云镜像', 409);
}
}
public static function assertProvisionableOnHost(
string $id,
int $hostId
): void {
$template = self::scopedProvisionableTemplate($id);
if (!CloudTemplateAvailabilityService::hostHasExactReplica(
$template,
$hostId
)) {
throw new CloudError('当前宿主机暂未准备该云镜像', 409);
}
}
private static function scopedProvisionableTemplate(
string $id
): CloudTemplate {
$template = CloudTemplate::query()
->where('id', self::templateId($id))
->whereIn('state', ['active', 'degraded'])->first();
if ($template === null) {
throw new CloudError('云镜像模板不存在或暂不可用', 409);
}
if (!self::activeJobSafelySettled($template, false)) {
throw new CloudError(
'云镜像上一任务尚未安全收敛,禁止提交新的修改',
409
);
}
return $template;
}
public static function saveStartupScript(string $id, $script,
$expectedRevision, $generationToken): array
{
$normalized = self::normalizeScript($script);
self::validateVersion($expectedRevision, $generationToken);
return (new CloudTemplate())->getConnection()->transaction(
static function () use (
$id, $normalized, $expectedRevision, $generationToken
): array {
$template = self::lockTemplateForMutation(
self::templateId($id)
);
if ($template === null || (string) $template->state === 'retired') {
throw new CloudError('云镜像模板不存在', 404);
}
if ((string) $template->state !== 'active'
|| (int) $template->revision !== $expectedRevision
|| !hash_equals((string) $template->generation_token,
(string) $generationToken)) {
throw new CloudError('初始化脚本已被修改,请重新打开对话框', 409);
}
$template->startup_script = $normalized;
$template->revision = (int) $template->revision + 1;
$template->updated_at = time();
$template->save();
CloudTemplateReplica::query()
->where('template_id', (string) $template->id)
->where('generation_token',
(string) $template->generation_token)
->where('state', 'active')->update([
'revision' => (int) $template->revision,
'updated_at' => time(),
]);
return self::scriptDto($template);
}, 3
);
}
public static function normalizeScript($script): string
{
if (!is_string($script) || preg_match('//u', $script) !== 1
|| str_contains($script, "\0")) {
throw new CloudError('启动脚本必须是有效 UTF-8 文本,且不能包含 NUL 字符', 422);
}
$script = str_replace("\r\n", "\n", $script);
if (strlen($script) > self::STARTUP_SCRIPT_MAX_BYTES) {
throw new CloudError('启动脚本不能超过 32 KiB', 422);
}
return $script;
}
private static function assertNoOrderReferencesLocked(
string $templateId
): void
{
foreach (CloudOrder::query()->whereIn('status', [
'awaiting_payment', 'queued', 'running',
])->orderBy('id')->lockForUpdate()->get(['id', 'spec_json']) as $order) {
$spec = json_decode((string) $order->spec_json, true);
if (is_array($spec) && !array_is_list($spec)
&& ($spec['template_id'] ?? null) === $templateId) {
throw new CloudError('云镜像仍被未完成订单使用,暂不能删除', 409);
}
}
}
private static function assertNoJobReferencesLocked(
string $templateId
): void {
$jobs = CloudJob::query()->whereIn('kind', ['create', 'reinstall'])
->where(static function ($query): void {
$query->where('phase', '<>', 'terminal')
->orWhere(static function ($failed): void {
$failed->where('phase', 'terminal')
->where('outcome', 'failed')
->where('effect_resolution', 'unknown');
});
})->lockForUpdate()->get(['sealed_payload']);
foreach ($jobs as $job) {
$payload = CloudSecrets::decrypt(
(string) $job->sealed_payload, 'job-payload'
);
if (($payload['body']['template_id'] ?? null) === $templateId) {
throw new CloudError('云镜像仍被虚拟机任务使用,暂不能删除', 409);
}
}
}
/**
* Acquire the canonical mutation boundary for one host-replica sync.
* The coordinator still owns replica and job validation; exposing this
* narrow lock keeps the parent -> template lock order in one module.
*/
public static function lockForReplicaSync(
string $id
): ?CloudTemplate {
return self::lockTemplateForMutation(self::templateId($id));
}
/**
* Discover the old parent without a row lock, then acquire the canonical
* parent -> catalog order and reject a pointer that changed in between.
*/
private static function lockTemplateForMutation(
string $id
): ?CloudTemplate {
$snapshot = CloudTemplate::query()->where('id', $id)->first();
if ($snapshot === null) {
return null;
}
$jobId = (int) ($snapshot->active_job_id ?? 0);
$parentSnapshot = $jobId > 0
? CloudJob::where('id', $jobId)->first() : null;
$parent = self::isTemplateAggregateParent($parentSnapshot)
? CloudJob::where('id', $jobId)
->where('execution_mode', 'aggregate')
->whereNull('parent_job_id')
->whereIn('kind', [
'template_import',
'template_metadata_sync',
'template_delete',
])->lockForUpdate()->first()
: null;
$template = CloudTemplate::query()->where('id', $id)
->lockForUpdate()->first();
if ($template === null) {
return null;
}
if ((int) ($template->active_job_id ?? 0) !== $jobId) {
throw new CloudError(
'云镜像任务状态已变化,请刷新后重试',
409
);
}
self::assertMutationBoundaryLocked($template, $parent);
return $template;
}
/** Never take a child/dangling pointer as the canonical parent lock. */
private static function isTemplateAggregateParent(?CloudJob $job): bool
{
return $job !== null
&& (string) $job->execution_mode === 'aggregate'
&& $job->parent_job_id === null
&& in_array((string) $job->kind, [
'template_import',
'template_metadata_sync',
'template_delete',
], true);
}
/** Do not overlap a new mutation with an active or unresolved effect. */
private static function assertMutationBoundaryLocked(
CloudTemplate $template,
?CloudJob $lockedParent = null
): void {
if (!self::activeJobSafelySettled(
$template,
true,
$lockedParent
)) {
throw new CloudError(
'云镜像上一任务尚未安全收敛,禁止提交新的修改', 409
);
}
}
/** A historical fail-open parent must not expose or mutate its template. */
private static function activeJobSafelySettled(
CloudTemplate $template,
bool $lockForUpdate = false,
?CloudJob $lockedParent = null
): bool {
$jobId = (int) ($template->active_job_id ?? 0);
if ($jobId < 1) {
// The catalog row is already locked by every mutation caller.
// Do not take the parent lock in the reverse worker lock order;
// instead, recognize any uniquely or ambiguously linked in-flight
// ledger and keep the mutation fenced until the parent-first
// recovery sweep repairs or diagnoses the pointer.
return !self::missingPointerRecoveryPending($template);
}
if ($template->exists) {
$bindings = CloudTemplate::query()
->where('active_job_id', $jobId)
->orderBy('id');
if ($lockForUpdate) {
$bindings->lockForUpdate();
}
$bound = $bindings->get(['id']);
if ($bound->count() !== 1
|| (string) $bound->first()->id
!== (string) $template->id) {
return false;
}
}
if ($lockedParent !== null
&& (int) $lockedParent->id !== $jobId) {
return false;
}
// A write boundary must arrive with the parent already locked. Never
// acquire a parent after the catalog row.
if ($lockForUpdate && $lockedParent === null) {
return false;
}
$job = $lockedParent ?? CloudJob::where('id', $jobId)->first();
return $job !== null && self::aggregateParentSafelySettled(
$job,
$lockForUpdate
) && self::currentParentProjectionMatches(
$template,
$job,
$lockForUpdate
);
}
/** The current resource must own every child and replica of its parent. */
private static function currentParentProjectionMatches(
CloudTemplate $template,
CloudJob $parent,
bool $lockForUpdate
): bool {
$expectedChildKind = match ((string) $parent->kind) {
'template_import' => 'template_import_replica',
'template_metadata_sync' => 'template_metadata_replica',
'template_delete' => 'template_delete_replica',
default => null,
};
if ($expectedChildKind === null) {
return false;
}
$childQuery = CloudJob::where(
'parent_job_id',
(int) $parent->id
)->orderBy('id');
if ($lockForUpdate) {
$childQuery->lockForUpdate();
}
$children = $childQuery->get();
$replicaQuery = CloudTemplateReplica::query()
->where('template_id', (string) $template->id)
->orderBy('host_id');
if ($lockForUpdate) {
$replicaQuery->lockForUpdate();
}
$replicas = $replicaQuery->get();
if ($children->isEmpty()
|| $children->count() !== $replicas->count()) {
return false;
}
$childResolutions = $children->map(
static fn (CloudJob $child): string =>
(string) $child->effect_resolution
)->unique()->values();
if ($childResolutions->contains(
static fn (string $resolution): bool => !in_array(
$resolution,
['applied', 'not_applied'],
true
)
)) {
return false;
}
$actualResolution = $childResolutions->count() === 1
? (string) $childResolutions->first() : 'mixed';
$publishedResolution = $actualResolution === 'mixed'
? 'applied' : $actualResolution;
$projectionStateMatches = match ((string) $parent->kind) {
'template_import' => (string) $template->state
=== ($actualResolution === 'mixed' ? 'degraded' : 'active'),
'template_metadata_sync' => (string) $template->state === 'active',
'template_delete' => (string) $template->state
=== ($actualResolution === 'mixed'
? 'delete_failed' : 'active'),
default => false,
};
if (!hash_equals(
(string) $parent->effect_resolution,
$publishedResolution
) || !$projectionStateMatches
|| ($actualResolution === 'mixed'
&& (string) $parent->kind !== 'template_metadata_sync'
&& !CloudJobService::hasPublishedPartialAggregateMarker(
$parent
))) {
return false;
}
$jobIds = $children->map(
static fn (CloudJob $child): int => (int) $child->id
)->all();
if (CloudTemplateReplica::query()->whereIn('job_id', $jobIds)
->where('template_id', '<>', (string) $template->id)->exists()
|| CloudUserIsoReplica::query()->whereIn(
'job_id',
$jobIds
)->exists()) {
return false;
}
foreach ($children as $child) {
$matches = $replicas->filter(
static fn (CloudTemplateReplica $replica): bool =>
(int) ($replica->job_id ?? 0) === (int) $child->id
);
$replica = $matches->count() === 1 ? $matches->first() : null;
$childResolution = (string) $child->effect_resolution;
$replicaRevision = (int) ($replica?->revision ?? 0);
$expectedState = match ((string) $parent->kind) {
'template_import' => $actualResolution === 'mixed'
&& $childResolution === 'not_applied'
? 'failed' : 'active',
'template_metadata_sync' => $childResolution === 'applied'
? 'active' : 'stale',
'template_delete' => $actualResolution === 'mixed'
? ($childResolution === 'applied'
? 'delete_succeeded' : 'delete_failed')
: ($replicaRevision === (int) $template->revision
? 'active' : 'stale'),
default => '',
};
$revisionInvalid = match ((string) $parent->kind) {
'template_import' => $childResolution === 'applied'
? $replicaRevision !== (int) $template->revision
: false,
'template_metadata_sync' => $childResolution === 'applied'
? $replicaRevision !== (int) $template->revision
: $replicaRevision >= (int) $template->revision,
'template_delete' => $replicaRevision
> (int) $template->revision,
default => true,
};
if ($replica === null
|| (int) ($child->parent_job_id ?? 0) !== (int) $parent->id
|| (int) $child->user_id !== (int) $parent->user_id
|| (string) $child->execution_mode !== 'agent'
|| (string) $child->kind !== $expectedChildKind
|| (int) $child->host_id !== (int) $replica->host_id
|| !hash_equals(
(string) $child->operation_id,
(string) $replica->operation_id
)
|| !hash_equals(
(string) $template->generation_token,
(string) $replica->generation_token
)
|| (string) $replica->state !== $expectedState
|| $revisionInvalid
|| ((string) $parent->kind === 'template_import'
&& $childResolution === 'not_applied'
? ((int) $replica->image_bytes !== 0
|| ((string) $replica->sha256 !== ''
&& !hash_equals(
(string) $template->sha256,
(string) $replica->sha256
)))
: ((int) $replica->image_bytes
!== (int) $template->image_bytes
|| !hash_equals(
(string) $template->sha256,
(string) $replica->sha256
)))) {
return false;
}
}
return true;
}
private static function aggregateParentSafelySettled(
CloudJob $job,
bool $lockForUpdate
): bool {
return !(
$job->parent_job_id !== null
|| (string) $job->execution_mode !== 'aggregate'
|| !in_array((string) $job->kind, [
'template_import',
'template_metadata_sync',
'template_delete',
], true)
|| CloudJobService::hasAggregateLocalStateConflict($job)
|| (string) $job->phase !== 'terminal'
|| !in_array(
(string) $job->effect_resolution,
['applied', 'not_applied'],
true
)
|| (bool) $job->finalization_incident
|| CloudJobService::aggregateParentRecoveryPending(
$job,
null,
$lockForUpdate
));
}
/**
* Treat a NULL/zero pointer as safe only when every current replica owns a
* settled, identity-matched job. A catalog may legitimately contain a mix
* of historical aggregate children and newer standalone repair jobs.
*/
private static function missingPointerRecoveryPending(
CloudTemplate $template
): bool {
$templateId = (string) ($template->id ?? '');
if ($templateId === '') {
return false;
}
$replicas = CloudTemplateReplica::query()
->where('template_id', $templateId)
->orderBy('host_id')
->get([
'host_id', 'job_id', 'state', 'operation_id',
'generation_token',
]);
if ($replicas->isEmpty()) {
return false;
}
$jobIds = $replicas->map(
static fn (CloudTemplateReplica $replica): int =>
(int) ($replica->job_id ?? 0)
)->filter(static fn (int $id): bool => $id > 0)
->unique()->values()->all();
// A replica without a child ledger is historical catalog data, not
// proof of an in-flight operation. A partial mapping is damage.
if ($jobIds === []) {
return false;
}
if (count($jobIds) !== $replicas->count()) {
return true;
}
if (CloudUserIsoReplica::query()->whereIn(
'job_id',
$jobIds
)->exists() || CloudTemplateReplica::query()->whereIn(
'job_id',
$jobIds
)->where('template_id', '<>', $templateId)->exists()) {
return true;
}
$children = CloudJob::whereIn('id', $jobIds)->orderBy('id')->get();
if ($children->count() !== count($jobIds)) {
return true;
}
$parentIds = [];
$hasStandalone = false;
foreach ($children as $child) {
$matches = $replicas->filter(
static fn (CloudTemplateReplica $replica): bool =>
(int) ($replica->job_id ?? 0) === (int) $child->id
);
$replica = $matches->count() === 1 ? $matches->first() : null;
$parentId = (int) ($child->parent_job_id ?? 0);
if ($replica === null
|| (string) $child->execution_mode !== 'agent'
|| (int) $child->host_id < 1
|| (int) $replica->host_id !== (int) $child->host_id
|| preg_match(
'/^[a-f0-9]{32}$/D',
(string) $child->operation_id
) !== 1
|| !hash_equals(
(string) $child->operation_id,
(string) $replica->operation_id
)
|| !hash_equals(
(string) $template->generation_token,
(string) $replica->generation_token
)) {
return true;
}
if ($parentId < 1) {
$hasStandalone = true;
if (!self::standaloneReplicaJobSafelySettled(
$template,
$replica,
$child
)) {
return true;
}
continue;
}
$parentIds[$parentId] = true;
}
foreach (array_keys($parentIds) as $parentId) {
$parent = CloudJob::find((int) $parentId);
$expectedChildKind = match ((string) ($parent?->kind ?? '')) {
'template_import' => 'template_import_replica',
'template_metadata_sync' => 'template_metadata_replica',
'template_delete' => 'template_delete_replica',
default => null,
};
if ($parent === null
|| $expectedChildKind === null
|| (string) $parent->execution_mode !== 'aggregate'
|| $parent->parent_job_id !== null
|| !self::aggregateParentSafelySettled($parent, false)
|| CloudTemplate::query()
->where('active_job_id', (int) $parent->id)
->where('id', '<>', $templateId)->exists()) {
return true;
}
foreach ($children->where('parent_job_id', (int) $parentId)
as $child) {
if ((string) $child->kind !== $expectedChildKind
|| (int) $child->user_id !== (int) $parent->user_id) {
return true;
}
}
}
if (!$hasStandalone && count($parentIds) === 1) {
$parent = CloudJob::find((int) array_key_first($parentIds));
$allChildrenBelongToCurrentReplicas = $parent !== null
&& CloudJob::where(
'parent_job_id',
(int) $parent->id
)->count() === $children->count();
if ($allChildrenBelongToCurrentReplicas
&& !self::currentParentProjectionMatches(
$template,
$parent,
false
)) {
return true;
}
}
return false;
}
private static function standaloneReplicaJobSafelySettled(
CloudTemplate $template,
CloudTemplateReplica $replica,
CloudJob $job
): bool {
if ($job->parent_job_id !== null
|| (string) $job->kind !== 'template_import_replica'
|| (string) $job->phase !== 'terminal'
|| !in_array((string) $job->effect_resolution, [
'applied', 'not_applied',
], true)
|| (bool) $job->finalization_incident
|| CloudJobService::hasAgentRecoveryEnvelopeConflict($job)) {
return false;
}
if ((string) $job->effect_resolution === 'not_applied') {
return (bool) $job->safe_to_resubmit
&& (string) $replica->state === 'failed'
&& (int) $replica->image_bytes === 0;
}
return (string) $replica->state === 'active'
&& (int) $replica->revision === (int) $template->revision
&& (int) $replica->image_bytes === (int) $template->image_bytes
&& hash_equals(
(string) $template->sha256,
(string) $replica->sha256
);
}
/** Return the exact settled mixed parent that permits delete-only cleanup. */
private static function settledMixedCleanupParentKind(
CloudTemplate $template
): ?string {
if ((int) ($template->active_job_id ?? 0) > 0
|| !in_array(
(string) $template->state,
['degraded', 'delete_failed'],
true
)
|| self::missingPointerRecoveryPending($template)) {
return null;
}
$replica = CloudTemplateReplica::query()
->where('template_id', (string) $template->id)
->whereNotNull('job_id')->orderBy('host_id')->first();
$child = $replica === null ? null : CloudJob::find(
(int) $replica->job_id
);
$parent = $child === null ? null : CloudJob::find(
(int) ($child->parent_job_id ?? 0)
);
$kind = (string) ($parent?->kind ?? '');
if ($parent === null
|| !in_array($kind, ['template_import', 'template_delete'], true)
|| CloudJobService::effectScope($parent) !== 'partial'
|| !self::aggregateParentSafelySettled($parent, false)
|| !self::currentParentProjectionMatches(
$template,
$parent,
false
)) {
return null;
}
return $kind;
}
private static function assertCurrentActiveReplica(
CloudTemplate $template,
bool $lockForUpdate = false
): void {
if (!self::hasCurrentActiveReplica($template, $lockForUpdate)) {
throw new CloudError('云镜像模板暂无可用宿主机副本', 409);
}
}
private static function hasCurrentActiveReplica(
CloudTemplate $template,
bool $lockForUpdate = false
): bool {
$query = CloudTemplateReplica::query()
->where('template_id', (string) $template->id)
->where('state', 'active')
->where('generation_token', (string) $template->generation_token)
->where('revision', (int) $template->revision)
->orderBy('host_id');
if ($lockForUpdate) {
$query->lockForUpdate();
}
return $query->first(['host_id']) !== null;
}
private static function lockedReplicas(string $id)
{
return CloudTemplateReplica::query()->where('template_id', $id)
->orderBy('host_id')->lockForUpdate()->get();
}
private static function templateBoundToParentLocked(
CloudJob $parent
): CloudTemplate {
$templates = CloudTemplate::query()
->where('active_job_id', (int) $parent->id)
->orderBy('id')
->lockForUpdate()
->get();
if ($templates->count() > 1) {
throw new CloudRecoveryAggregateStateConflict(
'云镜像汇总任务绑定了多个目录主记录',
409
);
}
if ($templates->isEmpty()) {
return self::repairMissingParentBindingLocked($parent);
}
return $templates->first();
}
/**
* Repair only a single damaged active_job_id field. The immutable child
* and replica ledgers must identify one in-flight catalog row exactly;
* this never creates a job or replays an Agent mutation.
*/
public static function repairMissingParentBindingLocked(
CloudJob $parent
): CloudTemplate {
$kind = (string) $parent->kind;
$expectedChildKind = match ($kind) {
'template_import' => 'template_import_replica',
'template_metadata_sync' => 'template_metadata_replica',
'template_delete' => 'template_delete_replica',
default => null,
};
$expectedStates = match ($kind) {
'template_import' => ['importing', 'error', 'degraded', 'active'],
'template_metadata_sync' => ['active'],
'template_delete' => ['deleting', 'delete_failed', 'active'],
default => [],
};
if ($expectedChildKind === null
|| $expectedStates === []
|| (string) $parent->execution_mode !== 'aggregate'
|| $parent->parent_job_id !== null
|| CloudJobService::hasAggregateLocalStateConflict($parent)) {
throw new CloudRecoveryInstanceStateConflict(
'云镜像活动任务指针缺失,且父任务状态不能证明唯一目录绑定',
409
);
}
// Discover without locks first so the established lock order remains
// parent -> catalog row -> children -> replicas. Every value is then
// re-read and verified under locks before the pointer is written.
$childIds = CloudJob::where('parent_job_id', (int) $parent->id)
->orderBy('id')->pluck('id')->map(
static fn ($id): int => (int) $id
)->all();
if ($childIds === []) {
throw new CloudRecoveryAggregateStateConflict(
'云镜像活动任务指针缺失,且父任务没有子任务账本',
409
);
}
$candidateIds = CloudTemplateReplica::query()
->whereIn('job_id', $childIds)
->orderBy('template_id')
->pluck('template_id')
->map(static fn ($id): string => (string) $id)
->unique()->values();
if ($candidateIds->isEmpty()) {
throw new CloudRecoveryInstanceStateConflict(
'云镜像活动任务指针缺失,副本账本无法定位目录主记录',
409
);
}
if ($candidateIds->count() !== 1) {
throw new CloudRecoveryOperationIdentityConflict(
'云镜像活动任务指针缺失,副本账本指向多个目录主记录',
409
);
}
$template = CloudTemplate::query()
->where('id', (string) $candidateIds->first())
->lockForUpdate()->first();
if ($template === null) {
throw new CloudRecoveryInstanceStateConflict(
'云镜像活动任务指针缺失,副本账本引用的目录主记录不存在',
409
);
}
$currentJobId = (int) ($template->active_job_id ?? 0);
if ($currentJobId > 0 && $currentJobId !== (int) $parent->id) {
throw new CloudRecoveryOperationIdentityConflict(
'云镜像活动任务正数指针指向其他任务,不能自动改写',
409
);
}
if (!in_array(
(string) $template->state,
$expectedStates,
true
)) {
throw new CloudRecoveryInstanceStateConflict(
'云镜像活动任务指针或目录状态与原父任务不一致',
409
);
}
$otherBindings = CloudTemplate::query()
->where('active_job_id', (int) $parent->id)
->where('id', '<>', (string) $template->id)
->orderBy('id')->lockForUpdate()->get(['id']);
if (!$otherBindings->isEmpty()) {
throw new CloudRecoveryOperationIdentityConflict(
'云镜像父任务已绑定其他目录主记录,不能修复活动任务指针',
409
);
}
$children = CloudJob::where('parent_job_id', (int) $parent->id)
->orderBy('id')->lockForUpdate()->get();
$replicas = self::lockedReplicas((string) $template->id);
if (CloudUserIsoReplica::query()->whereIn(
'job_id',
$childIds
)->exists()) {
throw new CloudRecoveryOperationIdentityConflict(
'云镜像活动任务子任务被 ISO 副本账本重复引用',
409
);
}
if ($children->count() !== count($childIds)
|| $replicas->count() !== $children->count()
|| preg_match(
'/^[a-f0-9]{32}$/D',
(string) $template->generation_token
) !== 1) {
throw new CloudRecoveryAggregateStateConflict(
'云镜像活动任务指针缺失,子任务与副本数量不一致',
409
);
}
if ($kind === 'template_metadata_sync'
&& !$replicas->contains(
static fn (CloudTemplateReplica $replica): bool => in_array(
(string) $replica->state,
['syncing', 'stale'],
true
)
)
&& !((string) $parent->phase === 'terminal'
&& (string) $parent->outcome === 'failed'
&& (string) $parent->status === 'failed'
&& (string) $parent->effect_resolution === 'unknown')
&& !(bool) $parent->finalization_incident) {
throw new CloudRecoveryInstanceStateConflict(
'云镜像元数据任务指针缺失,但当前账本不能证明仍有待恢复操作',
409
);
}
foreach ($children as $child) {
$matches = $replicas->filter(
static fn (CloudTemplateReplica $replica): bool =>
(int) ($replica->job_id ?? 0) === (int) $child->id
);
$replica = $matches->count() === 1 ? $matches->first() : null;
if ($replica === null
|| (int) ($child->parent_job_id ?? 0) !== (int) $parent->id
|| (int) $child->user_id !== (int) $parent->user_id
|| (string) $child->execution_mode !== 'agent'
|| (string) $child->kind !== $expectedChildKind
|| (int) $child->host_id < 1
|| (int) $replica->host_id !== (int) $child->host_id
|| preg_match(
'/^[a-f0-9]{32}$/D',
(string) $child->operation_id
) !== 1
|| !hash_equals(
(string) $child->operation_id,
(string) $replica->operation_id
)
|| !hash_equals(
(string) $template->generation_token,
(string) $replica->generation_token
)) {
throw new CloudRecoveryOperationIdentityConflict(
'云镜像活动任务指针缺失,子任务与副本身份不一致',
409
);
}
}
if ($currentJobId !== (int) $parent->id) {
$update = CloudTemplate::query()
->where('id', (string) $template->id)
->where(static function ($missing): void {
$missing->whereNull('active_job_id')
->orWhere('active_job_id', '<=', 0);
});
$updated = $update->update([
'active_job_id' => (int) $parent->id,
'updated_at' => time(),
]);
if ($updated !== 1) {
throw new CloudRecoveryOperationIdentityConflict(
'云镜像活动任务指针在修复时发生并发变化',
409
);
}
$template->refresh();
}
return $template;
}
private static function assertTemplateParentBindingLocked(
CloudTemplate $template,
CloudJob $parent
): void {
$bound = self::templateBoundToParentLocked($parent);
if (!hash_equals((string) $bound->id, (string) $template->id)
|| (int) $template->active_job_id !== (int) $parent->id) {
throw new CloudRecoveryOperationIdentityConflict(
'云镜像汇总任务与目录主记录身份不一致',
409
);
}
}
private static function parent(int $id, string $kind): CloudJob
{
$job = CloudJob::where('id', $id)->where('kind', $kind)
->lockForUpdate()->first();
if ($job === null) {
throw new CloudError('云镜像聚合任务不存在', 409);
}
return $job;
}
private static function find(string $id): CloudTemplate
{
$row = CloudTemplate::find(self::templateId($id));
if ($row === null || (string) $row->state === 'retired') {
throw new CloudError('云镜像模板不存在', 404);
}
return $row;
}
/**
* @param list<CloudTemplateReplica> $replicas
* @param array<int,array<string,mixed>> $hosts
*/
private static function adminDto(
CloudTemplate $row,
array $replicas,
array $hosts,
?CloudTemplateArtifact $artifact
): array
{
$partialCleanupKind = self::settledMixedCleanupParentKind($row);
$replicasByHost = [];
foreach ($replicas as $replica) {
$replicasByHost[(int) $replica->host_id] = $replica;
}
$matrix = [];
$summary = [
'hosts' => count($hosts),
'eligible' => 0,
'ready' => 0,
'repairable' => 0,
'attention' => 0,
];
foreach ($hosts as $hostId => $host) {
$replica = $replicasByHost[$hostId] ?? null;
$eligible = ($host['eligible'] ?? false) === true;
$plan = CloudTemplateReplicaCoordinator::repairPlan(
$row,
$replica,
$eligible
);
$exact = $replica !== null
&& CloudTemplateReplicaCoordinator::isExactReplica(
$row,
$replica
);
$summary['eligible'] += $eligible ? 1 : 0;
$summary['ready'] += $exact ? 1 : 0;
$summary['repairable'] += $plan['action'] !== null ? 1 : 0;
$summary['attention'] += $eligible && !$exact ? 1 : 0;
$matrix[] = [
'host_id' => $hostId,
'host_name' => (string) $host['name'],
'host_region' => (string) $host['region'],
'host_enabled' => (bool) $host['enabled'],
'host_eligible' => $eligible,
'host_record_present' =>
(bool) $host['record_present'],
'state' => $replica === null
? 'missing' : (string) $replica->state,
'revision' => $replica === null
? 0 : (int) $replica->revision,
'generation_token' => $replica === null
? '' : (string) $replica->generation_token,
'image_bytes' => $replica === null
? 0 : (int) $replica->image_bytes,
'sha256' => $replica === null
? '' : (string) $replica->sha256,
'error_code' => $replica === null
? '' : (string) $replica->error_code,
'operation_id' => $replica === null
? '' : (string) $replica->operation_id,
'observed_state' => $replica === null
? 'never' : (string) ($replica->observed_state ?? 'never'),
'observed_revision' => $replica === null
? 0 : (int) ($replica->observed_revision ?? 0),
'last_verified_at' => $replica === null
? 0 : (int) ($replica->last_verified_at ?? 0),
'exact' => $exact,
'repair_action' => $plan['action'],
'repair_reason' => $plan['reason'],
];
}
$result = [
'id' => (string) $row->id,
'catalog_key' => (string) $row->catalog_key,
'version_label' => (string) $row->version_label,
'is_default' => (bool) $row->is_default,
'name' => (string) $row->name,
'os_family' => (string) $row->os_family,
'os_version' => (string) $row->os_version,
'image_bytes' => (int) $row->image_bytes,
'sha256' => (string) $row->sha256,
'state' => (string) $row->state,
'startup_script_configured' => (string) $row->startup_script !== '',
'revision' => (int) $row->revision,
'generation_token' => (string) $row->generation_token,
'created_at' => (int) $row->created_at,
'updated_at' => (int) $row->updated_at,
'replica_summary' => $summary,
'replicas' => $matrix,
'artifact' => $artifact === null ? null : [
'state' => (string) $artifact->state,
'error_code' => (string) $artifact->error_code,
'delete_generation' =>
(int) $artifact->delete_generation,
'next_check_at' =>
(int) $artifact->delete_next_check_at,
],
];
if ($partialCleanupKind !== null) {
$result['cleanup_reason'] = $partialCleanupKind
=== 'template_import'
? 'partial_import' : 'partial_delete';
}
if ($artifact !== null
&& (string) $artifact->state === 'delete_attention') {
$result['cleanup_reason'] = 'artifact_delete_attention';
}
return $result;
}
private static function scriptDto(CloudTemplate $row): array
{
return ['id' => (string) $row->id,
'startup_script' => (string) $row->startup_script,
'revision' => (int) $row->revision,
'generation_token' => (string) $row->generation_token];
}
private static function validateVersion($revision, $generation): void
{
if (!is_int($revision) || $revision < 1
|| !is_string($generation)
|| preg_match('/^[a-f0-9]{32}$/D', $generation) !== 1) {
throw new CloudError('云镜像版本无效,请刷新后重试', 422);
}
}
private static function errorCode(array $operation, string $fallback): string
{
$code = $operation['error_code'] ?? null;
return is_string($code)
&& preg_match('/^[a-z][a-z0-9_]{0,63}$/D', $code) === 1
? $code : $fallback;
}
private static function templateId($value): string
{
if (!is_string($value)
|| preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/D', $value) !== 1) {
throw new CloudError('请选择有效的云镜像模板');
}
return $value;
}
private static function name($value): string
{
return self::label($value, '模板名称', 64);
}
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;
}
}