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/CloudTrafficPoolAccounting.php

1823 lines
76 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudInstance;
use App\Models\CloudServicePeriod;
use App\Models\CloudTrafficEntitlement;
use App\Models\CloudTrafficInstanceCursor;
use App\Models\CloudTrafficLedgerEvent;
use App\Models\CloudTrafficPool;
use App\Models\CloudTrafficPoolGroup;
use App\Models\CloudTrafficScanFailure;
/**
* Shared prepaid traffic accounting.
*
* The public interface accepts only authoritative service-period and durable
* instance-counter facts. FEFO allocation, idempotency, expiry, overage and
* projection verification remain local to this module. Agent mutations are
* deliberately outside this transaction seam.
*/
final class CloudTrafficPoolAccounting
{
public const CLOSING_SECONDS = 90;
/** Reconcile one service period into its one entitlement. */
public static function reconcileServicePeriod(
int $servicePeriodId,
string $idempotencyKey,
?int $now = null
): array {
$now ??= time();
$periodHint = CloudServicePeriod::find($servicePeriodId);
if ($periodHint === null) {
throw new CloudError('服务周期不存在', 404);
}
$groupId = (int) ($periodHint->traffic_pool_group_id ?? 0);
$group = $groupId > 0 ? CloudTrafficPoolGroup::find($groupId) : null;
if ($group === null || (string) $group->mode === 'disabled') {
return self::disabledResult($periodHint, $groupId);
}
$connection = $periodHint->getConnection();
return $connection->transaction(function () use (
$connection,
$servicePeriodId,
$groupId,
$idempotencyKey,
$now
): array {
self::insertPoolIfMissing(
$connection,
(int) CloudServicePeriod::findOrFail($servicePeriodId)->user_id,
$groupId,
$now
);
$pool = CloudTrafficPool::where('user_id',
(int) CloudServicePeriod::findOrFail($servicePeriodId)->user_id)
->where('traffic_pool_group_id', $groupId)
->lockForUpdate()->first();
if ($pool === null) {
throw new \RuntimeException('traffic_pool_missing_after_insert');
}
$period = CloudServicePeriod::where('id', $servicePeriodId)
->lockForUpdate()->first();
if ($period === null
|| (int) $period->user_id !== (int) $pool->user_id
|| (int) ($period->traffic_pool_group_id ?? 0) !== $groupId) {
throw new \RuntimeException('traffic_period_pool_identity_changed');
}
if ((int) $period->starts_at >= (int) $period->ends_at) {
throw new \RuntimeException('traffic_period_window_invalid');
}
$quota = max(0, (int) $period->traffic_quota_bytes);
$quotaMode = $quota === 0 ? 'unlimited' : 'finite';
if ((string) $period->traffic_quota_mode !== $quotaMode) {
$period->traffic_quota_mode = $quotaMode;
$period->updated_at = $now;
$period->save();
}
$entitlement = CloudTrafficEntitlement::where(
'service_period_id', $servicePeriodId
)->lockForUpdate()->first();
$changed = false;
if ($entitlement === null) {
$entitlement = new CloudTrafficEntitlement();
$entitlement->pool_id = (int) $pool->id;
$entitlement->user_id = (int) $period->user_id;
$entitlement->instance_id = (int) $period->instance_id;
$entitlement->service_period_id = (int) $period->id;
$entitlement->starts_at = (int) $period->starts_at;
$entitlement->ends_at = (int) $period->ends_at;
$entitlement->quota_mode = $quotaMode;
$entitlement->granted_bytes = $quota;
$entitlement->consumed_bytes = 0;
$entitlement->forfeited_bytes = 0;
$entitlement->state = 'scheduled';
$entitlement->version = 1;
$entitlement->created_at = $now;
$entitlement->updated_at = $now;
$entitlement->save();
self::appendEventLocked($pool, [
'event_key' => 'period:' . $servicePeriodId . ':scheduled',
'event_type' => 'entitlement_scheduled',
'source_type' => 'service_period',
'source_id' => (string) $servicePeriodId,
'source_revision' => 1,
'instance_id' => (int) $period->instance_id,
'service_period_id' => $servicePeriodId,
'entitlement_id' => (int) $entitlement->id,
'amount_bytes' => $quota,
'effective_at' => (int) $period->starts_at,
'observed_at' => null,
'payload' => [
'quota_mode' => $quotaMode,
'starts_at' => (int) $period->starts_at,
'ends_at' => (int) $period->ends_at,
],
]);
$changed = true;
} else {
self::assertEntitlementIdentity(
$entitlement,
$period,
$pool,
$quotaMode
);
}
if ($quota < (int) $entitlement->granted_bytes) {
self::markAttentionLocked(
$pool,
'traffic_entitlement_quota_decrease',
$idempotencyKey,
$now,
$period,
$entitlement
);
return self::resultLocked($pool, true,
'traffic_entitlement_quota_decrease');
}
if ($quota > (int) $entitlement->granted_bytes) {
if ((string) $entitlement->state === 'expired') {
self::markAttentionLocked(
$pool,
'traffic_expired_entitlement_changed',
$idempotencyKey,
$now,
$period,
$entitlement
);
return self::resultLocked($pool, true,
'traffic_expired_entitlement_changed');
}
$delta = $quota - (int) $entitlement->granted_bytes;
$entitlement->granted_bytes = $quota;
$entitlement->version = (int) $entitlement->version + 1;
$entitlement->updated_at = $now;
$entitlement->save();
self::appendEventLocked($pool, [
'event_key' => 'period:' . $servicePeriodId
. ':grant:' . $quota,
'event_type' => 'entitlement_increased',
'source_type' => 'service_period',
'source_id' => $idempotencyKey,
'source_revision' => (int) $entitlement->version,
'instance_id' => (int) $period->instance_id,
'service_period_id' => $servicePeriodId,
'entitlement_id' => (int) $entitlement->id,
'amount_bytes' => $delta,
'effective_at' => $now,
'observed_at' => null,
'payload' => ['target_granted_bytes' => $quota],
]);
$changed = true;
if ((string) $entitlement->state === 'exhausted'
&& $now < (int) $entitlement->ends_at) {
$entitlement->state = 'active';
$entitlement->updated_at = $now;
$entitlement->save();
}
}
$changed = self::convergeEntitlementStateLocked(
$pool,
$entitlement,
$now
) || $changed;
if ((string) $entitlement->state === 'active'
&& (int) $pool->overage_bytes > 0) {
$changed = self::settleOverageLocked(
$pool,
'period:' . $servicePeriodId . ':overage:'
. (int) $entitlement->granted_bytes,
$now
) || $changed;
}
self::recomputePoolProjectionLocked($pool, $now);
return self::resultLocked($pool, $changed, null);
}, 3);
}
/**
* Extend only the paid-use window of an existing traffic entitlement.
* The caller owns the surrounding compensation transaction; this method
* preserves the pool -> period -> entitlement lock order and never grants
* additional bytes or revives a closed entitlement.
*/
public static function extendEntitlementWindowForCompensationLocked(
int $servicePeriodId,
int $oldEnd,
int $newEnd,
int $compensationItemId,
int $now
): ?CloudTrafficEntitlement {
if ($servicePeriodId < 1 || $oldEnd < 1 || $newEnd <= $oldEnd
|| $compensationItemId < 1) {
throw new CloudError('流量权益补偿窗口无效', 409);
}
$hint = CloudServicePeriod::find($servicePeriodId);
if ($hint === null) {
throw new CloudError('服务周期不存在', 404);
}
$groupId = (int) ($hint->traffic_pool_group_id ?? 0);
$group = $groupId > 0 ? CloudTrafficPoolGroup::find($groupId) : null;
if ($group === null || (string) $group->mode === 'disabled') {
$period = CloudServicePeriod::where('id', $servicePeriodId)
->lockForUpdate()->first();
if ($period === null
|| !in_array((int) $period->ends_at,
[$oldEnd, $newEnd], true)
|| (int) $period->starts_at >= (int) $period->ends_at) {
throw new CloudError('非共享流量周期窗口不一致', 409);
}
$unexpected = CloudTrafficEntitlement::where(
'service_period_id', $servicePeriodId
)->lockForUpdate()->first();
if ($unexpected !== null) {
throw new CloudError('非共享流量周期存在异常权益', 409);
}
return null;
}
$pool = CloudTrafficPool::where('user_id', (int) $hint->user_id)
->where('traffic_pool_group_id', $groupId)
->lockForUpdate()->first();
if ($pool === null || (string) $pool->state === 'attention') {
throw new CloudError('共享流量池账本需要先完成核对', 409);
}
$period = CloudServicePeriod::where('id', $servicePeriodId)
->lockForUpdate()->first();
if ($period === null
|| (int) $period->user_id !== (int) $pool->user_id
|| (int) ($period->traffic_pool_group_id ?? 0) !== $groupId
|| !in_array((int) $period->ends_at,
[$oldEnd, $newEnd], true)
|| (int) $period->starts_at >= (int) $period->ends_at) {
throw new CloudError('共享流量周期窗口不一致', 409);
}
$entitlement = CloudTrafficEntitlement::where(
'service_period_id', $servicePeriodId
)->lockForUpdate()->first();
if ($entitlement === null) {
throw new CloudError('共享流量周期缺少权益账本', 409);
}
$quotaMode = max(0, (int) $period->traffic_quota_bytes) === 0
? 'unlimited' : 'finite';
$identityMatches = (int) $entitlement->pool_id === (int) $pool->id
&& (int) $entitlement->user_id === (int) $period->user_id
&& (int) $entitlement->instance_id === (int) $period->instance_id
&& (int) $entitlement->starts_at === (int) $period->starts_at
&& (string) $entitlement->quota_mode === $quotaMode;
if (!$identityMatches) {
throw new CloudError('共享流量权益身份不一致', 409);
}
$eventKey = 'compensation-item:' . $compensationItemId
. ':traffic-window';
$existing = CloudTrafficLedgerEvent::where(
'event_key', $eventKey
)->first();
if ($existing !== null) {
$payload = json_decode((string) $existing->payload_json, true);
if ((int) $entitlement->ends_at !== $newEnd
|| !in_array((int) $period->ends_at,
[$oldEnd, $newEnd], true)
|| (int) $existing->pool_id !== (int) $pool->id
|| (string) $existing->event_type
!== 'entitlement_window_extended'
|| (string) $existing->source_type
!== 'service_compensation'
|| (string) $existing->source_id
!== (string) $compensationItemId
|| (int) $existing->service_period_id !== $servicePeriodId
|| (int) $existing->entitlement_id !== (int) $entitlement->id
|| (int) $existing->amount_bytes !== 0
|| !is_array($payload)
|| (int) ($payload['old_ends_at'] ?? 0) !== $oldEnd
|| (int) ($payload['new_ends_at'] ?? 0) !== $newEnd) {
throw new CloudError('流量权益补偿幂等记录冲突', 409);
}
return $entitlement;
}
if ((int) $period->ends_at !== $oldEnd
|| (int) $entitlement->ends_at !== $oldEnd
|| !in_array((string) $entitlement->state,
['scheduled', 'active', 'exhausted'], true)) {
throw new CloudError('流量权益当前状态不允许延长', 409);
}
$entitlement->ends_at = $newEnd;
$entitlement->version = (int) $entitlement->version + 1;
$entitlement->updated_at = $now;
$entitlement->save();
self::appendEventLocked($pool, [
'event_key' => $eventKey,
'event_type' => 'entitlement_window_extended',
'source_type' => 'service_compensation',
'source_id' => (string) $compensationItemId,
'source_revision' => (int) $entitlement->version,
'instance_id' => (int) $period->instance_id,
'service_period_id' => (int) $period->id,
'entitlement_id' => (int) $entitlement->id,
'amount_bytes' => 0,
'effective_at' => $now,
'observed_at' => null,
'payload' => [
'old_ends_at' => $oldEnd,
'new_ends_at' => $newEnd,
],
]);
self::recomputePoolProjectionLocked($pool, $now);
return $entitlement;
}
/** Settle one instance's already-persisted monotonic public counters. */
public static function settleInstanceUsage(
int $instanceId,
?int $observedAt = null
): array {
return self::settleInstanceUsageAttempt(
$instanceId,
$observedAt,
0
);
}
private static function settleInstanceUsageAttempt(
int $instanceId,
?int $observedAt,
int $attempt
): array {
$instanceHint = CloudInstance::find($instanceId);
if ($instanceHint === null) {
throw new CloudError('实例不存在', 404);
}
$snapshotObservedAt = max(0, (int) $instanceHint->traffic_synced_at);
if ($observedAt === null || $observedAt !== $snapshotObservedAt) {
$observedAt = $snapshotObservedAt;
}
$snapshotDownload = max(0,
(int) $instanceHint->lifetime_download_bytes);
$snapshotUpload = max(0,
(int) $instanceHint->lifetime_upload_bytes);
$snapshotUserId = (int) $instanceHint->user_id;
$periodHint = self::periodForObservation($instanceId, $observedAt);
if ($periodHint === null) {
return self::disabledInstanceResult($instanceId);
}
$periodId = (int) $periodHint->id;
$groupId = (int) ($periodHint->traffic_pool_group_id ?? 0);
$group = $groupId > 0 ? CloudTrafficPoolGroup::find($groupId) : null;
if ($group === null || (string) $group->mode === 'disabled') {
return self::disabledInstanceResult($instanceId);
}
$settledAt = time();
self::reconcileServicePeriod(
$periodId,
'usage-prerequisite:' . $instanceId . ':' . $periodId,
$settledAt
);
$connection = $instanceHint->getConnection();
$result = $connection->transaction(function () use (
$connection,
$instanceId,
$periodId,
$groupId,
$observedAt,
$settledAt,
$snapshotDownload,
$snapshotUpload,
$snapshotUserId
): array {
$period = CloudServicePeriod::find($periodId);
if ($period === null || (int) $period->instance_id !== $instanceId
|| (int) ($period->traffic_pool_group_id ?? 0) !== $groupId) {
return self::disabledInstanceResult($instanceId);
}
$pool = CloudTrafficPool::where('user_id', $snapshotUserId)
->where('traffic_pool_group_id', $groupId)
->lockForUpdate()->first();
if ($pool === null) {
throw new \RuntimeException('traffic_pool_missing_for_usage');
}
$instance = CloudInstance::find($instanceId);
if ($instance === null
|| (int) $instance->user_id !== $snapshotUserId
|| (int) $instance->traffic_synced_at !== $observedAt
|| max(0, (int) $instance->lifetime_download_bytes)
!== $snapshotDownload
|| max(0, (int) $instance->lifetime_upload_bytes)
!== $snapshotUpload) {
return ['retry_snapshot' => true];
}
$download = max(0, (int) $instance->lifetime_download_bytes);
$upload = max(0, (int) $instance->lifetime_upload_bytes);
$baselineDownload = $period->download_base_bytes === null
? $download : max(0, (int) $period->download_base_bytes);
$baselineUpload = $period->upload_base_bytes === null
? $upload : max(0, (int) $period->upload_base_bytes);
$connection->table('cloud_traffic_instance_cursors')
->insertOrIgnore([
'instance_id' => $instanceId,
'user_id' => (int) $instance->user_id,
'pool_id' => (int) $pool->id,
'accounted_download_bytes' => $baselineDownload,
'accounted_upload_bytes' => $baselineUpload,
'last_observed_at' => 0,
'last_event_id' => null,
'state' => 'ready',
'attention_code' => '',
'version' => 0,
'updated_at' => time(),
]);
$cursor = CloudTrafficInstanceCursor::where(
'instance_id', $instanceId
)->lockForUpdate()->first();
if ($cursor === null) {
throw new \RuntimeException('traffic_cursor_missing_after_insert');
}
if ((int) $cursor->pool_id !== (int) $pool->id
|| (int) $cursor->user_id !== (int) $instance->user_id) {
self::markCursorAttentionLocked(
$pool,
$cursor,
'traffic_cursor_pool_changed',
$observedAt
);
return self::resultLocked(
$pool,
true,
'traffic_cursor_pool_changed'
);
}
if ($download < (int) $cursor->accounted_download_bytes
|| $upload < (int) $cursor->accounted_upload_bytes) {
self::markCursorAttentionLocked(
$pool,
$cursor,
'traffic_counter_regression',
$observedAt
);
return self::resultLocked(
$pool,
true,
'traffic_counter_regression'
);
}
return self::applyUsageDeltaLocked(
$pool,
$cursor,
$instance,
$period,
$observedAt,
$settledAt
);
}, 3);
if (($result['retry_snapshot'] ?? false) === true) {
if ($attempt >= 2) {
throw new CloudError('流量采样持续变化,请稍后重试', 409);
}
return self::settleInstanceUsageAttempt(
$instanceId,
null,
$attempt + 1
);
}
return $result;
}
/** Read the only supported pool projection for user and admin pages. */
public static function snapshot(
int $userId,
int $trafficPoolGroupId,
?int $at = null
): array {
$key = $userId . ':' . $trafficPoolGroupId;
$snapshots = self::snapshots([[
'user_id' => $userId,
'traffic_pool_group_id' => $trafficPoolGroupId,
]], $at);
return $snapshots[$key]
?? self::emptySnapshot($userId, $trafficPoolGroupId);
}
/** Read many canonical projections without a query loop per pool. */
public static function snapshots(array $identities, ?int $at = null): array
{
$at ??= time();
$pairs = [];
foreach ($identities as $identity) {
$userId = max(0, (int) ($identity['user_id'] ?? 0));
$groupId = max(0,
(int) ($identity['traffic_pool_group_id'] ?? 0));
if ($userId < 1 || $groupId < 1) {
continue;
}
$pairs[$userId . ':' . $groupId] = [
'user_id' => $userId,
'traffic_pool_group_id' => $groupId,
];
}
if ($pairs === []) {
return [];
}
$pools = CloudTrafficPool::where(function ($query) use ($pairs): void {
foreach ($pairs as $pair) {
$query->orWhere(function ($branch) use ($pair): void {
$branch->where('user_id', $pair['user_id'])
->where('traffic_pool_group_id',
$pair['traffic_pool_group_id']);
});
}
})->get();
$poolsByKey = [];
$poolIds = [];
foreach ($pools as $pool) {
$key = (int) $pool->user_id . ':'
. (int) $pool->traffic_pool_group_id;
if (!isset($pairs[$key])) {
continue;
}
$poolsByKey[$key] = $pool;
$poolIds[] = (int) $pool->id;
}
$activeByPool = [];
$lastObservedByPool = [];
if ($poolIds !== []) {
foreach (CloudTrafficEntitlement::whereIn('pool_id', $poolIds)
->where('quota_mode', 'finite')
->whereIn('state', ['active', 'exhausted'])
->where('starts_at', '<=', $at)->where('ends_at', '>', $at)
->orderBy('ends_at')->orderBy('id')->get() as $entitlement) {
$activeByPool[(int) $entitlement->pool_id][] = $entitlement;
}
foreach (CloudTrafficInstanceCursor::whereIn('pool_id', $poolIds)
->selectRaw('pool_id, MAX(last_observed_at) AS last_observed_at')
->groupBy('pool_id')->get() as $cursor) {
$lastObservedByPool[(int) $cursor->pool_id] =
$cursor->last_observed_at === null
? null : (int) $cursor->last_observed_at;
}
}
$result = [];
foreach ($pairs as $key => $pair) {
$pool = $poolsByKey[$key] ?? null;
if ($pool === null) {
$result[$key] = self::emptySnapshot(
$pair['user_id'],
$pair['traffic_pool_group_id']
);
continue;
}
$granted = 0;
$consumed = 0;
$available = 0;
$nextExpiryAt = null;
$nextExpiryBytes = 0;
foreach ($activeByPool[(int) $pool->id] ?? [] as $entitlement) {
$granted += (int) $entitlement->granted_bytes;
$consumed += (int) $entitlement->consumed_bytes;
$remaining = self::entitlementRemaining($entitlement);
$available += $remaining;
if ($nextExpiryAt === null) {
$nextExpiryAt = (int) $entitlement->ends_at;
}
if ((int) $entitlement->ends_at === $nextExpiryAt) {
$nextExpiryBytes += $remaining;
}
}
$result[$key] = [
'pool_id' => (int) $pool->id,
'user_id' => $pair['user_id'],
'traffic_pool_group_id' => $pair['traffic_pool_group_id'],
'state' => (string) $pool->state,
'active_entitlement_bytes' => $granted,
'active_consumed_bytes' => $consumed,
'available_bytes' => $available,
'overage_bytes' => (int) $pool->overage_bytes,
'next_expiry_at' => $nextExpiryAt,
'next_expiry_bytes' => $nextExpiryBytes,
'last_observed_at' =>
$lastObservedByPool[(int) $pool->id] ?? null,
'version' => (int) $pool->version,
];
}
return $result;
}
private static function emptySnapshot(int $userId, int $groupId): array
{
return [
'pool_id' => null,
'user_id' => $userId,
'traffic_pool_group_id' => $groupId,
'state' => 'available',
'active_entitlement_bytes' => 0,
'active_consumed_bytes' => 0,
'available_bytes' => 0,
'overage_bytes' => 0,
'next_expiry_at' => null,
'next_expiry_bytes' => 0,
'last_observed_at' => null,
'version' => 0,
];
}
/**
* Clear an attention fence only after the exact pool version and every
* durable accounting invariant have been re-verified. This is a new
* audited resolution generation, never a replay of a remote mutation.
*/
public static function resolveAttention(
int $poolId,
int $expectedVersion,
string $resolutionKey,
?int $now = null
): array {
if (preg_match(
'/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/D',
$resolutionKey
) !== 1) {
throw new CloudError(
'账本核对标识必须是小写规范 UUIDv4'
);
}
$now ??= time();
$hint = CloudTrafficPool::find($poolId);
if ($hint === null) {
throw new CloudError('流量池不存在', 404);
}
return $hint->getConnection()->transaction(function () use (
$poolId,
$expectedVersion,
$resolutionKey,
$now
): array {
$pool = CloudTrafficPool::where('id', $poolId)
->lockForUpdate()->first();
if ($pool === null) {
throw new CloudError('流量池不存在', 404);
}
if ((int) $pool->version !== $expectedVersion) {
throw new CloudError('流量池状态已变化,请刷新后重新核对', 409);
}
if ((string) $pool->state !== 'attention') {
return self::resultLocked($pool, false, null);
}
$verification = self::verifyProjection($poolId, $now);
if (!$verification['valid']) {
throw new CloudError('流量池账本投影仍不一致,不能解除安全栅栏', 409);
}
$latestResolution = CloudTrafficLedgerEvent::where(
'pool_id', $poolId
)->where('event_type', 'attention_resolved')->max('id');
$unresolvedEvents = CloudTrafficLedgerEvent::where(
'pool_id', $poolId
)->where('id', '>', (int) ($latestResolution ?? 0))
->whereIn('event_type', [
'accounting_attention',
'counter_attention',
])->orderBy('id')->get();
$counterInstanceIds = [];
foreach ($unresolvedEvents as $event) {
if ((string) $event->event_type === 'counter_attention'
&& (int) ($event->instance_id ?? 0) > 0) {
$counterInstanceIds[(int) $event->instance_id] = true;
}
}
$cursors = CloudTrafficInstanceCursor::query()
->where('state', 'attention')
->where(function ($query) use (
$poolId,
$counterInstanceIds
): void {
$query->where('pool_id', $poolId);
if ($counterInstanceIds !== []) {
$query->orWhereIn(
'instance_id',
array_keys($counterInstanceIds)
);
}
})->orderBy('instance_id')
->lockForUpdate()->get();
$settledCursorCount = 0;
foreach ($cursors as $cursor) {
$instance = CloudInstance::find((int) $cursor->instance_id);
if ($instance === null
|| (int) $cursor->pool_id !== $poolId
|| (int) $cursor->user_id !== (int) $pool->user_id
|| (int) $instance->lifetime_download_bytes
< (int) $cursor->accounted_download_bytes
|| (int) $instance->lifetime_upload_bytes
< (int) $cursor->accounted_upload_bytes) {
throw new CloudError('流量累计计数尚未追平,不能解除安全栅栏', 409);
}
if ((int) $instance->lifetime_download_bytes
> (int) $cursor->accounted_download_bytes
|| (int) $instance->lifetime_upload_bytes
> (int) $cursor->accounted_upload_bytes) {
$observedAt = max(0, (int) $instance->traffic_synced_at);
$period = self::periodForObservation(
(int) $instance->id,
$observedAt
);
if ($period === null
|| (int) $period->user_id !== (int) $pool->user_id
|| (int) ($period->traffic_pool_group_id ?? 0)
!== (int) $pool->traffic_pool_group_id
|| !CloudTrafficEntitlement::where(
'service_period_id', (int) $period->id
)->exists()) {
throw new CloudError('流量累计增量缺少可核对的服务周期', 409);
}
self::applyUsageDeltaLocked(
$pool,
$cursor,
$instance,
$period,
$observedAt,
$now
);
$settledCursorCount++;
}
}
foreach ($unresolvedEvents as $event) {
if ((string) $event->event_type === 'accounting_attention') {
self::assertAccountingAttentionResolvedLocked(
$pool,
$event
);
}
}
foreach ($cursors as $cursor) {
if ((string) $cursor->state !== 'attention') {
continue;
}
$cursor->state = 'ready';
$cursor->attention_code = '';
$cursor->version = (int) $cursor->version + 1;
$cursor->updated_at = $now;
$cursor->save();
}
self::appendEventLocked($pool, [
// The operator-supplied UUID is globally unique. Keeping the
// pool ID out of this identity lets the ledger event-key
// constraint reject reuse across different pools as well.
'event_key' => 'attention-resolution:' . $resolutionKey,
'event_type' => 'attention_resolved',
'source_type' => 'admin_reconciliation',
'source_id' => $resolutionKey,
'source_revision' => 1,
'instance_id' => null,
'service_period_id' => null,
'entitlement_id' => null,
'amount_bytes' => 0,
'effective_at' => $now,
'observed_at' => null,
'payload' => [
'expected_version' => $expectedVersion,
'cleared_cursor_count' => count($cursors),
'settled_cursor_count' => $settledCursorCount,
'resolved_attention_count' => count($unresolvedEvents),
'projection_verified' => true,
],
]);
$pool->state = 'available';
$pool->updated_at = $now;
$pool->save();
self::recomputePoolProjectionLocked($pool, $now);
return self::resultLocked($pool, true, null);
}, 3);
}
/** Verify mutable projections against the immutable event ledger. */
public static function verifyProjection(int $poolId, ?int $at = null): array
{
$at ??= time();
$pool = CloudTrafficPool::find($poolId);
if ($pool === null) {
throw new CloudError('流量池不存在', 404);
}
$errors = [];
foreach (CloudTrafficEntitlement::where('pool_id', $poolId)
->orderBy('id')->get() as $entitlement) {
$events = CloudTrafficLedgerEvent::where(
'entitlement_id', (int) $entitlement->id
)->get();
$granted = 0;
$consumed = 0;
$forfeited = 0;
foreach ($events as $event) {
$amount = (int) $event->amount_bytes;
if (in_array((string) $event->event_type,
['entitlement_scheduled', 'entitlement_increased'], true)) {
$granted += $amount;
} elseif (in_array((string) $event->event_type,
['usage_allocated', 'overage_settled'], true)) {
$consumed += $amount;
} elseif ((string) $event->event_type
=== 'entitlement_forfeited') {
$forfeited += $amount;
}
}
if ($granted !== (int) $entitlement->granted_bytes
|| $consumed !== (int) $entitlement->consumed_bytes
|| $forfeited !== (int) $entitlement->forfeited_bytes) {
$errors[] = 'entitlement:' . (int) $entitlement->id;
}
}
$ledgerOverage = (int) CloudTrafficLedgerEvent::where(
'pool_id', $poolId
)->where('event_type', 'overage_recorded')->sum('amount_bytes')
- (int) CloudTrafficLedgerEvent::where('pool_id', $poolId)
->where('event_type', 'overage_settled')->sum('amount_bytes');
if ($ledgerOverage !== (int) $pool->overage_bytes) {
$errors[] = 'pool:overage';
}
$projectedAvailable = 0;
foreach (CloudTrafficEntitlement::where('pool_id', $poolId)
->where('state', 'active')
->where('starts_at', '<=', $at)
->where('ends_at', '>', $at)
->get() as $entitlement) {
$projectedAvailable += self::entitlementRemaining($entitlement);
}
if ($projectedAvailable !== (int) $pool->available_bytes) {
$errors[] = 'pool:available';
}
return ['valid' => $errors === [], 'errors' => $errors];
}
/** Discover missing and due period projections without locking instances. */
public static function reconcileDue(
int $limit = 200,
?int $now = null,
int $afterPeriodId = 0
): array
{
$now ??= time();
$limit = max(1, $limit);
$afterPeriodId = max(0, $afterPeriodId);
$periodIds = [];
$missing = CloudServicePeriod::query()
->leftJoin('cloud_traffic_entitlements as traffic_entitlement',
'traffic_entitlement.service_period_id', '=',
'cloud_service_periods.id')
->leftJoin('cloud_traffic_scan_failures as missing_failure',
static function ($join): void {
$join->on('missing_failure.subject_id', '=',
'cloud_service_periods.id')
->where('missing_failure.scan_kind', '=', 'period');
})
->join('cloud_traffic_pool_groups as traffic_group',
'traffic_group.id', '=',
'cloud_service_periods.traffic_pool_group_id')
->whereIn('traffic_group.mode', ['shadow', 'enforced'])
->whereIn('cloud_service_periods.status',
['scheduled', 'active', 'exhausted', 'finished'])
->whereNull('traffic_entitlement.id')
->where(function ($retry) use ($now): void {
$retry->whereNull('missing_failure.id')
->orWhere('missing_failure.retry_at', '<=', $now);
})
->where('cloud_service_periods.id', '>', $afterPeriodId)
->orderBy('cloud_service_periods.id')->limit($limit)
->pluck('cloud_service_periods.id')->all();
$due = CloudTrafficEntitlement::query()
->leftJoin('cloud_traffic_scan_failures as due_failure',
static function ($join): void {
$join->on('due_failure.subject_id', '=',
'cloud_traffic_entitlements.service_period_id')
->where('due_failure.scan_kind', '=', 'period');
})
->join('cloud_traffic_pools as due_pool',
'due_pool.id', '=',
'cloud_traffic_entitlements.pool_id')
->join('cloud_traffic_pool_groups as due_group',
'due_group.id', '=',
'due_pool.traffic_pool_group_id')
->whereIn('due_group.mode', ['shadow', 'enforced'])
->where(function ($retry) use ($now): void {
$retry->whereNull('due_failure.id')
->orWhere('due_failure.retry_at', '<=', $now);
})
->where('cloud_traffic_entitlements.service_period_id', '>',
$afterPeriodId)
->where(function ($query) use ($now): void {
$query->where(function ($scheduled) use ($now): void {
$scheduled->where(
'cloud_traffic_entitlements.state', 'scheduled'
)->where('cloud_traffic_entitlements.starts_at',
'<=', $now);
})->orWhere(function ($ending) use ($now): void {
$ending->whereIn(
'cloud_traffic_entitlements.state',
['active', 'exhausted']
)->where('cloud_traffic_entitlements.ends_at',
'<=', $now);
})->orWhere(function ($closing) use ($now): void {
$closing->where(
'cloud_traffic_entitlements.state', 'closing'
)->where('cloud_traffic_entitlements.closed_at',
'<=', $now);
});
})->orderBy('cloud_traffic_entitlements.service_period_id')
->limit($limit)
->pluck('cloud_traffic_entitlements.service_period_id')->all();
$changed = CloudTrafficEntitlement::query()
->leftJoin('cloud_traffic_scan_failures as changed_failure',
static function ($join): void {
$join->on('changed_failure.subject_id', '=',
'cloud_traffic_entitlements.service_period_id')
->where('changed_failure.scan_kind', '=', 'period');
})
->join('cloud_service_periods as traffic_period',
'traffic_period.id', '=',
'cloud_traffic_entitlements.service_period_id')
->join('cloud_traffic_pools as changed_pool',
'changed_pool.id', '=',
'cloud_traffic_entitlements.pool_id')
->join('cloud_traffic_pool_groups as changed_group',
'changed_group.id', '=',
'changed_pool.traffic_pool_group_id')
->whereIn('changed_group.mode', ['shadow', 'enforced'])
->where(function ($retry) use ($now): void {
$retry->whereNull('changed_failure.id')
->orWhere('changed_failure.retry_at', '<=', $now);
})
->where('cloud_traffic_entitlements.service_period_id', '>',
$afterPeriodId)
->whereColumn(
'traffic_period.traffic_quota_bytes',
'>',
'cloud_traffic_entitlements.granted_bytes'
)->orderBy('cloud_traffic_entitlements.service_period_id')
->limit($limit)
->pluck('cloud_traffic_entitlements.service_period_id')
->all();
foreach (array_merge($missing, $due, $changed) as $id) {
$periodIds[(int) $id] = true;
}
ksort($periodIds, SORT_NUMERIC);
$periodIds = array_slice($periodIds, 0, $limit, true);
$processed = 0;
$errors = [];
foreach (array_keys($periodIds) as $periodId) {
try {
self::reconcileServicePeriod(
$periodId,
'period-scan:' . $periodId,
$now
);
self::clearScanFailure('period', $periodId);
$processed++;
} catch (\Throwable $error) {
self::recordScanFailure('period', $periodId, $error, $now);
$errors[] = [
'period_id' => $periodId,
'error' => get_class($error),
];
}
}
$selectedIds = array_keys($periodIds);
$nextCursor = count($selectedIds) >= $limit
? (int) max($selectedIds) : 0;
return [
'processed' => $processed,
'errors' => $errors,
'next_cursor' => $nextCursor,
];
}
/** Discover persisted counters that have not yet crossed the accounting seam. */
public static function settlePendingUsage(
int $limit = 200,
int $afterInstanceId = 0
): array
{
$now = time();
$limit = max(1, $limit);
$afterInstanceId = max(0, $afterInstanceId);
$rows = CloudInstance::query()
->leftJoin('cloud_traffic_instance_cursors as traffic_cursor',
'traffic_cursor.instance_id', '=', 'cloud_instances.id')
->leftJoin('cloud_traffic_scan_failures as instance_failure',
static function ($join): void {
$join->on('instance_failure.subject_id', '=',
'cloud_instances.id')
->where('instance_failure.scan_kind', '=', 'instance');
})
->whereExists(function ($eligible): void {
$eligible->selectRaw('1')
->from('cloud_service_periods as eligible_period')
->join('cloud_traffic_pool_groups as eligible_group',
'eligible_group.id', '=',
'eligible_period.traffic_pool_group_id')
->whereColumn('eligible_period.instance_id',
'cloud_instances.id')
->whereIn('eligible_group.mode',
['shadow', 'enforced']);
})
->where(function ($query): void {
$query->where(function ($missing): void {
$missing->whereNull('traffic_cursor.instance_id')
->where('cloud_instances.traffic_synced_at', '>', 0);
})->orWhere('traffic_cursor.state', 'ready');
})
->where(function ($query): void {
$query->whereNull('traffic_cursor.instance_id')
->orWhereColumn('cloud_instances.lifetime_download_bytes',
'>', 'traffic_cursor.accounted_download_bytes')
->orWhereColumn('cloud_instances.lifetime_upload_bytes',
'>', 'traffic_cursor.accounted_upload_bytes')
->orWhereColumn('cloud_instances.lifetime_download_bytes',
'<', 'traffic_cursor.accounted_download_bytes')
->orWhereColumn('cloud_instances.lifetime_upload_bytes',
'<', 'traffic_cursor.accounted_upload_bytes');
})->where(function ($retry) use ($now): void {
$retry->whereNull('instance_failure.id')
->orWhere('instance_failure.retry_at', '<=', $now);
})->where('cloud_instances.id', '>', $afterInstanceId)
->orderBy('cloud_instances.id')->limit($limit)->distinct()
->get([
'cloud_instances.id',
'cloud_instances.traffic_synced_at',
]);
$processed = 0;
$errors = [];
foreach ($rows as $row) {
try {
self::settleInstanceUsage(
(int) $row->id,
(int) $row->traffic_synced_at
);
self::clearScanFailure('instance', (int) $row->id);
$processed++;
} catch (\Throwable $error) {
self::recordScanFailure(
'instance',
(int) $row->id,
$error,
$now
);
$errors[] = [
'instance_id' => (int) $row->id,
'error' => get_class($error),
];
}
}
$nextCursor = count($rows) >= $limit
? (int) $rows->last()->id : 0;
return [
'processed' => $processed,
'errors' => $errors,
'next_cursor' => $nextCursor,
];
}
private static function recordScanFailure(
string $scanKind,
int $subjectId,
\Throwable $error,
int $now
): void {
if (!in_array($scanKind, ['period', 'instance'], true)
|| $subjectId < 1) {
return;
}
$model = new CloudTrafficScanFailure();
$connection = $model->getConnection();
$connection->transaction(function () use (
$connection,
$scanKind,
$subjectId,
$error,
$now
): void {
$subjectExists = $scanKind === 'period'
? CloudServicePeriod::where('id', $subjectId)
->select('id')->lockForUpdate()->first() !== null
: CloudInstance::where('id', $subjectId)
->select('id')->lockForUpdate()->first() !== null;
if (!$subjectExists) {
return;
}
$connection->table('cloud_traffic_scan_failures')
->insertOrIgnore([
'scan_kind' => $scanKind,
'subject_id' => $subjectId,
'attempt_count' => 0,
'last_error_code' => '',
'retry_at' => $now,
'first_failed_at' => $now,
'last_failed_at' => $now,
]);
$failure = CloudTrafficScanFailure::where(
'scan_kind', $scanKind
)->where('subject_id', $subjectId)->lockForUpdate()->first();
if ($failure === null) {
return;
}
$attempt = min(65535, (int) $failure->attempt_count + 1);
$class = get_class($error);
$separator = strrpos($class, '\\');
$code = $separator === false
? $class : substr($class, $separator + 1);
$backoff = min(3600, 30 * (2 ** min(7, $attempt - 1)));
$failure->attempt_count = $attempt;
$failure->last_error_code = substr($code, 0, 128);
$failure->retry_at = $now + $backoff;
$failure->last_failed_at = $now;
$failure->save();
}, 3);
}
private static function clearScanFailure(
string $scanKind,
int $subjectId
): void {
CloudTrafficScanFailure::where('scan_kind', $scanKind)
->where('subject_id', $subjectId)->delete();
}
private static function assertAccountingAttentionResolvedLocked(
CloudTrafficPool $pool,
CloudTrafficLedgerEvent $event
): void {
$periodId = (int) ($event->service_period_id ?? 0);
$entitlementId = (int) ($event->entitlement_id ?? 0);
$period = $periodId > 0
? CloudServicePeriod::where('id', $periodId)
->lockForUpdate()->first()
: null;
$entitlement = $entitlementId > 0
? CloudTrafficEntitlement::where('id', $entitlementId)
->lockForUpdate()->first()
: null;
if ($period === null || $entitlement === null) {
throw new CloudError('服务周期账务冲突仍需人工补偿', 409);
}
$quota = max(0, (int) $period->traffic_quota_bytes);
$quotaMode = $quota === 0 ? 'unlimited' : 'finite';
if ((int) $entitlement->pool_id !== (int) $pool->id
|| (int) $period->user_id !== (int) $pool->user_id
|| (int) ($period->traffic_pool_group_id ?? 0)
!== (int) $pool->traffic_pool_group_id
|| (int) $entitlement->service_period_id !== (int) $period->id
|| (int) $entitlement->instance_id !== (int) $period->instance_id
|| (int) $entitlement->starts_at !== (int) $period->starts_at
|| (int) $entitlement->ends_at !== (int) $period->ends_at
|| (string) $entitlement->quota_mode !== $quotaMode
|| (int) $entitlement->granted_bytes !== $quota) {
throw new CloudError('服务周期账务冲突仍需人工补偿', 409);
}
}
private static function periodForObservation(
int $instanceId,
int $observedAt
): ?CloudServicePeriod {
$period = CloudServicePeriod::where('instance_id', $instanceId)
->where('starts_at', '<=', $observedAt)
->where('ends_at', '>=', $observedAt)
->orderByDesc('starts_at')->orderByDesc('id')->first();
if ($period !== null) {
return $period;
}
// Traffic observed during an expiry gap belongs to the last paid
// period's pool (normally as overage), never to a later renewal.
// Advancing that pool's cursor prevents the next paid period from
// being charged for bytes transferred while no service was active.
return CloudServicePeriod::where('instance_id', $instanceId)
->where('starts_at', '<=', $observedAt)
->orderByDesc('starts_at')->orderByDesc('id')->first();
}
/**
* Apply one monotonic counter delta while the pool and cursor are locked.
* The caller must preserve pool -> cursor -> entitlement lock order.
*/
private static function applyUsageDeltaLocked(
CloudTrafficPool $pool,
CloudTrafficInstanceCursor $cursor,
CloudInstance $instance,
CloudServicePeriod $period,
int $observedAt,
int $now
): array {
$applyAt = max($now, time());
$endedEntitlements = CloudTrafficEntitlement::where(
'pool_id', (int) $pool->id
)->whereIn('state', ['active', 'exhausted', 'closing'])
->where('ends_at', '<=', $applyAt)
->orderBy('ends_at')->orderBy('id')->lockForUpdate()->get();
foreach ($endedEntitlements as $endedEntitlement) {
self::convergeEntitlementStateLocked(
$pool,
$endedEntitlement,
$applyAt
);
}
$download = max(0, (int) $instance->lifetime_download_bytes);
$upload = max(0, (int) $instance->lifetime_upload_bytes);
$downloadDelta = $download
- (int) $cursor->accounted_download_bytes;
$uploadDelta = $upload - (int) $cursor->accounted_upload_bytes;
if ($downloadDelta < 0 || $uploadDelta < 0) {
throw new CloudError('流量累计计数尚未追平,不能解除安全栅栏', 409);
}
$delta = $downloadDelta + $uploadDelta;
if ($delta === 0) {
if ($observedAt > (int) $cursor->last_observed_at) {
$cursor->last_observed_at = $observedAt;
$cursor->updated_at = $applyAt;
$cursor->save();
}
self::recomputePoolProjectionLocked($pool, $applyAt);
return self::resultLocked($pool, false, null);
}
$instanceId = (int) $instance->id;
$sourceId = 'instance:' . $instanceId . ':rx:' . $download
. ':tx:' . $upload;
$lastEventId = null;
if ((string) $period->traffic_quota_mode !== 'unlimited') {
$remaining = $delta;
$entitlements = CloudTrafficEntitlement::where(
'pool_id', (int) $pool->id
)->where('quota_mode', 'finite')
->where('starts_at', '<=', $observedAt)
->where(function ($query) use (
$observedAt,
$applyAt
): void {
$query->where(function ($active) use (
$observedAt,
$applyAt
): void {
$active->where('state', 'active')
->where('ends_at', '>=', $observedAt)
->where('ends_at', '>', $applyAt);
})->orWhere(function ($closing) use (
$observedAt,
$applyAt
): void {
$closing->where('state', 'closing')
->where('ends_at', '>=', $observedAt)
->where('closed_at', '>', $applyAt);
});
})->orderBy('ends_at')->orderBy('id')
->lockForUpdate()->get();
$ordinal = 0;
foreach ($entitlements as $entitlement) {
if ($remaining <= 0) {
break;
}
$available = self::entitlementRemaining($entitlement);
if ($available <= 0) {
continue;
}
$take = min($available, $remaining);
$entitlement->consumed_bytes =
(int) $entitlement->consumed_bytes + $take;
if (self::entitlementRemaining($entitlement) === 0
&& (string) $entitlement->state === 'active') {
$entitlement->state = 'exhausted';
}
$entitlement->version = (int) $entitlement->version + 1;
$entitlement->updated_at = $applyAt;
$entitlement->save();
$event = self::appendEventLocked($pool, [
'event_key' => $sourceId . ':allocation:'
. (int) $entitlement->id,
'event_type' => 'usage_allocated',
'source_type' => 'traffic_observation',
'source_id' => $sourceId,
'source_revision' => 1,
'instance_id' => $instanceId,
'service_period_id' =>
(int) $entitlement->service_period_id,
'entitlement_id' => (int) $entitlement->id,
'amount_bytes' => $take,
'effective_at' => $observedAt,
'observed_at' => $observedAt,
'payload' => [
'download_delta_bytes' => $downloadDelta,
'upload_delta_bytes' => $uploadDelta,
'ordinal' => $ordinal,
'entitlement_id' => (int) $entitlement->id,
],
]);
$lastEventId = (int) $event->id;
$remaining -= $take;
$ordinal++;
}
if ($remaining > 0) {
$pool->overage_bytes = (int) $pool->overage_bytes + $remaining;
$event = self::appendEventLocked($pool, [
'event_key' => $sourceId . ':overage',
'event_type' => 'overage_recorded',
'source_type' => 'traffic_observation',
'source_id' => $sourceId,
'source_revision' => 1,
'instance_id' => $instanceId,
'service_period_id' => (int) $period->id,
'entitlement_id' => null,
'amount_bytes' => $remaining,
'effective_at' => $observedAt,
'observed_at' => $observedAt,
'payload' => [
'download_delta_bytes' => $downloadDelta,
'upload_delta_bytes' => $uploadDelta,
],
]);
$lastEventId = (int) $event->id;
}
}
$cursor->accounted_download_bytes = $download;
$cursor->accounted_upload_bytes = $upload;
$cursor->last_observed_at = max(
(int) $cursor->last_observed_at,
$observedAt
);
$cursor->last_event_id = $lastEventId ?? $cursor->last_event_id;
$cursor->state = 'ready';
$cursor->attention_code = '';
$cursor->version = (int) $cursor->version + 1;
$cursor->updated_at = $applyAt;
$cursor->save();
self::recomputePoolProjectionLocked($pool, $applyAt);
return self::resultLocked($pool, true, null);
}
private static function insertPoolIfMissing(
$connection,
int $userId,
int $groupId,
int $now
): void {
$connection->table('cloud_traffic_pools')->insertOrIgnore([
'user_id' => $userId,
'traffic_pool_group_id' => $groupId,
'state' => 'available',
'available_bytes' => 0,
'overage_bytes' => 0,
'version' => 0,
'last_sequence' => 0,
'last_event_id' => null,
'created_at' => $now,
'updated_at' => $now,
]);
}
private static function assertEntitlementIdentity(
CloudTrafficEntitlement $entitlement,
CloudServicePeriod $period,
CloudTrafficPool $pool,
string $quotaMode
): void {
if ((int) $entitlement->pool_id !== (int) $pool->id
|| (int) $entitlement->user_id !== (int) $period->user_id
|| (int) $entitlement->instance_id !== (int) $period->instance_id
|| (int) $entitlement->starts_at !== (int) $period->starts_at
|| (int) $entitlement->ends_at !== (int) $period->ends_at
|| (string) $entitlement->quota_mode !== $quotaMode) {
throw new \RuntimeException('traffic_entitlement_identity_conflict');
}
}
private static function convergeEntitlementStateLocked(
CloudTrafficPool $pool,
CloudTrafficEntitlement $entitlement,
int $now
): bool {
$state = (string) $entitlement->state;
if ($state === 'expired') {
return false;
}
if ($now < (int) $entitlement->starts_at) {
return false;
}
if ($now < (int) $entitlement->ends_at) {
if ($state === 'scheduled') {
$entitlement->state = (string) $entitlement->quota_mode
=== 'unlimited'
? 'active'
: (self::entitlementRemaining($entitlement) > 0
? 'active' : 'exhausted');
$entitlement->activated_at = $now;
$entitlement->version = (int) $entitlement->version + 1;
$entitlement->updated_at = $now;
$entitlement->save();
self::appendEventLocked($pool, [
'event_key' => 'entitlement:' . (int) $entitlement->id
. ':activated',
'event_type' => 'entitlement_activated',
'source_type' => 'service_period',
'source_id' => (string) $entitlement->service_period_id,
'source_revision' => 1,
'instance_id' => (int) $entitlement->instance_id,
'service_period_id' =>
(int) $entitlement->service_period_id,
'entitlement_id' => (int) $entitlement->id,
'amount_bytes' => 0,
'effective_at' => (int) $entitlement->starts_at,
'observed_at' => null,
'payload' => [],
]);
return true;
}
return false;
}
$remaining = self::entitlementRemaining($entitlement);
if ($remaining === 0) {
return self::expireEntitlementLocked(
$pool,
$entitlement,
$now
);
}
if ($state !== 'closing') {
$entitlement->state = 'closing';
$entitlement->closed_at = (int) $entitlement->ends_at
+ self::CLOSING_SECONDS;
$entitlement->version = (int) $entitlement->version + 1;
$entitlement->updated_at = $now;
$entitlement->save();
self::appendEventLocked($pool, [
'event_key' => 'entitlement:' . (int) $entitlement->id
. ':closing',
'event_type' => 'entitlement_closing',
'source_type' => 'service_period',
'source_id' => (string) $entitlement->service_period_id,
'source_revision' => 1,
'instance_id' => (int) $entitlement->instance_id,
'service_period_id' => (int) $entitlement->service_period_id,
'entitlement_id' => (int) $entitlement->id,
'amount_bytes' => 0,
'effective_at' => (int) $entitlement->ends_at,
'observed_at' => null,
'payload' => ['closing_deadline_at' =>
(int) $entitlement->closed_at],
]);
if ((int) $entitlement->closed_at <= $now) {
self::expireEntitlementLocked($pool, $entitlement, $now);
}
return true;
}
if ((int) $entitlement->closed_at > $now) {
return false;
}
return self::expireEntitlementLocked($pool, $entitlement, $now);
}
private static function expireEntitlementLocked(
CloudTrafficPool $pool,
CloudTrafficEntitlement $entitlement,
int $now
): bool {
if ((string) $entitlement->state === 'expired') {
return false;
}
$remaining = self::entitlementRemaining($entitlement);
if ($remaining > 0) {
$entitlement->forfeited_bytes =
(int) $entitlement->forfeited_bytes + $remaining;
self::appendEventLocked($pool, [
'event_key' => 'entitlement:' . (int) $entitlement->id
. ':forfeited',
'event_type' => 'entitlement_forfeited',
'source_type' => 'service_period',
'source_id' => (string) $entitlement->service_period_id,
'source_revision' => 1,
'instance_id' => (int) $entitlement->instance_id,
'service_period_id' => (int) $entitlement->service_period_id,
'entitlement_id' => (int) $entitlement->id,
'amount_bytes' => $remaining,
'effective_at' => (int) $entitlement->ends_at,
'observed_at' => null,
'payload' => [],
]);
}
$entitlement->state = 'expired';
$entitlement->closed_at = $now;
$entitlement->version = (int) $entitlement->version + 1;
$entitlement->updated_at = $now;
$entitlement->save();
return true;
}
private static function settleOverageLocked(
CloudTrafficPool $pool,
string $sourceId,
int $now
): bool {
$remainingDebt = (int) $pool->overage_bytes;
if ($remainingDebt <= 0) {
return false;
}
$entitlements = CloudTrafficEntitlement::where(
'pool_id', (int) $pool->id
)->where('quota_mode', 'finite')->where('state', 'active')
->where('ends_at', '>', $now)
->orderBy('ends_at')->orderBy('id')->lockForUpdate()->get();
$ordinal = 0;
foreach ($entitlements as $entitlement) {
if ($remainingDebt <= 0) {
break;
}
$available = self::entitlementRemaining($entitlement);
if ($available <= 0) {
continue;
}
$take = min($available, $remainingDebt);
$entitlement->consumed_bytes =
(int) $entitlement->consumed_bytes + $take;
if (self::entitlementRemaining($entitlement) === 0) {
$entitlement->state = 'exhausted';
}
$entitlement->version = (int) $entitlement->version + 1;
$entitlement->updated_at = $now;
$entitlement->save();
self::appendEventLocked($pool, [
'event_key' => $sourceId . ':settled:' . $ordinal,
'event_type' => 'overage_settled',
'source_type' => 'overage',
'source_id' => $sourceId,
'source_revision' => 1,
'instance_id' => (int) $entitlement->instance_id,
'service_period_id' => (int) $entitlement->service_period_id,
'entitlement_id' => (int) $entitlement->id,
'amount_bytes' => $take,
'effective_at' => $now,
'observed_at' => null,
'payload' => [],
]);
$remainingDebt -= $take;
$ordinal++;
}
$pool->overage_bytes = $remainingDebt;
return $remainingDebt !== (int) $pool->overage_bytes || $ordinal > 0;
}
private static function appendEventLocked(
CloudTrafficPool $pool,
array $data
): CloudTrafficLedgerEvent {
$eventKey = self::normalizeEventKey(
(string) $data['event_key'],
(string) $data['event_type']
);
$payload = (array) ($data['payload'] ?? []);
$payloadJson = json_encode(
$payload,
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
| JSON_UNESCAPED_UNICODE
);
$envelope = [
'pool_id' => (int) $pool->id,
'event_type' => (string) $data['event_type'],
'source_type' => (string) $data['source_type'],
'source_id' => (string) $data['source_id'],
'source_revision' => (int) ($data['source_revision'] ?? 1),
'instance_id' => $data['instance_id'] ?? null,
'service_period_id' => $data['service_period_id'] ?? null,
'entitlement_id' => $data['entitlement_id'] ?? null,
'amount_bytes' => (int) ($data['amount_bytes'] ?? 0),
'effective_at' => (int) $data['effective_at'],
'observed_at' => $data['observed_at'] ?? null,
'payload' => $payload,
];
$payloadHash = hash('sha256', json_encode(
$envelope,
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
| JSON_UNESCAPED_UNICODE
));
$existing = CloudTrafficLedgerEvent::where('event_key', $eventKey)
->first();
if ($existing !== null) {
if (!hash_equals((string) $existing->payload_hash, $payloadHash)) {
throw new \RuntimeException('traffic_event_idempotency_conflict');
}
return $existing;
}
$event = new CloudTrafficLedgerEvent();
$event->pool_id = (int) $pool->id;
$event->user_id = (int) $pool->user_id;
$event->pool_sequence = (int) $pool->last_sequence + 1;
$event->event_key = $eventKey;
$event->event_type = (string) $data['event_type'];
$event->source_type = (string) $data['source_type'];
$event->source_id = (string) $data['source_id'];
$event->source_revision = (int) ($data['source_revision'] ?? 1);
$event->payload_hash = $payloadHash;
$event->instance_id = $data['instance_id'] ?? null;
$event->service_period_id = $data['service_period_id'] ?? null;
$event->entitlement_id = $data['entitlement_id'] ?? null;
$event->amount_bytes = (int) ($data['amount_bytes'] ?? 0);
$event->effective_at = (int) $data['effective_at'];
$event->observed_at = $data['observed_at'] ?? null;
$event->payload_json = $payloadJson;
$event->created_at = time();
$event->save();
$pool->last_sequence = (int) $event->pool_sequence;
$pool->last_event_id = (int) $event->id;
$pool->version = (int) $pool->version + 1;
$pool->updated_at = time();
$pool->save();
return $event;
}
private static function normalizeEventKey(
string $eventKey,
string $eventType
): string {
if (strlen($eventKey) <= 191) {
return $eventKey;
}
return substr($eventType, 0, 32) . ':' . hash('sha256', $eventKey);
}
private static function recomputePoolProjectionLocked(
CloudTrafficPool $pool,
int $now
): void {
$available = 0;
$activeFinite = 0;
foreach (CloudTrafficEntitlement::where('pool_id', (int) $pool->id)
->where('quota_mode', 'finite')
->whereIn('state', ['active', 'exhausted'])
->where('ends_at', '>', $now)
->lockForUpdate()->get() as $entitlement) {
$activeFinite++;
$available += self::entitlementRemaining($entitlement);
}
$attention = (string) $pool->state === 'attention'
|| CloudTrafficInstanceCursor::where(
'pool_id', (int) $pool->id
)->where('state', 'attention')->exists();
$state = $attention ? 'attention'
: (((int) $pool->overage_bytes > 0
|| ($activeFinite > 0 && $available === 0))
? 'exhausted' : 'available');
if ((int) $pool->available_bytes !== $available
|| (string) $pool->state !== $state) {
$pool->available_bytes = $available;
$pool->state = $state;
$pool->version = (int) $pool->version + 1;
}
$pool->updated_at = $now;
$pool->save();
}
private static function markAttentionLocked(
CloudTrafficPool $pool,
string $code,
string $sourceId,
int $now,
CloudServicePeriod $period,
CloudTrafficEntitlement $entitlement
): void {
$eventKey = self::normalizeEventKey(
'attention:' . $code . ':' . $sourceId,
'accounting_attention'
);
$existing = CloudTrafficLedgerEvent::where(
'event_key', $eventKey
)->first();
if ($existing !== null) {
$payload = json_decode((string) $existing->payload_json, true);
if ((int) $existing->pool_id !== (int) $pool->id
|| (string) $existing->event_type !== 'accounting_attention'
|| (string) $existing->source_id !== $sourceId
|| (int) $existing->service_period_id !== (int) $period->id
|| (int) $existing->entitlement_id !== (int) $entitlement->id
|| (string) ($payload['attention_code'] ?? '') !== $code) {
throw new \RuntimeException(
'traffic_event_idempotency_conflict'
);
}
$pool->state = 'attention';
$pool->updated_at = $now;
$pool->save();
return;
}
$pool->state = 'attention';
self::appendEventLocked($pool, [
'event_key' => $eventKey,
'event_type' => 'accounting_attention',
'source_type' => 'service_period',
'source_id' => $sourceId,
'source_revision' => 1,
'instance_id' => (int) $period->instance_id,
'service_period_id' => (int) $period->id,
'entitlement_id' => (int) $entitlement->id,
'amount_bytes' => 0,
'effective_at' => $now,
'observed_at' => null,
'payload' => ['attention_code' => $code],
]);
$pool->save();
}
private static function markCursorAttentionLocked(
CloudTrafficPool $pool,
CloudTrafficInstanceCursor $cursor,
string $code,
int $observedAt
): void {
if ((string) $cursor->state === 'attention'
&& (string) $cursor->attention_code === $code) {
if ((string) $pool->state !== 'attention') {
$pool->state = 'attention';
$pool->updated_at = time();
$pool->save();
}
return;
}
$cursor->state = 'attention';
$cursor->attention_code = $code;
$cursor->version = (int) $cursor->version + 1;
$cursor->updated_at = time();
$cursor->save();
$pool->state = 'attention';
self::appendEventLocked($pool, [
'event_key' => 'cursor:' . (int) $cursor->instance_id
. ':attention:' . $code . ':' . (int) $cursor->version,
'event_type' => 'counter_attention',
'source_type' => 'traffic_observation',
'source_id' => (string) $cursor->instance_id,
'source_revision' => (int) $cursor->version,
'instance_id' => (int) $cursor->instance_id,
'service_period_id' => null,
'entitlement_id' => null,
'amount_bytes' => 0,
'effective_at' => $observedAt,
'observed_at' => $observedAt,
'payload' => ['attention_code' => $code],
]);
$pool->save();
}
private static function entitlementRemaining(
CloudTrafficEntitlement $entitlement
): int {
return max(0, (int) $entitlement->granted_bytes
- (int) $entitlement->consumed_bytes
- (int) $entitlement->forfeited_bytes);
}
private static function resultLocked(
CloudTrafficPool $pool,
bool $changed,
?string $attentionCode
): array {
return [
'enabled' => true,
'pool_id' => (int) $pool->id,
'version' => (int) $pool->version,
'changed' => $changed,
'state' => (string) $pool->state,
'available_bytes' => (int) $pool->available_bytes,
'overage_bytes' => (int) $pool->overage_bytes,
'attention_code' => $attentionCode,
];
}
private static function disabledResult(
CloudServicePeriod $period,
int $groupId
): array {
return [
'enabled' => false,
'service_period_id' => (int) $period->id,
'traffic_pool_group_id' => $groupId > 0 ? $groupId : null,
'changed' => false,
];
}
private static function disabledInstanceResult(int $instanceId): array
{
return [
'enabled' => false,
'instance_id' => $instanceId,
'changed' => false,
];
}
}