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/CloudOrderService.php

291 lines
15 KiB
PHTML

<?php
namespace App\Services\Cloud;
use App\Models\CloudInvoice;
use App\Models\CloudInstance;
use App\Models\CloudJob;
use App\Models\CloudNetworkLine;
use App\Models\CloudOffer;
use App\Models\CloudOrder;
use App\Models\CloudRegion;
use App\Models\CloudResourcePool;
use App\Models\Shop;
use App\Models\User;
final class CloudOrderService
{
/** Unpaid provisioning invoices reserve finite stock for thirty minutes. */
public const PAYMENT_WINDOW_SECONDS = 1800;
private const AUTOMATIC_NAME_SCAN_LIMIT = 256;
public static function purchase(array $input, array $actor): CloudOrder
{
CloudInput::only($input, ['offer_id', 'source', 'template_id', 'guest_ssh_key_id',
'root_password', 'name', 'idempotency_key']);
$requestedName = CloudInput::optionalName($input['name'] ?? null);
// Missing, null and an empty field describe the same request. Keep the
// fingerprint stable without storing a generated name in the request.
$input['name'] = $requestedName ?? '';
$idempotency = $input['idempotency_key'] ?? '';
if (!is_string($idempotency) || preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $idempotency) !== 1) {
throw new CloudError('请提供 16 至 128 字符的请求幂等标识');
}
$offerId = filter_var($input['offer_id'] ?? null, FILTER_VALIDATE_INT);
if (!$offerId || $offerId < 1) {
throw new CloudError('请选择可用的销售方案');
}
$source = $input['source'] ?? 'cloud';
if ($source !== 'cloud') {
throw new CloudError('当前只支持从云镜像部署实例');
}
$template = CloudInput::template($input['template_id'] ?? '');
ksort($input);
$requestHash = hash_hmac('sha256', json_encode($input, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES), CloudSecrets::key('payload_key'));
return (new User())->getConnection()->transaction(function () use ($input, $actor, $offerId, $source, $requestedName, $template, $idempotency, $requestHash) {
CloudTemplateDeletionService::assertAvailable($template);
$user = User::where('id', $actor['user_id'])->lockForUpdate()->first();
if ($user === null || (int) $user->enable !== 1) {
throw new CloudError('账户不可用', 403);
}
if ((int) $user->restrict_balance_purchase === 1) {
throw new CloudError('账户套餐购买服务已被管理员停用', 403);
}
$existing = CloudOrder::where('user_id', $user->id)->where('idempotency_key', $idempotency)->first();
if ($existing !== null) {
if (!hash_equals($existing->request_hash, $requestHash)) {
throw new CloudError('同一请求标识不能用于不同订单', 409);
}
return $existing;
}
// Generate only after an idempotency replay has been resolved, so
// retries return the original order and its original display name.
$name = $requestedName ?? self::automaticName($user);
$offer = CloudOffer::where('id', $offerId)->lockForUpdate()->first();
if ($offer === null || !(bool) $offer->status || (int) $offer->stock === 0
|| strtoupper((string) $offer->currency) !== 'USD') {
throw new CloudError('销售方案不可购买或已售罄', 409);
}
$plan = Shop::where('id', (int) $offer->plan_id)->lockForUpdate()->first();
$pool = CloudResourcePool::find((int) $offer->resource_pool_id);
$line = $pool === null ? null : CloudNetworkLine::find((int) $pool->line_id);
$region = $line === null ? null : CloudRegion::find((int) $line->region_id);
if ($plan === null || (int) $plan->status !== 1
|| $pool === null || (string) $pool->status !== 'active'
|| $line === null || (string) $line->status !== 'active'
|| $region === null || (string) $region->status !== 'active'
|| (!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,
'bandwidth_mbps' => (int) $plan->bandwidth_mbps, 'network' => ''];
$credential = null;
$key = CloudSSHKeys::owned($input['guest_ssh_key_id'] ?? null, (int) $user->id);
$password = CloudInput::password($input['root_password'] ?? null);
$payload += ['template_id' => $template, 'guest_ssh_public_key' => $key?->public_key ?? '',
'root_password' => $password, 'public_ip_cidr' => '', 'gateway' => '', 'dns_servers' => []];
$credential = ['password' => $password, 'login_name' => 'root',
'auth_mode' => $key ? 'password_and_key' : 'password'];
$safeSpec = CloudInput::safeResult($payload);
$safeSpec['plan_name'] = $plan->name;
$safeSpec['plan_id'] = (int) $plan->id;
$safeSpec['offer_id'] = (int) $offer->id;
$safeSpec['offer_name'] = (string) $offer->name;
$safeSpec['resource_pool_id'] = (int) $pool->id;
$safeSpec['resource_pool_name'] = (string) $pool->name;
$safeSpec['line_id'] = (int) $line->id;
$safeSpec['line_name'] = (string) $line->name;
$safeSpec['region_id'] = (int) $region->id;
$safeSpec['country_code'] = strtoupper((string) $region->country_code);
$safeSpec['region'] = (string) $region->name;
$safeSpec['currency'] = 'USD';
$safeSpec['price_version'] = (int) $offer->price_version;
$safeSpec['validity_days'] = (int) $plan->validity_days;
$safeSpec['traffic_quota_bytes'] = (int) $plan->traffic_quota_bytes;
$safeSpec['renewal_price'] = CloudMoney::decimal($price);
$order = new CloudOrder();
$order->user_id = $user->id;
$order->plan_id = $plan->id;
$order->offer_id = $offer->id;
$order->resource_pool_id = $pool->id;
$order->host_id = null;
$order->reservation_id = null;
$order->idempotency_key = $idempotency;
$order->request_hash = $requestHash;
$order->amount = CloudMoney::decimal($price);
$order->currency = 'USD';
$order->status = 'awaiting_payment';
$order->spec_json = json_encode($safeSpec, JSON_THROW_ON_ERROR);
$order->payload_cipher = CloudSecrets::encrypt(['method' => 'POST',
'resource' => 'vms', 'body' => $payload, 'credential' => $credential]);
$order->created_at = $order->updated_at = time();
if ((int) $offer->stock > 0) {
$offer->stock--;
$offer->updated_at = time();
$offer->save();
$order->stock_reserved_at = time();
}
$order->save();
CloudInvoiceService::issueProvision($order, $plan, $offer, time());
return $order;
}, 3);
}
private static function automaticName(User $user): string
{
$occupied = [];
foreach (CloudInstance::where('user_id', $user->id)
->where('status', '<>', 'deleted')->orderByDesc('id')
->limit(self::AUTOMATIC_NAME_SCAN_LIMIT)->pluck('name') as $name) {
if (is_string($name) && $name !== '') {
$occupied[$name] = true;
}
}
foreach (CloudOrder::where('user_id', $user->id)->whereIn('status',
['awaiting_payment', 'queued', 'running', 'uncertain'])
->orderByDesc('id')->limit(self::AUTOMATIC_NAME_SCAN_LIMIT)
->get(['spec_json']) as $order) {
$spec = json_decode((string) $order->spec_json, true);
$name = is_array($spec) ? ($spec['name'] ?? null) : null;
if (is_string($name) && $name !== '') {
$occupied[$name] = true;
}
}
for ($attempt = 0; $attempt < 32; $attempt++) {
$name = CloudInput::generateInstanceName();
if (!isset($occupied[$name])) {
return $name;
}
}
throw new CloudError('暂时无法生成唯一实例名称,请重试', 503);
}
/**
* Transfer a paid provisioning invoice into the worker queue.
*
* The caller owns the surrounding wallet transaction and has locked the
* user, invoice and order rows in that order. The unique job order key is
* the final database guard against duplicate payment callbacks.
*/
public static function queuePaidProvision(CloudInvoice $invoice,
CloudOrder $order): CloudOrder
{
if ((string) $invoice->purpose !== 'provision'
|| (int) $invoice->order_id !== (int) $order->id
|| (int) $invoice->user_id !== (int) $order->user_id
|| (int) $invoice->plan_id !== (int) $order->plan_id
|| (int) $invoice->offer_id !== (int) $order->offer_id
|| strtoupper((string) $invoice->currency) !== 'USD'
|| strtoupper((string) $order->currency) !== 'USD'
|| CloudMoney::cents((string) $invoice->amount)
!== CloudMoney::cents((string) $order->amount)) {
throw new CloudError('开通账单与订单快照不匹配', 409);
}
if (in_array((string) $order->status,
['queued', 'running', 'uncertain', 'succeeded'], true)) {
if (!CloudJob::where('order_id', $order->id)->exists()) {
throw new CloudError('开通订单缺少任务记录,请联系管理员', 409);
}
return $order;
}
if ((string) $order->status !== 'awaiting_payment'
|| !is_string($order->payload_cipher)
|| trim((string) $order->payload_cipher) === '') {
throw new CloudError('开通订单已失效或不可支付', 409);
}
$payload = CloudSecrets::decrypt((string) $order->payload_cipher);
if (($payload['method'] ?? null) !== 'POST'
|| ($payload['resource'] ?? null) !== 'vms'
|| !is_array($payload['body'] ?? null)) {
throw new CloudError('开通订单的加密请求无效', 409);
}
// Freeze the complete effective platform deny policy at the payment
// boundary. An unpaid order therefore receives the current catalog,
// while a queued/retried create can never drift after an administrator
// edits or deletes a test rule.
$platformPolicy = CloudPlatformTestNetworkPolicy::snapshotForProvisioning();
$payload['body']['platform_network_policy_snapshot'] = $platformPolicy;
$orderSpec = json_decode((string) $order->spec_json, true);
if (!is_array($orderSpec) || array_is_list($orderSpec)) {
throw new CloudError('开通订单的规格快照无效', 409);
}
$orderSpec['platform_network_policy_snapshot'] = $platformPolicy;
$order->spec_json = json_encode($orderSpec, JSON_THROW_ON_ERROR
| JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$offer = CloudOffer::where('id', (int) $order->offer_id)
->lockForUpdate()->first();
$plan = Shop::where('id', (int) $order->plan_id)->lockForUpdate()->first();
if ($offer === null || !(bool) $offer->status || $plan === null
|| (int) $plan->status !== 1
|| (int) $offer->plan_id !== (int) $plan->id
|| (int) $offer->resource_pool_id !== (int) $order->resource_pool_id) {
throw new CloudError('该销售方案已经失效,不能继续支付', 409);
}
$placement = CloudPlacementService::reserve(
$order, $offer, $plan, $payload
);
$job = new CloudJob();
$job->operation_id = (string) $placement['reservation']->operation_id;
$job->order_id = $order->id;
$job->user_id = $order->user_id;
$job->host_id = $placement['host']->id;
$job->kind = 'create';
$job->status = 'queued';
$job->payload_cipher = CloudSecrets::encrypt($placement['payload']);
$job->available_at = $job->created_at = $job->updated_at = time();
$job->save();
// The worker now owns the sole recoverable credential copy.
$order->payload_cipher = null;
$order->status = 'queued';
$order->updated_at = time();
$order->save();
return $order;
}
/** Release a finite plan reservation exactly once. */
public static function releaseStock(CloudOrder $order): void
{
if ($order->stock_reserved_at === null || $order->stock_released_at !== null) {
return;
}
$offer = CloudOffer::where('id', $order->offer_id)->lockForUpdate()->first();
if ($offer !== null && (int) $offer->stock >= 0) {
$offer->stock = (int) $offer->stock + 1;
$offer->updated_at = time();
$offer->save();
}
$order->stock_released_at = time();
$order->updated_at = time();
$order->save();
}
public static function display(CloudOrder $order): array
{
$job = CloudJob::where('order_id', $order->id)->first();
$invoice = CloudInvoice::where('order_id', $order->id)->first();
$error = $job === null ? null : CloudOperationErrorCatalog::userMessage(
(string) $job->kind, (string) $job->status, $job->error_code, true
);
$jobStatus = $job === null
? null
: (CloudOperationErrorCatalog::userStatus($job->status) ?? 'unknown');
return ['id' => (string) $order->id, 'user_id' => (int) $order->user_id, 'status' => $order->status, 'amount' => (string) $order->amount,
'offer_id' => (int) $order->offer_id,
'instance_id' => $order->instance_id === null ? null : (string) $order->instance_id,
'created_at' => (int) $order->created_at, 'updated_at' => (int) ($job?->updated_at ?? $order->updated_at),
'invoice_id' => $invoice === null ? null : (string) $invoice->id,
'job_id' => $job === null ? '' : (string) $job->id,
'job_status' => $jobStatus, 'attempts' => (int) ($job?->attempts ?? 0),
'error' => $error];
}
}