diff --git a/web/app/Services/Cloud/CloudTrafficPoolAccounting.php b/web/app/Services/Cloud/CloudTrafficPoolAccounting.php new file mode 100644 index 00000000..b67d8c85 --- /dev/null +++ b/web/app/Services/Cloud/CloudTrafficPoolAccounting.php @@ -0,0 +1,1469 @@ +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); + } + + /** 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 { + $at ??= time(); + $pool = CloudTrafficPool::where('user_id', $userId) + ->where('traffic_pool_group_id', $trafficPoolGroupId)->first(); + if ($pool === null) { + return [ + 'pool_id' => null, + 'user_id' => $userId, + 'traffic_pool_group_id' => $trafficPoolGroupId, + '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, + ]; + } + $active = CloudTrafficEntitlement::where('pool_id', (int) $pool->id) + ->where('quota_mode', 'finite') + ->whereIn('state', ['active', 'exhausted']) + ->where('starts_at', '<=', $at)->where('ends_at', '>', $at) + ->orderBy('ends_at')->orderBy('id')->get(); + $granted = 0; + $consumed = 0; + $available = 0; + $nextExpiryAt = null; + $nextExpiryBytes = 0; + foreach ($active 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; + } + } + $lastObserved = CloudTrafficInstanceCursor::where( + 'pool_id', (int) $pool->id + )->max('last_observed_at'); + return [ + 'pool_id' => (int) $pool->id, + 'user_id' => $userId, + 'traffic_pool_group_id' => $trafficPoolGroupId, + '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' => $lastObserved === null + ? null : (int) $lastObserved, + 'version' => (int) $pool->version, + ]; + } + + /** + * 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 { + $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, [ + 'event_key' => 'attention-resolution:' . $poolId . ':' + . $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): array + { + $now ??= time(); + $periodIds = []; + $missing = CloudServicePeriod::query() + ->leftJoin('cloud_traffic_entitlements as traffic_entitlement', + 'traffic_entitlement.service_period_id', '=', + 'cloud_service_periods.id') + ->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') + ->orderBy('cloud_service_periods.id')->limit($limit) + ->pluck('cloud_service_periods.id')->all(); + foreach ($missing as $id) { + $periodIds[(int) $id] = true; + } + if (count($periodIds) < $limit) { + $due = CloudTrafficEntitlement::query() + ->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 ($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.id') + ->limit($limit - count($periodIds)) + ->pluck('cloud_traffic_entitlements.service_period_id')->all(); + foreach ($due as $id) { + $periodIds[(int) $id] = true; + } + } + if (count($periodIds) < $limit) { + $changed = CloudTrafficEntitlement::query() + ->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']) + ->whereColumn( + 'traffic_period.traffic_quota_bytes', + '>', + 'cloud_traffic_entitlements.granted_bytes' + )->orderBy('cloud_traffic_entitlements.id') + ->limit($limit - count($periodIds)) + ->pluck('cloud_traffic_entitlements.service_period_id') + ->all(); + foreach ($changed as $id) { + $periodIds[(int) $id] = true; + } + } + $processed = 0; + $errors = []; + foreach (array_keys($periodIds) as $periodId) { + try { + self::reconcileServicePeriod( + $periodId, + 'period-scan:' . $periodId, + $now + ); + $processed++; + } catch (\Throwable $error) { + $errors[] = [ + 'period_id' => $periodId, + 'error' => get_class($error), + ]; + } + } + return ['processed' => $processed, 'errors' => $errors]; + } + + /** Discover persisted counters that have not yet crossed the accounting seam. */ + public static function settlePendingUsage(int $limit = 200): array + { + $rows = CloudInstance::query() + ->leftJoin('cloud_traffic_instance_cursors as traffic_cursor', + 'traffic_cursor.instance_id', '=', 'cloud_instances.id') + ->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'); + })->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 + ); + $processed++; + } catch (\Throwable $error) { + $errors[] = [ + 'instance_id' => (int) $row->id, + 'error' => get_class($error), + ]; + } + } + return ['processed' => $processed, 'errors' => $errors]; + } + + 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, + ]; + } +} diff --git a/web/tests/CloudTrafficPoolAccountingTest.php b/web/tests/CloudTrafficPoolAccountingTest.php new file mode 100644 index 00000000..3ab55999 --- /dev/null +++ b/web/tests/CloudTrafficPoolAccountingTest.php @@ -0,0 +1,658 @@ +addConnection([ + 'driver' => 'sqlite', + 'database' => ':memory:', +], 'default'); +$capsule->setAsGlobal(); +$capsule->bootEloquent(); +$schema = $capsule->schema('default'); + +$schema->create('cloud_traffic_pool_groups', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('code')->unique(); + $table->string('name'); + $table->string('mode'); + $table->integer('created_at'); + $table->integer('updated_at'); +}); +$schema->create('cloud_instances', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('user_id'); + $table->integer('current_period_id')->nullable(); + $table->integer('lifetime_download_bytes')->default(0); + $table->integer('lifetime_upload_bytes')->default(0); + $table->integer('traffic_synced_at')->default(0); + $table->string('status')->default('active'); + $table->integer('created_at'); + $table->integer('updated_at'); +}); +$schema->create('cloud_service_periods', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('instance_id'); + $table->integer('user_id'); + $table->integer('plan_id')->nullable(); + $table->integer('order_id')->nullable(); + $table->integer('renewal_id')->nullable(); + $table->integer('traffic_pool_group_id')->nullable(); + $table->string('traffic_quota_mode')->default('finite'); + $table->integer('starts_at'); + $table->integer('ends_at'); + $table->integer('traffic_quota_bytes')->default(0); + $table->integer('download_base_bytes')->nullable(); + $table->integer('upload_base_bytes')->nullable(); + $table->integer('download_used_bytes')->default(0); + $table->integer('upload_used_bytes')->default(0); + $table->string('status')->default('scheduled'); + $table->integer('activated_at')->nullable(); + $table->integer('created_at'); + $table->integer('updated_at'); + $table->unique('order_id'); + $table->unique('renewal_id'); +}); +$schema->create('cloud_traffic_pools', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('user_id'); + $table->integer('traffic_pool_group_id'); + $table->string('state'); + $table->integer('available_bytes')->default(0); + $table->integer('overage_bytes')->default(0); + $table->integer('version')->default(0); + $table->integer('last_sequence')->default(0); + $table->integer('last_event_id')->nullable(); + $table->integer('created_at'); + $table->integer('updated_at'); + $table->unique(['user_id', 'traffic_pool_group_id']); +}); +$schema->create('cloud_traffic_entitlements', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('pool_id'); + $table->integer('user_id'); + $table->integer('instance_id'); + $table->integer('service_period_id')->unique(); + $table->integer('starts_at'); + $table->integer('ends_at'); + $table->string('quota_mode'); + $table->integer('granted_bytes')->default(0); + $table->integer('consumed_bytes')->default(0); + $table->integer('forfeited_bytes')->default(0); + $table->string('state'); + $table->integer('activated_at')->nullable(); + $table->integer('closed_at')->nullable(); + $table->integer('version')->default(0); + $table->integer('created_at'); + $table->integer('updated_at'); +}); +$schema->create('cloud_traffic_ledger_events', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('pool_id'); + $table->integer('user_id'); + $table->integer('pool_sequence'); + $table->string('event_key')->unique(); + $table->string('event_type'); + $table->string('source_type'); + $table->string('source_id'); + $table->integer('source_revision'); + $table->string('payload_hash'); + $table->integer('instance_id')->nullable(); + $table->integer('service_period_id')->nullable(); + $table->integer('entitlement_id')->nullable(); + $table->integer('amount_bytes'); + $table->integer('effective_at'); + $table->integer('observed_at')->nullable(); + $table->text('payload_json'); + $table->integer('created_at'); + $table->unique(['pool_id', 'pool_sequence']); +}); +$schema->create('cloud_traffic_instance_cursors', static function (Blueprint $table): void { + $table->integer('instance_id')->primary(); + $table->integer('user_id'); + $table->integer('pool_id'); + $table->integer('accounted_download_bytes')->default(0); + $table->integer('accounted_upload_bytes')->default(0); + $table->integer('last_observed_at')->default(0); + $table->integer('last_event_id')->nullable(); + $table->string('state'); + $table->string('attention_code'); + $table->integer('version')->default(0); + $table->integer('updated_at'); +}); + +$base = time(); +Capsule::table('cloud_traffic_pool_groups')->insert([ + ['id' => 1, 'code' => 'line-a', 'name' => 'Line A', 'mode' => 'shadow', + 'created_at' => $base, 'updated_at' => $base], + ['id' => 2, 'code' => 'line-b', 'name' => 'Line B', 'mode' => 'shadow', + 'created_at' => $base, 'updated_at' => $base], + ['id' => 3, 'code' => 'line-c', 'name' => 'Line C', 'mode' => 'shadow', + 'created_at' => $base, 'updated_at' => $base], + ['id' => 4, 'code' => 'line-d', 'name' => 'Line D', 'mode' => 'shadow', + 'created_at' => $base, 'updated_at' => $base], +]); + +$newInstance = static function (int $id, int $userId = 7) use ($base): CloudInstance { + $instance = new CloudInstance(); + $instance->id = $id; + $instance->user_id = $userId; + $instance->current_period_id = null; + $instance->lifetime_download_bytes = 0; + $instance->lifetime_upload_bytes = 0; + $instance->traffic_synced_at = 0; + $instance->status = 'active'; + $instance->created_at = $base; + $instance->updated_at = $base; + $instance->save(); + return $instance; +}; +$newPeriod = static function ( + CloudInstance $instance, + int $id, + int $groupId, + int $quota, + int $startsAt, + int $endsAt, + string $mode = 'finite' +) use ($base): CloudServicePeriod { + $period = new CloudServicePeriod(); + $period->id = $id; + $period->instance_id = (int) $instance->id; + $period->user_id = (int) $instance->user_id; + $period->traffic_pool_group_id = $groupId; + $period->traffic_quota_mode = $mode; + $period->starts_at = $startsAt; + $period->ends_at = $endsAt; + $period->traffic_quota_bytes = $quota; + $period->download_base_bytes = 0; + $period->upload_base_bytes = 0; + $period->download_used_bytes = 0; + $period->upload_used_bytes = 0; + $period->status = $startsAt <= $base ? 'active' : 'scheduled'; + $period->activated_at = $startsAt <= $base ? $base : null; + $period->created_at = $base; + $period->updated_at = $base; + $period->save(); + $instance->current_period_id = $id; + $instance->save(); + return $period; +}; + +$instanceA = $newInstance(11); +$instanceB = $newInstance(12); +$instanceC = $newInstance(13); +$periodA = $newPeriod($instanceA, 101, 1, 200, $base, $base + 100); +$periodB = $newPeriod($instanceB, 102, 1, 200, $base, $base + 200); +$periodC = $newPeriod($instanceC, 103, 1, 50, $base, $base + 300); +foreach ([$periodA, $periodB, $periodC] as $period) { + $result = CloudTrafficPoolAccounting::reconcileServicePeriod( + (int) $period->id, + 'test-period:' . (int) $period->id, + $base + 1 + ); + $assert($result['enabled'] === true, 'Active period was not materialized.'); +} + +$instanceA->lifetime_download_bytes = 250; +$instanceA->lifetime_upload_bytes = 50; +$instanceA->traffic_synced_at = $base + 10; +$instanceA->save(); +$settled = CloudTrafficPoolAccounting::settleInstanceUsage(11, $base + 10); +$assert($settled['available_bytes'] === 150, + 'FEFO settlement produced the wrong remaining balance.'); +$entitlements = CloudTrafficEntitlement::orderBy('ends_at')->get(); +$assert((int) $entitlements[0]->consumed_bytes === 200 + && (int) $entitlements[1]->consumed_bytes === 100 + && (int) $entitlements[2]->consumed_bytes === 0, + 'Usage was not allocated in strict FEFO order.'); + +$ledgerCount = CloudTrafficLedgerEvent::count(); +CloudTrafficPoolAccounting::settleInstanceUsage(11, $base + 10); +$assert(CloudTrafficLedgerEvent::count() === $ledgerCount, + 'A repeated cumulative observation changed the immutable ledger.'); + +CloudTrafficPoolAccounting::reconcileServicePeriod( + 101, + 'test-expire:101', + $base + 101 +); +$assert((string) CloudTrafficEntitlement::where( + 'service_period_id', 101)->first()->state === 'expired' + && CloudTrafficPoolAccounting::snapshot(7, 1, $base + 101)['available_bytes'] + === 150, + 'A fully consumed expired entitlement deducted the pool twice.'); + +$instanceB->lifetime_download_bytes = 120; +$instanceB->traffic_synced_at = $base + 110; +$instanceB->save(); +CloudTrafficPoolAccounting::settleInstanceUsage(12, $base + 110); +$assert(CloudTrafficPoolAccounting::snapshot(7, 1, $base + 110)[ + 'available_bytes'] === 30, + 'A second instance did not consume the same shared pool.'); + +$instanceC->lifetime_download_bytes = 40; +$instanceC->traffic_synced_at = $base + 120; +$instanceC->save(); +$exhausted = CloudTrafficPoolAccounting::settleInstanceUsage(13, $base + 120); +$assert($exhausted['state'] === 'exhausted' + && $exhausted['available_bytes'] === 0 + && $exhausted['overage_bytes'] === 10, + 'Sampling overage was not retained as explicit debt.'); + +$unlimited = $newInstance(14); +$unlimitedPeriod = $newPeriod( + $unlimited, + 104, + 1, + 0, + $base, + $base + 350, + 'unlimited' +); +CloudTrafficPoolAccounting::reconcileServicePeriod( + 104, + 'test-unlimited:104', + $base + 1 +); +$unlimited->lifetime_download_bytes = 1_000; +$unlimited->traffic_synced_at = $base + 130; +$unlimited->save(); +CloudTrafficPoolAccounting::settleInstanceUsage(14, $base + 130); +$pool = CloudTrafficPool::where('user_id', 7) + ->where('traffic_pool_group_id', 1)->first(); +$assert((int) $pool->overage_bytes === 10, + 'Unlimited-instance traffic consumed or increased the finite pool.'); + +$future = $newInstance(15); +$futurePeriod = $newPeriod( + $future, + 105, + 1, + 100, + $base + 400, + $base + 800 +); +CloudTrafficPoolAccounting::reconcileServicePeriod( + 105, + 'test-future:105', + $base + 200 +); +$assert(CloudTrafficPoolAccounting::snapshot(7, 1, $base + 200)[ + 'available_bytes'] === 0, + 'A future renewal contributed quota before starts_at.'); +CloudTrafficPoolAccounting::reconcileServicePeriod( + 105, + 'test-activate:105', + $base + 400 +); +$afterActivation = CloudTrafficPoolAccounting::snapshot(7, 1, $base + 400); +$assert($afterActivation['available_bytes'] === 90 + && $afterActivation['overage_bytes'] === 0, + 'A new entitlement did not settle sampling debt before exposing balance.'); + +$futurePeriod = CloudServicePeriod::find(105); +$futurePeriod->traffic_quota_bytes = 150; +$futurePeriod->updated_at = $base + 410; +$futurePeriod->save(); +CloudTrafficPoolAccounting::reconcileServicePeriod( + 105, + 'test-upgrade:105:150', + $base + 410 +); +CloudTrafficPoolAccounting::reconcileServicePeriod( + 105, + 'test-upgrade:105:150', + $base + 410 +); +$afterUpgrade = CloudTrafficPoolAccounting::snapshot(7, 1, $base + 410); +$assert($afterUpgrade['available_bytes'] === 140, + 'Upgrade delta was missing or was granted more than once.'); + +CloudTrafficPoolAccounting::reconcileServicePeriod( + 105, + 'test-close:105', + $base + 801 +); +$closing = CloudTrafficEntitlement::where('service_period_id', 105)->first(); +$assert((string) $closing->state === 'closing' + && CloudTrafficPoolAccounting::snapshot(7, 1, $base + 801)[ + 'available_bytes'] === 0, + 'Expired unused quota remained visible during bounded closing.'); +CloudTrafficPoolAccounting::reconcileServicePeriod( + 105, + 'test-finalize:105', + $base + 801 + CloudTrafficPoolAccounting::CLOSING_SECONDS +); +$expired = CloudTrafficEntitlement::where('service_period_id', 105)->first(); +$assert((string) $expired->state === 'expired' + && (int) $expired->forfeited_bytes === 140, + 'Closing did not forfeit only the entitlement unused balance.'); + +$other = $newInstance(21, 7); +$otherPeriod = $newPeriod($other, 201, 2, 500, $base, $base + 900); +CloudTrafficPoolAccounting::reconcileServicePeriod( + 201, + 'test-other-line:201', + $base + 1 +); +$assert(CloudTrafficPoolAccounting::snapshot(7, 2, $base + 1)[ + 'available_bytes'] === 500 + && CloudTrafficPoolAccounting::snapshot(7, 1, $base + 1)[ + 'available_bytes'] === 0, + 'Different traffic-pool groups were merged.'); + +$other->lifetime_download_bytes = 100; +$other->traffic_synced_at = $base + 20; +$other->save(); +CloudTrafficPoolAccounting::settleInstanceUsage(21, $base + 20); +$other->lifetime_download_bytes = 90; +$other->traffic_synced_at = $base + 21; +$other->save(); +$regression = CloudTrafficPoolAccounting::settleInstanceUsage(21, $base + 21); +$assert($regression['state'] === 'attention' + && $regression['attention_code'] === 'traffic_counter_regression', + 'A durable counter regression silently refunded or recharged traffic.'); +$attentionLedgerCount = CloudTrafficLedgerEvent::count(); +$attentionCursorVersion = (int) CloudTrafficInstanceCursor::find(21)->version; +CloudTrafficPoolAccounting::settlePendingUsage(200); +$assert(CloudTrafficLedgerEvent::count() === $attentionLedgerCount + && (int) CloudTrafficInstanceCursor::find(21)->version + === $attentionCursorVersion, + 'The normal scanner repeatedly rewrote an attention cursor.'); +try { + CloudTrafficPoolAccounting::resolveAttention( + (int) $regression['pool_id'], + (int) $regression['version'], + 'test-regression-unresolved', + $base + 22 + ); + throw new RuntimeException('Unresolved counter regression was cleared.'); +} catch (CloudError $error) { + $assert($error->httpStatus === 409, + 'Unresolved attention returned the wrong status.'); +} +$other->lifetime_download_bytes = 150; +$other->traffic_synced_at = $base + 23; +$other->save(); +$resolved = CloudTrafficPoolAccounting::resolveAttention( + (int) $regression['pool_id'], + (int) $regression['version'], + 'test-regression-resolved', + $base + 23 +); +$assert($resolved['state'] === 'available' + && $resolved['attention_code'] === null + && $resolved['available_bytes'] === 350, + 'Verified attention did not settle pending bytes before recovery.'); + +$accountingInstance = $newInstance(22, 8); +$accountingPeriod = $newPeriod( + $accountingInstance, 202, 2, 100, $base, $base + 900 +); +CloudTrafficPoolAccounting::reconcileServicePeriod( + 202, 'test-accounting-attention:initial', $base + 1 +); +$accountingPeriod->traffic_quota_bytes = 90; +$accountingPeriod->save(); +$accountingAttention = CloudTrafficPoolAccounting::reconcileServicePeriod( + 202, 'test-accounting-attention:decrease', $base + 2 +); +$accountingAttentionEvents = CloudTrafficLedgerEvent::count(); +$retriedAccountingAttention = CloudTrafficPoolAccounting::reconcileServicePeriod( + 202, 'test-accounting-attention:decrease', $base + 3 +); +$assert(CloudTrafficLedgerEvent::count() === $accountingAttentionEvents + && $retriedAccountingAttention['state'] === 'attention', + 'Retrying the same accounting fence changed its immutable event envelope.'); +try { + CloudTrafficPoolAccounting::resolveAttention( + (int) $accountingAttention['pool_id'], + (int) $accountingAttention['version'], + 'test-accounting-attention:unfixed', + $base + 3 + ); + throw new RuntimeException('Unfixed accounting conflict was cleared.'); +} catch (CloudError $error) { + $assert($error->httpStatus === 409, + 'Unfixed accounting attention returned the wrong status.'); +} +$accountingPeriod = CloudServicePeriod::find(202); +$accountingPeriod->traffic_quota_bytes = 100; +$accountingPeriod->save(); +$accountingResolved = CloudTrafficPoolAccounting::resolveAttention( + (int) $accountingAttention['pool_id'], + (int) $accountingAttention['version'], + 'test-accounting-attention:fixed', + $base + 4 +); +$assert($accountingResolved['state'] === 'available', + 'A corrected service-period conflict had no audited recovery exit.'); + +$finiteToUnlimited = $newInstance(31); +$finiteOld = $newPeriod( + $finiteToUnlimited, 301, 3, 100, $base, $base + 100 +); +$unlimitedNew = $newPeriod( + $finiteToUnlimited, 302, 3, 0, $base + 100, $base + 200, 'unlimited' +); +CloudTrafficPoolAccounting::reconcileServicePeriod( + 301, 'test-finite-old:301', $base + 1 +); +CloudTrafficPoolAccounting::reconcileServicePeriod( + 302, 'test-unlimited-new:302', $base + 101 +); +$finiteToUnlimited->lifetime_download_bytes = 60; +$finiteToUnlimited->traffic_synced_at = $base + 90; +$finiteToUnlimited->save(); +CloudTrafficPoolAccounting::settleInstanceUsage(31, $base + 90); +$assert(CloudTrafficPoolAccounting::snapshot(7, 3, $base + 90)[ + 'available_bytes'] === 40, + 'A delayed finite-period sample was ignored after switching to unlimited.'); + +$unlimitedToFinite = $newInstance(41); +$unlimitedOld = $newPeriod( + $unlimitedToFinite, 401, 4, 0, $base, $base + 100, 'unlimited' +); +$finiteNew = $newPeriod( + $unlimitedToFinite, 402, 4, 100, $base + 100, $base + 200 +); +CloudTrafficPoolAccounting::reconcileServicePeriod( + 401, 'test-unlimited-old:401', $base + 1 +); +CloudTrafficPoolAccounting::reconcileServicePeriod( + 402, 'test-finite-new:402', $base + 101 +); +$unlimitedToFinite->lifetime_download_bytes = 60; +$unlimitedToFinite->traffic_synced_at = $base + 90; +$unlimitedToFinite->save(); +CloudTrafficPoolAccounting::settleInstanceUsage(41, $base + 90); +$assert(CloudTrafficPoolAccounting::snapshot(7, 4, $base + 90)[ + 'available_bytes'] === 0, + 'A delayed unlimited-period sample consumed future finite quota.'); +$unlimitedToFinite->lifetime_download_bytes = 70; +$unlimitedToFinite->traffic_synced_at = $base + 110; +$unlimitedToFinite->save(); +CloudTrafficPoolAccounting::settleInstanceUsage(41, $base + 110); +$assert(CloudTrafficPoolAccounting::snapshot(7, 4, $base + 110)[ + 'available_bytes'] === 90, + 'Finite-period traffic after the boundary was not charged exactly once.'); + +$finishedWithTraffic = $newInstance(51, 9); +$finishedTrafficPeriod = $newPeriod( + $finishedWithTraffic, + 501, + 1, + 100, + $base - 200, + $base - 30 +); +$finishedTrafficPeriod->status = 'finished'; +$finishedTrafficPeriod->save(); +$finishedWithTraffic->lifetime_download_bytes = 30; +$finishedWithTraffic->traffic_synced_at = $base - 40; +$finishedWithTraffic->save(); +CloudTrafficPoolAccounting::settlePendingUsage(200); +$finishedEntitlement = CloudTrafficEntitlement::where( + 'service_period_id', 501 +)->first(); +$assert($finishedEntitlement !== null + && (int) $finishedEntitlement->consumed_bytes === 30 + && (int) CloudTrafficInstanceCursor::find(51)->accounted_download_bytes + === 30, + 'A finished period lost its last persisted traffic sample.'); +CloudTrafficPoolAccounting::reconcileDue(200, $base + 61); +$finishedEntitlement->refresh(); +$assert((string) $finishedEntitlement->state === 'expired' + && (int) $finishedEntitlement->forfeited_bytes === 70, + 'A finished period did not converge after settling its final sample.'); + +$finishedWithoutTraffic = $newInstance(52, 10); +$finishedPeriod = $newPeriod( + $finishedWithoutTraffic, + 502, + 1, + 80, + $base - 300, + $base - 200 +); +$finishedPeriod->status = 'finished'; +$finishedPeriod->save(); +CloudTrafficPoolAccounting::reconcileDue(200, $base); +$finishedProjection = CloudTrafficEntitlement::where( + 'service_period_id', 502 +)->first(); +$assert($finishedProjection !== null + && (string) $finishedProjection->state === 'expired', + 'A finished period without an entitlement was permanently skipped.'); + +$deletedInstance = $newInstance(53, 11); +$deletedPeriod = $newPeriod( + $deletedInstance, 503, 1, 100, $base, $base + 500 +); +CloudTrafficPoolAccounting::reconcileServicePeriod( + 503, 'test-deleted-tail:initial', $base + 1 +); +$deletedInstance->lifetime_download_bytes = 40; +$deletedInstance->traffic_synced_at = $base + 20; +$deletedInstance->status = 'deleted'; +$deletedInstance->save(); +CloudTrafficPoolAccounting::settlePendingUsage(200); +$deletedCursor = CloudTrafficInstanceCursor::find(53); +$assert($deletedCursor !== null + && (int) $deletedCursor->accounted_download_bytes === 40, + 'Deleting an instance skipped its final persisted counter delta.'); + +$lateClosingInstance = $newInstance(54, 12); +$lateClosingPeriod = $newPeriod( + $lateClosingInstance, + 504, + 1, + 100, + $base - 300, + $base - 200 +); +CloudTrafficPoolAccounting::reconcileServicePeriod( + 504, 'test-late-closing:activate', $base - 250 +); +CloudTrafficPoolAccounting::reconcileServicePeriod( + 504, 'test-late-closing:expire', $base +); +$lateClosingEntitlement = CloudTrafficEntitlement::where( + 'service_period_id', 504 +)->first(); +$closingEvent = CloudTrafficLedgerEvent::where( + 'entitlement_id', (int) $lateClosingEntitlement->id +)->where('event_type', 'entitlement_closing')->first(); +$closingPayload = json_decode((string) $closingEvent->payload_json, true); +$assert((string) $lateClosingEntitlement->state === 'expired' + && (int) ($closingPayload['closing_deadline_at'] ?? 0) + === $base - 200 + CloudTrafficPoolAccounting::CLOSING_SECONDS, + 'Closing was incorrectly extended from the discovery time.'); + +$lateAttentionInstance = $newInstance(55, 13); +$lateAttentionPeriod = $newPeriod( + $lateAttentionInstance, + 505, + 1, + 100, + $base, + $base + 30 +); +CloudTrafficPoolAccounting::reconcileServicePeriod( + 505, 'test-late-attention:initial', $base + 1 +); +$lateAttentionInstance->lifetime_download_bytes = 50; +$lateAttentionInstance->traffic_synced_at = $base + 10; +$lateAttentionInstance->save(); +CloudTrafficPoolAccounting::settleInstanceUsage(55, $base + 10); +$lateAttentionInstance->lifetime_download_bytes = 40; +$lateAttentionInstance->traffic_synced_at = $base + 20; +$lateAttentionInstance->save(); +CloudTrafficPoolAccounting::settleInstanceUsage(55, $base + 20); +CloudTrafficPoolAccounting::reconcileServicePeriod( + 505, 'test-late-attention:closing', $base + 31 +); +$lateAttentionInstance->lifetime_download_bytes = 60; +$lateAttentionInstance->traffic_synced_at = $base + 20; +$lateAttentionInstance->save(); +$lateAttentionPool = CloudTrafficPool::where('user_id', 13) + ->where('traffic_pool_group_id', 1)->first(); +$lateAttentionResult = CloudTrafficPoolAccounting::resolveAttention( + (int) $lateAttentionPool->id, + (int) $lateAttentionPool->version, + 'test-late-attention:resolve', + $base + 121 +); +$lateAttentionEntitlement = CloudTrafficEntitlement::where( + 'service_period_id', 505 +)->first(); +$assert((int) $lateAttentionEntitlement->consumed_bytes === 50 + && (int) $lateAttentionEntitlement->forfeited_bytes === 50 + && $lateAttentionResult['overage_bytes'] === 10, + 'Attention recovery consumed expired quota after the closing deadline.'); + +$snapshotInstance = $newInstance(56, 14); +$snapshotPeriod = $newPeriod( + $snapshotInstance, 506, 1, 100, $base, $base + 500 +); +CloudTrafficPoolAccounting::reconcileServicePeriod( + 506, 'test-snapshot:initial', $base + 1 +); +$snapshotInstance->lifetime_download_bytes = 20; +$snapshotInstance->traffic_synced_at = $base + 10; +$snapshotInstance->save(); +CloudTrafficPoolAccounting::settleInstanceUsage(56, $base + 5); +$snapshotEvent = CloudTrafficLedgerEvent::where('instance_id', 56) + ->where('event_type', 'usage_allocated')->first(); +$assert($snapshotEvent !== null + && (int) $snapshotEvent->observed_at === $base + 10, + 'Counters were paired with a stale observation timestamp.'); + +$idleScan = CloudTrafficPoolAccounting::settlePendingUsage(1); +$assert($idleScan['processed'] === 0, + 'An instance without a trusted sample poisoned the bounded scan queue.'); + +$verification = CloudTrafficPoolAccounting::verifyProjection((int) $pool->id); +$assert($verification['valid'] === true, + 'Immutable ledger does not reproduce entitlement or pool projections: ' + . implode(',', $verification['errors'])); + +echo "Cloud traffic pool accounting checks passed.\n"; diff --git a/web/tests/CloudTrafficPoolLockOrderContractTest.php b/web/tests/CloudTrafficPoolLockOrderContractTest.php new file mode 100644 index 00000000..b342ca2d --- /dev/null +++ b/web/tests/CloudTrafficPoolLockOrderContractTest.php @@ -0,0 +1,90 @@ + $value !== false)); + $end = $ends === [] ? strlen($source) : min($ends); + return substr($source, $start, $end - $start); +}; + +$settle = $method('settleInstanceUsageAttempt', 'private'); +$poolLock = strpos($settle, "->where('traffic_pool_group_id', \$groupId)\n ->lockForUpdate()"); +$cursorLock = strpos($settle, + "'instance_id', \$instanceId\n )->lockForUpdate()"); +$applyUsage = strpos($settle, 'self::applyUsageDeltaLocked('); +$helperStart = strpos($source, + 'private static function applyUsageDeltaLocked('); +$helperEnd = strpos($source, "\n private static function ", + $helperStart + 1); +$helper = $helperStart === false ? '' : substr( + $source, + $helperStart, + ($helperEnd === false ? strlen($source) : $helperEnd) - $helperStart +); +$entitlementLock = strpos($helper, "->lockForUpdate()->get();"); +$assert($poolLock !== false && $cursorLock !== false + && $applyUsage !== false && $entitlementLock !== false + && $poolLock < $cursorLock && $cursorLock < $applyUsage, + 'Usage settlement no longer follows pool -> cursor -> entitlement locks.'); +$assert(!str_contains($settle, + "CloudInstance::where('id', \$instanceId)->lockForUpdate()") + && !str_contains($settle, 'CloudAgentClient'), + 'Pool accounting must not lock an instance first or call an Agent.'); +$assert(str_contains($settle, 'snapshotObservedAt') + && str_contains($settle, "'retry_snapshot' => true"), + 'Usage settlement no longer binds counters to one durable sample time.'); + +$period = $method('reconcileServicePeriod'); +$periodPoolLock = strpos($period, + "->where('traffic_pool_group_id', \$groupId)\n ->lockForUpdate()"); +$periodRowLock = strpos($period, + "CloudServicePeriod::where('id', \$servicePeriodId)\n ->lockForUpdate()"); +$periodEntitlementLock = strpos($period, + "'service_period_id', \$servicePeriodId\n )->lockForUpdate()"); +$assert($periodPoolLock !== false && $periodRowLock !== false + && $periodEntitlementLock !== false + && $periodPoolLock < $periodRowLock + && $periodRowLock < $periodEntitlementLock, + 'Period reconciliation no longer locks pool before period and entitlement.'); + +$due = $method('reconcileDue'); +$assert(str_contains($due, + "->whereIn('due_group.mode', ['shadow', 'enforced'])") + && str_contains($due, + "->whereIn('changed_group.mode', ['shadow', 'enforced'])"), + 'Disabled groups can permanently starve due-period reconciliation.'); +$assert(str_contains($source, "'amount_bytes' => (int) (\$data['amount_bytes'] ?? 0)") + && str_contains($source, "'effective_at' => (int) \$data['effective_at']") + && str_contains($source, "'entitlement_id' => \$data['entitlement_id'] ?? null"), + 'Event idempotency hash does not cover the complete accounting envelope.'); +$assert(str_contains($source, 'public static function resolveAttention(') + && str_contains($source, 'expectedVersion') + && str_contains($source, "'event_type' => 'attention_resolved'"), + 'Attention fences have no versioned, audited recovery interface.'); +$pending = $method('settlePendingUsage'); +$assert(str_contains($pending, "->orWhere('traffic_cursor.state', 'ready')") + && !str_contains($pending, + "->where('cloud_instances.status', '<>', 'deleted')"), + 'Normal scans must isolate attention cursors and settle deleted tail data.'); + +echo "Cloud traffic pool lock-order contract passed.\n";