You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/Cloud/CloudTrafficPoolReadModel.php

749 lines
30 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudInstance;
use App\Models\CloudInstanceNetworkPolicyState;
use App\Models\CloudInstanceNetworkRestriction;
use App\Models\CloudNetworkLine;
use App\Models\CloudServicePeriod;
use App\Models\CloudTrafficEntitlement;
use App\Models\CloudTrafficPoolGroup;
/** Actor-safe user projection for enforced shared traffic pools. */
final class CloudTrafficPoolReadModel
{
public static function forUser(int $userId, ?int $now = null): array
{
$now ??= time();
if ($userId < 1) {
return ['items' => [], 'generated_at' => $now];
}
$currentInstances = CloudInstance::where('user_id', $userId)
->where('status', 'active')->whereNotNull('current_period_id')
->get(['id', 'current_period_id']);
$periodIds = $currentInstances->pluck('current_period_id')->map(
static fn ($id): int => (int) $id
)->unique()->values()->all();
$periodsById = $periodIds === [] ? collect()
: CloudServicePeriod::where('user_id', $userId)
->whereIn('id', $periodIds)
->where('traffic_quota_mode', 'finite')
->whereIn('status', ['active', 'exhausted'])
->where('starts_at', '<=', $now)->where('ends_at', '>', $now)
->whereNotNull('traffic_pool_group_id')
->get([
'id', 'instance_id', 'user_id', 'traffic_pool_group_id',
'traffic_quota_mode', 'traffic_quota_bytes', 'starts_at',
'ends_at', 'status',
])->keyBy('id');
$currentPeriods = [];
foreach ($currentInstances as $instance) {
$period = $periodsById->get((int) $instance->current_period_id);
if ($period !== null
&& (int) $period->instance_id === (int) $instance->id) {
$currentPeriods[(int) $period->id] = $period;
}
}
$periodGroupIds = array_values(array_unique(array_map(
static fn (CloudServicePeriod $period): int =>
(int) $period->traffic_pool_group_id,
$currentPeriods
)));
$poolGroupIds = CloudTrafficEntitlement::query()
->join('cloud_traffic_pools as traffic_pool',
'traffic_pool.id', '=', 'cloud_traffic_entitlements.pool_id')
->where('traffic_pool.user_id', $userId)
->where('cloud_traffic_entitlements.user_id', $userId)
->where('cloud_traffic_entitlements.quota_mode', 'finite')
->whereIn('cloud_traffic_entitlements.state',
['active', 'exhausted'])
->where('cloud_traffic_entitlements.starts_at', '<=', $now)
->where('cloud_traffic_entitlements.ends_at', '>', $now)
->distinct()->pluck('traffic_pool.traffic_pool_group_id')->map(
static fn ($id): int => (int) $id
)->all();
$groupIds = array_values(array_unique(array_merge(
$poolGroupIds,
$periodGroupIds
)));
$groups = $groupIds === [] ? collect()
: CloudTrafficPoolGroup::whereIn('id', $groupIds)
->where('mode', 'enforced')->orderBy('id')->get()->keyBy('id');
$visibleGroupIds = $groups->keys()->map(
static fn ($id): int => (int) $id
)->all();
$instancesByGroup = self::instancesByGroup(
$userId,
$visibleGroupIds,
$now
);
$identities = array_map(static fn (int $groupId): array => [
'user_id' => $userId,
'traffic_pool_group_id' => $groupId,
], $visibleGroupIds);
$snapshots = CloudTrafficPoolAccounting::snapshots($identities, $now);
$entitlements = $currentPeriods === [] ? collect()
: CloudTrafficEntitlement::whereIn(
'service_period_id', array_keys($currentPeriods)
)->get([
'pool_id', 'user_id', 'instance_id', 'service_period_id',
'quota_mode', 'granted_bytes', 'state', 'starts_at', 'ends_at',
])->keyBy('service_period_id');
$pendingGroups = [];
foreach ($currentPeriods as $period) {
$groupId = (int) $period->traffic_pool_group_id;
$snapshot = $snapshots[$userId . ':' . $groupId] ?? null;
$entitlement = $entitlements->get((int) $period->id);
if ($snapshot === null || $snapshot['pool_id'] === null
|| $entitlement === null
|| (int) $entitlement->pool_id !== (int) $snapshot['pool_id']
|| (int) $entitlement->user_id !== $userId
|| (int) $entitlement->instance_id
!== (int) $period->instance_id
|| (string) $entitlement->quota_mode !== 'finite'
|| (int) $entitlement->granted_bytes
!== (int) $period->traffic_quota_bytes
|| !in_array((string) $entitlement->state,
['active', 'exhausted'], true)
|| (int) $entitlement->starts_at !== (int) $period->starts_at
|| (int) $entitlement->ends_at !== (int) $period->ends_at) {
$pendingGroups[$groupId] = true;
}
}
$poolStates = [];
foreach ($visibleGroupIds as $groupId) {
$poolStates[$groupId] = (string) (
$snapshots[$userId . ':' . $groupId]['state'] ?? 'available'
);
}
$networkStates = self::networkStates($instancesByGroup, $poolStates);
$regionScopes = self::regionScopes($visibleGroupIds);
$items = [];
foreach ($groups as $group) {
$groupId = (int) $group->id;
$item = self::poolDto(
$group,
$instancesByGroup[$groupId] ?? [],
$networkStates[$groupId] ?? 'clear',
$snapshots[$userId . ':' . $groupId],
isset($pendingGroups[$groupId])
);
$item['region_scope'] = self::publicRegionScope(
$regionScopes[$groupId] ?? self::unassignedRegionScope()
);
$items[] = $item;
}
$regionGroups = self::regionGroups($items, $regionScopes);
return [
'items' => $items,
'region_groups' => $regionGroups,
'region_count' => count($regionGroups),
'pool_count' => count($items),
'generated_at' => $now,
];
}
/** Resolve the exact accounting vocabulary used by one instance detail. */
public static function forPeriod(
int $userId,
?CloudServicePeriod $period,
?int $now = null
): array {
$now ??= time();
if ($period === null || (int) $period->user_id !== $userId) {
return self::legacy();
}
return self::forPeriods([$period], $now)[(int) $period->id]
?? self::legacy();
}
/** Resolve many periods while projecting each user/line pool only once. */
public static function forPeriods(array $periods, ?int $now = null): array
{
$now ??= time();
$results = [];
$finite = [];
$groupIds = [];
$identities = [];
foreach ($periods as $period) {
if (!$period instanceof CloudServicePeriod || (int) $period->id < 1
|| (int) $period->user_id < 1) {
continue;
}
$periodId = (int) $period->id;
$quotaMode = (string) ($period->traffic_quota_mode ?? '');
if ($quotaMode === 'unlimited'
|| ($quotaMode === ''
&& (int) ($period->traffic_quota_bytes ?? 0) === 0)) {
$results[$periodId] = [
'traffic_accounting_mode' => 'unlimited',
'traffic_pool' => null,
];
continue;
}
$groupId = (int) ($period->traffic_pool_group_id ?? 0);
if ($groupId < 1) {
$results[$periodId] = self::legacy();
continue;
}
$finite[$periodId] = [
'user_id' => (int) $period->user_id,
'group_id' => $groupId,
'instance_id' => (int) $period->instance_id,
'quota_bytes' => max(0,
(int) $period->traffic_quota_bytes),
'starts_at' => (int) $period->starts_at,
'ends_at' => (int) $period->ends_at,
];
$groupIds[] = $groupId;
$key = (int) $period->user_id . ':' . $groupId;
$identities[$key] = [
'user_id' => (int) $period->user_id,
'traffic_pool_group_id' => $groupId,
];
}
$groups = $groupIds === [] ? collect()
: CloudTrafficPoolGroup::whereIn('id', array_values(array_unique(
$groupIds
)))->where('mode', 'enforced')->get()->keyBy('id');
$snapshots = CloudTrafficPoolAccounting::snapshots(
array_values($identities),
$now
);
$entitlements = $finite === [] ? collect()
: CloudTrafficEntitlement::whereIn(
'service_period_id', array_keys($finite)
)->get([
'pool_id', 'user_id', 'instance_id', 'service_period_id',
'quota_mode', 'granted_bytes', 'state', 'starts_at', 'ends_at',
])->keyBy('service_period_id');
$pendingByPool = [];
foreach ($finite as $periodId => $identity) {
$key = $identity['user_id'] . ':' . $identity['group_id'];
$snapshot = $snapshots[$key] ?? null;
$entitlement = $entitlements->get($periodId);
if ($snapshot === null || $snapshot['pool_id'] === null
|| $entitlement === null
|| (int) $entitlement->pool_id !== (int) $snapshot['pool_id']
|| (int) $entitlement->user_id !== $identity['user_id']
|| (int) $entitlement->instance_id
!== $identity['instance_id']
|| (string) $entitlement->quota_mode !== 'finite'
|| (int) $entitlement->granted_bytes
!== $identity['quota_bytes']
|| !in_array((string) $entitlement->state,
['active', 'exhausted'], true)
|| (int) $entitlement->starts_at !== $identity['starts_at']
|| (int) $entitlement->ends_at !== $identity['ends_at']) {
$pendingByPool[$key] = true;
}
}
$poolCache = [];
foreach ($finite as $periodId => $identity) {
$group = $groups->get($identity['group_id']);
if ($group === null) {
$results[$periodId] = self::legacy();
continue;
}
$cacheKey = $identity['user_id'] . ':' . $identity['group_id'];
if (!isset($poolCache[$cacheKey])) {
$snapshot = $snapshots[$cacheKey];
$poolCache[$cacheKey] = self::poolDto(
$group,
[],
(string) $snapshot['state'] === 'attention'
? 'attention' : 'clear',
$snapshot,
isset($pendingByPool[$cacheKey])
);
}
$results[$periodId] = [
'traffic_accounting_mode' => 'pooled',
'traffic_pool' => $poolCache[$cacheKey],
];
}
return $results;
}
/*
* The browser never receives the persistent pool id or ledger version;
* those identifiers belong to administrator reconciliation only.
*/
private static function poolDto(
CloudTrafficPoolGroup $group,
array $instances,
string $networkState,
array $snapshot,
bool $forcePreparing = false
): array {
$projectionReady = !$forcePreparing
&& $snapshot['pool_id'] !== null;
return [
'group_id' => (int) $group->id,
'name' => (string) $group->name,
'projection_ready' => $projectionReady,
'state' => $projectionReady
? (string) $snapshot['state'] : 'preparing',
'active_entitlement_bytes' =>
(int) $snapshot['active_entitlement_bytes'],
'active_consumed_bytes' =>
(int) $snapshot['active_consumed_bytes'],
'available_bytes' => (int) $snapshot['available_bytes'],
'overage_bytes' => (int) $snapshot['overage_bytes'],
'next_expiry_at' => $snapshot['next_expiry_at'] === null
? null : (int) $snapshot['next_expiry_at'],
'next_expiry_bytes' => (int) $snapshot['next_expiry_bytes'],
'last_observed_at' => $snapshot['last_observed_at'] === null
? null : (int) $snapshot['last_observed_at'],
'network_restriction_state' => $networkState,
'instances' => array_values($instances),
];
}
/** @return array<int,list<array<string,mixed>>> */
private static function instancesByGroup(
int $userId,
array $groupIds,
int $now
): array {
if ($groupIds === []) {
return [];
}
$periods = CloudServicePeriod::where('user_id', $userId)
->whereIn('traffic_pool_group_id', $groupIds)
->where('traffic_quota_mode', 'finite')
->whereIn('status', ['active', 'exhausted'])
->where('starts_at', '<=', $now)->where('ends_at', '>', $now)
->orderBy('id')->get([
'id', 'instance_id', 'user_id', 'traffic_pool_group_id',
'starts_at', 'ends_at', 'traffic_quota_mode', 'status',
'traffic_quota_bytes',
])->keyBy('id');
if ($periods->isEmpty()) {
return [];
}
$instances = CloudInstance::where('user_id', $userId)
->where('status', 'active')
->whereIn('current_period_id', $periods->keys()->all())
->orderBy('id')->get([
'id', 'user_id', 'current_period_id', 'name', 'status',
'service_status', 'network_status', 'expires_at',
'traffic_download_bytes', 'traffic_upload_bytes',
]);
$result = [];
foreach ($instances as $instance) {
$period = $periods->get((int) $instance->current_period_id);
if ($period === null
|| (int) $period->instance_id !== (int) $instance->id
|| (int) $period->user_id !== $userId) {
continue;
}
$download = max(0, (int) $instance->traffic_download_bytes);
$upload = max(0, (int) $instance->traffic_upload_bytes);
$groupId = (int) $period->traffic_pool_group_id;
$result[$groupId][] = [
'id' => (string) $instance->id,
'name' => (string) $instance->name,
'traffic_download_bytes' => $download,
'traffic_upload_bytes' => $upload,
'traffic_used_bytes' => $download + $upload,
'period_traffic_quota_bytes' => max(
0,
(int) $period->traffic_quota_bytes
),
'service_expires_at' => $instance->expires_at === null
? null : (int) $instance->expires_at,
'network_status' => (string) $instance->network_status,
];
}
return $result;
}
/**
* Resolve every visible commercial group to one display scope in one
* query. A cross-region pool remains one pool: duplicating it beneath
* each region would duplicate the same accounting projection visually.
*
* @return array<int,array<string,mixed>>
*/
private static function regionScopes(array $groupIds): array
{
if ($groupIds === []) {
return [];
}
$rows = CloudNetworkLine::query()
->leftJoin('cloud_regions as traffic_region',
'traffic_region.id', '=', 'cloud_network_lines.region_id')
->whereIn('cloud_network_lines.traffic_pool_group_id', $groupIds)
->orderBy('traffic_region.sort')->orderBy('traffic_region.id')
->orderBy('cloud_network_lines.sort')
->orderBy('cloud_network_lines.id')
->get([
'cloud_network_lines.traffic_pool_group_id as group_id',
'cloud_network_lines.region_id as line_region_id',
'traffic_region.id as region_id',
'traffic_region.code as region_code',
'traffic_region.name as region_name',
'traffic_region.sort as region_sort',
]);
$regionsByGroup = [];
$unresolved = [];
foreach ($rows as $row) {
$groupId = (int) $row->group_id;
$regionId = (int) ($row->region_id ?? 0);
if ($regionId < 1 || (int) ($row->line_region_id ?? 0) < 1) {
$unresolved[$groupId] = true;
continue;
}
$regionsByGroup[$groupId][$regionId] = [
'id' => $regionId,
'code' => (string) $row->region_code,
'name' => (string) $row->region_name,
'sort' => (int) $row->region_sort,
];
}
$scopes = [];
foreach ($groupIds as $groupId) {
$groupId = (int) $groupId;
$regions = array_values($regionsByGroup[$groupId] ?? []);
usort($regions, static fn (array $left, array $right): int =>
[$left['sort'], $left['id']] <=> [$right['sort'], $right['id']]
);
if (isset($unresolved[$groupId]) || $regions === []) {
$scope = self::unassignedRegionScope();
$scope['regions'] = $regions;
$scopes[$groupId] = $scope;
continue;
}
if (count($regions) > 1) {
$scopes[$groupId] = [
'key' => 'region:cross',
'kind' => 'cross_region',
'region' => null,
'regions' => $regions,
'name' => '跨地区线路组',
'description' => '涉及 ' . implode('、', array_column(
$regions, 'name'
)),
'_sort' => PHP_INT_MAX - 1,
'_region_id' => PHP_INT_MAX - 1,
];
continue;
}
$region = $regions[0];
$scopes[$groupId] = [
'key' => 'region:' . $region['code'],
'kind' => 'region',
'region' => $region,
'regions' => $regions,
'name' => $region['name'],
'description' => '按线路独立核算共享额度',
'_sort' => $region['sort'],
'_region_id' => $region['id'],
];
}
return $scopes;
}
/** @return array<string,mixed> */
private static function unassignedRegionScope(): array
{
return [
'key' => 'region:unassigned',
'kind' => 'unassigned',
'region' => null,
'regions' => [],
'name' => '地区待配置',
'description' => '线路尚未绑定有效地区',
'_sort' => PHP_INT_MAX,
'_region_id' => PHP_INT_MAX,
];
}
/** @return array<string,mixed> */
private static function publicRegionScope(array $scope): array
{
$regions = [];
foreach ($scope['regions'] ?? [] as $region) {
$regions[] = [
'code' => (string) ($region['code'] ?? ''),
'name' => (string) ($region['name'] ?? '未知地区'),
];
}
$region = $scope['region'] ?? null;
return [
'kind' => (string) $scope['kind'],
'region' => is_array($region) ? [
'code' => (string) ($region['code'] ?? ''),
'name' => (string) ($region['name'] ?? ''),
] : null,
'regions' => $regions,
];
}
/** @return list<array<string,mixed>> */
private static function regionGroups(array $items, array $scopes): array
{
$decorated = [];
foreach ($items as $item) {
$groupId = (int) ($item['group_id'] ?? 0);
$scope = $scopes[$groupId] ?? self::unassignedRegionScope();
$decorated[] = [
'sort' => (int) $scope['_sort'],
'region_id' => (int) $scope['_region_id'],
'group_id' => $groupId,
'scope' => $scope,
'item' => $item,
];
}
usort($decorated, static fn (array $left, array $right): int =>
[$left['sort'], $left['region_id'], $left['group_id']]
<=> [$right['sort'], $right['region_id'], $right['group_id']]
);
$groups = [];
foreach ($decorated as $row) {
$scope = $row['scope'];
$key = (string) $scope['key'];
if (!isset($groups[$key])) {
$groups[$key] = [
'key' => $key,
'kind' => (string) $scope['kind'],
'name' => (string) $scope['name'],
'description' => (string) $scope['description'],
'regions' => [],
'_regions' => [],
'pool_count' => 0,
'instance_count' => 0,
'summary_state' => (string) $scope['kind'] === 'unassigned'
? 'attention' : 'available',
'requires_attention' =>
(string) $scope['kind'] === 'unassigned',
'default_open' => false,
'items' => [],
];
}
foreach ($scope['regions'] ?? [] as $region) {
$regionId = (int) ($region['id'] ?? 0);
if ($regionId > 0) {
$groups[$key]['_regions'][$regionId] = $region;
}
}
$item = $row['item'];
$groups[$key]['items'][] = $item;
$groups[$key]['pool_count']++;
$groups[$key]['instance_count'] += count($item['instances'] ?? []);
$candidate = self::regionPoolState($item);
if (self::regionStatePriority($candidate)
> self::regionStatePriority($groups[$key]['summary_state'])) {
$groups[$key]['summary_state'] = $candidate;
}
$groups[$key]['requires_attention'] =
$groups[$key]['summary_state'] !== 'available';
}
$groups = array_values($groups);
foreach ($groups as &$group) {
$regions = array_values($group['_regions']);
usort($regions, static fn (array $left, array $right): int =>
[$left['sort'], $left['id']] <=> [$right['sort'], $right['id']]
);
$scope = ['kind' => $group['kind'], 'region' => null,
'regions' => $regions];
$group['regions'] = self::publicRegionScope($scope)['regions'];
if ($group['kind'] === 'cross_region') {
$group['description'] = '涉及 ' . implode('、', array_column(
$group['regions'], 'name'
));
}
unset($group['_regions']);
}
unset($group);
$hasAttention = false;
foreach ($groups as $group) {
$hasAttention = $hasAttention
|| (bool) $group['requires_attention'];
}
foreach ($groups as $index => &$group) {
$group['default_open'] = count($groups) === 1
|| ($hasAttention
? (bool) $group['requires_attention']
: $index === 0);
}
unset($group);
return $groups;
}
private static function regionPoolState(array $pool): string
{
$state = (string) ($pool['state'] ?? '');
$network = (string) ($pool['network_restriction_state'] ?? '');
if (!in_array($state,
['available', 'exhausted', 'attention', 'preparing'], true)
|| !in_array($network,
['clear', 'applying', 'restricted', 'attention'], true)) {
return 'attention';
}
if ($state === 'attention' || $network === 'attention') {
return 'attention';
}
if ($network === 'restricted') {
return 'restricted';
}
if ($state === 'exhausted') {
return 'exhausted';
}
if ($network === 'applying') {
return 'applying';
}
return $state === 'preparing' ? 'preparing' : 'available';
}
private static function regionStatePriority(string $state): int
{
return match ($state) {
'attention' => 5,
'restricted' => 4,
'exhausted' => 3,
'applying' => 2,
'preparing' => 1,
default => 0,
};
}
/** @return array<int,string> */
private static function networkStates(
array $instancesByGroup,
array $poolStatesByGroup
): array {
$instanceIds = [];
foreach ($instancesByGroup as $instances) {
foreach ($instances as $instance) {
$instanceIds[] = (int) $instance['id'];
}
}
$restrictions = [];
$otherActiveReasons = [];
$policies = [];
if ($instanceIds !== []) {
foreach (CloudInstanceNetworkRestriction::whereIn(
'instance_id', $instanceIds
)->get() as $row) {
$instanceId = (int) $row->instance_id;
if ((string) $row->reason_code === 'traffic_pool_exhausted') {
$restrictions[$instanceId] = $row;
} elseif ((bool) $row->desired_active) {
$otherActiveReasons[$instanceId] = true;
}
}
foreach (CloudInstanceNetworkPolicyState::whereIn(
'instance_id', $instanceIds
)->get() as $row) {
$policies[(int) $row->instance_id] = $row;
}
}
$groupIds = array_values(array_unique(array_merge(
array_map('intval', array_keys($instancesByGroup)),
array_map('intval', array_keys($poolStatesByGroup))
)));
$states = [];
foreach ($groupIds as $groupId) {
$instances = $instancesByGroup[$groupId] ?? [];
$poolState = (string) (
$poolStatesByGroup[$groupId] ?? 'available'
);
$state = $poolState === 'attention' ? 'attention' : 'clear';
$activeRestriction = false;
foreach ($instances as $instance) {
$instanceId = (int) $instance['id'];
$restriction = $restrictions[$instanceId] ?? null;
$policy = $policies[$instanceId] ?? null;
$desired = $restriction !== null
&& (bool) $restriction->desired_active;
$activeRestriction = $activeRestriction || $desired;
$candidate = self::instanceNetworkState(
$restriction,
$policy,
isset($otherActiveReasons[$instanceId]),
(string) ($instance['network_status'] ?? '')
);
if ($candidate === 'attention') {
$state = 'attention';
break;
}
if ($candidate === 'applying' && $state !== 'attention') {
$state = 'applying';
} elseif ($candidate === 'restricted'
&& $state === 'clear') {
$state = 'restricted';
}
}
if ($state === 'clear' && $instances !== []
&& $poolState === 'exhausted' && !$activeRestriction) {
$state = 'attention';
}
$states[(int) $groupId] = $state;
}
return $states;
}
private static function instanceNetworkState(
$restriction,
$policy,
bool $otherActiveReason,
string $instanceNetworkStatus
): string {
$desired = $restriction !== null
&& (bool) $restriction->desired_active;
if (!$desired) {
if ($restriction === null || $otherActiveReason
|| $policy === null) {
return 'clear';
}
$state = (string) $policy->state;
$desiredSuspended = (bool) $policy->desired_suspended;
$appliedSuspended = (bool) $policy->applied_suspended;
$restoring = in_array($instanceNetworkStatus,
['restoring', 'restore_pending'], true)
|| (!$desiredSuspended && $appliedSuspended);
if (!$restoring) {
return $desiredSuspended ? 'attention' : 'clear';
}
if (in_array($state, ['failed', 'unknown'], true)) {
return 'attention';
}
return in_array($state, ['pending', 'applying'], true)
|| $desiredSuspended !== $appliedSuspended
? 'applying' : 'clear';
}
if ($policy === null) {
return 'attention';
}
$state = (string) $policy->state;
if (in_array($state, ['failed', 'unknown'], true)) {
return 'attention';
}
if (in_array($state, ['pending', 'applying'], true)
|| (bool) $policy->desired_suspended
!== (bool) $policy->applied_suspended) {
return 'applying';
}
return $state === 'applied'
&& (bool) $policy->desired_suspended
&& (bool) $policy->applied_suspended
? 'restricted' : 'attention';
}
private static function legacy(): array
{
return [
'traffic_accounting_mode' => 'legacy',
'traffic_pool' => null,
];
}
}