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.
682 lines
28 KiB
PHP
682 lines
28 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 [
|
|
'line_pools' => [],
|
|
'line_pool_count' => 0,
|
|
'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);
|
|
$coverageByGroup = self::coverageByGroup($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])
|
|
);
|
|
$items[] = $item;
|
|
}
|
|
$linePools = self::linePools($items, $coverageByGroup);
|
|
return [
|
|
'line_pools' => $linePools,
|
|
'line_pool_count' => count($linePools),
|
|
'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::query()
|
|
->leftJoin('cloud_resource_pools as instance_resource_pool',
|
|
'instance_resource_pool.id', '=',
|
|
'cloud_instances.resource_pool_id')
|
|
->leftJoin('cloud_network_lines as instance_line',
|
|
'instance_line.id', '=', 'instance_resource_pool.line_id')
|
|
->leftJoin('cloud_regions as instance_region',
|
|
'instance_region.id', '=', 'instance_line.region_id')
|
|
->where('cloud_instances.user_id', $userId)
|
|
->where('cloud_instances.status', 'active')
|
|
->whereIn('cloud_instances.current_period_id',
|
|
$periods->keys()->all())
|
|
->orderBy('cloud_instances.id')->get([
|
|
'cloud_instances.id as id',
|
|
'cloud_instances.user_id as user_id',
|
|
'cloud_instances.current_period_id as current_period_id',
|
|
'cloud_instances.name as name',
|
|
'cloud_instances.status as status',
|
|
'cloud_instances.service_status as service_status',
|
|
'cloud_instances.network_status as network_status',
|
|
'cloud_instances.expires_at as expires_at',
|
|
'cloud_instances.traffic_download_bytes as traffic_download_bytes',
|
|
'cloud_instances.traffic_upload_bytes as traffic_upload_bytes',
|
|
'instance_line.traffic_pool_group_id as placement_group_id',
|
|
'instance_region.id as region_id',
|
|
'instance_region.code as region_code',
|
|
'instance_region.name as region_name',
|
|
]);
|
|
$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;
|
|
$regionId = (int) ($instance->region_id ?? 0);
|
|
$placementGroupId = (int) ($instance->placement_group_id ?? 0);
|
|
$placementReady = $regionId > 0
|
|
&& $placementGroupId === $groupId;
|
|
$result[$groupId][] = [
|
|
'id' => (string) $instance->id,
|
|
'name' => (string) $instance->name,
|
|
'region' => $regionId > 0 ? [
|
|
'code' => (string) ($instance->region_code ?? ''),
|
|
'name' => (string) ($instance->region_name ?? ''),
|
|
] : null,
|
|
'placement_scope_state' => $placementReady
|
|
? 'ready' : 'attention',
|
|
'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;
|
|
}
|
|
|
|
/**
|
|
* Project one visible commercial line group exactly once. Regions describe
|
|
* coverage only; they never create another quota or accounting identity.
|
|
*
|
|
* @return list<array<string,mixed>>
|
|
*/
|
|
private static function linePools(array $items, array $coverageByGroup): array
|
|
{
|
|
$linePools = [];
|
|
foreach ($items as $item) {
|
|
$groupId = (int) ($item['group_id'] ?? 0);
|
|
$coverage = $coverageByGroup[$groupId] ?? [
|
|
'complete' => false,
|
|
'regions' => [],
|
|
];
|
|
$publicCoverage = self::publicCoverage(
|
|
is_array($coverage['regions'] ?? null)
|
|
? $coverage['regions'] : []
|
|
);
|
|
$summaryState = self::linePoolState($item);
|
|
if (($coverage['complete'] ?? false) !== true
|
|
|| $publicCoverage === []) {
|
|
$summaryState = 'attention';
|
|
}
|
|
foreach ($item['instances'] ?? [] as $instance) {
|
|
if (($instance['placement_scope_state'] ?? 'attention')
|
|
!== 'ready') {
|
|
$summaryState = 'attention';
|
|
break;
|
|
}
|
|
}
|
|
$item['key'] = 'line-group:' . $groupId;
|
|
$item['coverage_regions'] = $publicCoverage;
|
|
$item['coverage_region_count'] = count($publicCoverage);
|
|
$item['instance_count'] = count($item['instances'] ?? []);
|
|
$item['summary_state'] = $summaryState;
|
|
$item['requires_attention'] = $summaryState !== 'available';
|
|
$item['default_open'] = false;
|
|
$linePools[] = $item;
|
|
}
|
|
|
|
$hasAttention = false;
|
|
foreach ($linePools as $linePool) {
|
|
$hasAttention = $hasAttention
|
|
|| (bool) $linePool['requires_attention'];
|
|
}
|
|
foreach ($linePools as $index => &$linePool) {
|
|
$linePool['default_open'] = count($linePools) === 1
|
|
|| ($hasAttention
|
|
? (bool) $linePool['requires_attention']
|
|
: $index === 0);
|
|
}
|
|
unset($linePool);
|
|
return $linePools;
|
|
}
|
|
|
|
/**
|
|
* Resolve every visible commercial group to its coverage regions in one
|
|
* query. Coverage is descriptive only and never becomes an accounting
|
|
* identity or another UI grouping layer.
|
|
*
|
|
* @return array<int,array<string,mixed>>
|
|
*/
|
|
private static function coverageByGroup(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,
|
|
];
|
|
}
|
|
|
|
$coverage = [];
|
|
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']]
|
|
);
|
|
$coverage[$groupId] = [
|
|
'complete' => !isset($unresolved[$groupId])
|
|
&& $regions !== [],
|
|
'regions' => $regions,
|
|
];
|
|
}
|
|
return $coverage;
|
|
}
|
|
|
|
/** @return list<array{code:string,name:string}> */
|
|
private static function publicCoverage(array $regions): array
|
|
{
|
|
$public = [];
|
|
foreach ($regions as $region) {
|
|
if (!is_array($region)) {
|
|
continue;
|
|
}
|
|
$public[] = [
|
|
'code' => (string) ($region['code'] ?? ''),
|
|
'name' => (string) ($region['name'] ?? '未知地区'),
|
|
];
|
|
}
|
|
return $public;
|
|
}
|
|
|
|
private static function linePoolState(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';
|
|
}
|
|
|
|
/** @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,
|
|
];
|
|
}
|
|
}
|