id )->orderBy('id')->get(); $period = self::assertUpgradeableState( $instance, $user, $periods, $now ); $reservation = $instance->reservation_id === null ? null : CloudResourceReservation::where( 'id', (int) $instance->reservation_id )->first(); $source = self::sourceSnapshot( $instance, $period, $reservation, $now ); $balance = CloudMoney::cents((string) $user->money); $offers = []; $rows = CloudOffer::where( 'resource_pool_id', (int) $instance->resource_pool_id )->where('status', 1)->where('currency', 'USD') ->where('stock', '<>', 0)->where('id', '<>', (int) $instance->offer_id) ->orderByDesc('sort')->orderBy('id')->get(); $planIds = $rows->pluck('plan_id')->map( static fn ($id): int => (int) $id )->unique()->values()->all(); $plans = $planIds === [] ? collect() : Shop::whereIn('id', $planIds)->get()->keyBy('id'); foreach ($rows as $offer) { $plan = $plans->get((int) $offer->plan_id); if ($plan === null) { continue; } try { $target = self::targetSnapshot($offer, $plan, $source); if (!CloudPlacementService::isUpgradeCapacityAvailable( $instance, $target['resources'] )) { continue; } $amount = self::quoteCents($source, $target, $now); } catch (CloudError $error) { continue; } $offers[] = self::optionDto($target, $amount, $balance); } return [ 'instance_id' => (string) $instance->id, 'currency' => 'USD', 'quoted_at' => $now, 'expires_at' => (int) $instance->expires_at, 'remaining_seconds' => max(0, (int) $period->ends_at - $now), 'current' => [ 'plan_id' => (int) $source['plan_id'], 'offer_id' => (int) $source['offer_id'], 'name' => (string) $source['plan_name'], 'cpu_cores' => (int) $source['resources']['cpu_cores'], 'memory_mib' => (int) $source['resources']['memory_mib'], 'disk_gib' => (int) $source['resources']['disk_gib'], 'bandwidth_mbps' => (int) $source['resources']['bandwidth_mbps'], 'validity_days' => (int) $source['renewal_days'], 'traffic_quota_bytes' => (int) $source['current_traffic_quota_bytes'], 'renewal_price' => (string) $source['renewal_price'], ], 'offers' => $offers, 'can_upgrade' => $offers !== [], 'message' => $offers === [] ? '当前资源池没有符合条件且容量充足的升级套餐。' : '', ]; } /** * Read the immutable target purchased by an upgrade invoice. * * Display callers deliberately fall back to identifiers when escrow is * unavailable; they must never substitute the instance's later mutable * specification into a historical bill. */ public static function invoiceTargetSnapshot( CloudInvoice $invoice, ?CloudJob $job ): ?array { if ($job === null || (string) $invoice->purpose !== self::PURPOSE || (string) $job->kind !== 'instance_upgrade' || (int) $job->invoice_id !== (int) $invoice->id || (int) $job->user_id !== (int) $invoice->user_id || (int) $job->instance_id !== (int) $invoice->instance_id || !is_string($job->sealed_payload) || trim((string) $job->sealed_payload) === '') { return null; } try { $payload = CloudSecrets::decrypt( (string) $job->sealed_payload, 'job-payload' ); [, $target, $amountCents] = self::upgradePayload($job, $payload); if ((int) $invoice->plan_id !== (int) $target['plan_id'] || (int) $invoice->offer_id !== (int) $target['offer_id'] || (string) $invoice->currency !== 'USD' || CloudMoney::cents((string) $invoice->amount) !== $amountCents || (int) $invoice->validity_days !== (int) $target['validity_days'] || (int) $invoice->traffic_quota_bytes !== (int) $target['traffic_quota_bytes'] || !hash_equals( 'instance-upgrade-' . (int) $job->id, (string) $invoice->payment_reference )) { return null; } return $target; } catch (\Throwable $error) { return null; } } /** Charge one exact quote and reserve a single-dispatch Agent resize. */ public static function enqueue( CloudInstance $instance, User $user, array $actor, int $offerId, string $expectedAmount ): CloudJob { if ($offerId < 1) { throw new CloudError('请选择有效的升级套餐'); } $expectedCents = CloudMoney::cents($expectedAmount); $requestKey = self::requestKey($actor); return (new User())->getConnection()->transaction(function () use ( $instance, $user, $actor, $offerId, $expectedCents, $requestKey ): CloudJob { $lockedUser = User::where('id', (int) $user->id) ->lockForUpdate()->first(); $locked = CloudInstance::where('id', (int) $instance->id) ->lockForUpdate()->first(); if ($lockedUser === null || $locked === null) { throw new CloudError('实例或账户不存在', 404); } self::assertOwner($locked, $lockedUser); if ((int) ($actor['user_id'] ?? 0) !== (int) $lockedUser->id) { throw new CloudError('只能升级自己持有的实例', 403); } $prior = CloudJob::where('user_id', (int) $lockedUser->id) ->where('request_idempotency_key', $requestKey) ->lockForUpdate()->first(); if ($prior !== null) { return self::assertReplay( $prior, $locked, $offerId, $expectedCents ); } // Preserve the existing finance lock order: wallet -> instance -> // renewal invoice/payment -> service period -> catalog/capacity. $renewalInvoices = self::renewalInvoices($locked, true); self::assertNoPendingRenewalPayment($renewalInvoices, true); $periods = CloudServicePeriod::where( 'instance_id', (int) $locked->id )->orderBy('id')->lockForUpdate()->get(); $now = time(); $period = self::assertUpgradeableState( $locked, $lockedUser, $periods, $now ); $reservation = $locked->reservation_id === null ? null : CloudResourceReservation::where( 'id', (int) $locked->reservation_id )->first(); $source = self::sourceSnapshot( $locked, $period, $reservation, $now ); $targetRef = CloudOffer::find($offerId); if ($targetRef === null) { throw new CloudError('升级套餐不存在', 404); } $offerIds = array_values(array_unique([ (int) $source['offer_id'], $offerId, ])); sort($offerIds, SORT_NUMERIC); $offers = CloudOffer::whereIn('id', $offerIds)->orderBy('id') ->lockForUpdate()->get()->keyBy('id'); $sourceOffer = $offers->get((int) $source['offer_id']); $targetOffer = $offers->get($offerId); if ($sourceOffer === null || $targetOffer === null || (int) $targetOffer->id !== (int) $targetRef->id) { throw new CloudError('升级套餐目录已变化,请刷新后重试', 409); } if (!self::stockModeMatches( $sourceOffer, (string) $source['stock_mode'] )) { throw new CloudError('当前套餐库存模式已变化,请先核对实例账本', 409); } $planIds = array_values(array_unique([ (int) $source['plan_id'], (int) $targetOffer->plan_id, ])); sort($planIds, SORT_NUMERIC); $plans = Shop::whereIn('id', $planIds)->orderBy('id') ->lockForUpdate()->get()->keyBy('id'); $sourcePlan = $plans->get((int) $source['plan_id']); $targetPlan = $plans->get((int) $targetOffer->plan_id); if ($sourcePlan === null || $targetPlan === null) { throw new CloudError('升级套餐目录已变化,请刷新后重试', 409); } $target = self::targetSnapshot($targetOffer, $targetPlan, $source); $amountCents = self::quoteCents($source, $target, $now); if ($amountCents !== $expectedCents) { throw new CloudError('升级费用已变化,请刷新后重新确认', 409); } $balance = CloudMoney::cents((string) $lockedUser->money); if ($balance < $amountCents) { throw new CloudError('账户余额不足', 409); } $body = [ 'from_vcpu' => (int) $source['resources']['cpu_cores'], 'target_vcpu' => (int) $target['resources']['cpu_cores'], 'from_memory_mib' => (int) $source['resources']['memory_mib'], 'target_memory_mib' => (int) $target['resources']['memory_mib'], 'from_disk_gib' => (int) $source['resources']['disk_gib'], 'target_disk_gib' => (int) $target['resources']['disk_gib'], 'from_bandwidth_mbps' => (int) $source['resources']['bandwidth_mbps'], 'target_bandwidth_mbps' => (int) $target['resources']['bandwidth_mbps'], 'confirm_shutdown' => true, ]; $amount = CloudMoney::decimal($amountCents); $metadata = [ 'owner_id' => (int) $locked->user_id, 'can_manage' => false, 'upgrade_snapshot' => [ 'version' => self::SNAPSHOT_VERSION, 'charged_amount' => $amount, 'reservation_id' => (int) $source['reservation_id'], 'source' => $source, 'target' => $target, ], ]; [$job, $created] = CloudJobService::reserveStandaloneAgentMutation( $actor, (int) $locked->host_id, 'instance_upgrade', 'POST', '/v1/vms/' . rawurlencode((string) $locked->uuid) . '/resources', $body, $metadata, [ 'instance_id' => (int) $locked->id, 'offer_id' => $offerId, 'expected_amount' => $amount, 'source_spec_hash' => (string) $source['spec_hash'], 'current_period_id' => (int) $source['current_period_id'], 'current_period_ends_at' => (int) $source['current_period_ends_at'], 'target_price_version' => (int) $target['price_version'], 'target_revision' => (int) $target['revision'], ] ); if (!$created) { return self::assertReplay( $job, $locked, $offerId, $expectedCents ); } $job->instance_id = (int) $locked->id; CloudPlacementService::reserveUpgradeCapacityLocked( $locked, $offerId, $source['resources'], $target['resources'] ); if ((string) $target['stock_mode'] === 'finite') { if ((int) $targetOffer->stock < 1) { throw new CloudError('升级套餐已售罄,请刷新后重试', 409); } $targetOffer->stock = (int) $targetOffer->stock - 1; $targetOffer->updated_at = $now; $targetOffer->save(); } $invoice = new CloudInvoice(); $invoice->invoice_no = 'VC' . gmdate('YmdHis') . strtoupper(bin2hex(random_bytes(8))); $invoice->purpose = self::PURPOSE; $invoice->instance_id = (int) $locked->id; $invoice->order_id = null; $invoice->user_id = (int) $lockedUser->id; $invoice->plan_id = (int) $target['plan_id']; $invoice->offer_id = (int) $target['offer_id']; $invoice->renewal_id = null; $invoice->renews_expires_at = null; $invoice->due_at = $now; $invoice->amount = $amount; $invoice->currency = 'USD'; $invoice->validity_days = (int) $target['validity_days']; $invoice->traffic_quota_bytes = (int) $target['traffic_quota_bytes']; $invoice->status = 'paid'; $invoice->paid_via = 'balance'; $invoice->payment_reference = 'instance-upgrade-' . (int) $job->id; $invoice->paid_at = $now; $invoice->created_at = $invoice->updated_at = $now; $invoice->save(); $lockedUser->money = CloudMoney::decimal($balance - $amountCents); $lockedUser->save(); $job->invoice_id = (int) $invoice->id; $job->updated_at = $now; $job->save(); return $job; }, 3); } /** * Finalize the financial, stock, capacity and service-period ledgers. * Called by CloudWorkerService while wallet and job rows are locked. */ public static function finishJobLocked( CloudJob $job, string $resourceStatus, $result, array $payload, ?User $user ): void { if ((string) $job->kind !== 'instance_upgrade') { return; } $now = time(); $resolution = match ($resourceStatus) { 'succeeded' => 'applied', 'failed' => 'not_applied', 'uncertain' => 'unknown', default => throw new CloudError('实例升级任务结论无效', 409), }; [$source, $target, $amountCents, $reservationId] = self::upgradePayload($job, $payload); $instance = $job->instance_id === null ? null : CloudInstance::where('id', (int) $job->instance_id) ->lockForUpdate()->first(); $invoice = $job->invoice_id === null ? null : CloudInvoice::where('id', (int) $job->invoice_id) ->lockForUpdate()->first(); if ($instance === null || $invoice === null || (int) $instance->user_id !== (int) $job->user_id || (int) $invoice->instance_id !== (int) $instance->id || (int) $invoice->user_id !== (int) $job->user_id || (string) $invoice->purpose !== self::PURPOSE || (string) $invoice->currency !== 'USD' || CloudMoney::cents((string) $invoice->amount) !== $amountCents || !hash_equals( 'instance-upgrade-' . (int) $job->id, (string) $invoice->payment_reference )) { throw new CloudRecoveryInstanceStateConflict( '实例升级资金账本关联不一致', 409 ); } if ((string) $invoice->status === 'refunded') { if ($resolution === 'not_applied') { return; } throw new CloudRecoveryInstanceStateConflict( '已退款的实例升级不能再确认生效', 409 ); } if ((string) $invoice->status !== 'paid' || (string) $invoice->paid_via !== 'balance' || $invoice->paid_at === null) { throw new CloudRecoveryInstanceStateConflict( '实例升级账单未处于已支付状态', 409 ); } if (!hash_equals( (string) $source['spec_hash'], hash('sha256', (string) $instance->spec_json) ) || (int) $instance->plan_id !== (int) $source['plan_id'] || (int) $instance->offer_id !== (int) $source['offer_id'] || (int) $instance->current_period_id !== (int) $source['current_period_id']) { throw new CloudRecoveryInstanceStateConflict( '实例升级前的不可变快照已发生变化', 409 ); } $offerIds = [(int) $source['offer_id'], (int) $target['offer_id']]; sort($offerIds, SORT_NUMERIC); $offers = CloudOffer::whereIn('id', array_values(array_unique($offerIds))) ->orderBy('id')->lockForUpdate()->get()->keyBy('id'); $sourceOffer = $offers->get((int) $source['offer_id']); $targetOffer = $offers->get((int) $target['offer_id']); if ($sourceOffer === null || $targetOffer === null || !self::stockModeMatches($sourceOffer, (string) $source['stock_mode']) || !self::stockModeMatches($targetOffer, (string) $target['stock_mode'])) { throw new CloudRecoveryInstanceStateConflict( '实例升级库存账本模式已发生变化', 409 ); } CloudPlacementService::finishUpgradeCapacityLocked( $instance, $reservationId, (int) $source['offer_id'], (int) $target['offer_id'], $source['resources'], $target['resources'], $resolution ); if ($resolution === 'unknown') { return; } if ($resolution === 'not_applied') { if ($user === null || (int) $user->id !== (int) $job->user_id) { throw new CloudRecoveryInstanceStateConflict( '实例升级退款账户不存在', 409 ); } if ((string) $target['stock_mode'] === 'finite') { $targetOffer->stock = (int) $targetOffer->stock + 1; $targetOffer->updated_at = $now; $targetOffer->save(); } $balance = CloudMoney::cents((string) $user->money); $user->money = CloudMoney::decimal($balance + $amountCents); $user->save(); $invoice->status = 'refunded'; $invoice->updated_at = $now; $invoice->save(); CloudInvoiceService::refreshRenewalAfterUpgradeLocked( $instance, $now ); return; } self::assertAppliedResult($instance, $source, $target, $result); $period = CloudServicePeriod::where( 'id', (int) $source['current_period_id'] )->where('instance_id', (int) $instance->id) ->lockForUpdate()->first(); if ($period === null || (int) $period->ends_at !== (int) $source['current_period_ends_at'] || !in_array((string) $period->status, ['active', 'exhausted'], true)) { throw new CloudRecoveryInstanceStateConflict( '实例升级的当前服务周期已发生变化', 409 ); } $spec = json_decode((string) $instance->spec_json, true); if (!is_array($spec) || array_is_list($spec)) { throw new CloudRecoveryInstanceStateConflict( '实例升级前的规格记录损坏', 409 ); } $spec['vcpu'] = (int) $target['resources']['cpu_cores']; $spec['cpu_cores'] = (int) $target['resources']['cpu_cores']; $spec['memory_mib'] = (int) $target['resources']['memory_mib']; $spec['disk_gib'] = (int) $target['resources']['disk_gib']; $spec['bandwidth_mbps'] = (int) $target['resources']['bandwidth_mbps']; $spec['plan_id'] = (int) $target['plan_id']; $spec['plan_name'] = (string) $target['plan_name']; $spec['offer_id'] = (int) $target['offer_id']; $spec['offer_name'] = (string) $target['offer_name']; $spec['price_version'] = (int) $target['price_version']; $spec['stock_mode'] = (string) $target['stock_mode']; $spec['validity_days'] = (int) $target['validity_days']; $spec['traffic_quota_bytes'] = (int) $target['traffic_quota_bytes']; $spec['renewal_price'] = (string) $target['price']; if (($source['automatic_backup'] ?? false) === true) { $spec['backup_price'] = (string) $target['backup_price']; } unset($spec['agent_metadata_version']); $period->plan_id = (int) $target['plan_id']; $period->traffic_quota_bytes = (int) $target['traffic_quota_bytes']; CloudTrafficPoolPeriodBinding::bindPeriod( $period, $period->traffic_pool_group_id === null ? null : (int) $period->traffic_pool_group_id, (int) $target['traffic_quota_bytes'] ); $used = max(0, (int) $period->download_used_bytes) + max(0, (int) $period->upload_used_bytes); $quota = (int) $target['traffic_quota_bytes']; if ((string) $period->status === 'exhausted' && ($quota === 0 || $used < $quota)) { $period->status = 'active'; $aggregateNetworkPolicy = CloudInstanceNetworkPolicy::isEnforcedPeriod($period) || CloudInstanceNetworkPolicy::hasState((int) $instance->id); if (!$aggregateNetworkPolicy && in_array((string) $instance->network_status, ['blocking', 'blocked_traffic', 'block_failed'], true)) { $instance->network_status = 'restore_pending'; $instance->network_suspended_at = null; } } $period->updated_at = $now; $period->save(); $instance->plan_id = (int) $target['plan_id']; $instance->offer_id = (int) $target['offer_id']; $instance->renewal_price = (string) $target['price']; $instance->renewal_days = (int) $target['validity_days']; $instance->renewal_traffic_bytes = (int) $target['traffic_quota_bytes']; $instance->traffic_quota_bytes = (int) $target['traffic_quota_bytes']; $instance->spec_json = json_encode( $spec, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); $instance->updated_at = $now; $instance->save(); CloudAutomaticBackupService::refreshPriceAfterUpgradeLocked( $instance, $targetOffer ); CloudInvoiceService::refreshRenewalAfterUpgradeLocked( $instance, $now ); if ((string) $source['stock_mode'] === 'finite') { $sourceOffer->stock = (int) $sourceOffer->stock + 1; $sourceOffer->updated_at = $now; $sourceOffer->save(); } } /** @return array{0:array,1:array,2:int,3:int} */ private static function upgradePayload(CloudJob $job, array $payload): array { $upgrade = $payload['upgrade_snapshot'] ?? null; $body = $payload['body'] ?? null; if (!is_array($upgrade) || array_is_list($upgrade) || (int) ($upgrade['version'] ?? 0) !== self::SNAPSHOT_VERSION || !is_array($upgrade['source'] ?? null) || !is_array($upgrade['target'] ?? null) || !is_array($body) || array_is_list($body) || ($body['confirm_shutdown'] ?? null) !== true) { throw new CloudRecoveryPayloadUnavailable( '实例升级恢复快照不完整', 409 ); } $source = $upgrade['source']; $target = $upgrade['target']; $amountCents = CloudMoney::cents( (string) ($upgrade['charged_amount'] ?? '') ); $reservationId = filter_var( $upgrade['reservation_id'] ?? null, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]] ); $expected = [ 'from_vcpu' => $source['resources']['cpu_cores'] ?? null, 'target_vcpu' => $target['resources']['cpu_cores'] ?? null, 'from_memory_mib' => $source['resources']['memory_mib'] ?? null, 'target_memory_mib' => $target['resources']['memory_mib'] ?? null, 'from_disk_gib' => $source['resources']['disk_gib'] ?? null, 'target_disk_gib' => $target['resources']['disk_gib'] ?? null, 'from_bandwidth_mbps' => $source['resources']['bandwidth_mbps'] ?? null, 'target_bandwidth_mbps' => $target['resources']['bandwidth_mbps'] ?? null, ]; foreach ($expected as $field => $value) { if (!is_int($value) || $value < 1 || ($body[$field] ?? null) !== $value) { throw new CloudRecoveryPayloadUnavailable( '实例升级请求与不可变快照不一致', 409 ); } } if ($reservationId === false || (int) ($source['reservation_id'] ?? 0) !== $reservationId || (int) ($source['offer_id'] ?? 0) < 1 || (int) ($target['offer_id'] ?? 0) < 1 || !is_string($source['spec_hash'] ?? null) || preg_match('/^[a-f0-9]{64}$/D', $source['spec_hash']) !== 1) { throw new CloudRecoveryPayloadUnavailable( '实例升级账本快照无效', 409 ); } return [$source, $target, $amountCents, (int) $reservationId]; } private static function assertAppliedResult( CloudInstance $instance, array $source, array $target, $result ): void { if (!is_array($result) || array_is_list($result) || ($result['resources_resized'] ?? null) !== true || ($result['power_state_restored'] ?? null) !== true || !is_bool($result['originally_running'] ?? null) || !is_string($result['uuid'] ?? null) || !hash_equals( strtolower((string) $instance->uuid), strtolower((string) $result['uuid']) )) { throw new CloudError( 'Agent 成功结果缺少已确认的资源升级证据', 502 ); } $status = $result['status'] ?? null; $originallyRunning = $result['originally_running']; if (!is_string($status) || ($originallyRunning && !in_array($status, ['running', 'blocked'], true)) || (!$originallyRunning && !in_array($status, ['shutoff', 'crashed'], true))) { throw new CloudError( 'Agent 成功结果没有确认实例恢复到升级前电源状态', 502 ); } $checks = [ 'from_vcpu' => (int) $source['resources']['cpu_cores'], 'target_vcpu' => (int) $target['resources']['cpu_cores'], 'applied_vcpu' => (int) $target['resources']['cpu_cores'], 'from_memory_mib' => (int) $source['resources']['memory_mib'], 'target_memory_mib' => (int) $target['resources']['memory_mib'], 'applied_memory_mib' => (int) $target['resources']['memory_mib'], 'from_disk_gib' => (int) $source['resources']['disk_gib'], 'target_disk_gib' => (int) $target['resources']['disk_gib'], 'applied_disk_gib' => (int) $target['resources']['disk_gib'], 'from_bandwidth_mbps' => (int) $source['resources']['bandwidth_mbps'], 'target_bandwidth_mbps' => (int) $target['resources']['bandwidth_mbps'], 'applied_bandwidth_mbps' => (int) $target['resources']['bandwidth_mbps'], ]; foreach ($checks as $field => $expected) { if (!is_int($result[$field] ?? null) || (int) $result[$field] !== $expected) { throw new CloudError( 'Agent 成功结果与目标资源规格不一致', 502 ); } } } private static function assertOwner( CloudInstance $instance, User $user ): void { if ((int) $user->enable !== 1) { throw new CloudError('账户不可用', 403); } if ((int) $instance->user_id !== (int) $user->id) { throw new CloudError('只能升级自己持有的实例', 403); } } private static function assertUpgradeableState( CloudInstance $instance, User $user, $periods, int $now ): CloudServicePeriod { if ((string) $instance->status !== 'active' || (string) $instance->service_status !== 'active' || $instance->expires_at === null || (int) $instance->expires_at <= $now || $instance->current_period_id === null || $instance->reservation_id === null || $instance->plan_id === null || $instance->offer_id === null || $instance->resource_pool_id === null || $instance->renewal_price === null || (int) $instance->renewal_days < 1) { throw new CloudError('当前实例状态不支持套餐升级', 409); } if (CloudJobService::blockingQueryForInstance( (int) $instance->id )->exists()) { throw new CloudError('实例已有未完成或待核对任务,请稍后重试', 409); } CloudInstanceMigrationService::assertInstanceMutationAvailable( $instance, 'plan_upgrade' ); if (CloudInstanceSnapshot::where('instance_id', (int) $instance->id) ->whereIn('state', self::SNAPSHOT_STATES)->exists()) { throw new CloudError('实例保留有快照,请先删除全部快照后再升级', 409); } foreach ($periods as $candidate) { if ((string) $candidate->status === 'scheduled') { throw new CloudError( '实例已有提前续费周期,当前不能变更套餐', 409 ); } } $period = $periods->first(static fn ($candidate): bool => (int) $candidate->id === (int) $instance->current_period_id); if (!$period instanceof CloudServicePeriod || (int) $period->instance_id !== (int) $instance->id || (int) $period->user_id !== (int) $user->id || !in_array((string) $period->status, ['active', 'exhausted'], true) || (int) $period->starts_at > $now || (int) $period->ends_at <= $now || (int) $period->ends_at !== (int) $instance->expires_at) { throw new CloudError('实例当前服务周期不支持套餐升级', 409); } return $period; } private static function sourceSnapshot( CloudInstance $instance, CloudServicePeriod $period, ?CloudResourceReservation $reservation, int $now ): array { $spec = json_decode((string) $instance->spec_json, true); if (!is_array($spec) || array_is_list($spec) || $reservation === null) { throw new CloudError('实例资源规格账本不完整', 409); } $resources = [ 'cpu_cores' => self::positiveInt( $spec['vcpu'] ?? $spec['cpu_cores'] ?? null ), 'memory_mib' => self::positiveInt($spec['memory_mib'] ?? null), 'disk_gib' => self::positiveInt($spec['disk_gib'] ?? null), 'bandwidth_mbps' => self::positiveInt( $spec['bandwidth_mbps'] ?? null ), ]; if (in_array(false, $resources, true) || (string) $reservation->state !== 'committed' || (int) ($reservation->instance_id ?? 0) !== (int) $instance->id || (int) $reservation->user_id !== (int) $instance->user_id || (int) $reservation->host_id !== (int) $instance->host_id || (int) $reservation->resource_pool_id !== (int) $instance->resource_pool_id || (int) $reservation->offer_id !== (int) $instance->offer_id || (int) $reservation->cpu_cores !== $resources['cpu_cores'] || (int) $reservation->memory_mib !== $resources['memory_mib'] || (int) $reservation->disk_gib !== $resources['disk_gib']) { throw new CloudError('实例规格与容量预留账本不一致', 409); } $stockMode = $spec['stock_mode'] ?? null; if (!in_array($stockMode, ['finite', 'unlimited'], true)) { throw new CloudError('实例缺少购买时的库存快照', 409); } $renewalCents = CloudMoney::cents((string) $instance->renewal_price); if ($renewalCents < 0 || (int) $period->traffic_quota_bytes !== (int) $instance->traffic_quota_bytes) { throw new CloudError('实例续费或流量快照不一致', 409); } $trafficPoolGroupId = $period->traffic_pool_group_id === null ? null : (int) $period->traffic_pool_group_id; $trafficQuotaMode = (string) $period->traffic_quota_mode; if ($trafficPoolGroupId !== null && $trafficQuotaMode !== CloudTrafficPoolPeriodBinding::quotaMode( (int) $period->traffic_quota_bytes )) { throw new CloudError('实例流量池计费快照不一致', 409); } return [ 'plan_id' => (int) $instance->plan_id, 'offer_id' => (int) $instance->offer_id, 'resource_pool_id' => (int) $instance->resource_pool_id, 'reservation_id' => (int) $reservation->id, 'current_period_id' => (int) $period->id, 'current_period_starts_at' => (int) $period->starts_at, 'current_period_ends_at' => (int) $period->ends_at, 'traffic_pool_group_id' => $trafficPoolGroupId, 'traffic_quota_mode' => $trafficQuotaMode, 'renewal_price' => CloudMoney::decimal($renewalCents), 'renewal_days' => (int) $instance->renewal_days, 'renewal_traffic_bytes' => max(0, (int) $instance->renewal_traffic_bytes), 'current_traffic_quota_bytes' => max(0, (int) $period->traffic_quota_bytes), 'plan_name' => is_string($spec['plan_name'] ?? null) ? (string) $spec['plan_name'] : '当前套餐', 'offer_name' => is_string($spec['offer_name'] ?? null) ? (string) $spec['offer_name'] : '当前套餐', 'stock_mode' => $stockMode, 'automatic_backup' => ($spec['automatic_backup'] ?? null) === true, 'resources' => $resources, 'spec_hash' => hash('sha256', (string) $instance->spec_json), 'quoted_at' => $now, ]; } private static function targetSnapshot( CloudOffer $offer, Shop $plan, array $source ): array { if ((int) $offer->id === (int) $source['offer_id'] || !(bool) $offer->status || (int) $plan->status !== 1 || (int) $offer->stock === 0 || strtoupper((string) $offer->currency) !== 'USD' || (int) $offer->plan_id !== (int) $plan->id || (int) $offer->resource_pool_id !== (int) $source['resource_pool_id'] || (int) $plan->validity_days !== (int) $source['renewal_days']) { throw new CloudError('目标套餐不符合当前实例的升级条件', 409); } $resources = [ 'cpu_cores' => self::positiveInt($plan->cpu_cores), 'memory_mib' => self::positiveInt($plan->memory_mib), 'disk_gib' => self::positiveInt($plan->disk_gib), 'bandwidth_mbps' => self::positiveInt($plan->bandwidth_mbps), ]; if (in_array(false, $resources, true)) { throw new CloudError('目标套餐资源规格无效', 409); } $increased = false; foreach (array_keys($resources) as $field) { if ($resources[$field] < (int) $source['resources'][$field]) { throw new CloudError('套餐升级不能降低任何资源规格', 409); } $increased = $increased || $resources[$field] > (int) $source['resources'][$field]; } if (!$increased) { throw new CloudError('目标套餐必须至少提升一项资源规格', 409); } $traffic = max(0, (int) $plan->traffic_quota_bytes); CloudTrafficPoolPeriodBinding::assertUpgradeQuotaTransition( $source['traffic_pool_group_id'] === null ? null : (int) $source['traffic_pool_group_id'], (string) $source['traffic_quota_mode'], $traffic ); if (!self::quotaAtLeast( $traffic, (int) $source['current_traffic_quota_bytes'] ) || !self::quotaAtLeast( $traffic, (int) $source['renewal_traffic_bytes'] )) { throw new CloudError('套餐升级不能降低当前或续费流量额度', 409); } $priceCents = CloudMoney::cents((string) $offer->price); if ($priceCents <= CloudMoney::cents( (string) $source['renewal_price'] )) { throw new CloudError('目标套餐价格必须高于当前续费价格', 409); } return [ 'plan_id' => (int) $plan->id, 'offer_id' => (int) $offer->id, 'resource_pool_id' => (int) $offer->resource_pool_id, 'plan_name' => (string) $plan->name, 'offer_name' => (string) $offer->name, 'price' => CloudMoney::decimal($priceCents), 'price_version' => (int) $offer->price_version, 'backup_price' => CloudMoney::decimal( CloudMoney::cents((string) $offer->backup_price) ), 'revision' => (int) $offer->revision, 'stock_mode' => (int) $offer->stock === -1 ? 'unlimited' : 'finite', 'validity_days' => (int) $plan->validity_days, 'traffic_quota_bytes' => $traffic, 'resources' => $resources, ]; } private static function quoteCents( array $source, array $target, int $now ): int { $difference = CloudMoney::cents((string) $target['price']) - CloudMoney::cents((string) $source['renewal_price']); $total = (int) $source['renewal_days'] * 86400; $remaining = min( $total, max(0, (int) $source['current_period_ends_at'] - $now) ); if ($difference < 1 || $total < 1 || $remaining < 1) { throw new CloudError('当前服务周期已不能提交套餐升级', 409); } // Overflow-safe ceil(difference * remaining / total). $whole = intdiv($difference, $total) * $remaining; $remainder = $difference % $total; $partial = intdiv( $remainder * $remaining + $total - 1, $total ); return max(1, $whole + $partial); } private static function optionDto( array $target, int $amountCents, int $balanceCents ): array { return [ 'offer_id' => (int) $target['offer_id'], 'plan_id' => (int) $target['plan_id'], 'name' => (string) $target['offer_name'], 'plan_name' => (string) $target['plan_name'], 'cpu_cores' => (int) $target['resources']['cpu_cores'], 'memory_mib' => (int) $target['resources']['memory_mib'], 'disk_gib' => (int) $target['resources']['disk_gib'], 'bandwidth_mbps' => (int) $target['resources']['bandwidth_mbps'], 'validity_days' => (int) $target['validity_days'], 'traffic_quota_bytes' => (int) $target['traffic_quota_bytes'], 'amount' => CloudMoney::decimal($amountCents), 'renewal_price' => (string) $target['price'], 'currency' => 'USD', 'balance_sufficient' => $balanceCents >= $amountCents, ]; } private static function renewalInvoices( CloudInstance $instance, bool $lock ) { $query = CloudInvoice::where('instance_id', (int) $instance->id) ->where('purpose', 'renewal') ->whereIn('status', ['open', 'overdue']) ->orderBy('id'); return ($lock ? $query->lockForUpdate() : $query)->get(); } private static function assertNoPendingRenewalPayment( $invoices, bool $lock ): void { $ids = $invoices->pluck('id')->map( static fn ($id): int => (int) $id )->values()->all(); if ($ids === []) { return; } $query = CloudInvoicePayment::whereIn('invoice_id', $ids) ->whereIn('status', self::PENDING_PAYMENT_STATES) ->orderBy('id'); if (($lock ? $query->lockForUpdate() : $query)->exists()) { throw new CloudError( '续费账单正在处理支付,暂时不能升级套餐', 409 ); } foreach ($ids as $invoiceId) { if (CloudJobService::blockingQueryForInvoice($invoiceId) ->exists()) { throw new CloudError( '续费账单正在创建支付订单或等待核对,暂时不能升级套餐', 409 ); } } } private static function requestKey(array $actor): string { $key = $actor['request_idempotency_key'] ?? null; if (!is_string($key) || preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $key) !== 1) { throw new CloudError('实例升级必须提供有效的请求幂等标识', 400); } return $key; } private static function assertReplay( CloudJob $job, CloudInstance $instance, int $offerId, int $expectedCents ): CloudJob { $invoice = $job->invoice_id === null ? null : CloudInvoice::where('id', (int) $job->invoice_id)->first(); if ((string) $job->kind !== 'instance_upgrade' || (int) $job->instance_id !== (int) $instance->id || (int) $job->user_id !== (int) $instance->user_id || $invoice === null || (int) $invoice->user_id !== (int) $job->user_id || (int) $invoice->instance_id !== (int) $instance->id || (int) $invoice->offer_id !== $offerId || (string) $invoice->purpose !== self::PURPOSE || (string) $invoice->currency !== 'USD' || CloudMoney::cents((string) $invoice->amount) !== $expectedCents || !hash_equals( 'instance-upgrade-' . (int) $job->id, (string) $invoice->payment_reference )) { throw new CloudError('同一请求标识不能用于不同的实例升级', 409); } return $job; } private static function positiveInt($value) { $parsed = filter_var( $value, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => PHP_INT_MAX]] ); return $parsed === false ? false : (int) $parsed; } private static function quotaAtLeast(int $target, int $source): bool { return $source === 0 ? $target === 0 : ($target === 0 || $target >= $source); } private static function stockModeMatches( CloudOffer $offer, string $mode ): bool { return ($mode === 'unlimited' && (int) $offer->stock === -1) || ($mode === 'finite' && (int) $offer->stock >= 0); } }