feat(traffic): add administrator rollout controls
parent
ac67a2de7b
commit
3beb24fff8
@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controllers;
|
||||
|
||||
use App\Services\Cloud\CloudAccess;
|
||||
use App\Services\Cloud\CloudAdminTrafficPoolService;
|
||||
use App\Services\Cloud\CloudError;
|
||||
use App\Services\Cloud\CloudInput;
|
||||
|
||||
/** Administrator API for shared traffic-pool rollout and line identity. */
|
||||
final class CloudAdminTrafficPoolController
|
||||
{
|
||||
private function actor($request, bool $write): array
|
||||
{
|
||||
$actor = $request->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)
|
||||
));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,741 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
use App\Models\CloudInstance;
|
||||
use App\Models\CloudInstanceNetworkPolicyState;
|
||||
use App\Models\CloudInstanceNetworkRestriction;
|
||||
use App\Models\CloudNetworkLine;
|
||||
use App\Models\CloudOrder;
|
||||
use App\Models\CloudResourcePool;
|
||||
use App\Models\CloudServicePeriod;
|
||||
use App\Models\CloudTrafficEntitlement;
|
||||
use App\Models\CloudTrafficInstanceCursor;
|
||||
use App\Models\CloudTrafficPool;
|
||||
use App\Models\CloudTrafficPoolGroup;
|
||||
use App\Models\CloudTrafficScanFailure;
|
||||
use Illuminate\Database\QueryException;
|
||||
|
||||
/** Administrator traffic-pool catalog, rollout state machine and safety gate. */
|
||||
final class CloudAdminTrafficPoolService
|
||||
{
|
||||
private const MODES = ['disabled', 'shadow', 'enforced'];
|
||||
private const SAMPLE_FRESHNESS_SECONDS = 300;
|
||||
|
||||
public static function page(array $query = []): array
|
||||
{
|
||||
$items = [];
|
||||
foreach (CloudTrafficPoolGroup::orderBy('id')->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<int> */
|
||||
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;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
$root = dirname(__DIR__);
|
||||
$read = static function (string $path) use ($root): string {
|
||||
$value = file_get_contents($root . '/' . $path);
|
||||
if (!is_string($value)) {
|
||||
throw new RuntimeException('Unable to read ' . $path);
|
||||
}
|
||||
return $value;
|
||||
};
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
$routes = $read('config/routes_cloud.php');
|
||||
$controller = $read('app/Controllers/CloudAdminTrafficPoolController.php');
|
||||
$service = $read('app/Services/Cloud/CloudAdminTrafficPoolService.php');
|
||||
$binding = $read('app/Services/Cloud/CloudTrafficPoolPeriodBinding.php');
|
||||
|
||||
$assert(str_contains($routes,
|
||||
"'/admin/traffic-pool-groups'")
|
||||
&& str_contains($routes,
|
||||
"'/admin/traffic-pool-groups/{id:[1-9][0-9]*}'")
|
||||
&& str_contains($routes,
|
||||
"'/admin/traffic-pool-groups/{id:[1-9][0-9]*}/lines'")
|
||||
&& substr_count($routes, 'CloudAdminTrafficPoolController:') >= 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";
|
||||
@ -0,0 +1,613 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Services\Cloud\CloudAdminTrafficPoolService;
|
||||
use App\Services\Cloud\CloudError;
|
||||
use Illuminate\Database\Capsule\Manager as Capsule;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
$expectConflict = static function (callable $callable, string $message) use (
|
||||
$assert
|
||||
): void {
|
||||
try {
|
||||
$callable();
|
||||
} catch (CloudError $error) {
|
||||
$assert($error->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";
|
||||
Loading…
Reference in New Issue