feat(traffic): implement shared pool accounting
parent
af35909a8c
commit
33e6a1ae72
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,658 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
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\Services\Cloud\CloudTrafficPoolAccounting;
|
||||
use App\Services\Cloud\CloudError;
|
||||
use Illuminate\Database\Capsule\Manager as Capsule;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
$capsule = new Capsule();
|
||||
$capsule->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";
|
||||
@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
$source = file_get_contents(dirname(__DIR__)
|
||||
. '/app/Services/Cloud/CloudTrafficPoolAccounting.php');
|
||||
if (!is_string($source)) {
|
||||
throw new RuntimeException('Unable to read traffic-pool accounting module.');
|
||||
}
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
$method = static function (
|
||||
string $name,
|
||||
string $visibility = 'public'
|
||||
) use ($source): string {
|
||||
$start = strpos($source,
|
||||
$visibility . ' static function ' . $name . '(');
|
||||
if ($start === false) {
|
||||
throw new RuntimeException('Missing method ' . $name);
|
||||
}
|
||||
$next = strpos($source, "\n public static function ", $start + 1);
|
||||
$private = strpos($source, "\n private static function ", $start + 1);
|
||||
$ends = array_values(array_filter([$next, $private],
|
||||
static fn ($value): bool => $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";
|
||||
Loading…
Reference in New Issue