feat: close offer availability against pool capacity

dev
admin 2 months ago
parent 328b18b8e3
commit 5e8f623e2a

@ -36,7 +36,6 @@ final class CloudDeploymentPageService
->join('cloud_network_lines as line', 'line.id', '=', 'pool.line_id')
->join('cloud_regions as region', 'region.id', '=', 'line.region_id')
->where('offer.status', 1)
->where('offer.stock', '<>', 0)
->where('offer.currency', 'USD')
->where('plan.status', 1)
->where('pool.status', 'active')
@ -51,14 +50,33 @@ final class CloudDeploymentPageService
->orderByDesc('offer.sort')->orderBy('offer.id')
->get([
'offer.id as offer_id', 'offer.name as offer_name',
'offer.price as offer_price',
'offer.price as offer_price', 'offer.stock as offer_stock',
'plan.cpu_cores', 'plan.memory_mib', 'plan.bandwidth_mbps',
'plan.disk_gib', 'plan.validity_days', 'plan.traffic_quota_bytes',
'pool.id as internal_pool_id',
'line.id as line_id', 'line.name as line_name', 'line.is_default',
'region.id as region_id', 'region.name as region_name',
'region.country_code',
]);
$capacityKey = static fn ($row): string => implode(':', [
(int) $row->internal_pool_id,
(int) $row->cpu_cores,
(int) $row->memory_mib,
(int) $row->disk_gib,
]);
$capacityRequests = [];
foreach ($rows as $row) {
$capacityRequests[$capacityKey($row)] = [
'pool_id' => (int) $row->internal_pool_id,
'cpu_cores' => (int) $row->cpu_cores,
'memory_mib' => (int) $row->memory_mib,
'disk_gib' => (int) $row->disk_gib,
];
}
$capacity = CloudPlacementService::poolCapacityAvailability(
$capacityRequests
);
$regions = [];
$lines = [];
$offers = [];
@ -84,6 +102,7 @@ final class CloudDeploymentPageService
}
$trafficBytes = max(0, (int) $row->traffic_quota_bytes);
$trafficGiB = intdiv($trafficBytes, self::GIB);
$offerCapacityKey = $capacityKey($row);
$offers[] = [
'id' => (int) $row->offer_id,
'name' => trim((string) $row->offer_name),
@ -99,6 +118,8 @@ final class CloudDeploymentPageService
'traffic_quota_bytes' => $trafficBytes,
'traffic_gib' => $trafficGiB,
'traffic_tib' => self::formatDecimalUnit($trafficGiB, 1024, 10),
'sellable' => (int) $row->offer_stock !== 0
&& ($capacity[$offerCapacityKey] ?? false),
];
}

@ -83,6 +83,14 @@ final class CloudOrderService
|| (!CloudNetworkLineFeature::enabled() && !(bool) $line->is_default)) {
throw new CloudError('该销售方案的地区、线路或资源池暂不可用', 409);
}
if (!CloudPlacementService::isPoolCapacityAvailable(
(int) $pool->id,
(int) $plan->cpu_cores,
(int) $plan->memory_mib,
(int) $plan->disk_gib
)) {
throw new CloudError('该销售方案当前没有足够的可用资源或公网 IP', 409);
}
$price = CloudMoney::cents($offer->price);
$payload = ['source' => $source, 'name' => $name, 'vcpu' => (int) $plan->cpu_cores,
'memory_mib' => (int) $plan->memory_mib, 'disk_gib' => (int) $plan->disk_gib,

@ -28,6 +28,85 @@ final class CloudPlacementService
private const GIB = 1073741824;
private const ACTIVE_RESERVATIONS = ['held', 'uncertain'];
/**
* Advisory capacity check for an already-authorized active pool chain.
*
* Catalog construction has already joined and filtered the offer, plan,
* pool, line and region. Keeping this method resource-only avoids loading
* those models once per public offer while sharing the scheduler's exact
* host, reservation and address predicates.
*/
public static function isPoolCapacityAvailable(int $poolId, int $cpuCores,
int $memoryMib, int $diskGib): bool
{
$availability = self::poolCapacityAvailability(['single' => [
'pool_id' => $poolId,
'cpu_cores' => $cpuCores,
'memory_mib' => $memoryMib,
'disk_gib' => $diskGib,
]]);
return $availability['single'] ?? false;
}
/**
* Batch advisory availability without locks or resource reservation.
*
* @param array<string,array{pool_id:int,cpu_cores:int,memory_mib:int,
* disk_gib:int}> $requests
* @return array<string,bool>
*/
public static function poolCapacityAvailability(array $requests): array
{
$availability = [];
$byPool = [];
foreach ($requests as $key => $resources) {
$availability[$key] = false;
if (!is_array($resources)) {
continue;
}
$poolId = (int) ($resources['pool_id'] ?? 0);
$normalized = [
'cpu_cores' => (int) ($resources['cpu_cores'] ?? 0),
'memory_mib' => (int) ($resources['memory_mib'] ?? 0),
'disk_gib' => (int) ($resources['disk_gib'] ?? 0),
];
if ($poolId < 1 || min($normalized) < 1) {
continue;
}
$byPool[$poolId][$key] = $normalized;
}
foreach ($byPool as $poolId => $poolRequests) {
$candidateRows = self::candidateHostRows((int) $poolId);
if ($candidateRows->isEmpty()) {
continue;
}
$pendingByHost = self::pendingUsageByHost($candidateRows);
$availableIpHosts = array_fill_keys(
CloudPublicIp::query()->whereIn('host_id',
$candidateRows->pluck('id')->all())
->where('state', 'available')->distinct()
->pluck('host_id')->map(
static fn ($id): int => (int) $id
)->all(),
true
);
foreach ($poolRequests as $key => $resources) {
foreach ($candidateRows as $candidate) {
$hostId = (int) $candidate->id;
if (isset($availableIpHosts[$hostId])
&& self::hasCapacity($candidate, $candidate,
$pendingByHost[$hostId] ?? self::emptyUsage(),
$resources)) {
$availability[$key] = true;
break;
}
}
}
}
return $availability;
}
/**
* Select a host and reserve one concrete public IP exactly once.
*
@ -81,94 +160,12 @@ final class CloudPlacementService
throw new CloudError('当前未开放线路选择,该销售方案暂不可购买', 409);
}
$freshAfter = time() - self::freshnessSeconds();
$candidateRows = CloudHost::join(
'cloud_host_capacity_policies as capacity_policy',
'capacity_policy.host_id', '=', 'cloud_hosts.id'
)->join(
'cloud_host_capacity_snapshots as capacity_snapshot',
'capacity_snapshot.host_id', '=', 'cloud_hosts.id'
)->where('cloud_hosts.resource_pool_id', (int) $pool->id)
->where('cloud_hosts.enabled', 1)
->where('cloud_hosts.scheduler_state', 'active')
->where('cloud_hosts.health_state', 'healthy')
->where('capacity_snapshot.sync_state', 'fresh')
->where('capacity_snapshot.last_attempt_at', '>=', $freshAfter)
->where('capacity_policy.configured_cpu_cores', '>', 0)
->where('capacity_policy.configured_memory_mib', '>', 0)
->where('capacity_policy.configured_disk_gib', '>', 0)
->get([
'cloud_hosts.id',
'capacity_policy.configured_cpu_cores',
'capacity_policy.configured_memory_mib',
'capacity_policy.configured_disk_gib',
'capacity_policy.safety_cpu_cores',
'capacity_policy.safety_memory_mib',
'capacity_policy.safety_disk_gib',
'capacity_policy.max_instances',
'capacity_snapshot.cpu_total_cores',
'capacity_snapshot.cpu_allocated_cores',
'capacity_snapshot.memory_total_mib',
'capacity_snapshot.memory_allocated_mib',
'capacity_snapshot.storage_total_bytes',
'capacity_snapshot.storage_allocated_bytes',
'capacity_snapshot.instance_total_count',
'capacity_snapshot.last_attempt_at',
]);
$candidateIds = $candidateRows->pluck('id')
->map(static fn ($id): int => (int) $id)->all();
$pendingByHost = [];
if ($candidateIds !== []) {
foreach (CloudResourceReservation::query()
->from('cloud_resource_reservations as reservation')
->join('cloud_host_capacity_snapshots as observed',
'observed.host_id', '=', 'reservation.host_id')
->whereIn('reservation.host_id', $candidateIds)
->where(function ($query): void {
$query->whereIn('reservation.state', self::ACTIVE_RESERVATIONS)
->orWhere(function ($recent): void {
$recent->where('reservation.state', 'committed')
->whereColumn('reservation.updated_at', '>=',
'observed.last_attempt_at');
});
})->selectRaw(
'reservation.host_id, COUNT(*) AS instance_count, '
. 'COALESCE(SUM(reservation.cpu_cores),0) AS cpu_sum, '
. 'COALESCE(SUM(reservation.memory_mib),0) AS memory_sum, '
. 'COALESCE(SUM(reservation.disk_gib),0) AS disk_sum'
)->groupBy('reservation.host_id')->get() as $pending) {
$pendingByHost[(int) $pending->host_id] = $pending;
}
}
$candidateRows = self::candidateHostRows((int) $pool->id);
$pendingByHost = self::pendingUsageByHost($candidateRows);
$candidates = $candidateRows->map(static function ($row) use ($pendingByHost): array {
$pending = $pendingByHost[(int) $row->id] ?? null;
$cpuTotal = max(1, min((int) $row->cpu_total_cores,
(int) $row->configured_cpu_cores)
- (int) $row->safety_cpu_cores);
$memoryTotal = max(1, min((int) $row->memory_total_mib,
(int) $row->configured_memory_mib)
- (int) $row->safety_memory_mib);
$storageTotal = max(1, min((int) $row->storage_total_bytes,
(int) $row->configured_disk_gib * self::GIB)
- ((int) $row->safety_disk_gib * self::GIB));
$instanceScore = (int) $row->max_instances > 0
? ((int) $row->instance_total_count
+ (int) ($pending->instance_count ?? 0))
/ (int) $row->max_instances
: 0.0;
return [
'id' => (int) $row->id,
'score' => max(
((int) $row->cpu_allocated_cores
+ (int) ($pending->cpu_sum ?? 0)) / $cpuTotal,
((int) $row->memory_allocated_mib
+ (int) ($pending->memory_sum ?? 0)) / $memoryTotal,
((int) $row->storage_allocated_bytes
+ ((int) ($pending->disk_sum ?? 0) * self::GIB))
/ $storageTotal,
$instanceScore
),
];
$pending = $pendingByHost[(int) $row->id] ?? self::emptyUsage();
return ['id' => (int) $row->id,
'score' => self::capacityScore($row, $row, $pending)];
})->sort(static fn (array $left, array $right): int =>
($left['score'] <=> $right['score']) ?: ($left['id'] <=> $right['id'])
)->values()->all();
@ -435,51 +432,14 @@ final class CloudPlacementService
->orderBy('id')->lockForUpdate()->get([
'id', 'state', 'cpu_cores', 'memory_mib', 'disk_gib', 'updated_at',
]);
$pending = [
'instance_count' => 0,
'cpu_sum' => 0,
'memory_sum' => 0,
'disk_sum' => 0,
];
foreach ($reservationRows as $row) {
// Timestamps have one-second precision. Treat an equal second
// conservatively as not yet observed; temporary double-counting is
// safer than oversubscription.
if ((string) $row->state === 'committed'
&& (int) $row->updated_at < (int) $snapshot->last_attempt_at) {
continue;
}
$pending['instance_count']++;
$pending['cpu_sum'] += (int) $row->cpu_cores;
$pending['memory_sum'] += (int) $row->memory_mib;
$pending['disk_sum'] += (int) $row->disk_gib;
}
$cpuLimit = max(0, min((int) $policy->configured_cpu_cores,
(int) $snapshot->cpu_total_cores) - (int) $policy->safety_cpu_cores);
$memoryLimit = max(0, min((int) $policy->configured_memory_mib,
(int) $snapshot->memory_total_mib) - (int) $policy->safety_memory_mib);
$configuredDisk = (int) $policy->configured_disk_gib * self::GIB;
$safetyDisk = (int) $policy->safety_disk_gib * self::GIB;
$diskLimit = max(0, min($configuredDisk,
(int) $snapshot->storage_total_bytes) - $safetyDisk);
$usedCpu = (int) $snapshot->cpu_allocated_cores + $pending['cpu_sum'];
$usedMemory = (int) $snapshot->memory_allocated_mib
+ $pending['memory_sum'];
$usedDisk = (int) $snapshot->storage_allocated_bytes
+ ($pending['disk_sum'] * self::GIB);
$instances = (int) $snapshot->instance_total_count
+ $pending['instance_count'];
if ($usedCpu + $resources['cpu_cores'] > $cpuLimit
|| $usedMemory + $resources['memory_mib'] > $memoryLimit
|| $usedDisk + ($resources['disk_gib'] * self::GIB) > $diskLimit
|| ((int) $policy->max_instances > 0
&& $instances + 1 > (int) $policy->max_instances)) {
$pending = self::reservationUsage(
$reservationRows, (int) $snapshot->last_attempt_at
);
if (!self::hasCapacity($policy, $snapshot, $pending, $resources)) {
return null;
}
$ip = CloudPublicIp::where('host_id', $hostId)->where('state', 'available')
->orderBy('id')->lockForUpdate()->first();
$ip = self::availablePublicIpQuery($hostId)->lockForUpdate()->first();
if ($ip === null) {
return null;
}
@ -613,6 +573,173 @@ final class CloudPlacementService
return [$host, $reservation];
}
private static function candidateHostRows(int $poolId)
{
$freshAfter = time() - self::freshnessSeconds();
return CloudHost::query()->join(
'cloud_host_capacity_policies as capacity_policy',
'capacity_policy.host_id', '=', 'cloud_hosts.id'
)->join(
'cloud_host_capacity_snapshots as capacity_snapshot',
'capacity_snapshot.host_id', '=', 'cloud_hosts.id'
)->where('cloud_hosts.resource_pool_id', $poolId)
->where('cloud_hosts.enabled', 1)
->where('cloud_hosts.scheduler_state', 'active')
->where('cloud_hosts.health_state', 'healthy')
->where('capacity_snapshot.sync_state', 'fresh')
->where('capacity_snapshot.last_attempt_at', '>=', $freshAfter)
->where('capacity_policy.configured_cpu_cores', '>', 0)
->where('capacity_policy.configured_memory_mib', '>', 0)
->where('capacity_policy.configured_disk_gib', '>', 0)
->get([
'cloud_hosts.id',
'capacity_policy.configured_cpu_cores',
'capacity_policy.configured_memory_mib',
'capacity_policy.configured_disk_gib',
'capacity_policy.safety_cpu_cores',
'capacity_policy.safety_memory_mib',
'capacity_policy.safety_disk_gib',
'capacity_policy.max_instances',
'capacity_snapshot.cpu_total_cores',
'capacity_snapshot.cpu_allocated_cores',
'capacity_snapshot.memory_total_mib',
'capacity_snapshot.memory_allocated_mib',
'capacity_snapshot.storage_total_bytes',
'capacity_snapshot.storage_allocated_bytes',
'capacity_snapshot.instance_total_count',
'capacity_snapshot.last_attempt_at',
]);
}
private static function pendingUsageByHost($candidateRows): array
{
$observedAt = [];
foreach ($candidateRows as $candidate) {
$observedAt[(int) $candidate->id] = (int) $candidate->last_attempt_at;
}
$candidateIds = array_keys($observedAt);
if ($candidateIds === []) {
return [];
}
$minimumObservedAt = min($observedAt);
$usage = [];
$rows = CloudResourceReservation::query()
->whereIn('host_id', $candidateIds)
->where(function ($query) use ($minimumObservedAt): void {
$query->whereIn('state', self::ACTIVE_RESERVATIONS)
->orWhere(function ($recent) use ($minimumObservedAt): void {
$recent->where('state', 'committed')
->where('updated_at', '>=', $minimumObservedAt);
});
})->get([
'host_id', 'state', 'cpu_cores', 'memory_mib', 'disk_gib',
'updated_at',
]);
foreach ($rows as $row) {
$hostId = (int) $row->host_id;
if ((string) $row->state === 'committed'
&& (int) $row->updated_at < $observedAt[$hostId]) {
continue;
}
$usage[$hostId] ??= self::emptyUsage();
$usage[$hostId]['instance_count']++;
$usage[$hostId]['cpu_sum'] += (int) $row->cpu_cores;
$usage[$hostId]['memory_sum'] += (int) $row->memory_mib;
$usage[$hostId]['disk_sum'] += (int) $row->disk_gib;
}
return $usage;
}
private static function reservationUsage($reservationRows,
int $lastAttemptAt): array
{
$usage = self::emptyUsage();
foreach ($reservationRows as $row) {
// Timestamps have one-second precision. Treat an equal second as
// not yet observed; temporary double-counting is safer than
// oversubscription.
if ((string) $row->state === 'committed'
&& (int) $row->updated_at < $lastAttemptAt) {
continue;
}
$usage['instance_count']++;
$usage['cpu_sum'] += (int) $row->cpu_cores;
$usage['memory_sum'] += (int) $row->memory_mib;
$usage['disk_sum'] += (int) $row->disk_gib;
}
return $usage;
}
private static function emptyUsage(): array
{
return [
'instance_count' => 0,
'cpu_sum' => 0,
'memory_sum' => 0,
'disk_sum' => 0,
];
}
private static function capacityState($policy, $snapshot,
array $usage): array
{
$cpuLimit = max(0, min((int) $policy->configured_cpu_cores,
(int) $snapshot->cpu_total_cores) - (int) $policy->safety_cpu_cores);
$memoryLimit = max(0, min((int) $policy->configured_memory_mib,
(int) $snapshot->memory_total_mib) - (int) $policy->safety_memory_mib);
$configuredDisk = (int) $policy->configured_disk_gib * self::GIB;
$safetyDisk = (int) $policy->safety_disk_gib * self::GIB;
$diskLimit = max(0, min($configuredDisk,
(int) $snapshot->storage_total_bytes) - $safetyDisk);
return [
'cpu_limit' => $cpuLimit,
'memory_limit' => $memoryLimit,
'disk_limit' => $diskLimit,
'cpu_used' => (int) $snapshot->cpu_allocated_cores
+ $usage['cpu_sum'],
'memory_used' => (int) $snapshot->memory_allocated_mib
+ $usage['memory_sum'],
'disk_used' => (int) $snapshot->storage_allocated_bytes
+ ($usage['disk_sum'] * self::GIB),
'instances' => (int) $snapshot->instance_total_count
+ $usage['instance_count'],
'max_instances' => (int) $policy->max_instances,
];
}
private static function hasCapacity($policy, $snapshot, array $usage,
array $resources): bool
{
$state = self::capacityState($policy, $snapshot, $usage);
return $state['cpu_used'] + $resources['cpu_cores'] <= $state['cpu_limit']
&& $state['memory_used'] + $resources['memory_mib']
<= $state['memory_limit']
&& $state['disk_used'] + ($resources['disk_gib'] * self::GIB)
<= $state['disk_limit']
&& ($state['max_instances'] < 1
|| $state['instances'] + 1 <= $state['max_instances']);
}
private static function capacityScore($policy, $snapshot,
array $usage): float
{
$state = self::capacityState($policy, $snapshot, $usage);
$instanceScore = $state['max_instances'] > 0
? $state['instances'] / $state['max_instances'] : 0.0;
return max(
$state['cpu_used'] / max(1, $state['cpu_limit']),
$state['memory_used'] / max(1, $state['memory_limit']),
$state['disk_used'] / max(1, $state['disk_limit']),
$instanceScore
);
}
private static function availablePublicIpQuery(int $hostId)
{
return CloudPublicIp::query()->where('host_id', $hostId)
->where('state', 'available')->orderBy('id');
}
private static function freshnessSeconds(): int
{
$value = filter_var(Config::get('cloud_capacity_fresh_seconds', 120),

@ -430,6 +430,7 @@ function saleOffers(regionId = state.selectedRegionId, lineId = state.selectedLi
&& String(offer?.line_id ?? '') === String(lineId)
&& String(offer?.currency || '').toUpperCase() === 'USD');
}
function isOfferSellable(offer) { return offer?.sellable === true; }
function defaultSaleLine(lines) { return lines.find(line => line.isDefault) || lines[0] || null; }
function applySaleCatalog(catalog) {
state.regions = bootstrapItems(catalog, 'regions');
@ -456,7 +457,7 @@ function setDeploymentStepEnabled(id, enabled) {
function updateCreateAvailability() {
const offer = saleOffers().find(item => String(item.id) === byId('vm-offer')?.value);
const validMedia = Boolean(byId('vm-template')?.value);
if (byId('create-submit')) byId('create-submit').disabled = state.mutationBusy || !offer || !validMedia;
if (byId('create-submit')) byId('create-submit').disabled = state.mutationBusy || !isOfferSellable(offer) || !validMedia;
}
function strongPassword(value) { return !value || (value.length >= 12 && value.length <= 128 && /^[\x21-\x7e]+$/.test(value) && /[A-Z]/.test(value) && /[a-z]/.test(value) && /[0-9]/.test(value) && /[^A-Za-z0-9]/.test(value)); }
function formatUsd(value) {
@ -536,12 +537,17 @@ function renderLinePicker() {
}
function renderOfferPicker() {
const container = byId('vm-offer-picker');
const selectedOfferId = byId('vm-offer').value;
const offerInput = byId('vm-offer');
let selectedOfferId = offerInput.value;
const offers = saleOffers();
if (!offers.length) {
container.replaceChildren(makeElement('p', 'template-catalog-empty', '当前选择暂无可用实例规格。'));
return;
}
if (!offers.some(offer => String(offer.id) === selectedOfferId && isOfferSellable(offer))) {
offerInput.value = '';
selectedOfferId = '';
}
const header = makeElement('div', 'offer-table-head');
['名称', 'CPU', '内存', '硬盘', '每期流量', '价格'].forEach(label => header.append(makeElement('span', '', label)));
const rows = offers.map(offer => {
@ -549,19 +555,27 @@ function renderOfferPicker() {
const memory = formatMemoryGiB(offer.memory_mib);
const traffic = formatTrafficTiB(offer.traffic_tib);
const price = formatUsd(offer.price);
const sellable = isOfferSellable(offer);
const name = makeElement('strong', 'offer-option-name', offer.name);
if (!sellable) name.append(makeElement('span', 'offer-option-status', '暂时售罄'));
button.type = 'button';
button.dataset.offerId = String(offer.id);
button.setAttribute('aria-pressed', String(selectedOfferId === String(offer.id)));
button.setAttribute('aria-label', `选择实例规格 ${offer.name},${offer.cpu_cores} vCPU,内存 ${memory},硬盘 ${offer.disk_gib} GB,每期流量 ${traffic},价格 ${price}`);
button.classList.toggle('is-sold-out', !sellable);
button.disabled = !sellable;
button.setAttribute('aria-disabled', String(!sellable));
button.setAttribute('aria-pressed', String(sellable && selectedOfferId === String(offer.id)));
button.setAttribute('aria-label', sellable
? `选择实例规格 ${offer.name},${offer.cpu_cores} vCPU,内存 ${memory},硬盘 ${offer.disk_gib} GB,每期流量 ${traffic},价格 ${price}`
: `实例规格 ${offer.name},${offer.cpu_cores} vCPU,内存 ${memory},硬盘 ${offer.disk_gib} GB,每期流量 ${traffic},价格 ${price},暂时售罄`);
button.append(
makeElement('strong', 'offer-option-name', offer.name),
name,
makeElement('span', 'offer-option-value', `${offer.cpu_cores} vCPU`),
makeElement('span', 'offer-option-value', memory),
makeElement('span', 'offer-option-value', `${offer.disk_gib} GB`),
makeElement('span', 'offer-option-value', traffic),
makeElement('strong', 'offer-option-price', price),
);
button.addEventListener('click', () => void selectOffer(String(offer.id)));
if (sellable) button.addEventListener('click', () => void selectOffer(String(offer.id)));
return button;
});
container.replaceChildren(header, ...rows);
@ -602,7 +616,7 @@ async function selectLine(lineId) {
async function selectOffer(offerId) {
if (state.mutationBusy) return;
const offer = saleOffers().find(item => String(item.id) === String(offerId));
if (!offer) return;
if (!isOfferSellable(offer)) return;
byId('vm-offer').value = String(offer.id);
byId('vm-offer-picker').querySelectorAll('.offer-option').forEach(button => {
button.setAttribute('aria-pressed', String(button.dataset.offerId === String(offer.id)));
@ -724,6 +738,7 @@ async function buy(event) {
if (!byId('vm-offer').value) return showError('create-error', '请先选择可用实例规格。');
const selectedOffer = saleOffers().find(offer => String(offer.id) === byId('vm-offer').value);
if (!selectedOffer) return showError('create-error', '地区、线路与实例规格不匹配,请重新选择。');
if (!isOfferSellable(selectedOffer)) return showError('create-error', '该实例规格暂时售罄,请选择其他规格。');
const purchaseSummary = `${formatUsd(selectedOffer.price)},${offerBillingLabel(selectedOffer)}`;
if (!confirm(`确认创建此实例?将先生成 ${purchaseSummary} 的开通账单,支付完成后才会开始创建。`)) return;
state.mutationBusy = true;

@ -230,8 +230,13 @@ tbody tr:hover{background:#fcfefe}
.offer-option[aria-pressed="true"]{z-index:1;background:#eef9fa;box-shadow:inset 0 0 0 2px #2eabb4;color:#30485d}
.offer-option[aria-pressed="true"]::after{content:"✓";position:absolute;top:8px;right:10px;display:grid;place-items:center;width:21px;height:21px;border-radius:50%;background:#18a6b0;color:#fff;font-size:12px;font-weight:900}
.offer-option-name,.offer-option-price{min-width:0;color:#273d52;font-size:12px;overflow-wrap:anywhere}
.offer-option-name{display:flex;align-items:center;gap:7px;flex-wrap:wrap}
.offer-option-price{color:#0d929d;font-size:13px}
.offer-option-value{min-width:0;font-size:11px;font-weight:700;white-space:nowrap}
.offer-option.is-sold-out{cursor:not-allowed;opacity:1;background:#f8fafb;color:#8b99a6}
.offer-option.is-sold-out:hover{background:#f8fafb}
.offer-option.is-sold-out .offer-option-name,.offer-option.is-sold-out .offer-option-price{color:#697b8c}
.offer-option-status{display:inline-flex;align-items:center;min-height:20px;padding:2px 7px;border-radius:999px;background:#edf1f4;color:#6f7e8c;font-size:9px;font-weight:800;line-height:1;white-space:nowrap}
/* Keep every user-facing button control free of browser or hover underlines.
Plain content and navigation links intentionally keep their own styling. */
body[data-cloud-page] :is(button, [role="button"], .button, .row-button, .icon-button, .vu-btn, .vu-icon-btn),
@ -277,5 +282,5 @@ body.vu-body .ssh-key-picker-manage:hover {
.offer-option>:nth-child(5)::before{content:"每期流量"}
.offer-option>:nth-child(6)::before{content:"价格"}
}
@media(max-width:510px){.deployment-step{padding-bottom:23px;margin-bottom:22px}.deployment-step-heading{margin-bottom:16px}.region-picker,.line-picker{grid-template-columns:1fr}.region-option{min-height:66px}.line-option{min-height:54px}.offer-option{grid-template-columns:repeat(4,minmax(0,1fr));grid-template-rows:auto auto;gap:12px 8px;min-height:108px;padding:15px 14px 14px 16px}.offer-option::after{content:"";position:absolute;top:13px;right:14px;display:grid;place-items:center;width:22px;height:22px;border:1.5px solid #bdccd4;border-radius:50%;background:#fff;color:transparent;font-size:12px;font-weight:900}.offer-option[aria-pressed="true"]{box-shadow:none}.offer-option[aria-pressed="true"]::after{content:"✓";top:13px;right:14px;width:22px;height:22px;border:1.5px solid #18a6b0;background:#18a6b0;color:#fff}.offer-option-name{grid-column:1/3;grid-row:1;align-self:center;font-size:14px}.offer-option-price{display:block;grid-column:3/5;grid-row:1;align-self:center;justify-self:end;padding-right:30px;font-size:14px;white-space:nowrap}.offer-option-price::before{display:none;content:none}.offer-option-value{display:grid;grid-row:2;gap:4px;white-space:normal}.offer-option-value::before{color:#718599;font-size:9px;font-weight:800;white-space:nowrap}.offer-option>:nth-child(2){grid-column:1}.offer-option>:nth-child(3){grid-column:2}.offer-option>:nth-child(4){grid-column:3}.offer-option>:nth-child(5){grid-column:4}.template-family-card{height:140px;min-height:140px;border:1px solid #dce7ec;border-radius:12px;background:#fff;overflow:hidden;box-shadow:none}.template-family-summary{height:100%;min-height:100%;border:0;border-radius:inherit;background:transparent}.template-family-card[open]{z-index:70;border-color:#a8dadd;box-shadow:0 12px 28px rgba(30,66,82,.14)}.template-family-card.has-selection{border-color:#2eabb4;background:#f5fbfb}.template-versions{position:absolute;inset:0;z-index:80;width:auto;height:auto;max-height:none;margin:0;padding:6px 8px 40px;overflow-y:auto;border:0;border-radius:inherit;background:#fbfdfd;box-shadow:none;overscroll-behavior:contain;-webkit-overflow-scrolling:touch}.template-family-card[open] .template-family-footer{position:absolute;right:7px;bottom:7px;z-index:90;width:32px;min-height:32px;border-radius:999px;background:#eaf8f8}.template-family-card[open] .template-family-selection{display:none}.user-iso-row{align-items:flex-start;flex-direction:column}.user-iso-row .row-button{width:100%}}
@media(max-width:510px){.deployment-step{padding-bottom:23px;margin-bottom:22px}.deployment-step-heading{margin-bottom:16px}.region-picker,.line-picker{grid-template-columns:1fr}.region-option{min-height:66px}.line-option{min-height:54px}.offer-option{grid-template-columns:repeat(4,minmax(0,1fr));grid-template-rows:auto auto;gap:12px 8px;min-height:108px;padding:15px 14px 14px 16px}.offer-option::after{content:"";position:absolute;top:13px;right:14px;display:grid;place-items:center;width:22px;height:22px;border:1.5px solid #bdccd4;border-radius:50%;background:#fff;color:transparent;font-size:12px;font-weight:900}.offer-option[aria-pressed="true"]{box-shadow:none}.offer-option[aria-pressed="true"]::after{content:"✓";top:13px;right:14px;width:22px;height:22px;border:1.5px solid #18a6b0;background:#18a6b0;color:#fff}.offer-option.is-sold-out::after{display:none}.offer-option-name{grid-column:1/3;grid-row:1;align-self:center;font-size:14px}.offer-option-price{display:block;grid-column:3/5;grid-row:1;align-self:center;justify-self:end;padding-right:30px;font-size:14px;white-space:nowrap}.offer-option.is-sold-out .offer-option-price{padding-right:0}.offer-option-price::before{display:none;content:none}.offer-option-value{display:grid;grid-row:2;gap:4px;white-space:normal}.offer-option-value::before{color:#718599;font-size:9px;font-weight:800;white-space:nowrap}.offer-option>:nth-child(2){grid-column:1}.offer-option>:nth-child(3){grid-column:2}.offer-option>:nth-child(4){grid-column:3}.offer-option>:nth-child(5){grid-column:4}.template-family-card{height:140px;min-height:140px;border:1px solid #dce7ec;border-radius:12px;background:#fff;overflow:hidden;box-shadow:none}.template-family-summary{height:100%;min-height:100%;border:0;border-radius:inherit;background:transparent}.template-family-card[open]{z-index:70;border-color:#a8dadd;box-shadow:0 12px 28px rgba(30,66,82,.14)}.template-family-card.has-selection{border-color:#2eabb4;background:#f5fbfb}.template-versions{position:absolute;inset:0;z-index:80;width:auto;height:auto;max-height:none;margin:0;padding:6px 8px 40px;overflow-y:auto;border:0;border-radius:inherit;background:#fbfdfd;box-shadow:none;overscroll-behavior:contain;-webkit-overflow-scrolling:touch}.template-family-card[open] .template-family-footer{position:absolute;right:7px;bottom:7px;z-index:90;width:32px;min-height:32px;border-radius:999px;background:#eaf8f8}.template-family-card[open] .template-family-selection{display:none}.user-iso-row{align-items:flex-start;flex-direction:column}.user-iso-row .row-button{width:100%}}
.vm-state-sync{display:block;margin-top:4px;color:#8b9aaa;font-size:10px;line-height:1.35;white-space:nowrap}.vm-state-sync.stale{color:#b98129}.vm-state-sync.offline{color:#bd5b63}.vm-detail-state-stack{display:flex;flex-direction:column;align-items:flex-end;gap:3px}.vm-detail-state-stack .vm-state-sync{margin-top:0}

@ -46,8 +46,8 @@
{if !$default_line_has_offers}<div class="offer-table-head"><span>名称</span><span>CPU</span><span>内存</span><span>硬盘</span><span>每期流量</span><span>价格</span></div>{/if}
{assign var=default_line_has_offers value=true}
{assign var=offer_memory_gib value=$offer.memory_mib/1024}
<button class="offer-option" type="button" data-offer-id="{$offer.id|escape:"html"}" aria-pressed="false" aria-label="选择实例规格 {$offer.name|escape:"html"}">
<strong class="offer-option-name">{$offer.name|escape:"html"}</strong>
<button class="offer-option{if empty($offer.sellable)} is-sold-out{/if}" type="button" data-offer-id="{$offer.id|escape:"html"}" aria-pressed="false" aria-disabled="{if empty($offer.sellable)}true{else}false{/if}" aria-label="{if empty($offer.sellable)}实例规格 {$offer.name|escape:"html"},暂时售罄{else}选择实例规格 {$offer.name|escape:"html"}{/if}"{if empty($offer.sellable)} disabled{/if}>
<strong class="offer-option-name">{$offer.name|escape:"html"}{if empty($offer.sellable)}<span class="offer-option-status">暂时售罄</span>{/if}</strong>
<span class="offer-option-value">{$offer.cpu_cores|escape:"html"} vCPU</span>
<span class="offer-option-value">{$offer_memory_gib|string_format:"%g"|escape:"html"} GB</span>
<span class="offer-option-value">{$offer.disk_gib|escape:"html"} GB</span>

@ -1,2 +1,2 @@
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
{assign var=venix_asset_version value='2026100310' scope='global'}
{assign var=venix_asset_version value='2026100311' scope='global'}

@ -62,7 +62,9 @@ $assert(str_contains($feature, "CONFIG_KEY = 'cloud_network_lines_enabled'")
$assert(str_contains($placement,
"->whereIn('state', ['held', 'uncertain', 'committed'])")
&& str_contains($placement, "->orderBy('id')->lockForUpdate()->get([")
&& str_contains($placement, "\$pending['cpu_sum'] += (int) \$row->cpu_cores")
&& str_contains($placement, '$pending = self::reservationUsage(')
&& str_contains($placement, 'private static function reservationUsage(')
&& str_contains($placement, "\$usage['cpu_sum'] += (int) \$row->cpu_cores")
&& !str_contains($placement, "COALESCE(SUM(cpu_cores)")
&& str_contains($placement,
"CloudResourceReservation::where('order_id', (int) \$order->id)->exists()")

@ -27,6 +27,7 @@ $reinstallTemplate = file_get_contents($root . '/resources/views/venix/cloud/pag
$deployModule = file_get_contents($root . '/public/cloud/deploy.js');
$reinstallModule = file_get_contents($root . '/public/cloud/reinstall.js');
$runtime = file_get_contents($root . '/public/cloud/runtime.js');
$cloudStyles = file_get_contents($root . '/public/cloud/styles.css');
$routes = file_get_contents($root . '/config/routes_cloud.php');
$cloudShell = file_get_contents($root . '/resources/views/venix/cloud/page.tpl');
$layoutAssets = file_get_contents($root . '/resources/views/venix/layout_assets.tpl');
@ -45,10 +46,15 @@ $selectLine = $section($runtime, 'async function selectLine(',
'async function selectOffer(');
$selectOffer = $section($runtime, 'async function selectOffer(',
'async function openCreate(');
$updateCreateAvailability = $section($runtime, 'function updateCreateAvailability(',
'function strongPassword(');
$renderOfferPicker = $section($runtime, 'function renderOfferPicker(',
'async function selectRegion(');
$buy = $section($runtime, 'async function buy(',
'function clearReinstallPasswordCard(');
$saleCatalog = $section($service, 'public static function saleCatalog(',
'public static function sshKeys(');
$publicOfferDto = $section($saleCatalog, '$offers[] = [', ' ];');
$catalogApi = $section($apiController, 'public function catalog(',
'public function orders(');
$resourcesApi = $section($apiController, 'public function resources(',
@ -92,17 +98,20 @@ $assert(str_contains($saleCatalog, "->join('shop as plan'")
&& str_contains($saleCatalog, "->join('cloud_resource_pools as pool'")
&& str_contains($saleCatalog, "->join('cloud_network_lines as line'")
&& str_contains($saleCatalog, "->join('cloud_regions as region'")
&& str_contains($saleCatalog, "->where('offer.stock', '<>', 0)")
&& !str_contains($saleCatalog, "->where('offer.stock', '<>', 0)")
&& str_contains($saleCatalog, "->where('offer.currency', 'USD')")
&& str_contains($saleCatalog, "\$query->where('line.is_default', 1)")
&& str_contains($saleCatalog, "'lines_enabled' => \$linesEnabled")
&& str_contains($saleCatalog, "'currency' => 'USD'")
&& str_contains($publicOfferDto, "'sellable' =>")
&& str_contains($saleCatalog, "'traffic_tib' => self::formatDecimalUnit(\$trafficGiB, 1024, 10)")
&& str_contains($service, 'private static function formatDecimalUnit(')
&& !str_contains($saleCatalog, "'host_id' =>")
&& !str_contains($saleCatalog, "'plan_id' =>")
&& !str_contains($saleCatalog, "'resource_pool_id' =>"),
'Public sale catalog must follow the active offer chain, enforce the default-line switch and omit placement identities.');
&& !str_contains($publicOfferDto, "'host_id' =>")
&& !str_contains($publicOfferDto, "'plan_id' =>")
&& !str_contains($publicOfferDto, "'resource_pool_id' =>")
&& !str_contains($publicOfferDto, "'public_ip' =>")
&& !str_contains($publicOfferDto, "'capacity' =>"),
'Public sale catalog must retain sold-out offers with a sellable flag, enforce the default-line switch and omit placement or capacity details.');
$assert(str_contains($service, "private const TEMPLATE_SNAPSHOT_KEY")
&& str_contains($service, 'TEMPLATE_SNAPSHOT_REFRESH_SECONDS')
&& str_contains($service, "'checked_at' => time()")
@ -135,6 +144,17 @@ $assert(str_contains($deployTemplate, 'id="deploy-bootstrap" type="application/j
&& !str_contains($deployTemplate, 'host_id')
&& !str_contains($deployTemplate, 'plan_id'),
'Deployment HTML must immediately show regions, optional lines, offers, images and saved keys without host identities.');
$assert(str_contains($deployTemplate,
'class="offer-option{if empty($offer.sellable)} is-sold-out{/if}"')
&& str_contains($deployTemplate,
'aria-disabled="{if empty($offer.sellable)}true{else}false{/if}"')
&& str_contains($deployTemplate, '{if empty($offer.sellable)} disabled{/if}')
&& str_contains($deployTemplate, 'class="offer-option-status">暂时售罄</span>')
&& str_contains($deployTemplate, ',暂时售罄{else}选择实例规格')
&& str_contains($cloudStyles, '.offer-option.is-sold-out')
&& str_contains($cloudStyles, '.offer-option-status')
&& str_contains($cloudStyles, '.offer-option.is-sold-out::after{display:none}'),
'Deployment SSR must keep sold-out offers visible, labelled and non-interactive on desktop and mobile.');
$assert(str_contains($deployModule, "readBootstrap('deploy-bootstrap')")
&& str_contains($deployModule, "initializeSession('create', bootstrap?.user)")
&& str_contains($deployModule, 'openCreate(bootstrap)')
@ -184,6 +204,21 @@ $assert($selectRegion !== '' && $selectLine !== '' && $selectOffer !== ''
&& str_contains($buy, 'provisionInvoiceFingerprint(body)')
&& str_contains($buy, 'pendingProvisionInvoiceKey(fingerprint)'),
'Changing a region, line or offer must preserve the global image and purchasing must keep offer-scoped idempotency.');
$assert(str_contains($runtime,
'function isOfferSellable(offer) { return offer?.sellable === true; }')
&& str_contains($renderOfferPicker,
"if (!sellable) name.append(makeElement('span', 'offer-option-status', '暂时售罄'));")
&& str_contains($renderOfferPicker, "button.classList.toggle('is-sold-out', !sellable)")
&& str_contains($renderOfferPicker, 'button.disabled = !sellable')
&& str_contains($renderOfferPicker,
"button.setAttribute('aria-disabled', String(!sellable))")
&& str_contains($renderOfferPicker,
'offers.some(offer => String(offer.id) === selectedOfferId && isOfferSellable(offer))')
&& str_contains($selectOffer, 'if (!isOfferSellable(offer)) return;')
&& str_contains($updateCreateAvailability, '!isOfferSellable(offer)')
&& str_contains($buy, 'if (!isOfferSellable(selectedOffer))')
&& str_contains($buy, '该实例规格暂时售罄,请选择其他规格。'),
'Hydration and fallback rendering must never select, enable or submit a sold-out offer.');
$assert(str_contains($catalogApi, 'CloudDeploymentPageService::saleCatalog()')
&& str_contains($resourcesApi, 'CloudDeploymentPageService::freshTemplateCatalog($actor)')

@ -47,6 +47,7 @@ namespace {
use App\Services\Cloud\CloudInstanceDiscovery;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudMoney;
use App\Services\Cloud\CloudDeploymentPageService;
use App\Services\Cloud\CloudTemplateDeletionService;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
@ -69,7 +70,7 @@ namespace {
$schema->create('cloud_host_capacity_policies', function (Blueprint $t) { $t->integer('host_id')->primary(); foreach (['configured_cpu_cores', 'configured_memory_mib', 'configured_disk_gib', 'safety_cpu_cores', 'safety_memory_mib', 'safety_disk_gib', 'max_instances', 'created_at', 'updated_at'] as $v) { $t->integer($v)->default(0); } });
$schema->create('cloud_host_capacity_snapshots', function (Blueprint $t) { $t->integer('host_id')->primary(); foreach (['cpu_total_cores', 'cpu_allocated_cores', 'cpu_available_cores', 'memory_total_mib', 'memory_allocated_mib', 'memory_available_mib', 'storage_total_bytes', 'storage_allocated_bytes', 'storage_available_bytes', 'instance_total_count', 'instance_running_count', 'public_ip_configured', 'public_ip_total_count', 'public_ip_reserved_count', 'public_ip_allocated_count', 'public_ip_available_count'] as $v) { $t->integer($v)->default(0); } $t->string('sync_state')->default('never'); foreach (['observed_at', 'last_attempt_at', 'revision', 'attempt_generation'] as $v) { $t->integer($v)->default(0); } $t->string('last_error_code')->default(''); $t->integer('created_at'); $t->integer('updated_at'); });
$schema->create('cloud_public_ips', function (Blueprint $t) { $t->increments('id'); $t->integer('host_id'); $t->string('address')->unique(); $t->integer('prefix_length'); $t->string('state'); $t->integer('reservation_id')->nullable()->unique(); $t->integer('instance_id')->nullable(); $t->string('operation_id')->nullable()->unique(); $t->integer('created_at'); $t->integer('updated_at'); });
$schema->create('cloud_offers', function (Blueprint $t) { $t->increments('id'); $t->integer('plan_id'); $t->integer('resource_pool_id'); $t->string('code'); $t->string('name'); $t->string('price'); $t->string('currency')->default('USD'); $t->integer('price_version')->default(1); $t->integer('revision')->default(1); $t->integer('status')->default(1); $t->integer('stock')->default(-1); $t->integer('sort')->default(0); $t->integer('created_at'); $t->integer('updated_at'); });
$schema->create('cloud_offers', function (Blueprint $t) { $t->increments('id'); $t->integer('plan_id'); $t->integer('resource_pool_id'); $t->string('code')->unique(); $t->string('name'); $t->string('price'); $t->string('currency')->default('USD'); $t->integer('price_version')->default(1); $t->integer('revision')->default(1); $t->integer('status')->default(1); $t->integer('stock')->default(-1); $t->integer('sort')->default(0); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['plan_id', 'resource_pool_id']); });
$schema->create('cloud_template_retirements', function (Blueprint $t) { $t->string('template_id')->primary(); $t->string('state')->default('deleting'); $t->integer('template_created_at')->default(0); $t->integer('created_at'); $t->integer('updated_at'); });
$schema->create('cloud_template_catalog_locks', function (Blueprint $t) { $t->integer('id')->primary(); $t->integer('updated_at'); $t->string('lease_token')->nullable(); $t->string('lease_kind')->nullable(); $t->integer('lease_until')->default(0); });
$schema->create('cloud_orders', function (Blueprint $t) { $t->increments('id'); foreach (['user_id', 'plan_id', 'offer_id', 'resource_pool_id'] as $v) { $t->integer($v); } $t->integer('host_id')->nullable(); $t->integer('reservation_id')->nullable()->unique(); $t->string('idempotency_key'); $t->string('request_hash'); $t->string('amount'); $t->string('currency')->default('USD'); $t->string('status'); $t->text('spec_json'); $t->text('payload_cipher')->nullable(); $t->integer('instance_id')->nullable(); $t->integer('refunded_at')->nullable(); $t->integer('stock_reserved_at')->nullable(); $t->integer('stock_released_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['user_id', 'idempotency_key']); });
@ -92,7 +93,9 @@ namespace {
$snapshot = new CloudHostCapacitySnapshot(); $snapshot->host_id = $host->id; $snapshot->cpu_total_cores = 64; $snapshot->cpu_allocated_cores = 0; $snapshot->cpu_available_cores = 64; $snapshot->memory_total_mib = 131072; $snapshot->memory_allocated_mib = 0; $snapshot->memory_available_mib = 131072; $snapshot->storage_total_bytes = 4096 * 1073741824; $snapshot->storage_allocated_bytes = 0; $snapshot->storage_available_bytes = 4096 * 1073741824; $snapshot->instance_total_count = 0; $snapshot->instance_running_count = 0; $snapshot->public_ip_configured = true; $snapshot->public_ip_total_count = 4; $snapshot->public_ip_reserved_count = 0; $snapshot->public_ip_allocated_count = 0; $snapshot->public_ip_available_count = 4; $snapshot->sync_state = 'fresh'; $snapshot->observed_at = $now; $snapshot->last_attempt_at = $now; $snapshot->revision = 1; $snapshot->last_error_code = ''; $snapshot->created_at = $snapshot->updated_at = $now; $snapshot->save();
foreach (['203.0.113.18', '203.0.113.19', '203.0.113.20', '203.0.113.21'] as $address) { $ip = new CloudPublicIp(); $ip->host_id = $host->id; $ip->address = $address; $ip->prefix_length = 28; $ip->state = 'available'; $ip->created_at = $ip->updated_at = $now; $ip->save(); }
$plan = new Shop(); $plan->name = 'plan'; $plan->cpu_cores = 2; $plan->memory_mib = 2048; $plan->bandwidth_mbps = 100; $plan->disk_gib = 20; $plan->validity_days = 30; $plan->traffic_quota_bytes = 1024 * 1024 * 1024; $plan->status = 1; $plan->sort = 0; $plan->save();
$soldOutPlan = new Shop(); $soldOutPlan->name = 'sold-out-plan'; $soldOutPlan->cpu_cores = 2; $soldOutPlan->memory_mib = 2048; $soldOutPlan->bandwidth_mbps = 100; $soldOutPlan->disk_gib = 20; $soldOutPlan->validity_days = 30; $soldOutPlan->traffic_quota_bytes = 1024 * 1024 * 1024; $soldOutPlan->status = 1; $soldOutPlan->sort = 0; $soldOutPlan->save();
$offer = new CloudOffer(); $offer->plan_id = $plan->id; $offer->resource_pool_id = $pool->id; $offer->code = 'test-offer'; $offer->name = 'Test Offer'; $offer->price = '9.99'; $offer->currency = 'USD'; $offer->price_version = 1; $offer->status = 1; $offer->stock = 10; $offer->sort = 0; $offer->created_at = $offer->updated_at = $now; $offer->save();
$soldOutOffer = new CloudOffer(); $soldOutOffer->plan_id = $soldOutPlan->id; $soldOutOffer->resource_pool_id = $pool->id; $soldOutOffer->code = 'sold-out-offer'; $soldOutOffer->name = 'Sold Out Offer'; $soldOutOffer->price = '8.99'; $soldOutOffer->currency = 'USD'; $soldOutOffer->price_version = 1; $soldOutOffer->status = 1; $soldOutOffer->stock = 0; $soldOutOffer->sort = 0; $soldOutOffer->created_at = $soldOutOffer->updated_at = $now; $soldOutOffer->save();
$actor = ['user_id' => 1, 'is_admin' => false, 'is_super_admin' => false, 'can_manage' => false, 'session_id' => ''];
$wrongOperationClient = new CloudEngineClient(new Client(['handler' => HandlerStack::create(new MockHandler([
new Response(422, [], '{"operation_id":"another-operation","status":"failed","safe_to_refund":true}')
@ -104,6 +107,59 @@ namespace {
$assert($expected->httpStatus === 502, 'Mismatched operation response exposed an unexpected status.');
}
$input = ['offer_id' => 1, 'source' => 'cloud', 'name' => 'vm-one', 'template_id' => 'alma10-1234abcd-0123456789abcdef', 'idempotency_key' => 'test-request-key-0001'];
$catalogConnection = Capsule::connection('default');
$catalogConnection->flushQueryLog();
$catalogConnection->enableQueryLog();
$catalog = CloudDeploymentPageService::saleCatalog();
$catalogQueryCount = count($catalogConnection->getQueryLog());
$catalogConnection->disableQueryLog();
$assert(count($catalog['offers'] ?? []) === 2
&& ($catalog['offers'][0]['sellable'] ?? null) === true
&& ($catalog['offers'][1]['sellable'] ?? null) === false
&& $catalogQueryCount <= 5,
'Catalog availability hid a sold-out offer, misclassified capacity, or queried per offer.');
$host->health_state = 'unhealthy';
$host->updated_at = time();
$host->save();
$unavailableCatalog = CloudDeploymentPageService::saleCatalog();
$assert(count($unavailableCatalog['offers'] ?? []) === 2
&& ($unavailableCatalog['offers'][0]['sellable'] ?? null) === false
&& ($unavailableCatalog['offers'][1]['sellable'] ?? null) === false,
'An unavailable pool was hidden or exposed as sellable.');
try {
CloudOrderService::purchase(array_replace($input, [
'name' => 'vm-unavailable',
'idempotency_key' => 'test-unavailable-offer-0001',
]), $actor);
throw new RuntimeException('Unavailable capacity created an order.');
} catch (CloudError $e) {
$assert($e->httpStatus === 409,
'Unavailable capacity returned the wrong status.');
}
$assert(CloudOrder::count() === 0 && CloudInvoice::count() === 0
&& CloudOffer::find(1)->stock === 10,
'Rejected availability admission created finance state or consumed stock.');
$host->health_state = 'healthy';
$host->updated_at = time();
$host->save();
CloudPublicIp::query()->update(['state' => 'reserved', 'updated_at' => time()]);
$noAddressCatalog = CloudDeploymentPageService::saleCatalog();
$assert(($noAddressCatalog['offers'][0]['sellable'] ?? null) === false,
'A pool without an available public IP remained sellable.');
try {
CloudOrderService::purchase(array_replace($input, [
'name' => 'vm-without-ip',
'idempotency_key' => 'test-unavailable-address-0001',
]), $actor);
throw new RuntimeException('Missing public IP created an order.');
} catch (CloudError $e) {
$assert($e->httpStatus === 409,
'Missing public IP returned the wrong status.');
}
$assert(CloudOrder::count() === 0 && CloudInvoice::count() === 0
&& CloudOffer::find(1)->stock === 10,
'Address admission failure created finance state or consumed stock.');
CloudPublicIp::query()->update(['state' => 'available', 'updated_at' => time()]);
$first = CloudOrderService::purchase($input, $actor);
$same = CloudOrderService::purchase($input, $actor);
$openingInvoice = CloudInvoice::where('order_id', $first->id)->first();

@ -295,12 +295,15 @@ $assert(str_contains($deployTemplate, 'id="deploy-bootstrap" type="application/j
'Deployment HTML must contain regions, optional lines, offers, images and SSH keys before hydration.');
$assert(str_contains($deploymentPageService, "->join('cloud_resource_pools as pool'")
&& str_contains($deploymentPageService, "->join('cloud_network_lines as line'")
&& str_contains($deploymentPageService, "->where('offer.stock', '<>', 0)")
&& !str_contains($deploymentPageService, "->where('offer.stock', '<>', 0)")
&& str_contains($deploymentPageService,
'CloudPlacementService::poolCapacityAvailability(')
&& str_contains($deploymentPageService, "'sellable' =>")
&& str_contains($deploymentPageService, "\$query->where('line.is_default', 1)")
&& str_contains($cloudPageController, '$defaultRegionId = $regions === [] ? 0 : (int) $regions[0][\'id\']')
&& str_contains($cloudPageController, "'default_line_id' => \$defaultLineId")
&& str_contains($cloudPageController, "'cloud_deploy_bootstrap_json' => \$this->safeJson(\$payload)"),
'Deployment SSR must follow the active offer chain and select the first available region and line.');
'Deployment SSR must retain sold-out offers, calculate pool availability, and select the first available region and line.');
$assert(str_contains($deployModule, "readBootstrap('deploy-bootstrap')")
&& str_contains($deployModule, "initializeSession('create', bootstrap?.user)")
&& str_contains($deployModule, 'openCreate(bootstrap)')

Loading…
Cancel
Save