diff --git a/web/app/Command/CloudTrafficPoolAttention.php b/web/app/Command/CloudTrafficPoolAttention.php new file mode 100644 index 00000000..cf17ded1 --- /dev/null +++ b/web/app/Command/CloudTrafficPoolAttention.php @@ -0,0 +1,362 @@ + '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 */ + 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; + } +} diff --git a/web/app/Command/XCat.php b/web/app/Command/XCat.php index c192201e..bef15158 100644 --- a/web/app/Command/XCat.php +++ b/web/app/Command/XCat.php @@ -23,6 +23,8 @@ class XCat 'cloudInit' => CloudSetup::initialize(), 'cloudWorker' => CloudWorker::run($this->argv) === 0, 'cloudLifecycle' => CloudLifecycle::run($this->argv) === 0, + 'cloudTrafficPoolAttention' => + CloudTrafficPoolAttention::run($this->argv) === 0, 'cloudRepairInstanceMetadata' => CloudRepairInstanceMetadata::run($this->argv) === 0, 'setTelegram' => $this->setTelegram(), @@ -100,6 +102,9 @@ class XCat . " php xcat cloudInit\n" . " php xcat cloudWorker [--once] [--policy-only|--vpc-batch-only|--recovery-only]\n" . " php xcat cloudLifecycle [--once]\n" + . " php xcat cloudTrafficPoolAttention inspect --pool-id=N\n" + . " php xcat cloudTrafficPoolAttention inspect-resolution --resolution-key=UUID\n" + . " php xcat cloudTrafficPoolAttention resolve --pool-id=N --expected-version=V --resolution-key=UUID --apply --confirm=RESOLVE_TRAFFIC_POOL:N:V:UUID\n" . " php xcat cloudRepairInstanceMetadata [--apply] [--limit=N] [--after-id=N]\n" . " php xcat setTelegram\n" . " php xcat backup\n" diff --git a/web/app/Services/Cloud/CloudTrafficPoolAccounting.php b/web/app/Services/Cloud/CloudTrafficPoolAccounting.php index 3360a88f..9523edd3 100644 --- a/web/app/Services/Cloud/CloudTrafficPoolAccounting.php +++ b/web/app/Services/Cloud/CloudTrafficPoolAccounting.php @@ -513,6 +513,14 @@ final class CloudTrafficPoolAccounting string $resolutionKey, ?int $now = null ): array { + if (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', + $resolutionKey + ) !== 1) { + throw new CloudError( + '账本核对标识必须是小写规范 UUIDv4' + ); + } $now ??= time(); $hint = CloudTrafficPool::find($poolId); if ($hint === null) { @@ -632,8 +640,10 @@ final class CloudTrafficPoolAccounting $cursor->save(); } self::appendEventLocked($pool, [ - 'event_key' => 'attention-resolution:' . $poolId . ':' - . $resolutionKey, + // The operator-supplied UUID is globally unique. Keeping the + // pool ID out of this identity lets the ledger event-key + // constraint reject reuse across different pools as well. + 'event_key' => 'attention-resolution:' . $resolutionKey, 'event_type' => 'attention_resolved', 'source_type' => 'admin_reconciliation', 'source_id' => $resolutionKey, diff --git a/web/tests/CloudTrafficPoolAccountingTest.php b/web/tests/CloudTrafficPoolAccountingTest.php index 65c1fbda..223968a4 100644 --- a/web/tests/CloudTrafficPoolAccountingTest.php +++ b/web/tests/CloudTrafficPoolAccountingTest.php @@ -410,7 +410,19 @@ try { CloudTrafficPoolAccounting::resolveAttention( (int) $regression['pool_id'], (int) $regression['version'], - 'test-regression-unresolved', + 'not-a-resolution-uuid', + $base + 22 + ); + throw new RuntimeException('A non-UUID attention resolution was accepted.'); +} catch (CloudError $error) { + $assert($error->httpStatus === 422, + 'Invalid attention resolution identity returned the wrong status.'); +} +try { + CloudTrafficPoolAccounting::resolveAttention( + (int) $regression['pool_id'], + (int) $regression['version'], + '00000000-0000-4000-8000-000000000001', $base + 22 ); throw new RuntimeException('Unresolved counter regression was cleared.'); @@ -424,7 +436,7 @@ $other->save(); $resolved = CloudTrafficPoolAccounting::resolveAttention( (int) $regression['pool_id'], (int) $regression['version'], - 'test-regression-resolved', + '00000000-0000-4000-8000-000000000002', $base + 23 ); $assert($resolved['state'] === 'available' @@ -455,7 +467,7 @@ try { CloudTrafficPoolAccounting::resolveAttention( (int) $accountingAttention['pool_id'], (int) $accountingAttention['version'], - 'test-accounting-attention:unfixed', + '00000000-0000-4000-8000-000000000003', $base + 3 ); throw new RuntimeException('Unfixed accounting conflict was cleared.'); @@ -469,7 +481,7 @@ $accountingPeriod->save(); $accountingResolved = CloudTrafficPoolAccounting::resolveAttention( (int) $accountingAttention['pool_id'], (int) $accountingAttention['version'], - 'test-accounting-attention:fixed', + '00000000-0000-4000-8000-000000000004', $base + 4 ); $assert($accountingResolved['state'] === 'available', @@ -647,7 +659,7 @@ $lateAttentionPool = CloudTrafficPool::where('user_id', 13) $lateAttentionResult = CloudTrafficPoolAccounting::resolveAttention( (int) $lateAttentionPool->id, (int) $lateAttentionPool->version, - 'test-late-attention:resolve', + '00000000-0000-4000-8000-000000000005', $base + 121 ); $lateAttentionEntitlement = CloudTrafficEntitlement::where( diff --git a/web/tests/CloudTrafficPoolAttentionCommandTest.php b/web/tests/CloudTrafficPoolAttentionCommandTest.php new file mode 100644 index 00000000..7c1e425e --- /dev/null +++ b/web/tests/CloudTrafficPoolAttentionCommandTest.php @@ -0,0 +1,136 @@ +invoke(null, [ + 'xcat', 'cloudTrafficPoolAttention', 'inspect', '--pool-id=42', +]); +$assert($inspection === ['action' => 'inspect', 'pool_id' => 42], + 'Inspect did not preserve the exact validated pool identity.'); + +$uuid = '550e8400-e29b-41d4-a716-446655440000'; +$confirm = 'RESOLVE_TRAFFIC_POOL:42:9:' . $uuid; +$resolution = $parse->invoke(null, [ + 'xcat', 'cloudTrafficPoolAttention', 'resolve', + '--resolution-key=' . $uuid, + '--confirm=' . $confirm, + '--expected-version=9', + '--apply', + '--pool-id=42', +]); +$assert($resolution === [ + 'action' => 'resolve', 'pool_id' => 42, + 'expected_version' => 9, 'resolution_key' => $uuid, + ], + 'Resolve did not bind the exact pool, version and resolution UUID.'); + +$resolutionInspection = $parse->invoke(null, [ + 'xcat', 'cloudTrafficPoolAttention', 'inspect-resolution', + '--resolution-key=' . $uuid, +]); +$assert($resolutionInspection === [ + 'action' => 'inspect-resolution', 'resolution_key' => $uuid, + ], + 'Resolution inspection did not bind the exact immutable UUID.'); + +$invalidCases = [ + ['inspect'], + ['inspect', '--pool-id=0'], + ['inspect', '--pool-id=01'], + ['inspect', '--pool-id=42', '--extra=true'], + ['inspect', '--pool-id=42', '--pool-id=42'], + ['inspect-resolution'], + ['inspect-resolution', '--resolution-key=invalid'], + ['inspect-resolution', '--resolution-key=' . $uuid, '--extra=true'], + ['resolve', '--pool-id=42', '--expected-version=9', + '--resolution-key=' . $uuid, '--confirm=' . $confirm], + ['resolve', '--pool-id=42', '--expected-version=9', + '--resolution-key=' . $uuid, '--apply', '--confirm=wrong'], + ['resolve', '--pool-id=42', '--expected-version=9', + '--resolution-key=' . $uuid, '--apply=true', + '--confirm=' . $confirm], + ['resolve', '--pool-id=42', '--expected-version=0', + '--resolution-key=' . $uuid, '--apply', '--confirm=' . $confirm], + ['resolve', '--pool-id=42', '--expected-version=9', + '--resolution-key=550e8400-e29b-11d4-a716-446655440000', + '--apply', '--confirm=' . $confirm], + ['resolve', '--pool-id=42', '--expected-version=9', + '--resolution-key=' . $uuid, '--apply', '--confirm=' . $confirm, + '--force'], +]; +foreach ($invalidCases as $case) { + try { + $parse->invoke(null, array_merge([ + 'xcat', 'cloudTrafficPoolAttention', + ], $case)); + throw new RuntimeException( + 'Invalid arguments were accepted: ' . implode(' ', $case) + ); + } catch (ReflectionException $error) { + throw $error; + } catch (Throwable $error) { + $previous = $error instanceof ReflectionException + ? $error : ($error->getPrevious() ?? $error); + $assert($previous instanceof InvalidArgumentException, + 'Invalid arguments produced the wrong failure: ' + . implode(' ', $case)); + } +} + +$source = file_get_contents(dirname(__DIR__) + . '/app/Command/CloudTrafficPoolAttention.php'); +$accounting = file_get_contents(dirname(__DIR__) + . '/app/Services/Cloud/CloudTrafficPoolAccounting.php'); +$xcat = file_get_contents(dirname(__DIR__) . '/app/Command/XCat.php'); +$assert(is_string($source) && is_string($accounting) && is_string($xcat), + 'Unable to read traffic-pool maintenance sources.'); +$assert(str_contains($source, + 'CloudTrafficPoolAccounting::resolveAttention(') + && str_contains($source, 'CloudTrafficPoolAccounting::verifyProjection(') + && !str_contains($source, 'CloudAgentClient') + && !str_contains($source, 'CloudJob') + && !str_contains($source, 'CloudInstanceNetworkRestriction') + && !str_contains($source, '?callable') + && !str_contains($source, '->update(') + && !str_contains($source, '->delete('), + 'Maintenance CLI bypasses accounting or acquired a remote/direct mutation.'); +$assert(str_contains($accounting, + "'event_key' => 'attention-resolution:' . \$resolutionKey") + && str_contains($accounting, + '账本核对标识必须是小写规范 UUIDv4'), + 'Resolution UUID is not a global accounting-module invariant.'); +$assert(str_contains($xcat, "'cloudTrafficPoolAttention'") + && str_contains($xcat, 'inspect-resolution --resolution-key=UUID') + && str_contains($xcat, '--confirm=RESOLVE_TRAFFIC_POOL:N:V:UUID'), + 'The audited maintenance command is not reachable or documented by XCat.'); + +$childCode = 'require ' . var_export( + dirname(__DIR__) . '/vendor/autoload.php', + true +) . '; exit((new \\App\\Command\\XCat([' + . "'xcat','cloudTrafficPoolAttention','inspect','--pool-id=bad'" + . ']))->boot());'; +$process = proc_open( + [PHP_BINARY, '-r', $childCode], + [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], + $pipes +); +$assert(is_resource($process), 'Unable to start the XCat exit-code probe.'); +$childStdout = stream_get_contents($pipes[1]); +$childStderr = stream_get_contents($pipes[2]); +fclose($pipes[1]); +fclose($pipes[2]); +$childStatus = proc_close($process); +$assert($childStatus === 1 && $childStdout === '' + && str_contains($childStderr, 'pool-id 必须是正整数'), + 'Formal XCat routing did not fail closed through stderr and exit code 1.'); + +echo "Cloud traffic-pool attention command safety contract passed.\n"; diff --git a/web/tests/CloudTrafficPoolAttentionIntegrationTest.php b/web/tests/CloudTrafficPoolAttentionIntegrationTest.php new file mode 100644 index 00000000..28d9b4e0 --- /dev/null +++ b/web/tests/CloudTrafficPoolAttentionIntegrationTest.php @@ -0,0 +1,377 @@ +addConnection([ + 'driver' => 'sqlite', + 'database' => ':memory:', +], 'default'); +$capsule->setAsGlobal(); +$capsule->bootEloquent(); +$schema = $capsule->schema('default'); + +$schema->create('cloud_traffic_pool_groups', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('code')->unique(); + $table->string('name'); + $table->string('mode'); + $table->integer('created_at'); + $table->integer('updated_at'); +}); +$schema->create('cloud_instances', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('user_id'); + $table->integer('current_period_id')->nullable(); + $table->integer('lifetime_download_bytes')->default(0); + $table->integer('lifetime_upload_bytes')->default(0); + $table->integer('traffic_synced_at')->default(0); + $table->string('status')->default('active'); + $table->integer('created_at'); + $table->integer('updated_at'); +}); +$schema->create('cloud_service_periods', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('instance_id'); + $table->integer('user_id'); + $table->integer('plan_id')->nullable(); + $table->integer('order_id')->nullable(); + $table->integer('renewal_id')->nullable(); + $table->integer('traffic_pool_group_id')->nullable(); + $table->string('traffic_quota_mode')->default('finite'); + $table->integer('starts_at'); + $table->integer('ends_at'); + $table->integer('traffic_quota_bytes')->default(0); + $table->integer('download_base_bytes')->nullable(); + $table->integer('upload_base_bytes')->nullable(); + $table->integer('download_used_bytes')->default(0); + $table->integer('upload_used_bytes')->default(0); + $table->string('status')->default('active'); + $table->integer('activated_at')->nullable(); + $table->integer('created_at'); + $table->integer('updated_at'); +}); +$schema->create('cloud_traffic_pools', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('user_id'); + $table->integer('traffic_pool_group_id'); + $table->string('state'); + $table->integer('available_bytes')->default(0); + $table->integer('overage_bytes')->default(0); + $table->integer('version')->default(0); + $table->integer('last_sequence')->default(0); + $table->integer('last_event_id')->nullable(); + $table->integer('created_at'); + $table->integer('updated_at'); + $table->unique(['user_id', 'traffic_pool_group_id']); +}); +$schema->create('cloud_traffic_entitlements', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('pool_id'); + $table->integer('user_id'); + $table->integer('instance_id'); + $table->integer('service_period_id')->unique(); + $table->integer('starts_at'); + $table->integer('ends_at'); + $table->string('quota_mode'); + $table->integer('granted_bytes')->default(0); + $table->integer('consumed_bytes')->default(0); + $table->integer('forfeited_bytes')->default(0); + $table->string('state'); + $table->integer('activated_at')->nullable(); + $table->integer('closed_at')->nullable(); + $table->integer('version')->default(0); + $table->integer('created_at'); + $table->integer('updated_at'); +}); +$schema->create('cloud_traffic_ledger_events', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('pool_id'); + $table->integer('user_id'); + $table->integer('pool_sequence'); + $table->string('event_key')->unique(); + $table->string('event_type'); + $table->string('source_type'); + $table->string('source_id'); + $table->integer('source_revision'); + $table->string('payload_hash'); + $table->integer('instance_id')->nullable(); + $table->integer('service_period_id')->nullable(); + $table->integer('entitlement_id')->nullable(); + $table->integer('amount_bytes'); + $table->integer('effective_at'); + $table->integer('observed_at')->nullable(); + $table->text('payload_json'); + $table->integer('created_at'); + $table->unique(['pool_id', 'pool_sequence']); +}); +$schema->create('cloud_traffic_instance_cursors', static function (Blueprint $table): void { + $table->integer('instance_id')->primary(); + $table->integer('user_id'); + $table->integer('pool_id'); + $table->integer('accounted_download_bytes')->default(0); + $table->integer('accounted_upload_bytes')->default(0); + $table->integer('last_observed_at')->default(0); + $table->integer('last_event_id')->nullable(); + $table->string('state'); + $table->string('attention_code'); + $table->integer('version')->default(0); + $table->integer('updated_at'); +}); + +$now = time(); +Capsule::table('cloud_traffic_pool_groups')->insert([ + ['id' => 1, 'code' => 'pool-a', 'name' => 'Pool A', 'mode' => 'shadow', + 'created_at' => $now, 'updated_at' => $now], + ['id' => 2, 'code' => 'pool-b', 'name' => 'Pool B', 'mode' => 'shadow', + 'created_at' => $now, 'updated_at' => $now], +]); + +$makeAttention = static function ( + int $instanceId, + int $periodId, + int $userId, + int $groupId +) use ($now): array { + $instance = new CloudInstance(); + $instance->id = $instanceId; + $instance->user_id = $userId; + $instance->current_period_id = $periodId; + $instance->lifetime_download_bytes = 0; + $instance->lifetime_upload_bytes = 0; + $instance->traffic_synced_at = $now; + $instance->status = 'active'; + $instance->created_at = $now; + $instance->updated_at = $now; + $instance->save(); + $period = new CloudServicePeriod(); + $period->id = $periodId; + $period->instance_id = $instanceId; + $period->user_id = $userId; + $period->traffic_pool_group_id = $groupId; + $period->traffic_quota_mode = 'finite'; + $period->starts_at = $now - 10; + $period->ends_at = $now + 3600; + $period->traffic_quota_bytes = 1000; + $period->download_base_bytes = 0; + $period->upload_base_bytes = 0; + $period->download_used_bytes = 0; + $period->upload_used_bytes = 0; + $period->status = 'active'; + $period->activated_at = $now - 10; + $period->created_at = $now; + $period->updated_at = $now; + $period->save(); + CloudTrafficPoolAccounting::reconcileServicePeriod( + $periodId, + 'attention-cli-period:' . $periodId, + $now + ); + $instance->lifetime_download_bytes = 100; + $instance->traffic_synced_at = $now + 1; + $instance->save(); + CloudTrafficPoolAccounting::settleInstanceUsage($instanceId, $now + 1); + $instance->lifetime_download_bytes = 90; + $instance->traffic_synced_at = $now + 2; + $instance->save(); + $attention = CloudTrafficPoolAccounting::settleInstanceUsage( + $instanceId, + $now + 2 + ); + return [$instance, $attention]; +}; +$run = static function (array $arguments): array { + ob_start(); + try { + $status = CloudTrafficPoolAttention::run(array_merge([ + 'xcat', 'cloudTrafficPoolAttention', + ], $arguments)); + $output = (string) ob_get_clean(); + return [$status, json_decode($output, true, 512, JSON_THROW_ON_ERROR)]; + } catch (Throwable $error) { + ob_end_clean(); + throw $error; + } +}; + +[$instance, $attention] = $makeAttention(11, 101, 7, 1); +$poolId = (int) $attention['pool_id']; +$beforePool = CloudTrafficPool::findOrFail($poolId); +$beforeLedger = CloudTrafficLedgerEvent::count(); +[$status, $inspection] = $run(['inspect', '--pool-id=' . $poolId]); +$afterInspect = CloudTrafficPool::findOrFail($poolId); +$assert($status === 0 && $inspection['state'] === 'attention' + && $inspection['version'] === (int) $beforePool->version + && $inspection['projection_valid'] === true + && !array_key_exists('user_id', $inspection) + && !array_key_exists('instance_id', $inspection) + && !array_key_exists('attention_cursor_ids', $inspection) + && !array_key_exists('unresolved_attention_event_ids', $inspection) + && $inspection['attention_cursor_count'] === 1 + && $inspection['unresolved_attention_event_count'] === 1 + && !str_contains(json_encode($inspection, JSON_THROW_ON_ERROR), + 'entitlement:') + && CloudTrafficLedgerEvent::count() === $beforeLedger + && (int) $afterInspect->version === (int) $beforePool->version, + 'Inspect changed accounting state or leaked user/instance identity.'); + +$missingResolutionUuid = '99999999-9999-4999-8999-999999999999'; +[$status, $missingResolution] = $run([ + 'inspect-resolution', + '--resolution-key=' . $missingResolutionUuid, +]); +$assert($status === 0 && $missingResolution['committed'] === false + && $missingResolution['resolution_key'] === $missingResolutionUuid, + 'A missing resolution UUID was not reported read-only.'); + +$unfixedUuid = '11111111-1111-4111-8111-111111111111'; +$unfixedConfirm = 'RESOLVE_TRAFFIC_POOL:' . $poolId . ':' + . (int) $beforePool->version . ':' . $unfixedUuid; +try { + $run([ + 'resolve', '--pool-id=' . $poolId, + '--expected-version=' . (int) $beforePool->version, + '--resolution-key=' . $unfixedUuid, '--apply', + '--confirm=' . $unfixedConfirm, + ]); + throw new RuntimeException('Unfixed counter regression was resolved.'); +} catch (CloudError $error) { + $assert($error->httpStatus === 409 + && CloudTrafficLedgerEvent::where( + 'event_type', 'attention_resolved' + )->count() === 0, + 'Unfixed attention changed the immutable ledger.'); +} + +$instance->lifetime_download_bytes = 125; +$instance->traffic_synced_at = $now + 3; +$instance->save(); +$resolvedUuid = '22222222-2222-4222-8222-222222222222'; +$version = (int) CloudTrafficPool::findOrFail($poolId)->version; +$confirm = 'RESOLVE_TRAFFIC_POOL:' . $poolId . ':' . $version . ':' + . $resolvedUuid; +[$status, $resolved] = $run([ + 'resolve', '--pool-id=' . $poolId, + '--expected-version=' . $version, + '--resolution-key=' . $resolvedUuid, '--apply', + '--confirm=' . $confirm, +]); +$assert($status === 0 && $resolved['state'] === 'available' + && $resolved['before_version'] === $version + && $resolved['after_version'] > $version + && CloudTrafficLedgerEvent::where( + 'event_key', 'attention-resolution:' . $resolvedUuid + )->count() === 1, + 'Verified CLI recovery did not create one audited resolution generation.'); + +[$status, $resolutionInspection] = $run([ + 'inspect-resolution', '--resolution-key=' . $resolvedUuid, +]); +$assert($status === 0 && $resolutionInspection['committed'] === true + && $resolutionInspection['pool_id'] === $poolId + && $resolutionInspection['expected_version'] === $version + && $resolutionInspection['current_pool_state'] === 'available', + 'A lost resolve response cannot be reconciled by immutable UUID.'); + +$resolvedCount = CloudTrafficLedgerEvent::where( + 'event_type', 'attention_resolved' +)->count(); +try { + $run([ + 'resolve', '--pool-id=' . $poolId, + '--expected-version=' . $version, + '--resolution-key=' . $resolvedUuid, '--apply', + '--confirm=' . $confirm, + ]); + throw new RuntimeException('A used resolution key was accepted again.'); +} catch (RuntimeException $error) { + $assert(str_contains($error->getMessage(), 'resolution-key 已使用') + && str_contains($error->getMessage(), 'inspect-resolution') + && CloudTrafficLedgerEvent::where( + 'event_type', 'attention_resolved' + )->count() === $resolvedCount, + 'Repeated recovery wrote another resolution event.'); +} + +[$secondInstance, $secondAttention] = $makeAttention(12, 102, 8, 2); +$secondPoolId = (int) $secondAttention['pool_id']; +$secondVersion = (int) $secondAttention['version']; +$crossConfirm = 'RESOLVE_TRAFFIC_POOL:' . $secondPoolId . ':' + . $secondVersion . ':' . $resolvedUuid; +try { + $run([ + 'resolve', '--pool-id=' . $secondPoolId, + '--expected-version=' . $secondVersion, + '--resolution-key=' . $resolvedUuid, '--apply', + '--confirm=' . $crossConfirm, + ]); + throw new RuntimeException('A cross-pool resolution UUID was reused.'); +} catch (RuntimeException $error) { + $assert(str_contains($error->getMessage(), 'resolution-key 已使用') + && str_contains($error->getMessage(), 'inspect-resolution') + && (string) CloudTrafficPool::findOrFail($secondPoolId)->state + === 'attention', + 'Cross-pool key reuse changed the second pool.'); +} + +$secondInstance->lifetime_download_bytes = 125; +$secondInstance->traffic_synced_at = $now + 3; +$secondInstance->save(); +$beforeCrossPoolConflict = CloudTrafficPool::findOrFail($secondPoolId); +try { + CloudTrafficPoolAccounting::resolveAttention( + $secondPoolId, + (int) $beforeCrossPoolConflict->version, + $resolvedUuid, + $now + 3 + ); + throw new RuntimeException('Core accounting reused a resolution UUID.'); +} catch (RuntimeException $error) { + $assert(str_contains( + $error->getMessage(), + 'traffic_event_idempotency_conflict' + ) + && (string) CloudTrafficPool::findOrFail($secondPoolId)->state + === 'attention' + && CloudTrafficLedgerEvent::where( + 'event_type', 'attention_resolved' + )->count() === $resolvedCount, + 'Global resolution UUID conflict did not roll back atomically.'); +} + +$secondPool = CloudTrafficPool::findOrFail($secondPoolId); +$staleUuid = '33333333-3333-4333-8333-333333333333'; +$staleVersion = max(1, (int) $secondPool->version - 1); +$staleConfirm = 'RESOLVE_TRAFFIC_POOL:' . $secondPoolId . ':' + . $staleVersion . ':' . $staleUuid; +try { + $run([ + 'resolve', '--pool-id=' . $secondPoolId, + '--expected-version=' . $staleVersion, + '--resolution-key=' . $staleUuid, '--apply', + '--confirm=' . $staleConfirm, + ]); + throw new RuntimeException('A stale pool version was accepted.'); +} catch (CloudError $error) { + $assert($error->httpStatus === 409 + && (string) CloudTrafficPool::findOrFail($secondPoolId)->state + === 'attention', + 'Stale-version recovery changed the pool.'); +} + +echo "Cloud traffic-pool attention CLI integration checks passed.\n";