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

323 lines
12 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudInstance;
use App\Models\CloudInvoice;
use App\Models\CloudJob;
use App\Models\CloudOrder;
use App\Models\CloudResourceReservation;
use App\Models\User;
/**
* Atomically closes the PHP ledgers for a create operation that did not apply.
*
* This service never contacts an Agent and never submits a host mutation. A
* terminal unknown-effect create can be resolved only from fresh read-only
* absence evidence. The original failed receipt remains immutable; only its
* effect-resolution audit columns are written after the refund and placement
* cleanup have committed in the same transaction.
*/
final class CloudCreateFailureFinalizer
{
/**
* Validate the only create resolution supported by the current DTO.
*
* The inspection intentionally omits the complete, signed create result,
* so an "applied" conclusion cannot safely materialize an instance.
*/
public static function assertResolutionSupported(
CloudJob $job,
string $resolution,
array $inspection
): void {
if ((string) $job->kind !== 'create') {
return;
}
if ($job->order_id === null) {
throw new CloudError('开通任务缺少订单关联,不能解除资源栅栏', 409);
}
if ($resolution !== 'not_applied') {
throw new CloudError(
'开通任务不能仅凭只读检查确认已应用;缺少可安全物化实例的完整 Agent 成功结果',
409
);
}
if (($inspection['operation_id'] ?? null)
!== (string) $job->operation_id
|| ($inspection['outcome'] ?? null) !== 'failed'
|| ($inspection['summary_code'] ?? null) !== 'operation_failed'
|| ($inspection['error_code'] ?? null) !== 'creation_absent') {
throw new CloudError(
'开通任务只有在宿主机确认虚拟机及面板管理资源均不存在后才能退款并解除栅栏',
409
);
}
}
/**
* Finalize an already-failed, unknown-effect create as not applied.
*
* Wallet, invoice, order, stock, reservation and public-IP state are
* settled before effect_resolution is written. The transaction either
* commits every ledger transition or none of them.
*/
public static function resolveNotApplied(
int $jobId,
string $operationId,
int $actorId,
string $reason,
array $inspection,
int $now
): void {
$source = CloudJob::where('id', $jobId)->first();
if ($source === null) {
throw new CloudError('任务不存在', 404);
}
self::assertResolutionSupported($source, 'not_applied', $inspection);
(new CloudJob())->getConnection()->transaction(function () use (
$source,
$jobId,
$operationId,
$actorId,
$reason,
$inspection,
$now
): void {
$user = User::where('id', (int) $source->user_id)
->lockForUpdate()->first();
$order = CloudOrder::where('id', (int) $source->order_id)
->lockForUpdate()->first();
$job = CloudJob::where('id', $jobId)->lockForUpdate()->first();
if ($job === null || $user === null || $order === null
|| (string) $job->kind !== 'create'
|| (int) $job->user_id !== (int) $user->id
|| (int) $job->order_id !== (int) $order->id
|| (int) $order->user_id !== (int) $user->id
|| !hash_equals((string) $job->operation_id, $operationId)) {
throw new CloudError('开通任务与资金账本关联不一致', 409);
}
self::assertResolutionSupported(
$job,
'not_applied',
$inspection
);
if ((string) $job->phase !== 'terminal'
|| (string) $job->outcome !== 'failed'
|| (string) $job->effect_resolution !== 'unknown'
|| !(bool) $job->effect_may_have_applied) {
throw new CloudError('任务不处于可确认的影响未知状态', 409);
}
self::refundAndReleaseLocked(
$job,
$user,
$order,
'create_effect_not_applied',
$now
);
// Keep the original failed receipt immutable. These audit fields
// are deliberately written last, after every financial/resource
// transition above has succeeded inside this transaction.
$job->effect_resolution = 'not_applied';
$job->effect_resolved_at = $now;
$job->effect_resolved_by = $actorId;
$job->effect_resolution_reason = $reason;
$job->updated_at = $now;
$job->save();
}, 3);
}
/**
* Create-specific replacement for the generic emergency terminal write.
*
* Returning false means this is not an order-backed create. A caller must
* never follow a true return with the generic job-only fallback.
*/
public static function forceTerminalFailure(
int $jobId,
string $leaseToken,
bool $effectMayHaveApplied,
bool $safeToResubmit,
string $errorCode
): bool {
$source = CloudJob::where('id', $jobId)->first();
if ($source === null || (string) $source->kind !== 'create'
|| $source->order_id === null) {
return false;
}
return (bool) (new CloudJob())->getConnection()->transaction(
function () use (
$source,
$jobId,
$leaseToken,
$effectMayHaveApplied,
$safeToResubmit,
$errorCode
): bool {
$user = User::where('id', (int) $source->user_id)
->lockForUpdate()->first();
$order = CloudOrder::where('id', (int) $source->order_id)
->lockForUpdate()->first();
$job = CloudJob::where('id', $jobId)->lockForUpdate()->first();
if ($job === null || (string) $job->phase === 'terminal') {
return true;
}
if ($user === null || $order === null
|| (string) $job->kind !== 'create'
|| (int) $job->user_id !== (int) $user->id
|| (int) $job->order_id !== (int) $order->id
|| (int) $order->user_id !== (int) $user->id
|| !hash_equals((string) ($job->lease_token ?? ''),
$leaseToken)) {
throw new CloudError('开通任务与资金账本关联不一致', 409);
}
$now = time();
// Without definitive no-effect evidence, preserve every paid
// resource and turn the placement into a durable safety fence.
if ($effectMayHaveApplied) {
CloudPlacementService::markUncertain($order);
$order->status = 'failed';
$order->updated_at = $now;
$order->save();
self::terminalizeLocked(
$job,
true,
false,
$errorCode,
$now
);
return true;
}
self::refundAndReleaseLocked(
$job,
$user,
$order,
'create_failed',
$now
);
self::terminalizeLocked(
$job,
false,
$safeToResubmit,
$errorCode,
$now
);
return true;
},
3
);
}
/**
* Settle the create ledgers while the caller holds user/order/job locks.
* This method is shared with the normal Agent receipt finalizer.
*/
public static function refundAndReleaseLocked(
CloudJob $job,
User $user,
CloudOrder $order,
string $releaseReason,
?int $now = null
): void {
$now ??= time();
if ((string) $job->kind !== 'create'
|| (int) $job->order_id !== (int) $order->id
|| (int) $job->user_id !== (int) $user->id
|| (int) $order->user_id !== (int) $user->id
|| !in_array((string) $order->status,
['queued', 'failed', 'uncertain'], true)
|| $job->instance_id !== null || $order->instance_id !== null) {
throw new CloudError('开通任务已有关联实例或资金账本不一致', 409);
}
$instance = CloudInstance::where('order_id', (int) $order->id)
->lockForUpdate()->first();
if ($instance !== null) {
throw new CloudError('开通订单已经物化实例,不能按未应用退款', 409);
}
$invoice = CloudInvoice::where('order_id', (int) $order->id)
->lockForUpdate()->first();
if ($invoice === null || (string) $invoice->purpose !== 'provision'
|| (int) $invoice->user_id !== (int) $user->id
|| (int) $invoice->order_id !== (int) $order->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) $invoice->status,
['paid', 'refunded'], true)) {
throw new CloudError('开通账单不处于可退款状态', 409);
}
$reservation = CloudResourceReservation::where(
'order_id', (int) $order->id
)->first();
if ($order->reservation_id === null || $reservation === null
|| (int) $order->reservation_id !== (int) $reservation->id
|| !hash_equals((string) $job->operation_id,
(string) $reservation->operation_id)) {
throw new CloudError('开通订单与资源预留关联不一致', 409);
}
$alreadyRefunded = $order->refunded_at !== null;
if (!$alreadyRefunded && (string) $invoice->status !== 'paid') {
throw new CloudError('开通退款幂等账本不一致', 409);
}
// These operations are themselves row-locked and idempotent. They run
// even on an idempotent replay so a prior version's incomplete local
// bookkeeping can be repaired without crediting the wallet twice.
CloudOrderService::releaseStock($order);
CloudPlacementService::release($order, $releaseReason);
if (!$alreadyRefunded) {
$user->money = CloudMoney::decimal(
CloudMoney::cents((string) $user->money)
+ CloudMoney::cents((string) $order->amount)
);
$user->save();
$order->refunded_at = $now;
}
$invoice->status = 'refunded';
$invoice->updated_at = $now;
$invoice->save();
$order->status = 'failed';
$order->sealed_payload = null;
$order->updated_at = $now;
$order->save();
}
private static function terminalizeLocked(
CloudJob $job,
bool $effectMayHaveApplied,
bool $safeToResubmit,
string $errorCode,
int $now
): void {
$job->phase = 'terminal';
$job->outcome = 'failed';
$job->status = 'failed';
$job->terminal_at = $now;
$job->effect_may_have_applied = $effectMayHaveApplied ? 1 : 0;
$job->safe_to_resubmit = $effectMayHaveApplied
? 0 : ($safeToResubmit ? 1 : 0);
$job->effect_resolution = $effectMayHaveApplied
? 'unknown' : 'not_applied';
$job->error_code = substr($errorCode, 0, 128);
$job->sealed_payload = CloudSecrets::encrypt([], 'job-payload');
$job->lease_token = null;
$job->lease_until = 0;
$job->available_at = 0;
$job->updated_at = $now;
$job->save();
}
}