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

478 lines
20 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudInstance;
use App\Models\CloudInstanceNetworkPolicyState;
use App\Models\CloudInstanceNetworkRestriction;
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);
$items = [];
foreach ($groups as $group) {
$groupId = (int) $group->id;
$items[] = self::poolDto(
$group,
$instancesByGroup[$groupId] ?? [],
$networkStates[$groupId] ?? 'clear',
$snapshots[$userId . ':' . $groupId],
isset($pendingGroups[$groupId])
);
}
return ['items' => $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',
])->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,
'service_expires_at' => $instance->expires_at === null
? null : (int) $instance->expires_at,
'network_status' => (string) $instance->network_status,
];
}
return $result;
}
/** @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,
];
}
}