From 3beb24fff8c141a09d79917b39a74697c97753b9 Mon Sep 17 00:00:00 2001 From: codex Date: Sun, 1 Nov 2026 00:17:52 +0800 Subject: [PATCH] feat(traffic): add administrator rollout controls --- web/app/Command/CloudSetup.php | 5 +- .../CloudAdminTrafficPoolController.php | 76 ++ web/app/Models/CloudTrafficPoolGroup.php | 1 + .../Cloud/CloudAdminTrafficPoolService.php | 741 ++++++++++++++++++ web/app/Services/Cloud/CloudJobService.php | 9 + .../Cloud/CloudTrafficPoolPeriodBinding.php | 21 +- web/config/routes_cloud.php | 11 + web/sql/cloud.sql | 1 + .../CloudAdminTrafficPoolContractTest.php | 87 ++ .../CloudAdminTrafficPoolServiceTest.php | 613 +++++++++++++++ web/tests/CloudFreshSchemaContractTest.php | 2 +- .../CloudRescueCatalogSchemaContractTest.php | 2 +- .../CloudTemplateImportIntentContractTest.php | 2 +- .../CloudTrafficPoolPeriodBindingTest.php | 34 +- .../CloudTrafficPoolSchemaContractTest.php | 4 +- web/tests/CloudVpcSchemaContractTest.php | 2 +- 16 files changed, 1598 insertions(+), 13 deletions(-) create mode 100644 web/app/Controllers/CloudAdminTrafficPoolController.php create mode 100644 web/app/Services/Cloud/CloudAdminTrafficPoolService.php create mode 100644 web/tests/CloudAdminTrafficPoolContractTest.php create mode 100644 web/tests/CloudAdminTrafficPoolServiceTest.php diff --git a/web/app/Command/CloudSetup.php b/web/app/Command/CloudSetup.php index 7548bc9e..1966b117 100644 --- a/web/app/Command/CloudSetup.php +++ b/web/app/Command/CloudSetup.php @@ -8,7 +8,7 @@ use App\Services\Config; /** Initializes only the clean-break PHP business and Agent log schemas. */ final class CloudSetup { - private const SCHEMA_VERSION = 'go-agent-wss-v22-network-policy'; + private const SCHEMA_VERSION = 'go-agent-wss-v23-traffic-admin'; private const MAIN_TABLES = [ 'cloud_regions', 'cloud_traffic_pool_groups', 'cloud_network_lines', 'cloud_resource_pools', @@ -57,7 +57,8 @@ final class CloudSetup ]; private const REQUIRED_MAIN_COLUMNS = [ 'cloud_traffic_pool_groups' => [ - 'id', 'code', 'name', 'mode', 'created_at', 'updated_at', + 'id', 'code', 'name', 'mode', 'revision', 'created_at', + 'updated_at', ], 'cloud_network_lines' => [ 'id', 'region_id', 'traffic_pool_group_id', 'code', 'name', diff --git a/web/app/Controllers/CloudAdminTrafficPoolController.php b/web/app/Controllers/CloudAdminTrafficPoolController.php new file mode 100644 index 00000000..e9012456 --- /dev/null +++ b/web/app/Controllers/CloudAdminTrafficPoolController.php @@ -0,0 +1,76 @@ +getAttribute('cloud_actor') + ?? CloudAccess::actor(false); + if (!($actor['is_admin'] ?? false)) { + throw new CloudError('需要管理员权限', 403); + } + if ($write) { + CloudAccess::manage($actor); + } + return $actor; + } + + private function json($response, array $payload, int $status = 200) + { + return $response->withJson($payload, $status) + ->withHeader('Cache-Control', 'private, no-store'); + } + + public function groups($request, $response, $args = []) + { + $method = strtoupper((string) $request->getMethod()); + $write = $method !== 'GET'; + $this->actor($request, $write); + $groupId = isset($args['id']) ? (int) $args['id'] : null; + if (!$write) { + return $this->json($response, $groupId === null + ? CloudAdminTrafficPoolService::page( + $request->getQueryParams() + ) + : CloudAdminTrafficPoolService::read($groupId)); + } + $body = CloudInput::object($request); + if ($groupId === null) { + CloudInput::only($body, ['code', 'name']); + return $this->json($response, + CloudAdminTrafficPoolService::create($body), 201); + } + CloudInput::only($body, ['name', 'mode', 'expected_revision']); + return $this->json($response, + CloudAdminTrafficPoolService::update($groupId, $body)); + } + + public function lines($request, $response, $args) + { + $this->actor($request, true); + $body = CloudInput::object($request); + CloudInput::only($body, ['line_ids', 'expected_revision']); + return $this->json($response, + CloudAdminTrafficPoolService::replaceLines( + (int) ($args['id'] ?? 0), + $body + )); + } + + public function readiness($request, $response, $args) + { + $this->actor($request, false); + return $this->json($response, + CloudAdminTrafficPoolService::readiness( + (int) ($args['id'] ?? 0) + )); + } +} diff --git a/web/app/Models/CloudTrafficPoolGroup.php b/web/app/Models/CloudTrafficPoolGroup.php index ce4a47c9..b2e75ffd 100644 --- a/web/app/Models/CloudTrafficPoolGroup.php +++ b/web/app/Models/CloudTrafficPoolGroup.php @@ -9,6 +9,7 @@ final class CloudTrafficPoolGroup extends Model protected $casts = [ 'id' => 'int', + 'revision' => 'int', 'created_at' => 'int', 'updated_at' => 'int', ]; diff --git a/web/app/Services/Cloud/CloudAdminTrafficPoolService.php b/web/app/Services/Cloud/CloudAdminTrafficPoolService.php new file mode 100644 index 00000000..f46d84b9 --- /dev/null +++ b/web/app/Services/Cloud/CloudAdminTrafficPoolService.php @@ -0,0 +1,741 @@ +get() as $group) { + $items[] = self::groupDto($group); + } + return [ + 'items' => $items, + 'lines' => self::lineCatalog(), + 'sample_freshness_seconds' => self::SAMPLE_FRESHNESS_SECONDS, + 'generated_at' => time(), + ]; + } + + public static function read(int $groupId): array + { + return ['item' => self::groupDto(self::findGroup($groupId))]; + } + + public static function create(array $input): array + { + $code = self::code($input['code'] ?? null); + $name = self::name($input['name'] ?? null); + $connection = (new CloudTrafficPoolGroup())->getConnection(); + try { + $groupId = $connection->transaction(function () use ( + $code, + $name + ): int { + if (CloudTrafficPoolGroup::where('code', $code)->exists()) { + throw new CloudError('流量池分组标识已存在', 409); + } + $now = time(); + $group = new CloudTrafficPoolGroup(); + $group->code = $code; + $group->name = $name; + $group->mode = 'disabled'; + $group->revision = 1; + $group->created_at = $now; + $group->updated_at = $now; + $group->save(); + return (int) $group->id; + }, 3); + } catch (QueryException $error) { + if (CloudTrafficPoolGroup::where('code', $code)->exists()) { + throw new CloudError('流量池分组标识已存在', 409); + } + throw $error; + } + return self::read($groupId); + } + + public static function update(int $groupId, array $input): array + { + $expectedRevision = self::revision( + $input['expected_revision'] ?? null + ); + $hint = self::findGroup($groupId); + $savedId = $hint->getConnection()->transaction(function () use ( + $groupId, + $input, + $expectedRevision + ): int { + $group = CloudTrafficPoolGroup::where('id', $groupId) + ->lockForUpdate()->first(); + if ($group === null) { + throw new CloudError('流量池分组不存在', 404); + } + self::assertRevision($group, $expectedRevision); + $name = array_key_exists('name', $input) + ? self::name($input['name']) : (string) $group->name; + $mode = array_key_exists('mode', $input) + ? self::mode($input['mode']) : (string) $group->mode; + self::assertModeTransition($group, $mode); + $group->name = $name; + $group->mode = $mode; + $group->revision = (int) $group->revision + 1; + $group->updated_at = time(); + $group->save(); + return (int) $group->id; + }, 3); + return self::read($savedId); + } + + public static function replaceLines(int $groupId, array $input): array + { + $requested = self::lineIds($input['line_ids'] ?? null); + $expectedRevision = self::revision( + $input['expected_revision'] ?? null + ); + $hint = self::findGroup($groupId); + $savedId = $hint->getConnection()->transaction(function () use ( + $groupId, + $requested, + $expectedRevision + ): int { + // Mapping is rare administrator work. Locking the complete line + // catalog provides one deterministic line(id ASC) -> group seam + // shared by purchases and concurrent group mappings. + $lines = CloudNetworkLine::where('id', '>', 0) + ->orderBy('id')->lockForUpdate()->get(); + $group = CloudTrafficPoolGroup::where('id', $groupId) + ->lockForUpdate()->first(); + if ($group === null) { + throw new CloudError('流量池分组不存在', 404); + } + self::assertRevision($group, $expectedRevision); + if ((string) $group->mode !== 'disabled') { + throw new CloudError( + '只有停用状态的流量池分组可以调整线路映射', + 409 + ); + } + $byId = []; + foreach ($lines as $line) { + $byId[(int) $line->id] = $line; + } + foreach ($requested as $lineId) { + if (!isset($byId[$lineId])) { + throw new CloudError('所选线路不存在', 404); + } + $owner = $byId[$lineId]->traffic_pool_group_id; + if ($owner !== null && (int) $owner !== $groupId) { + throw new CloudError('所选线路已属于其他流量池分组', 409); + } + } + $removed = []; + foreach ($byId as $lineId => $line) { + if ((int) ($line->traffic_pool_group_id ?? 0) === $groupId + && !in_array($lineId, $requested, true)) { + $removed[] = $lineId; + } + } + self::assertLinesMayLeave($groupId, $removed); + $now = time(); + if ($removed !== []) { + CloudNetworkLine::whereIn('id', $removed)->update([ + 'traffic_pool_group_id' => null, + 'updated_at' => $now, + ]); + } + if ($requested !== []) { + CloudNetworkLine::whereIn('id', $requested)->update([ + 'traffic_pool_group_id' => $groupId, + 'updated_at' => $now, + ]); + } + $group->revision = (int) $group->revision + 1; + $group->updated_at = $now; + $group->save(); + return (int) $group->id; + }, 3); + return self::read($savedId); + } + + public static function readiness( + int $groupId, + ?int $now = null + ): array { + return self::buildReadiness(self::findGroup($groupId), $now ?? time()); + } + + private static function assertModeTransition( + CloudTrafficPoolGroup $group, + string $target + ): void { + $current = (string) $group->mode; + if ($target === $current) { + return; + } + if ($current === 'enforced') { + throw new CloudError( + '已强制执行的共享流量池禁止回退或停用', + 409 + ); + } + if ($current === 'disabled' && $target === 'shadow') { + if (!CloudNetworkLine::where( + 'traffic_pool_group_id', (int) $group->id + )->exists()) { + throw new CloudError('进入影子核算前必须至少绑定一条线路', 409); + } + return; + } + if ($current === 'shadow' && $target === 'disabled') { + if (self::hasDurableReferences((int) $group->id)) { + throw new CloudError( + '流量池已生成冻结周期或账本投影,禁止停用', + 409 + ); + } + return; + } + if ($current === 'shadow' && $target === 'enforced') { + $readiness = self::buildReadiness($group, time()); + if (!$readiness['ready']) { + throw new CloudError( + '流量池尚未就绪:' . implode(',', array_column( + $readiness['blockers'], + 'code' + )), + 409 + ); + } + return; + } + throw new CloudError( + '流量池必须按停用、影子核算、强制执行顺序启用', + 409 + ); + } + + private static function buildReadiness( + CloudTrafficPoolGroup $group, + int $now + ): array { + $groupId = (int) $group->id; + $blockers = []; + $lineIds = CloudNetworkLine::where( + 'traffic_pool_group_id', $groupId + )->orderBy('id')->pluck('id')->map( + static fn ($id): int => (int) $id + )->all(); + $lineCount = count($lineIds); + if ($lineCount === 0) { + self::block($blockers, 'no_network_lines'); + } + $resourcePoolIds = $lineIds === [] ? [] + : CloudResourcePool::whereIn('line_id', $lineIds) + ->pluck('id')->map(static fn ($id): int => (int) $id)->all(); + if ($resourcePoolIds !== []) { + $orders = CloudOrder::whereIn( + 'resource_pool_id', $resourcePoolIds + )->whereIn('status', ['awaiting_payment', 'queued', 'failed']) + ->orderBy('id')->get(['id', 'status', 'spec_json']); + $failedOrderIds = $orders->filter( + static fn ($order): bool => + (string) $order->status === 'failed' + )->pluck('id')->map(static fn ($id): int => (int) $id)->all(); + $recoverableFailed = $failedOrderIds === [] ? [] + : CloudJobService::blockingCreateQueryForOrders( + $failedOrderIds + )->pluck('order_id')->map( + static fn ($id): int => (int) $id + )->flip()->all(); + foreach ($orders as $order) { + if ((string) $order->status === 'failed' + && !isset($recoverableFailed[(int) $order->id])) { + continue; + } + $spec = json_decode((string) $order->spec_json, true); + if (!is_array($spec) + || !is_int($spec['traffic_pool_group_id'] ?? null) + || $spec['traffic_pool_group_id'] !== $groupId) { + self::block( + $blockers, + 'line_frozen_identity_mismatch', + (int) $order->id + ); + } + } + $mismatchedPeriods = CloudServicePeriod::query() + ->join('cloud_instances as readiness_instance', + 'readiness_instance.id', '=', + 'cloud_service_periods.instance_id') + ->whereIn('readiness_instance.resource_pool_id', + $resourcePoolIds) + ->where('cloud_service_periods.traffic_quota_mode', 'finite') + ->whereIn('cloud_service_periods.status', + ['scheduled', 'active', 'exhausted']) + ->where(function ($query) use ($groupId): void { + $query->whereNull( + 'cloud_service_periods.traffic_pool_group_id' + )->orWhere( + 'cloud_service_periods.traffic_pool_group_id', + '<>', + $groupId + ); + })->orderBy('cloud_service_periods.id') + ->get(['cloud_service_periods.id']); + foreach ($mismatchedPeriods as $period) { + self::block( + $blockers, + 'line_frozen_identity_mismatch', + (int) $period->id + ); + } + } + + $periods = CloudServicePeriod::where( + 'traffic_pool_group_id', $groupId + )->where('traffic_quota_mode', 'finite')->whereIn( + 'status', ['scheduled', 'active', 'exhausted'] + )->orderBy('id')->get(); + $scanPeriodIds = CloudServicePeriod::where( + 'traffic_pool_group_id', $groupId + )->orderBy('id')->pluck('id')->map( + static fn ($id): int => (int) $id + )->all(); + $periodIds = []; + $instanceIds = []; + $activePeriods = []; + $expectedPoolByInstance = []; + $poolById = []; + foreach (CloudTrafficPool::where( + 'traffic_pool_group_id', $groupId + )->orderBy('id')->get() as $pool) { + $poolById[(int) $pool->id] = $pool; + if ((string) $pool->state === 'attention') { + self::block($blockers, 'pool_attention', (int) $pool->id); + } + try { + $verification = CloudTrafficPoolAccounting::verifyProjection( + (int) $pool->id, + $now + ); + if (!($verification['valid'] ?? false)) { + self::block( + $blockers, + 'projection_invalid', + (int) $pool->id + ); + } + } catch (\Throwable) { + self::block( + $blockers, + 'projection_invalid', + (int) $pool->id + ); + } + } + + foreach ($periods as $period) { + $periodId = (int) $period->id; + $instanceId = (int) $period->instance_id; + $periodIds[] = $periodId; + $instanceIds[$instanceId] = true; + $entitlement = CloudTrafficEntitlement::where( + 'service_period_id', $periodId + )->first(); + if ($entitlement === null) { + self::block($blockers, 'missing_entitlements', $periodId); + } else { + $pool = $poolById[(int) $entitlement->pool_id] ?? null; + $identityMatches = $pool !== null + && (int) $pool->user_id === (int) $period->user_id + && (int) $entitlement->user_id === (int) $period->user_id + && (int) $entitlement->instance_id === $instanceId + && (int) $entitlement->starts_at + === (int) $period->starts_at + && (int) $entitlement->ends_at === (int) $period->ends_at + && (string) $entitlement->quota_mode === 'finite' + && (int) $entitlement->granted_bytes + === (int) $period->traffic_quota_bytes; + $stateMatches = (string) $period->status === 'scheduled' + ? ((string) $entitlement->state === 'scheduled' + && (int) $period->starts_at > $now) + : (in_array((string) $entitlement->state, + ['active', 'exhausted'], true) + && (int) $period->starts_at <= $now + && (int) $period->ends_at > $now); + if ($pool === null) { + self::block($blockers, 'missing_pools', $periodId); + } elseif (!$identityMatches || !$stateMatches) { + self::block( + $blockers, + 'period_identity_mismatch', + $periodId + ); + } else { + $expectedPoolByInstance[$instanceId] = (int) $pool->id; + } + } + if (in_array((string) $period->status, + ['active', 'exhausted'], true) + && (int) $period->starts_at <= $now + && (int) $period->ends_at > $now) { + $activePeriods[$instanceId] = $period; + } + } + + foreach ($poolById as $poolId => $pool) { + if ((string) $pool->state === 'attention') { + continue; + } + $activeFinite = CloudTrafficEntitlement::where( + 'pool_id', $poolId + )->where('quota_mode', 'finite')->whereIn( + 'state', ['active', 'exhausted'] + )->where('starts_at', '<=', $now)->where('ends_at', '>', $now) + ->count(); + $expectedState = (int) $pool->overage_bytes > 0 + || ($activeFinite > 0 && (int) $pool->available_bytes === 0) + ? 'exhausted' : 'available'; + if ((string) $pool->state !== $expectedState) { + self::block($blockers, 'projection_invalid', $poolId); + } + } + + $cursorByInstance = []; + if ($poolById !== []) { + foreach (CloudTrafficInstanceCursor::whereIn( + 'pool_id', array_keys($poolById) + )->orderBy('instance_id')->get() as $cursor) { + $cursorByInstance[(int) $cursor->instance_id] = $cursor; + $instanceIds[(int) $cursor->instance_id] = true; + } + } + + $instances = []; + if ($instanceIds !== []) { + foreach (CloudInstance::whereIn('id', array_keys($instanceIds)) + ->get() as $instance) { + $instances[(int) $instance->id] = $instance; + } + } + foreach ($cursorByInstance as $instanceId => $cursor) { + $instance = $instances[$instanceId] ?? null; + if ($instance === null) { + self::block($blockers, 'instance_not_ready', $instanceId); + continue; + } + if ((int) $cursor->accounted_download_bytes + !== (int) $instance->lifetime_download_bytes + || (int) $cursor->accounted_upload_bytes + !== (int) $instance->lifetime_upload_bytes + || (int) $cursor->last_observed_at + < (int) $instance->traffic_synced_at) { + self::block($blockers, 'usage_unsettled', $instanceId); + } + } + $staleBefore = $now - self::SAMPLE_FRESHNESS_SECONDS; + foreach ($activePeriods as $instanceId => $period) { + $instance = $instances[$instanceId] ?? null; + if ($instance === null || (string) $instance->status !== 'active') { + self::block($blockers, 'instance_not_ready', $instanceId); + continue; + } + if (!in_array((string) $instance->network_status, [ + 'active', 'blocked_traffic', 'blocked_expired', + ], true)) { + self::block( + $blockers, + 'legacy_network_unsettled', + $instanceId + ); + } + $cursor = $cursorByInstance[$instanceId] ?? null; + $cursorPool = $cursor === null ? null + : ($poolById[(int) $cursor->pool_id] ?? null); + if ($cursor !== null && (string) $cursor->state === 'attention') { + self::block($blockers, 'cursor_attention', $instanceId); + } elseif ($cursor === null || $cursorPool === null + || !isset($expectedPoolByInstance[$instanceId]) + || (int) $cursor->pool_id + !== $expectedPoolByInstance[$instanceId] + || (int) $cursor->user_id !== (int) $period->user_id + || (int) $cursorPool->user_id !== (int) $period->user_id) { + self::block($blockers, 'cursor_missing', $instanceId); + } + if ((int) $instance->traffic_synced_at < $staleBefore + || $cursor === null + || (int) $cursor->last_observed_at < $staleBefore) { + self::block( + $blockers, + 'traffic_sample_stale', + $instanceId + ); + } + } + + if ($scanPeriodIds !== []) { + foreach (CloudTrafficScanFailure::where('scan_kind', 'period') + ->whereIn('subject_id', $scanPeriodIds)->get() as $failure) { + self::block( + $blockers, + 'traffic_scan_failures', + (int) $failure->subject_id + ); + } + } + $ids = array_keys($instanceIds); + if ($ids !== []) { + foreach (CloudTrafficScanFailure::where('scan_kind', 'instance') + ->whereIn('subject_id', $ids)->get() as $failure) { + self::block( + $blockers, + 'traffic_scan_failures', + (int) $failure->subject_id + ); + } + foreach (CloudInstanceNetworkPolicyState::whereIn( + 'instance_id', $ids + )->where('state', '<>', 'applied')->get() as $state) { + self::block( + $blockers, + 'policy_unsettled', + (int) $state->instance_id + ); + } + foreach (CloudInstanceNetworkRestriction::whereIn( + 'instance_id', $ids + )->where('reason_code', 'traffic_pool_exhausted') + ->where('desired_active', 1)->get() as $restriction) { + self::block( + $blockers, + 'traffic_restriction_present', + (int) $restriction->instance_id + ); + } + if (CloudJobService::blockingQueryForInstances($ids) + ->whereIn('kind', ['network_suspend', 'network_resume']) + ->exists()) { + self::block($blockers, 'network_job_unsettled'); + } + } + + ksort($blockers, SORT_STRING); + $list = []; + foreach ($blockers as $code => $subjects) { + $subjectIds = array_keys($subjects); + sort($subjectIds, SORT_NUMERIC); + $list[] = [ + 'code' => $code, + 'count' => count($subjectIds), + 'subject_ids' => array_slice($subjectIds, 0, 20), + ]; + } + return [ + 'ready' => $list === [], + 'can_enforce' => (string) $group->mode === 'shadow' + && $list === [], + 'checked_at' => $now, + 'sample_freshness_seconds' => self::SAMPLE_FRESHNESS_SECONDS, + 'line_count' => $lineCount, + 'pool_count' => count($poolById), + 'period_count' => count($periodIds), + 'active_instance_count' => count($activePeriods), + 'blockers' => $list, + ]; + } + + private static function groupDto(CloudTrafficPoolGroup $group): array + { + $lineIds = CloudNetworkLine::where( + 'traffic_pool_group_id', (int) $group->id + )->orderBy('id')->pluck('id')->map( + static fn ($id): int => (int) $id + )->all(); + $readiness = self::buildReadiness($group, time()); + $nextMode = match ((string) $group->mode) { + 'disabled' => 'shadow', + 'shadow' => 'enforced', + default => null, + }; + return [ + 'id' => (int) $group->id, + 'code' => (string) $group->code, + 'name' => (string) $group->name, + 'mode' => (string) $group->mode, + 'revision' => (int) $group->revision, + 'line_ids' => $lineIds, + 'line_count' => count($lineIds), + 'readiness' => $readiness, + 'actions' => [ + 'can_rename' => true, + 'can_replace_lines' => (string) $group->mode === 'disabled', + 'next_mode' => $nextMode, + 'can_advance' => $nextMode === 'shadow' + ? count($lineIds) > 0 + : ($nextMode === 'enforced' + && $readiness['ready']), + 'can_disable' => (string) $group->mode === 'shadow' + && !self::hasDurableReferences((int) $group->id), + ], + 'created_at' => (int) $group->created_at, + 'updated_at' => (int) $group->updated_at, + ]; + } + + private static function lineCatalog(): array + { + $items = []; + foreach (CloudNetworkLine::orderBy('region_id')->orderBy('sort') + ->orderBy('id')->get() as $line) { + $items[] = [ + 'id' => (int) $line->id, + 'region_id' => (int) $line->region_id, + 'code' => (string) $line->code, + 'name' => (string) $line->name, + 'status' => (string) $line->status, + 'traffic_pool_group_id' => + $line->traffic_pool_group_id === null + ? null : (int) $line->traffic_pool_group_id, + ]; + } + return $items; + } + + private static function hasDurableReferences(int $groupId): bool + { + return CloudServicePeriod::where( + 'traffic_pool_group_id', $groupId + )->exists() || CloudTrafficPool::where( + 'traffic_pool_group_id', $groupId + )->exists(); + } + + private static function assertLinesMayLeave( + int $groupId, + array $lineIds + ): void { + if ($lineIds === []) { + return; + } + if (self::hasDurableReferences($groupId)) { + throw new CloudError( + '流量池已生成冻结周期或账本投影,禁止移出线路', + 409 + ); + } + $poolIds = CloudResourcePool::whereIn('line_id', $lineIds) + ->pluck('id')->all(); + if ($poolIds !== [] && (CloudOrder::whereIn( + 'resource_pool_id', $poolIds + )->exists() || CloudInstance::whereIn( + 'resource_pool_id', $poolIds + )->exists())) { + throw new CloudError( + '已有订单或实例冻结了所选线路,禁止移出流量池分组', + 409 + ); + } + } + + private static function findGroup(int $groupId): CloudTrafficPoolGroup + { + $group = $groupId > 0 ? CloudTrafficPoolGroup::find($groupId) : null; + if ($group === null) { + throw new CloudError('流量池分组不存在', 404); + } + return $group; + } + + private static function assertRevision( + CloudTrafficPoolGroup $group, + int $expected + ): void { + if ((int) $group->revision !== $expected) { + throw new CloudError('流量池分组已被其他管理员修改,请刷新后重试', 409); + } + } + + private static function code(mixed $value): string + { + if (!is_string($value)) { + throw new CloudError('流量池分组标识无效'); + } + $value = strtolower(trim($value)); + if (preg_match('/^[a-z][a-z0-9_-]{1,63}$/D', $value) !== 1) { + throw new CloudError('流量池分组标识须为 2 至 64 位小写字母、数字、下划线或短横线'); + } + return $value; + } + + private static function name(mixed $value): string + { + if (!is_string($value) || ($value = trim($value)) === '' + || mb_strlen($value) > 80) { + throw new CloudError('流量池分组名称无效'); + } + return $value; + } + + private static function mode(mixed $value): string + { + if (!is_string($value) || !in_array($value, self::MODES, true)) { + throw new CloudError('流量池分组模式无效'); + } + return $value; + } + + private static function revision(mixed $value): int + { + if (!is_int($value) || $value < 1) { + throw new CloudError('流量池分组版本无效'); + } + return $value; + } + + /** @return list */ + private static function lineIds(mixed $value): array + { + if (!is_array($value) || !array_is_list($value) + || count($value) > 1000) { + throw new CloudError('线路列表无效'); + } + $ids = []; + foreach ($value as $lineId) { + if (!is_int($lineId) || $lineId < 1) { + throw new CloudError('线路列表无效'); + } + $ids[$lineId] = true; + } + $ids = array_keys($ids); + sort($ids, SORT_NUMERIC); + return $ids; + } + + private static function block( + array &$blockers, + string $code, + int $subjectId = 0 + ): void { + $blockers[$code][$subjectId] = true; + } +} diff --git a/web/app/Services/Cloud/CloudJobService.php b/web/app/Services/Cloud/CloudJobService.php index d6826e0e..883761fe 100644 --- a/web/app/Services/Cloud/CloudJobService.php +++ b/web/app/Services/Cloud/CloudJobService.php @@ -515,6 +515,15 @@ final class CloudJobService return $query; } + /** @param list $orderIds */ + public static function blockingCreateQueryForOrders(array $orderIds) + { + $query = CloudJob::whereIn('order_id', $orderIds) + ->where('kind', 'create'); + self::applyBlockingInstanceState($query); + return $query; + } + /** * Serialize host-global VPC route mutations before Agent admission. * Independent VM-port jobs remain concurrent. A terminal route with an diff --git a/web/app/Services/Cloud/CloudTrafficPoolPeriodBinding.php b/web/app/Services/Cloud/CloudTrafficPoolPeriodBinding.php index 397a5c09..5af1633e 100644 --- a/web/app/Services/Cloud/CloudTrafficPoolPeriodBinding.php +++ b/web/app/Services/Cloud/CloudTrafficPoolPeriodBinding.php @@ -26,12 +26,25 @@ final class CloudTrafficPoolPeriodBinding if ((int) $resourcePool->line_id !== (int) $line->id) { throw new CloudError('资源池与线路配置不一致', 409); } + // Administrator mapping and order snapshots share one catalog lock + // order: network line first, then its current traffic-pool group. + // Re-reading the line under lock prevents a NULL -> group mapping from + // racing an order that was built from a stale model instance. + $lockedLine = CloudNetworkLine::where('id', (int) $line->id) + ->lockForUpdate()->first(); + if ($lockedLine === null + || (int) $resourcePool->line_id !== (int) $lockedLine->id) { + throw new CloudError('资源池与线路配置不一致', 409); + } $groupId = self::nullableGroupId( - $line->traffic_pool_group_id ?? null + $lockedLine->traffic_pool_group_id ?? null ); - if ($groupId !== null - && CloudTrafficPoolGroup::find($groupId) === null) { - throw new CloudError('线路绑定的流量池分组不存在', 409); + if ($groupId !== null) { + $group = CloudTrafficPoolGroup::where('id', $groupId) + ->lockForUpdate()->first(); + if ($group === null) { + throw new CloudError('线路绑定的流量池分组不存在', 409); + } } return [ 'traffic_pool_group_id' => $groupId, diff --git a/web/config/routes_cloud.php b/web/config/routes_cloud.php index deeb6871..e26392f8 100644 --- a/web/config/routes_cloud.php +++ b/web/config/routes_cloud.php @@ -153,6 +153,17 @@ $app->group('/api/v1', function () { $this->get('/admin/billing/payments', 'App\Controllers\CloudAdminBillingController:payments'); $this->get('/admin/resources', 'App\Controllers\CloudAdminResourceController:resources'); + $this->map(['GET', 'POST'], '/admin/traffic-pool-groups', + 'App\Controllers\CloudAdminTrafficPoolController:groups'); + $this->map(['GET', 'PATCH'], + '/admin/traffic-pool-groups/{id:[1-9][0-9]*}', + 'App\Controllers\CloudAdminTrafficPoolController:groups'); + $this->put('/admin/traffic-pool-groups/{id:[1-9][0-9]*}/lines', + 'App\Controllers\CloudAdminTrafficPoolController:lines'); + $this->get( + '/admin/traffic-pool-groups/{id:[1-9][0-9]*}/readiness', + 'App\Controllers\CloudAdminTrafficPoolController:readiness' + ); $this->get('/admin/vpc-control', 'App\Controllers\CloudAdminVpcController:control'); $this->get('/admin/vpc-control/vpcs', diff --git a/web/sql/cloud.sql b/web/sql/cloud.sql index 29a73180..fe71218b 100644 --- a/web/sql/cloud.sql +++ b/web/sql/cloud.sql @@ -25,6 +25,7 @@ CREATE TABLE cloud_traffic_pool_groups ( code VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, name VARCHAR(80) NOT NULL, mode VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'disabled', + revision BIGINT UNSIGNED NOT NULL DEFAULT 1, created_at BIGINT UNSIGNED NOT NULL, updated_at BIGINT UNSIGNED NOT NULL, UNIQUE KEY cloud_traffic_pool_group_code (code), diff --git a/web/tests/CloudAdminTrafficPoolContractTest.php b/web/tests/CloudAdminTrafficPoolContractTest.php new file mode 100644 index 00000000..4ee012ff --- /dev/null +++ b/web/tests/CloudAdminTrafficPoolContractTest.php @@ -0,0 +1,87 @@ += 3, + 'Administrator traffic-pool routes are incomplete.'); +$assert(!preg_match( + "/delete\([^\n]*traffic-pool-groups|map\(\[[^\]]*DELETE[^\]]*\][^\n]*traffic-pool-groups/i", + $routes + ), + 'Traffic-pool groups must not expose a destructive delete route.'); + +$assert(str_contains($controller, 'CloudAccess::manage($actor)') + && str_contains($controller, "'Cache-Control', 'private, no-store'") + && str_contains($controller, "CloudInput::only(\$body") + && str_contains($controller, "['code', 'name']") + && str_contains($controller, "['name', 'mode', 'expected_revision']") + && str_contains($controller, "['line_ids', 'expected_revision']"), + 'Administrator traffic-pool writes are not permissioned or allow-listed.'); + +foreach (['page', 'create', 'update', 'replaceLines', 'readiness'] as $method) { + $assert(str_contains($service, + 'public static function ' . $method . '('), + 'Missing administrator traffic-pool service method: ' . $method); +} +$assert(str_contains($service, "'disabled'") + && str_contains($service, "'shadow'") + && str_contains($service, "'enforced'") + && preg_match('/enforced.{0,240}(?:cannot|禁止|不允许|409)/s', $service), + 'Traffic-pool mode changes do not visibly enforce the one-way state machine.'); +$assert(str_contains($service, "'ready'") + && str_contains($service, "'blockers'") + && str_contains($service, 'CloudTrafficPoolAccounting::verifyProjection(') + && str_contains($service, 'CloudTrafficScanFailure') + && str_contains($service, 'CloudInstanceNetworkPolicyState') + && str_contains($service, 'CloudJob'), + 'Enforced-mode readiness omits accounting, scan, policy, or job fences.'); + +$lineOrder = strpos($service, "->orderBy('id')"); +$lineLock = $lineOrder === false ? false + : strpos($service, '->lockForUpdate()', $lineOrder); +$groupLock = $lineLock === false ? false + : strpos($service, 'CloudTrafficPoolGroup::where(', $lineLock); +$assert($lineOrder !== false && $lineLock !== false + && $groupLock !== false + && strpos($service, '->lockForUpdate()', $groupLock) !== false, + 'Administrator mappings no longer lock ordered lines before the group.'); +$assert(!preg_match( + '/CloudTrafficPool::[\s\S]{0,180}->lockForUpdate\(\)/', + $service + ), + 'Administrator configuration crossed into the accounting pool lock domain.'); +$assert(str_contains($service, 'traffic_pool_group_id') + && str_contains($service, 'CloudServicePeriod') + && str_contains($service, 'CloudInstanceNetworkRestriction'), + 'Line remapping and mode rollback do not fence frozen period/policy use.'); + +$assert(preg_match( + '/CloudNetworkLine::where\([\s\S]{0,220}->lockForUpdate\(\)[\s\S]{0,400}CloudTrafficPoolGroup::where\([\s\S]{0,220}->lockForUpdate\(\)/', + $binding + ) === 1, + 'Purchase snapshot and administrator mappings lack a shared line-to-group lock.'); + +echo "Cloud administrator traffic-pool contract passed.\n"; diff --git a/web/tests/CloudAdminTrafficPoolServiceTest.php b/web/tests/CloudAdminTrafficPoolServiceTest.php new file mode 100644 index 00000000..cdf4da25 --- /dev/null +++ b/web/tests/CloudAdminTrafficPoolServiceTest.php @@ -0,0 +1,613 @@ +httpStatus === 409, $message . ' Wrong status.'); + return; + } + throw new RuntimeException($message); +}; + +$capsule = new Capsule(); +$capsule->addConnection([ + 'driver' => 'sqlite', + 'database' => ':memory:', +], 'default'); +$capsule->setAsGlobal(); +$capsule->bootEloquent(); +$schema = $capsule->schema('default'); + +$schema->create('cloud_traffic_pool_groups', static function (Blueprint $t): void { + $t->increments('id'); + $t->string('code')->unique(); + $t->string('name'); + $t->string('mode'); + $t->integer('revision')->default(1); + $t->integer('created_at'); + $t->integer('updated_at'); +}); +$schema->create('cloud_network_lines', static function (Blueprint $t): void { + $t->increments('id'); + $t->integer('region_id'); + $t->integer('traffic_pool_group_id')->nullable(); + $t->string('code'); + $t->string('name'); + $t->boolean('is_default')->default(false); + $t->string('status'); + $t->integer('sort')->default(0); + $t->integer('created_at'); + $t->integer('updated_at'); +}); +$schema->create('cloud_resource_pools', static function (Blueprint $t): void { + $t->increments('id'); + $t->integer('line_id'); +}); +$schema->create('cloud_orders', static function (Blueprint $t): void { + $t->increments('id'); + $t->integer('resource_pool_id')->nullable(); + $t->string('status'); + $t->text('spec_json'); +}); +$schema->create('cloud_instances', static function (Blueprint $t): void { + $t->increments('id'); + $t->integer('resource_pool_id')->nullable(); + $t->string('status')->default('active'); + $t->string('network_status')->default('active'); + $t->integer('traffic_synced_at')->default(0); + $t->integer('lifetime_download_bytes')->default(0); + $t->integer('lifetime_upload_bytes')->default(0); +}); +$schema->create('cloud_service_periods', static function (Blueprint $t): void { + $t->increments('id'); + $t->integer('instance_id'); + $t->integer('user_id'); + $t->integer('traffic_pool_group_id')->nullable(); + $t->string('traffic_quota_mode'); + $t->integer('starts_at'); + $t->integer('ends_at'); + $t->integer('traffic_quota_bytes'); + $t->string('status'); +}); +$schema->create('cloud_traffic_pools', static function (Blueprint $t): void { + $t->increments('id'); + $t->integer('user_id'); + $t->integer('traffic_pool_group_id'); + $t->string('state'); + $t->integer('available_bytes')->default(0); + $t->integer('overage_bytes')->default(0); + $t->integer('version')->default(0); + $t->integer('last_sequence')->default(0); + $t->integer('last_event_id')->nullable(); + $t->integer('created_at'); + $t->integer('updated_at'); +}); +$schema->create('cloud_traffic_entitlements', static function (Blueprint $t): void { + $t->increments('id'); + $t->integer('pool_id'); + $t->integer('user_id'); + $t->integer('instance_id'); + $t->integer('service_period_id')->unique(); + $t->integer('starts_at'); + $t->integer('ends_at'); + $t->string('quota_mode'); + $t->integer('granted_bytes'); + $t->integer('consumed_bytes')->default(0); + $t->integer('forfeited_bytes')->default(0); + $t->string('state'); + $t->integer('activated_at')->nullable(); + $t->integer('closed_at')->nullable(); + $t->integer('version')->default(0); + $t->integer('created_at'); + $t->integer('updated_at'); +}); +$schema->create('cloud_traffic_ledger_events', static function (Blueprint $t): void { + $t->increments('id'); + $t->integer('pool_id'); + $t->integer('user_id'); + $t->integer('pool_sequence'); + $t->string('event_key'); + $t->string('event_type'); + $t->string('source_type'); + $t->string('source_id'); + $t->integer('source_revision'); + $t->string('payload_hash'); + $t->integer('instance_id')->nullable(); + $t->integer('service_period_id')->nullable(); + $t->integer('entitlement_id')->nullable(); + $t->integer('amount_bytes'); + $t->integer('effective_at'); + $t->integer('observed_at')->nullable(); + $t->text('payload_json'); + $t->integer('created_at'); +}); +$schema->create('cloud_traffic_instance_cursors', static function (Blueprint $t): void { + $t->integer('instance_id')->primary(); + $t->integer('user_id'); + $t->integer('pool_id'); + $t->integer('accounted_download_bytes')->default(0); + $t->integer('accounted_upload_bytes')->default(0); + $t->integer('last_observed_at')->default(0); + $t->integer('last_event_id')->nullable(); + $t->string('state')->default('ready'); + $t->string('attention_code')->default(''); + $t->integer('version')->default(0); + $t->integer('updated_at'); +}); +$schema->create('cloud_traffic_scan_failures', static function (Blueprint $t): void { + $t->increments('id'); + $t->string('scan_kind'); + $t->integer('subject_id'); + $t->integer('attempt_count')->default(1); + $t->string('last_error_code'); + $t->integer('retry_at'); + $t->integer('first_failed_at'); + $t->integer('last_failed_at'); +}); +$schema->create('cloud_instance_network_policy_states', static function (Blueprint $t): void { + $t->integer('instance_id')->primary(); + $t->integer('user_id'); + $t->boolean('desired_suspended')->default(false); + $t->boolean('applied_suspended')->default(false); + $t->integer('revision')->default(1); + $t->string('state')->default('applied'); + $t->string('operation_id')->nullable(); + $t->integer('created_at'); + $t->integer('updated_at'); +}); +$schema->create('cloud_instance_network_restrictions', static function (Blueprint $t): void { + $t->integer('instance_id'); + $t->integer('user_id'); + $t->string('reason_code'); + $t->boolean('desired_active'); + $t->integer('revision'); + $t->string('source_type'); + $t->string('source_id'); + $t->integer('created_at'); + $t->integer('updated_at'); +}); +$schema->create('cloud_jobs', static function (Blueprint $t): void { + $t->increments('id'); + $t->integer('order_id')->nullable(); + $t->integer('instance_id')->nullable(); + $t->integer('host_id')->nullable(); + $t->string('kind'); + $t->string('operation_id')->nullable(); + $t->string('request_fingerprint')->nullable(); + $t->string('request_idempotency_key')->nullable(); + $t->string('phase'); + $t->string('outcome')->nullable(); + $t->string('status'); + $t->string('error_code')->nullable(); + $t->string('effect_resolution')->default('not_applicable'); + $t->boolean('effect_may_have_applied')->nullable(); + $t->boolean('safe_to_resubmit')->nullable(); + $t->string('execution_mode')->nullable(); + $t->integer('attempts')->nullable(); + $t->integer('dispatch_attempts')->nullable(); + $t->integer('dispatch_deadline_at')->nullable(); + $t->integer('dispatch_started_at')->nullable(); + $t->integer('agent_accepted_at')->nullable(); + $t->integer('dispatched_at')->nullable(); + $t->integer('receipt_deadline_at')->nullable(); + $t->integer('terminal_at')->nullable(); + $t->integer('completion_event_id')->nullable(); + $t->text('result_json')->nullable(); + $t->boolean('finalization_incident')->default(false); + $t->string('finalization_error_code')->nullable(); +}); + +$now = time(); +Capsule::table('cloud_network_lines')->insert([ + ['id' => 1, 'region_id' => 1, 'traffic_pool_group_id' => null, + 'code' => 'premium', 'name' => 'Premium', 'is_default' => 1, + 'status' => 'active', 'sort' => 0, 'created_at' => $now, + 'updated_at' => $now], + ['id' => 2, 'region_id' => 1, 'traffic_pool_group_id' => null, + 'code' => 'standard', 'name' => 'Standard', 'is_default' => 0, + 'status' => 'active', 'sort' => 1, 'created_at' => $now, + 'updated_at' => $now], +]); + +$created = CloudAdminTrafficPoolService::create([ + 'code' => 'premium_pool', + 'name' => 'Premium Pool', +]); +$groupId = (int) $created['item']['id']; +$assert($created['item']['mode'] === 'disabled' + && $created['item']['revision'] === 1, + 'A new traffic-pool group did not start disabled at revision one.'); + +$mapped = CloudAdminTrafficPoolService::replaceLines($groupId, [ + 'line_ids' => [1], + 'expected_revision' => 1, +]); +$assert($mapped['item']['line_ids'] === [1] + && $mapped['item']['revision'] === 2, + 'The line mapping was not saved atomically.'); + +$second = CloudAdminTrafficPoolService::create([ + 'code' => 'standard_pool', + 'name' => 'Standard Pool', +]); +$secondId = (int) $second['item']['id']; +CloudAdminTrafficPoolService::replaceLines($secondId, [ + 'line_ids' => [2], + 'expected_revision' => 1, +]); +$expectConflict( + static fn (): array => CloudAdminTrafficPoolService::replaceLines( + $groupId, + ['line_ids' => [1, 2], 'expected_revision' => 2] + ), + 'A line owned by another group was partially attached.' +); +$assert((int) Capsule::table('cloud_network_lines')->where('id', 1) + ->value('traffic_pool_group_id') === $groupId + && (int) Capsule::table('cloud_network_lines')->where('id', 2) + ->value('traffic_pool_group_id') === $secondId, + 'A failed mapping request left a partial catalog update.'); + +$expectConflict( + static fn (): array => CloudAdminTrafficPoolService::update( + $groupId, + ['name' => 'Stale', 'expected_revision' => 1] + ), + 'A stale administrator revision overwrote the group.' +); +$assert(CloudAdminTrafficPoolService::read($groupId)['item']['name'] + === 'Premium Pool', + 'A stale revision changed the group name.'); + +$shadow = CloudAdminTrafficPoolService::update($groupId, [ + 'mode' => 'shadow', + 'expected_revision' => 2, +]); +$assert($shadow['item']['mode'] === 'shadow' + && $shadow['item']['revision'] === 3, + 'The disabled group did not advance to shadow mode.'); + +Capsule::table('cloud_resource_pools')->insert([ + 'id' => 3, + 'line_id' => 1, +]); +Capsule::table('cloud_orders')->insert([ + 'id' => 4, + 'resource_pool_id' => 3, + 'status' => 'failed', + 'spec_json' => json_encode([ + 'traffic_pool_group_id' => null, + ], JSON_THROW_ON_ERROR), +]); +Capsule::table('cloud_jobs')->insert([ + 'id' => 40, + 'order_id' => 4, + 'instance_id' => null, + 'host_id' => 1, + 'kind' => 'create', + 'operation_id' => str_repeat('c', 32), + 'request_fingerprint' => str_repeat('d', 64), + 'request_idempotency_key' => 'traffic-pool-test-40', + 'phase' => 'terminal', + 'outcome' => 'failed', + 'status' => 'failed', + 'error_code' => 'operation_effect_unknown', + 'effect_resolution' => 'unknown', + 'effect_may_have_applied' => 1, + 'safe_to_resubmit' => 0, + 'execution_mode' => 'agent', + 'attempts' => 1, + 'dispatch_attempts' => 1, + 'dispatch_deadline_at' => $now + 30, + 'dispatch_started_at' => $now - 2, + 'dispatched_at' => $now - 2, + 'receipt_deadline_at' => $now + 28, + 'terminal_at' => $now, + 'finalization_incident' => 0, +]); +$frozenMismatch = CloudAdminTrafficPoolService::readiness($groupId, $now); +$assert(in_array('line_frozen_identity_mismatch', array_column( + $frozenMismatch['blockers'], + 'code' + ), true), + 'A recoverable failed order with the old line identity did not block enforcement.'); +Capsule::table('cloud_jobs')->where('id', 40)->update([ + 'error_code' => 'create_not_applied', + 'effect_resolution' => 'not_applied', + 'effect_may_have_applied' => 0, + 'safe_to_resubmit' => 1, +]); +$resolvedFailure = CloudAdminTrafficPoolService::readiness($groupId, $now); +$assert(!in_array('line_frozen_identity_mismatch', array_column( + $resolvedFailure['blockers'], + 'code' + ), true), + 'A definitively not-applied failed order permanently locked the group.'); +Capsule::table('cloud_jobs')->where('id', 40)->delete(); +Capsule::table('cloud_orders')->where('id', 4)->delete(); + +$periodStart = $now + 600; +$periodEnd = $periodStart + 3600; +Capsule::table('cloud_service_periods')->insert([ + 'id' => 10, + 'instance_id' => 100, + 'user_id' => 50, + 'traffic_pool_group_id' => $groupId, + 'traffic_quota_mode' => 'finite', + 'starts_at' => $periodStart, + 'ends_at' => $periodEnd, + 'traffic_quota_bytes' => 100, + 'status' => 'scheduled', +]); +$readiness = CloudAdminTrafficPoolService::readiness($groupId, $now); +$assert(in_array('missing_entitlements', array_column( + $readiness['blockers'], + 'code' + ), true), + 'A scheduled period without an entitlement did not block enforcement.'); +$expectConflict( + static fn (): array => CloudAdminTrafficPoolService::update( + $groupId, + ['mode' => 'enforced', 'expected_revision' => 3] + ), + 'A group with a missing entitlement entered enforced mode.' +); +$assert(CloudAdminTrafficPoolService::read($groupId)['item']['mode'] + === 'shadow', + 'A failed readiness gate changed the group mode.'); + +Capsule::table('cloud_traffic_pools')->insert([ + 'id' => 20, + 'user_id' => 50, + 'traffic_pool_group_id' => $groupId, + 'state' => 'available', + 'available_bytes' => 0, + 'overage_bytes' => 0, + 'version' => 1, + 'last_sequence' => 1, + 'last_event_id' => 30, + 'created_at' => $now, + 'updated_at' => $now, +]); +Capsule::table('cloud_traffic_entitlements')->insert([ + 'id' => 25, + 'pool_id' => 20, + 'user_id' => 50, + 'instance_id' => 100, + 'service_period_id' => 10, + 'starts_at' => $periodStart, + 'ends_at' => $periodEnd, + 'quota_mode' => 'finite', + 'granted_bytes' => 100, + 'consumed_bytes' => 0, + 'forfeited_bytes' => 0, + 'state' => 'scheduled', + 'activated_at' => null, + 'closed_at' => null, + 'version' => 1, + 'created_at' => $now, + 'updated_at' => $now, +]); +Capsule::table('cloud_traffic_ledger_events')->insert([ + 'id' => 30, + 'pool_id' => 20, + 'user_id' => 50, + 'pool_sequence' => 1, + 'event_key' => 'scheduled:10', + 'event_type' => 'entitlement_scheduled', + 'source_type' => 'service_period', + 'source_id' => '10', + 'source_revision' => 1, + 'payload_hash' => str_repeat('a', 64), + 'instance_id' => 100, + 'service_period_id' => 10, + 'entitlement_id' => 25, + 'amount_bytes' => 100, + 'effective_at' => $periodStart, + 'observed_at' => null, + 'payload_json' => '{}', + 'created_at' => $now, +]); + +$ready = CloudAdminTrafficPoolService::readiness($groupId, $now); +$assert($ready['ready'] === true && $ready['blockers'] === [], + 'A complete shadow projection did not pass readiness.'); +Capsule::table('cloud_traffic_entitlements')->where('id', 25)->update([ + 'state' => 'active', +]); +$wrongEntitlementState = CloudAdminTrafficPoolService::readiness( + $groupId, + $now +); +$assert(in_array('period_identity_mismatch', array_column( + $wrongEntitlementState['blockers'], + 'code' + ), true), + 'An active entitlement for a future scheduled period passed readiness.'); +Capsule::table('cloud_traffic_entitlements')->where('id', 25)->update([ + 'state' => 'scheduled', +]); + +Capsule::table('cloud_instances')->insert([ + 'id' => 100, + 'resource_pool_id' => 3, + 'status' => 'active', + 'network_status' => 'active', + 'traffic_synced_at' => $now, + 'lifetime_download_bytes' => 10, + 'lifetime_upload_bytes' => 20, +]); +Capsule::table('cloud_service_periods')->where('id', 10)->update([ + 'starts_at' => $now - 60, + 'ends_at' => $now + 3600, + 'status' => 'active', +]); +Capsule::table('cloud_traffic_entitlements')->where('id', 25)->update([ + 'starts_at' => $now - 60, + 'ends_at' => $now + 3600, + 'consumed_bytes' => 30, + 'state' => 'active', + 'activated_at' => $now - 60, +]); +Capsule::table('cloud_traffic_pools')->where('id', 20)->update([ + 'available_bytes' => 70, + 'last_sequence' => 2, + 'last_event_id' => 31, +]); +Capsule::table('cloud_traffic_ledger_events')->insert([ + 'id' => 31, + 'pool_id' => 20, + 'user_id' => 50, + 'pool_sequence' => 2, + 'event_key' => 'usage:100', + 'event_type' => 'usage_allocated', + 'source_type' => 'traffic_sample', + 'source_id' => '100', + 'source_revision' => 1, + 'payload_hash' => str_repeat('b', 64), + 'instance_id' => 100, + 'service_period_id' => 10, + 'entitlement_id' => 25, + 'amount_bytes' => 30, + 'effective_at' => $now, + 'observed_at' => $now, + 'payload_json' => '{}', + 'created_at' => $now, +]); +Capsule::table('cloud_traffic_pools')->insert([ + 'id' => 21, + 'user_id' => 51, + 'traffic_pool_group_id' => $groupId, + 'state' => 'available', + 'available_bytes' => 0, + 'overage_bytes' => 0, + 'version' => 1, + 'last_sequence' => 0, + 'last_event_id' => null, + 'created_at' => $now, + 'updated_at' => $now, +]); +Capsule::table('cloud_traffic_instance_cursors')->insert([ + 'instance_id' => 100, + 'user_id' => 50, + 'pool_id' => 21, + 'accounted_download_bytes' => 10, + 'accounted_upload_bytes' => 20, + 'last_observed_at' => $now, + 'last_event_id' => 31, + 'state' => 'ready', + 'attention_code' => '', + 'version' => 1, + 'updated_at' => $now, +]); +$wrongCursor = CloudAdminTrafficPoolService::readiness($groupId, $now); +$assert(in_array('cursor_missing', array_column( + $wrongCursor['blockers'], + 'code' + ), true), + 'A cursor pointing at another user pool passed readiness.'); +Capsule::table('cloud_traffic_instance_cursors')->where( + 'instance_id', 100 +)->update([ + 'pool_id' => 20, + 'accounted_download_bytes' => 0, + 'accounted_upload_bytes' => 0, +]); +$unsettled = CloudAdminTrafficPoolService::readiness($groupId, $now); +$assert(in_array('usage_unsettled', array_column( + $unsettled['blockers'], + 'code' + ), true), + 'A fresh but unaccounted traffic sample passed readiness.'); +Capsule::table('cloud_traffic_instance_cursors')->where( + 'instance_id', 100 +)->update([ + 'accounted_download_bytes' => 10, + 'accounted_upload_bytes' => 20, +]); +$ready = CloudAdminTrafficPoolService::readiness($groupId, $now); +$assert($ready['ready'] === true && $ready['blockers'] === [], + 'A fully settled active projection did not pass readiness.'); +Capsule::table('cloud_instances')->insert([ + 'id' => 101, + 'resource_pool_id' => 3, + 'status' => 'active', + 'network_status' => 'active', + 'traffic_synced_at' => $now, + 'lifetime_download_bytes' => 5, + 'lifetime_upload_bytes' => 0, +]); +Capsule::table('cloud_service_periods')->insert([ + 'id' => 11, + 'instance_id' => 101, + 'user_id' => 50, + 'traffic_pool_group_id' => $groupId, + 'traffic_quota_mode' => 'finite', + 'starts_at' => $now - 7200, + 'ends_at' => $now - 3600, + 'traffic_quota_bytes' => 100, + 'status' => 'finished', +]); +Capsule::table('cloud_traffic_instance_cursors')->insert([ + 'instance_id' => 101, + 'user_id' => 50, + 'pool_id' => 20, + 'accounted_download_bytes' => 0, + 'accounted_upload_bytes' => 0, + 'last_observed_at' => $now, + 'last_event_id' => 31, + 'state' => 'ready', + 'attention_code' => '', + 'version' => 1, + 'updated_at' => $now, +]); +Capsule::table('cloud_traffic_scan_failures')->insert([ + ['scan_kind' => 'period', 'subject_id' => 11, 'attempt_count' => 1, + 'last_error_code' => 'period_failed', 'retry_at' => $now + 60, + 'first_failed_at' => $now, 'last_failed_at' => $now], + ['scan_kind' => 'instance', 'subject_id' => 101, 'attempt_count' => 1, + 'last_error_code' => 'instance_failed', 'retry_at' => $now + 60, + 'first_failed_at' => $now, 'last_failed_at' => $now], +]); +$finishedDebt = CloudAdminTrafficPoolService::readiness($groupId, $now); +$finishedCodes = array_column($finishedDebt['blockers'], 'code'); +$assert(in_array('traffic_scan_failures', $finishedCodes, true) + && in_array('usage_unsettled', $finishedCodes, true), + 'Finished-period accounting debt was ignored by readiness.'); +Capsule::table('cloud_traffic_scan_failures')->delete(); +Capsule::table('cloud_traffic_instance_cursors')->where( + 'instance_id', 101 +)->delete(); +Capsule::table('cloud_service_periods')->where('id', 11)->delete(); +Capsule::table('cloud_instances')->where('id', 101)->delete(); +$enforced = CloudAdminTrafficPoolService::update($groupId, [ + 'mode' => 'enforced', + 'expected_revision' => 3, +]); +$assert($enforced['item']['mode'] === 'enforced' + && $enforced['item']['revision'] === 4, + 'A ready shadow group did not enter enforced mode.'); +$expectConflict( + static fn (): array => CloudAdminTrafficPoolService::update( + $groupId, + ['mode' => 'shadow', 'expected_revision' => 4] + ), + 'An enforced group was allowed to roll back.' +); + +echo "Cloud administrator traffic-pool service checks passed.\n"; diff --git a/web/tests/CloudFreshSchemaContractTest.php b/web/tests/CloudFreshSchemaContractTest.php index b13f135b..4920d019 100644 --- a/web/tests/CloudFreshSchemaContractTest.php +++ b/web/tests/CloudFreshSchemaContractTest.php @@ -22,7 +22,7 @@ $assert(stripos($schema, 'compatibility import') === false $assert(!preg_match('/\bengine_[A-Za-z0-9_]*\b/', $schema), 'cloud.sql retained an engine-prefixed identifier.'); $assert(str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v21-traffic-scan-backoff'") + "SCHEMA_VERSION = 'go-agent-wss-v23-traffic-admin'") && !str_contains($setup, "SCHEMA_VERSION = 'go-v1'"), 'Outbound Agent schema must reject the incompatible earlier Go database.'); $assert(str_contains($schema, diff --git a/web/tests/CloudRescueCatalogSchemaContractTest.php b/web/tests/CloudRescueCatalogSchemaContractTest.php index dc144ceb..6faea2c3 100644 --- a/web/tests/CloudRescueCatalogSchemaContractTest.php +++ b/web/tests/CloudRescueCatalogSchemaContractTest.php @@ -56,7 +56,7 @@ $assert($replica !== '' && str_contains($replica, 'cleanup_resolved_at BIGINT UNSIGNED'), 'Rescue replica cannot prove exact identity or retain cleanup debt.'); $assert(str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v21-traffic-scan-backoff'") + "SCHEMA_VERSION = 'go-agent-wss-v23-traffic-admin'") && str_contains($setup, "'cloud_rescue_artifact_delete_due'") && str_contains($setup, "'cloud_rescue_replica_cleanup'"), 'CloudSetup version or rescue catalog indexes are incomplete.'); diff --git a/web/tests/CloudTemplateImportIntentContractTest.php b/web/tests/CloudTemplateImportIntentContractTest.php index 88a29b8e..140364dd 100644 --- a/web/tests/CloudTemplateImportIntentContractTest.php +++ b/web/tests/CloudTemplateImportIntentContractTest.php @@ -63,7 +63,7 @@ $assert(str_contains($schema, && str_contains($schema, 'CONSTRAINT chk_cloud_template_import_completion CHECK (') && str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v21-traffic-scan-backoff'"), + "SCHEMA_VERSION = 'go-agent-wss-v23-traffic-admin'"), 'Template imports are missing durable identity or terminal-state constraints.'); $assert(str_contains($routes, "'/admin/cloud-template-imports'") && str_contains($routes, "'/admin/cloud-template-imports/{id}'") diff --git a/web/tests/CloudTrafficPoolPeriodBindingTest.php b/web/tests/CloudTrafficPoolPeriodBindingTest.php index b4530504..83e61856 100644 --- a/web/tests/CloudTrafficPoolPeriodBindingTest.php +++ b/web/tests/CloudTrafficPoolPeriodBindingTest.php @@ -41,15 +41,32 @@ $capsule->schema('default')->create( $table->string('code')->unique(); $table->string('name'); $table->string('mode'); + $table->integer('revision')->default(1); $table->integer('created_at'); $table->integer('updated_at'); } ); +$capsule->schema('default')->create( + 'cloud_network_lines', + static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('region_id')->default(1); + $table->integer('traffic_pool_group_id')->nullable(); + $table->string('code')->default('premium'); + $table->string('name')->default('Premium'); + $table->boolean('is_default')->default(false); + $table->string('status')->default('active'); + $table->integer('sort')->default(0); + $table->integer('created_at')->default(1); + $table->integer('updated_at')->default(1); + } +); Capsule::table('cloud_traffic_pool_groups')->insert([ 'id' => 7, 'code' => 'premium', 'name' => 'Premium', 'mode' => 'disabled', + 'revision' => 1, 'created_at' => 1, 'updated_at' => 1, ]); @@ -60,6 +77,15 @@ $pool->line_id = 5; $line = new CloudNetworkLine(); $line->id = 5; $line->traffic_pool_group_id = 7; +$line->region_id = 1; +$line->code = 'premium'; +$line->name = 'Premium'; +$line->is_default = false; +$line->status = 'active'; +$line->sort = 0; +$line->created_at = 1; +$line->updated_at = 1; +$line->save(); $snapshot = CloudTrafficPoolPeriodBinding::purchaseSnapshot( $pool, $line, @@ -70,14 +96,18 @@ $assert($snapshot === [ 'traffic_quota_mode' => 'finite', ], 'Purchase did not freeze the configured line group.'); -$line->traffic_pool_group_id = null; +Capsule::table('cloud_network_lines')->where('id', 5)->update([ + 'traffic_pool_group_id' => null, +]); $unbound = CloudTrafficPoolPeriodBinding::purchaseSnapshot($pool, $line, 0); $assert($unbound === [ 'traffic_pool_group_id' => null, 'traffic_quota_mode' => 'unlimited', ], 'An unbound line did not preserve the disabled accounting path.'); -$line->traffic_pool_group_id = 99; +Capsule::table('cloud_network_lines')->where('id', 5)->update([ + 'traffic_pool_group_id' => 99, +]); $expectConflict( static fn (): array => CloudTrafficPoolPeriodBinding::purchaseSnapshot($pool, $line, 100), diff --git a/web/tests/CloudTrafficPoolSchemaContractTest.php b/web/tests/CloudTrafficPoolSchemaContractTest.php index 4d0d1881..837ee776 100644 --- a/web/tests/CloudTrafficPoolSchemaContractTest.php +++ b/web/tests/CloudTrafficPoolSchemaContractTest.php @@ -50,6 +50,8 @@ $assert(str_contains($schema, $assert(str_contains($schema, "mode IN ('disabled','shadow','enforced')") + && str_contains($schema, + 'revision BIGINT UNSIGNED NOT NULL DEFAULT 1') && str_contains($schema, "state IN ('scheduled','active','closing','exhausted','expired')") && str_contains($schema, @@ -69,7 +71,7 @@ $assert(str_contains($schema, 'Service-period traffic-pool identity is not frozen or indexed.'); $assert(str_contains($setup, - "SCHEMA_VERSION = 'go-agent-wss-v22-network-policy'") + "SCHEMA_VERSION = 'go-agent-wss-v23-traffic-admin'") && str_contains($setup, "'chk_cloud_traffic_entitlement_balance'") && str_contains($setup, "'cloud_traffic_ledger_sequence'"), 'CloudSetup schema version or named-object validation is incomplete.'); diff --git a/web/tests/CloudVpcSchemaContractTest.php b/web/tests/CloudVpcSchemaContractTest.php index c65b5efe..d5a4ebd4 100644 --- a/web/tests/CloudVpcSchemaContractTest.php +++ b/web/tests/CloudVpcSchemaContractTest.php @@ -101,7 +101,7 @@ $assert(str_contains($jobs, 'vpc_id BIGINT UNSIGNED DEFAULT NULL') 'Cloud jobs cannot be correlated to VPC or VPC-port work.'); $assert(str_contains($setup, - "private const SCHEMA_VERSION = 'go-agent-wss-v21-traffic-scan-backoff'") + "private const SCHEMA_VERSION = 'go-agent-wss-v23-traffic-admin'") && str_contains($setup, "'name' => 'cloud_vpc_enabled'") && str_contains($setup, "'value' => 'false'") && str_contains($setup,