refactor(traffic): prune verified settlement buckets
parent
60bfebd8ea
commit
44d1a6344a
@ -0,0 +1,307 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
use App\Models\CloudTrafficLedgerEvent;
|
||||
use App\Models\CloudTrafficPool;
|
||||
use App\Models\CloudTrafficSettlementReceipt;
|
||||
use App\Models\CloudTrafficUsageSettlementBucket;
|
||||
|
||||
/**
|
||||
* Compacts old sealed settlement details without weakening replay safety.
|
||||
*
|
||||
* The immutable ledger event remains canonical. The compact receipt preserves
|
||||
* just enough identity and revision evidence for a later observation to start
|
||||
* a new revision instead of recreating an already sealed allocation.
|
||||
*/
|
||||
final class CloudTrafficSettlementRetention
|
||||
{
|
||||
public const RETENTION_SECONDS = 7 * 86400;
|
||||
public const MAX_BATCH = 2000;
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* scanned:int,
|
||||
* compacted:int,
|
||||
* skipped:int,
|
||||
* blocked:list<array{bucket_id:int,code:string}>
|
||||
* }
|
||||
*/
|
||||
public static function compact(
|
||||
int $limit = 200,
|
||||
?int $now = null
|
||||
): array {
|
||||
$now ??= time();
|
||||
if ($now < self::RETENTION_SECONDS) {
|
||||
throw new \InvalidArgumentException(
|
||||
'traffic_settlement_retention_clock_invalid'
|
||||
);
|
||||
}
|
||||
$limit = max(1, min(self::MAX_BATCH, $limit));
|
||||
$cutoff = $now - self::RETENTION_SECONDS;
|
||||
$ids = CloudTrafficUsageSettlementBucket::where('state', 'sealed')
|
||||
->where('updated_at', '<=', $cutoff)
|
||||
->orderBy('updated_at')->orderBy('id')->limit($limit)
|
||||
->pluck('id')->map(static fn ($id): int => (int) $id)->all();
|
||||
$compacted = 0;
|
||||
$skipped = 0;
|
||||
$blocked = [];
|
||||
foreach ($ids as $id) {
|
||||
try {
|
||||
if (self::compactOne($id, $cutoff, $now)) {
|
||||
$compacted++;
|
||||
} else {
|
||||
$skipped++;
|
||||
}
|
||||
} catch (\Throwable $error) {
|
||||
$code = str_starts_with($error->getMessage(), 'traffic_')
|
||||
? $error->getMessage()
|
||||
: 'traffic_settlement_compaction_failed';
|
||||
$blocked[] = ['bucket_id' => $id, 'code' => $code];
|
||||
error_log('cloud traffic settlement compaction blocked: '
|
||||
. $id . ':' . $code);
|
||||
}
|
||||
}
|
||||
return [
|
||||
'scanned' => count($ids),
|
||||
'compacted' => $compacted,
|
||||
'skipped' => $skipped,
|
||||
'blocked' => $blocked,
|
||||
];
|
||||
}
|
||||
|
||||
private static function compactOne(
|
||||
int $bucketId,
|
||||
int $cutoff,
|
||||
int $now
|
||||
): bool {
|
||||
$hint = CloudTrafficUsageSettlementBucket::find($bucketId);
|
||||
if ($hint === null) {
|
||||
return false;
|
||||
}
|
||||
$connection = $hint->getConnection();
|
||||
return $connection->transaction(static function () use (
|
||||
$bucketId,
|
||||
$cutoff,
|
||||
$now
|
||||
): bool {
|
||||
$poolId = (int) (CloudTrafficUsageSettlementBucket::where(
|
||||
'id', $bucketId
|
||||
)->value('pool_id') ?? 0);
|
||||
if ($poolId < 1) {
|
||||
return false;
|
||||
}
|
||||
$pool = CloudTrafficPool::where('id', $poolId)
|
||||
->lockForUpdate()->first();
|
||||
if ($pool === null) {
|
||||
throw new \RuntimeException(
|
||||
'traffic_settlement_compaction_pool_missing'
|
||||
);
|
||||
}
|
||||
$bucket = CloudTrafficUsageSettlementBucket::where(
|
||||
'id', $bucketId
|
||||
)->lockForUpdate()->first();
|
||||
if ($bucket === null || (string) $bucket->state !== 'sealed'
|
||||
|| (int) $bucket->updated_at > $cutoff) {
|
||||
return false;
|
||||
}
|
||||
$eventId = (int) ($bucket->sealed_event_id ?? 0);
|
||||
$event = $eventId > 0
|
||||
? CloudTrafficLedgerEvent::where('id', $eventId)
|
||||
->lockForUpdate()->first()
|
||||
: null;
|
||||
if ($event === null) {
|
||||
throw new \RuntimeException(
|
||||
'traffic_settlement_compaction_event_missing'
|
||||
);
|
||||
}
|
||||
self::assertEventMatches($pool, $bucket, $event);
|
||||
$receiptQuery = CloudTrafficSettlementReceipt::where(
|
||||
'pool_id', (int) $bucket->pool_id
|
||||
)->where('instance_id', (int) $bucket->instance_id)
|
||||
->where('service_period_id', (int) $bucket->service_period_id)
|
||||
->where('allocation_kind', (string) $bucket->allocation_kind)
|
||||
->where('allocation_target_id',
|
||||
(int) $bucket->allocation_target_id)
|
||||
->where('bucket_start', (int) $bucket->bucket_start)
|
||||
->where('bucket_seconds', (int) $bucket->bucket_seconds);
|
||||
$receipt = (clone $receiptQuery)->lockForUpdate()->first();
|
||||
if ($receipt === null) {
|
||||
$receipt = new CloudTrafficSettlementReceipt();
|
||||
$receipt->pool_id = (int) $bucket->pool_id;
|
||||
$receipt->user_id = (int) $bucket->user_id;
|
||||
$receipt->instance_id = (int) $bucket->instance_id;
|
||||
$receipt->service_period_id = (int) $bucket->service_period_id;
|
||||
$receipt->entitlement_id = $bucket->entitlement_id === null
|
||||
? null : (int) $bucket->entitlement_id;
|
||||
$receipt->allocation_kind = (string) $bucket->allocation_kind;
|
||||
$receipt->allocation_target_id =
|
||||
(int) $bucket->allocation_target_id;
|
||||
$receipt->bucket_start = (int) $bucket->bucket_start;
|
||||
$receipt->bucket_seconds = (int) $bucket->bucket_seconds;
|
||||
$receipt->max_revision = 0;
|
||||
$receipt->last_event_id = 0;
|
||||
$receipt->compacted_amount_bytes = 0;
|
||||
$receipt->compacted_event_count = 0;
|
||||
$receipt->last_payload_hash = str_repeat('0', 64);
|
||||
$receipt->compacted_at = $now;
|
||||
$receipt->updated_at = $now;
|
||||
}
|
||||
self::applyReceipt($receipt, $bucket, $event, $now);
|
||||
$receipt->save();
|
||||
$deleted = CloudTrafficUsageSettlementBucket::where(
|
||||
'id', $bucketId
|
||||
)->where('state', 'sealed')
|
||||
->where('sealed_event_id', (int) $event->id)->delete();
|
||||
if ($deleted !== 1) {
|
||||
throw new \RuntimeException(
|
||||
'traffic_settlement_compaction_delete_conflict'
|
||||
);
|
||||
}
|
||||
return true;
|
||||
}, 3);
|
||||
}
|
||||
|
||||
private static function applyReceipt(
|
||||
CloudTrafficSettlementReceipt $receipt,
|
||||
CloudTrafficUsageSettlementBucket $bucket,
|
||||
CloudTrafficLedgerEvent $event,
|
||||
int $now
|
||||
): void {
|
||||
foreach ([
|
||||
'user_id', 'instance_id', 'service_period_id',
|
||||
'allocation_target_id', 'bucket_start', 'bucket_seconds',
|
||||
] as $field) {
|
||||
if ((int) $receipt->{$field} !== (int) $bucket->{$field}) {
|
||||
throw new \RuntimeException(
|
||||
'traffic_settlement_compaction_receipt_conflict'
|
||||
);
|
||||
}
|
||||
}
|
||||
if ((string) $receipt->allocation_kind
|
||||
!== (string) $bucket->allocation_kind
|
||||
|| (int) ($receipt->entitlement_id ?? 0)
|
||||
!== (int) ($bucket->entitlement_id ?? 0)) {
|
||||
throw new \RuntimeException(
|
||||
'traffic_settlement_compaction_receipt_conflict'
|
||||
);
|
||||
}
|
||||
$revision = (int) $bucket->bucket_revision;
|
||||
$knownRevision = (int) $receipt->max_revision;
|
||||
if ($revision < $knownRevision
|
||||
|| ($revision === $knownRevision
|
||||
&& ((int) $receipt->last_event_id !== (int) $event->id
|
||||
|| !hash_equals(
|
||||
(string) $receipt->last_payload_hash,
|
||||
(string) $event->payload_hash
|
||||
)))) {
|
||||
throw new \RuntimeException(
|
||||
'traffic_settlement_compaction_receipt_conflict'
|
||||
);
|
||||
}
|
||||
if ($revision > $knownRevision) {
|
||||
$amount = (int) $bucket->amount_bytes;
|
||||
if ($amount > PHP_INT_MAX
|
||||
- (int) $receipt->compacted_amount_bytes
|
||||
|| (int) $receipt->compacted_event_count === PHP_INT_MAX) {
|
||||
throw new \OverflowException(
|
||||
'traffic_settlement_compaction_receipt_overflow'
|
||||
);
|
||||
}
|
||||
$receipt->max_revision = $revision;
|
||||
$receipt->last_event_id = (int) $event->id;
|
||||
$receipt->compacted_amount_bytes =
|
||||
(int) $receipt->compacted_amount_bytes + $amount;
|
||||
$receipt->compacted_event_count =
|
||||
(int) $receipt->compacted_event_count + 1;
|
||||
$receipt->last_payload_hash = (string) $event->payload_hash;
|
||||
}
|
||||
$receipt->compacted_at = $now;
|
||||
$receipt->updated_at = $now;
|
||||
}
|
||||
|
||||
private static function assertEventMatches(
|
||||
CloudTrafficPool $pool,
|
||||
CloudTrafficUsageSettlementBucket $bucket,
|
||||
CloudTrafficLedgerEvent $event
|
||||
): void {
|
||||
$kind = (string) $bucket->allocation_kind;
|
||||
$eventType = $kind === 'entitlement'
|
||||
? 'usage_allocated' : 'overage_recorded';
|
||||
if ((int) $bucket->pool_id !== (int) $pool->id
|
||||
|| (int) $bucket->user_id !== (int) $pool->user_id
|
||||
|| (int) $event->pool_id !== (int) $bucket->pool_id
|
||||
|| (int) $event->user_id !== (int) $bucket->user_id
|
||||
|| (string) $event->event_type !== $eventType
|
||||
|| (string) $event->source_type !== 'traffic_settlement'
|
||||
|| (string) $event->source_id !== (string) $bucket->id
|
||||
|| (int) $event->source_revision !== 1
|
||||
|| (int) ($event->instance_id ?? 0)
|
||||
!== (int) $bucket->instance_id
|
||||
|| (int) ($event->service_period_id ?? 0)
|
||||
!== (int) $bucket->service_period_id
|
||||
|| (int) ($event->entitlement_id ?? 0)
|
||||
!== (int) ($bucket->entitlement_id ?? 0)
|
||||
|| (int) $event->amount_bytes !== (int) $bucket->amount_bytes
|
||||
|| (int) $event->effective_at !== (int) $bucket->bucket_start
|
||||
|| (int) ($event->observed_at ?? 0)
|
||||
!== (int) $bucket->last_observed_at) {
|
||||
throw new \RuntimeException(
|
||||
'traffic_settlement_compaction_event_identity_mismatch'
|
||||
);
|
||||
}
|
||||
$payload = [
|
||||
'bucket_start' => (int) $bucket->bucket_start,
|
||||
'bucket_revision' => (int) $bucket->bucket_revision,
|
||||
'bucket_seconds' => (int) $bucket->bucket_seconds,
|
||||
'seal_at' => (int) $bucket->seal_at,
|
||||
'download_bytes' => (int) $bucket->download_bytes,
|
||||
'upload_bytes' => (int) $bucket->upload_bytes,
|
||||
'sample_count' => (int) $bucket->sample_count,
|
||||
'first_observed_at' => (int) $bucket->first_observed_at,
|
||||
'last_observed_at' => (int) $bucket->last_observed_at,
|
||||
];
|
||||
try {
|
||||
$storedPayload = json_decode(
|
||||
(string) $event->payload_json,
|
||||
true,
|
||||
512,
|
||||
JSON_THROW_ON_ERROR
|
||||
);
|
||||
} catch (\JsonException) {
|
||||
throw new \RuntimeException(
|
||||
'traffic_settlement_compaction_payload_invalid'
|
||||
);
|
||||
}
|
||||
if ($storedPayload !== $payload) {
|
||||
throw new \RuntimeException(
|
||||
'traffic_settlement_compaction_payload_mismatch'
|
||||
);
|
||||
}
|
||||
$envelope = [
|
||||
'pool_id' => (int) $pool->id,
|
||||
'event_type' => $eventType,
|
||||
'source_type' => 'traffic_settlement',
|
||||
'source_id' => (string) $bucket->id,
|
||||
'source_revision' => 1,
|
||||
'instance_id' => (int) $bucket->instance_id,
|
||||
'service_period_id' => (int) $bucket->service_period_id,
|
||||
'entitlement_id' => $bucket->entitlement_id === null
|
||||
? null : (int) $bucket->entitlement_id,
|
||||
'amount_bytes' => (int) $bucket->amount_bytes,
|
||||
'effective_at' => (int) $bucket->bucket_start,
|
||||
'observed_at' => (int) $bucket->last_observed_at,
|
||||
'payload' => $payload,
|
||||
];
|
||||
$expectedHash = hash('sha256', json_encode(
|
||||
$envelope,
|
||||
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
|
||||
| JSON_UNESCAPED_UNICODE
|
||||
));
|
||||
if (!hash_equals((string) $event->payload_hash, $expectedHash)) {
|
||||
throw new \RuntimeException(
|
||||
'traffic_settlement_compaction_payload_hash_mismatch'
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue