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

201 lines
9.9 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudHost;
use App\Models\CloudInvoice;
use App\Models\CloudInstance;
use App\Models\CloudJob;
use App\Models\CloudOrder;
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;
public static function purchase(array $input, array $actor): CloudOrder
{
CloudInput::only($input, ['plan_id', 'source', 'template_id', 'iso_path', 'guest_ssh_key_id',
'root_password', 'name', 'idempotency_key']);
$name = CloudInput::name($input['name'] ?? null);
$idempotency = $input['idempotency_key'] ?? '';
if (!is_string($idempotency) || preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $idempotency) !== 1) {
throw new CloudError('请提供 16 至 128 字符的请求幂等标识');
}
$planId = filter_var($input['plan_id'] ?? null, FILTER_VALIDATE_INT);
if (!$planId || $planId < 1) {
throw new CloudError('请选择套餐');
}
$source = $input['source'] ?? 'cloud';
if (!in_array($source, ['cloud', 'iso'], true)) {
throw new CloudError('系统来源无效');
}
$template = $input['template_id'] ?? '';
$iso = $input['iso_path'] ?? '';
if ($source === 'cloud') {
$template = CloudInput::template($template);
}
if ($source === 'iso' && (!is_string($iso) || $iso === '' || strlen($iso) > 255 || str_contains($iso, "\0"))) {
throw new CloudError('请选择安装 ISO');
}
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, $planId, $source, $name, $template, $iso, $idempotency, $requestHash) {
$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;
}
$maximum = max(1, (int) \App\Services\Config::get('cloud_max_instances_per_user', 20));
$active = CloudInstance::where('user_id', $user->id)->where('status', '<>', 'deleted')->count();
$reserved = CloudOrder::where('user_id', $user->id)->whereIn('status',
['awaiting_payment', 'queued', 'running', 'uncertain'])->count();
if ($active + $reserved >= $maximum) {
throw new CloudError('已达到账户虚拟机数量上限', 409);
}
$plan = Shop::where('id', $planId)->lockForUpdate()->first();
if ($plan === null || (int) $plan->status !== 1 || (int) $plan->stock === 0) {
throw new CloudError('套餐不可购买或已售罄', 409);
}
$host = CloudHost::where('id', $plan->host_id)->where('enabled', 1)->first();
if ($host === null) {
throw new CloudError('套餐对应宿主机暂不可用', 409);
}
$price = CloudMoney::cents($plan->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' => $host->default_network];
$credential = null;
if ($source === 'cloud') {
$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'];
} else {
$payload['iso'] = $iso;
}
$safeSpec = CloudInput::safeResult($payload);
$safeSpec['plan_name'] = $plan->name;
$safeSpec['plan_id'] = (int) $plan->id;
$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->host_id = $host->id;
$order->idempotency_key = $idempotency;
$order->request_hash = $requestHash;
$order->amount = CloudMoney::decimal($price);
$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) $plan->stock > 0) {
$plan->stock--;
$plan->save();
$order->stock_reserved_at = time();
}
$order->save();
CloudInvoiceService::issueProvision($order, $plan, time());
return $order;
}, 3);
}
/**
* 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
|| 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);
}
$job = new CloudJob();
$job->operation_id = bin2hex(random_bytes(16));
$job->order_id = $order->id;
$job->user_id = $order->user_id;
$job->host_id = $order->host_id;
$job->kind = 'create';
$job->status = 'queued';
$job->payload_cipher = $order->payload_cipher;
$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;
}
$plan = Shop::where('id', $order->plan_id)->lockForUpdate()->first();
if ($plan !== null && (int) $plan->stock >= 0) {
$plan->stock = (int) $plan->stock + 1;
$plan->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();
return ['id' => (string) $order->id, 'user_id' => (int) $order->user_id, 'status' => $order->status, 'amount' => (string) $order->amount,
'plan_id' => (int) $order->plan_id, 'host_id' => (int) $order->host_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' => $job?->status, 'attempts' => (int) ($job?->attempts ?? 0),
'error' => $job?->error_code];
}
}