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/Command/CloudTrafficPoolAttention.php

363 lines
14 KiB
PHTML

<?php
namespace App\Command;
use App\Models\CloudTrafficInstanceCursor;
use App\Models\CloudTrafficLedgerEvent;
use App\Models\CloudTrafficPool;
use App\Services\Cloud\CloudTrafficPoolAccounting;
/** Local-only, audited break-glass entry for traffic accounting attention. */
final class CloudTrafficPoolAttention
{
private const CONFIRM_PREFIX = 'RESOLVE_TRAFFIC_POOL';
public static function run(array $argv): int
{
$command = self::parse($argv);
if ($command['action'] === 'inspect') {
self::output(self::inspectPool($command['pool_id']));
return 0;
}
if ($command['action'] === 'inspect-resolution') {
self::output(self::inspectResolution(
$command['resolution_key']
));
return 0;
}
self::output(self::resolvePool(
$command['pool_id'],
$command['expected_version'],
$command['resolution_key']
));
return 0;
}
/** @return array{action:string,pool_id?:int,expected_version?:int,resolution_key?:string} */
private static function parse(array $argv): array
{
$action = (string) ($argv[2] ?? '');
if ($action === 'inspect') {
$options = self::options(array_slice($argv, 3), ['pool-id']);
return [
'action' => 'inspect',
'pool_id' => self::positiveInteger(
$options['pool-id'] ?? null,
'pool-id'
),
];
}
if ($action === 'resolve') {
$options = self::options(array_slice($argv, 3), [
'pool-id', 'expected-version', 'resolution-key',
'apply', 'confirm',
]);
$poolId = self::positiveInteger(
$options['pool-id'] ?? null,
'pool-id'
);
$expectedVersion = self::positiveInteger(
$options['expected-version'] ?? null,
'expected-version'
);
$resolutionKey = self::resolutionKey(
$options['resolution-key'] ?? null
);
if (($options['apply'] ?? null) !== true) {
throw new \InvalidArgumentException(
'解除 attention 必须显式提供 --apply'
);
}
$confirmation = self::confirmation(
$poolId,
$expectedVersion,
$resolutionKey
);
if (!is_string($options['confirm'] ?? null)
|| !hash_equals($confirmation, $options['confirm'])) {
throw new \InvalidArgumentException(
'确认词不匹配,请先执行 inspect 并绑定精确池版本'
);
}
return [
'action' => 'resolve',
'pool_id' => $poolId,
'expected_version' => $expectedVersion,
'resolution_key' => $resolutionKey,
];
}
if ($action === 'inspect-resolution') {
$options = self::options(
array_slice($argv, 3),
['resolution-key']
);
return [
'action' => 'inspect-resolution',
'resolution_key' => self::resolutionKey(
$options['resolution-key'] ?? null
),
];
}
throw new \InvalidArgumentException(
'用法:php xcat cloudTrafficPoolAttention inspect --pool-id=N;'
. '或 inspect-resolution --resolution-key=UUID;'
. '或 resolve --pool-id=N --expected-version=V '
. '--resolution-key=UUID --apply '
. '--confirm=RESOLVE_TRAFFIC_POOL:N:V:UUID'
);
}
private static function inspectPool(int $poolId): array
{
$pool = CloudTrafficPool::find($poolId);
if ($pool === null) {
throw new \RuntimeException('流量池不存在');
}
$observedState = (string) $pool->state;
$observedVersion = (int) $pool->version;
$verification = CloudTrafficPoolAccounting::verifyProjection($poolId);
$latestResolution = (int) (CloudTrafficLedgerEvent::where(
'pool_id', $poolId
)->where('event_type', 'attention_resolved')->max('id') ?? 0);
$eventCounts = CloudTrafficLedgerEvent::where('pool_id', $poolId)
->where('id', '>', $latestResolution)
->whereIn('event_type', [
'accounting_attention', 'counter_attention',
])->selectRaw('event_type, COUNT(*) AS aggregate')
->groupBy('event_type')->pluck('aggregate', 'event_type');
$cursorCount = CloudTrafficInstanceCursor::where(
'pool_id', $poolId
)->where('state', 'attention')->count();
$fresh = CloudTrafficPool::find($poolId);
if ($fresh === null || (string) $fresh->state !== $observedState
|| (int) $fresh->version !== $observedVersion) {
throw new \RuntimeException(
'流量池在核对期间已变化,请重新执行 inspect'
);
}
$issueCounts = [];
foreach (is_array($verification['errors'] ?? null)
? $verification['errors'] : [] as $error) {
$code = match (true) {
str_starts_with((string) $error, 'entitlement:') =>
'entitlement_projection_mismatch',
(string) $error === 'pool:overage' =>
'pool_overage_mismatch',
(string) $error === 'pool:available' =>
'pool_available_mismatch',
default => 'projection_mismatch',
};
$issueCounts[$code] = ($issueCounts[$code] ?? 0) + 1;
}
ksort($issueCounts, SORT_STRING);
$issues = [];
foreach ($issueCounts as $code => $count) {
$issues[] = ['code' => $code, 'count' => $count];
}
return [
'action' => 'inspect',
'pool_id' => (int) $pool->id,
'traffic_pool_group_id' => (int) $pool->traffic_pool_group_id,
'state' => (string) $fresh->state,
'version' => (int) $fresh->version,
'available_bytes' => (int) $fresh->available_bytes,
'overage_bytes' => (int) $fresh->overage_bytes,
'projection_valid' => (bool) ($verification['valid'] ?? false),
'projection_issues' => $issues,
'attention_cursor_count' => $cursorCount,
'unresolved_attention_event_count' =>
(int) ($eventCounts['accounting_attention'] ?? 0)
+ (int) ($eventCounts['counter_attention'] ?? 0),
'attention_categories' => [
'accounting_attention' =>
(int) ($eventCounts['accounting_attention'] ?? 0),
'counter_attention' =>
(int) ($eventCounts['counter_attention'] ?? 0),
],
'confirmation_prefix' => self::CONFIRM_PREFIX . ':' . $poolId
. ':' . (int) $fresh->version . ':',
];
}
private static function resolvePool(
int $poolId,
int $expectedVersion,
string $resolutionKey
): array {
$eventKey = self::resolutionEventKey($resolutionKey);
if (CloudTrafficLedgerEvent::where('event_key', $eventKey)->exists()
|| CloudTrafficLedgerEvent::where(
'source_type', 'admin_reconciliation'
)->where('source_id', $resolutionKey)->exists()) {
throw new \RuntimeException(
'resolution-key 已使用;请执行 inspect-resolution '
. '--resolution-key=<原 UUID> 核对,不要盲目重试'
);
}
$before = CloudTrafficPool::find($poolId);
if ($before === null) {
throw new \RuntimeException('流量池不存在');
}
if ((string) $before->state !== 'attention') {
throw new \RuntimeException('流量池当前不处于 attention 状态');
}
$result = CloudTrafficPoolAccounting::resolveAttention(
$poolId,
$expectedVersion,
$resolutionKey
);
if (($result['changed'] ?? false) !== true) {
throw new \RuntimeException('attention 未被解除,请重新 inspect');
}
$event = CloudTrafficLedgerEvent::where('event_key', $eventKey)
->where('pool_id', $poolId)
->where('event_type', 'attention_resolved')
->where('source_type', 'admin_reconciliation')
->where('source_id', $resolutionKey)->first();
$payload = $event === null ? null
: json_decode((string) $event->payload_json, true);
if ($event === null || !is_array($payload)
|| (int) ($payload['expected_version'] ?? -1)
!== $expectedVersion) {
throw new \RuntimeException(
'attention 已处理但审计事件核对失败;请执行 '
. 'inspect-resolution --resolution-key=<原 UUID> 并保留现场'
);
}
return [
'action' => 'resolve',
'pool_id' => $poolId,
'resolution_key' => $resolutionKey,
'before_version' => $expectedVersion,
'after_version' => (int) ($result['version'] ?? 0),
'state' => (string) ($result['state'] ?? ''),
'available_bytes' => (int) ($result['available_bytes'] ?? 0),
'overage_bytes' => (int) ($result['overage_bytes'] ?? 0),
'attention_resolved_event_id' => (int) $event->id,
];
}
private static function inspectResolution(string $resolutionKey): array
{
$event = CloudTrafficLedgerEvent::where(
'event_key', self::resolutionEventKey($resolutionKey)
)->first();
if ($event === null) {
return [
'action' => 'inspect-resolution',
'resolution_key' => $resolutionKey,
'committed' => false,
];
}
if ((string) $event->event_type !== 'attention_resolved'
|| (string) $event->source_type !== 'admin_reconciliation'
|| !hash_equals((string) $event->source_id, $resolutionKey)) {
throw new \RuntimeException(
'resolution-key 的不可变账本身份冲突,请保留现场'
);
}
$payload = json_decode((string) $event->payload_json, true);
$expectedVersion = is_array($payload)
? ($payload['expected_version'] ?? null) : null;
if (!is_int($expectedVersion) || $expectedVersion < 1) {
throw new \RuntimeException(
'resolution-key 的审计载荷无效,请保留现场'
);
}
$pool = CloudTrafficPool::find((int) $event->pool_id);
return [
'action' => 'inspect-resolution',
'resolution_key' => $resolutionKey,
'committed' => true,
'pool_id' => (int) $event->pool_id,
'expected_version' => $expectedVersion,
'resolved_at' => (int) $event->created_at,
'current_pool_exists' => $pool !== null,
'current_pool_state' => $pool === null
? null : (string) $pool->state,
'current_pool_version' => $pool === null
? null : (int) $pool->version,
];
}
/** @return array<string,string|true> */
private static function options(array $arguments, array $allowed): array
{
$result = [];
foreach ($arguments as $argument) {
if (!is_string($argument) || $argument === '') {
throw new \InvalidArgumentException('命令参数无效');
}
if ($argument === '--apply') {
$name = 'apply';
$value = true;
} elseif (preg_match('/^--([a-z][a-z-]*)=(.*)$/D',
$argument, $match) === 1) {
$name = $match[1];
$value = $match[2];
} else {
throw new \InvalidArgumentException(
'存在未知或格式无效的命令参数'
);
}
if (!in_array($name, $allowed, true)
|| array_key_exists($name, $result)) {
throw new \InvalidArgumentException(
'存在未知或重复的命令参数:' . $name
);
}
$result[$name] = $value;
}
if (count($result) !== count($allowed)) {
throw new \InvalidArgumentException('命令参数不完整');
}
return $result;
}
private static function positiveInteger(mixed $value, string $name): int
{
if (!is_string($value)
|| preg_match('/^[1-9][0-9]{0,18}$/D', $value) !== 1) {
throw new \InvalidArgumentException($name . ' 必须是正整数');
}
$integer = (int) $value;
if ($integer < 1 || (string) $integer !== $value) {
throw new \InvalidArgumentException($name . ' 超出有效范围');
}
return $integer;
}
private static function resolutionKey(mixed $value): string
{
if (!is_string($value) || preg_match(
'/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/D',
$value
) !== 1) {
throw new \InvalidArgumentException(
'resolution-key 必须是小写规范 UUIDv4'
);
}
return $value;
}
private static function confirmation(
int $poolId,
int $expectedVersion,
string $resolutionKey
): string {
return self::CONFIRM_PREFIX . ':' . $poolId . ':'
. $expectedVersion . ':' . $resolutionKey;
}
private static function resolutionEventKey(string $resolutionKey): string
{
return 'attention-resolution:' . $resolutionKey;
}
private static function output(array $value): void
{
echo json_encode($value, JSON_THROW_ON_ERROR
| JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . PHP_EOL;
}
}