refactor(traffic): prune verified hourly checkpoints
parent
59070a491f
commit
382346e1e5
@ -0,0 +1,279 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
use App\Models\CloudInstance;
|
||||
use App\Models\CloudServicePeriod;
|
||||
use App\Models\CloudTrafficInstanceCursor;
|
||||
use App\Models\User;
|
||||
|
||||
/**
|
||||
* Removes hot hourly traffic checkpoints only after compact evidence exists.
|
||||
*
|
||||
* Daily checkpoints preserve the cumulative history shape. A service period
|
||||
* that still needs an intra-day boundary must already have either persisted
|
||||
* base counters or an immutable boundary anchor before its hourly row can be
|
||||
* removed. Any ambiguous state retains data and has no billing side effect.
|
||||
*/
|
||||
final class CloudTrafficCheckpointRetention
|
||||
{
|
||||
public const RETENTION_SECONDS = 72 * 3600;
|
||||
public const MAX_INSTANCE_BATCH = 2000;
|
||||
private const MAX_ROWS_PER_INSTANCE = 2000;
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* scanned_instances:int,
|
||||
* scanned_rows:int,
|
||||
* deleted:int,
|
||||
* skipped:int,
|
||||
* next_cursor:int,
|
||||
* blocked:list<array{instance_id:int,code:string}>
|
||||
* }
|
||||
*/
|
||||
public static function prune(
|
||||
int $limit = 200,
|
||||
?int $now = null,
|
||||
int $afterInstanceId = 0
|
||||
): array {
|
||||
$now ??= time();
|
||||
if ($now < self::RETENTION_SECONDS) {
|
||||
throw new \InvalidArgumentException(
|
||||
'traffic_checkpoint_retention_clock_invalid'
|
||||
);
|
||||
}
|
||||
$limit = max(1, min(self::MAX_INSTANCE_BATCH, $limit));
|
||||
$afterInstanceId = max(0, $afterInstanceId);
|
||||
$cutoff = $now - self::RETENTION_SECONDS;
|
||||
$log = User::getConnectionResolver()->connection('log');
|
||||
foreach ([
|
||||
'cloud_vm_traffic_checkpoints',
|
||||
'cloud_vm_traffic_daily_checkpoints',
|
||||
'cloud_vm_traffic_boundary_anchors',
|
||||
] as $table) {
|
||||
if (!$log->getSchemaBuilder()->hasTable($table)) {
|
||||
throw new \RuntimeException(
|
||||
'traffic_checkpoint_retention_schema_missing'
|
||||
);
|
||||
}
|
||||
}
|
||||
$instanceIds = self::candidateInstanceIds(
|
||||
$log, $cutoff, $afterInstanceId, $limit
|
||||
);
|
||||
if ($instanceIds === [] && $afterInstanceId > 0) {
|
||||
$instanceIds = self::candidateInstanceIds($log, $cutoff, 0, $limit);
|
||||
}
|
||||
$deleted = 0;
|
||||
$skipped = 0;
|
||||
$scannedRows = 0;
|
||||
$blocked = [];
|
||||
foreach ($instanceIds as $instanceId) {
|
||||
try {
|
||||
$result = self::pruneInstance(
|
||||
$log, $instanceId, $cutoff
|
||||
);
|
||||
$deleted += $result['deleted'];
|
||||
$skipped += $result['skipped'];
|
||||
$scannedRows += $result['scanned'];
|
||||
foreach ($result['blocked'] as $code) {
|
||||
$blocked[] = [
|
||||
'instance_id' => $instanceId,
|
||||
'code' => $code,
|
||||
];
|
||||
}
|
||||
} catch (\Throwable $error) {
|
||||
$code = str_starts_with($error->getMessage(), 'traffic_')
|
||||
? $error->getMessage()
|
||||
: 'traffic_checkpoint_retention_failed';
|
||||
$blocked[] = [
|
||||
'instance_id' => $instanceId,
|
||||
'code' => $code,
|
||||
];
|
||||
}
|
||||
}
|
||||
return [
|
||||
'scanned_instances' => count($instanceIds),
|
||||
'scanned_rows' => $scannedRows,
|
||||
'deleted' => $deleted,
|
||||
'skipped' => $skipped,
|
||||
'next_cursor' => count($instanceIds) < $limit
|
||||
? 0 : max($instanceIds),
|
||||
'blocked' => $blocked,
|
||||
];
|
||||
}
|
||||
|
||||
/** @return list<int> */
|
||||
private static function candidateInstanceIds($log, int $cutoff,
|
||||
int $afterInstanceId, int $limit): array
|
||||
{
|
||||
return $log->table('cloud_vm_traffic_checkpoints')
|
||||
->where('instance_id', '>', $afterInstanceId)
|
||||
->where('first_observed_at', '<=', $cutoff)
|
||||
->distinct()->orderBy('instance_id')->limit($limit)
|
||||
->pluck('instance_id')
|
||||
->map(static fn ($id): int => (int) $id)
|
||||
->filter(static fn (int $id): bool => $id > 0)
|
||||
->values()->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{scanned:int,deleted:int,skipped:int,blocked:list<string>}
|
||||
*/
|
||||
private static function pruneInstance($log, int $instanceId,
|
||||
int $cutoff): array
|
||||
{
|
||||
$connection = CloudInstance::query()->getConnection();
|
||||
return $connection->transaction(static function () use (
|
||||
$log, $instanceId, $cutoff
|
||||
): array {
|
||||
$instance = CloudInstance::where('id', $instanceId)
|
||||
->lockForUpdate()->first([
|
||||
'id', 'user_id', 'lifetime_download_bytes',
|
||||
'lifetime_upload_bytes',
|
||||
]);
|
||||
if ($instance === null) {
|
||||
return self::blockedResult(
|
||||
'traffic_checkpoint_instance_missing'
|
||||
);
|
||||
}
|
||||
$cursor = CloudTrafficInstanceCursor::where(
|
||||
'instance_id', $instanceId
|
||||
)->lockForUpdate()->first(['instance_id', 'user_id', 'state']);
|
||||
if ($cursor !== null
|
||||
&& ((int) $cursor->user_id !== (int) $instance->user_id
|
||||
|| (string) $cursor->state === 'attention')) {
|
||||
return self::blockedResult(
|
||||
'traffic_checkpoint_cursor_attention'
|
||||
);
|
||||
}
|
||||
$periods = CloudServicePeriod::where('instance_id', $instanceId)
|
||||
->whereIn('status', ['scheduled', 'active', 'exhausted'])
|
||||
->where('starts_at', '<', $cutoff)
|
||||
->lockForUpdate()->get([
|
||||
'id', 'instance_id', 'user_id', 'starts_at',
|
||||
'download_base_bytes', 'upload_base_bytes', 'status',
|
||||
]);
|
||||
return $log->transaction(static function () use (
|
||||
$log, $instance, $instanceId, $cutoff, $periods
|
||||
): array {
|
||||
$rows = $log->table('cloud_vm_traffic_checkpoints')
|
||||
->where('instance_id', $instanceId)
|
||||
->where('first_observed_at', '<=', $cutoff)
|
||||
->orderBy('first_observed_at')
|
||||
->limit(self::MAX_ROWS_PER_INSTANCE)
|
||||
->lockForUpdate()->get();
|
||||
if ($rows->isEmpty()) {
|
||||
return [
|
||||
'scanned' => 0, 'deleted' => 0, 'skipped' => 0,
|
||||
'blocked' => [],
|
||||
];
|
||||
}
|
||||
$days = $rows->map(static fn ($row): int =>
|
||||
intdiv((int) $row->first_observed_at, 86400) * 86400
|
||||
)->unique()->values()->all();
|
||||
$dailyRows = $log->table(
|
||||
'cloud_vm_traffic_daily_checkpoints'
|
||||
)->where('instance_id', $instanceId)
|
||||
->whereIn('checkpoint_day', $days)
|
||||
->lockForUpdate()->get()->keyBy('checkpoint_day');
|
||||
$periodIds = $periods->pluck('id')->map(
|
||||
static fn ($id): int => (int) $id
|
||||
)->all();
|
||||
$anchors = $periodIds === [] ? collect() : $log->table(
|
||||
'cloud_vm_traffic_boundary_anchors'
|
||||
)->whereIn('service_period_id', $periodIds)
|
||||
->lockForUpdate()->get()->keyBy('service_period_id');
|
||||
$deleted = 0;
|
||||
$skipped = 0;
|
||||
$blocked = [];
|
||||
foreach ($rows as $row) {
|
||||
$code = self::rowBlocker(
|
||||
$row, $instance, $dailyRows, $periods, $anchors
|
||||
);
|
||||
if ($code !== null) {
|
||||
$skipped++;
|
||||
$blocked[$code] = true;
|
||||
continue;
|
||||
}
|
||||
$removed = $log->table('cloud_vm_traffic_checkpoints')
|
||||
->where('instance_id', $instanceId)
|
||||
->where('host_id', (int) $row->host_id)
|
||||
->where('vm_uuid', $row->vm_uuid)
|
||||
->where('checkpoint_hour',
|
||||
(int) $row->checkpoint_hour)
|
||||
->delete();
|
||||
if ($removed !== 1) {
|
||||
throw new \RuntimeException(
|
||||
'traffic_checkpoint_delete_conflict'
|
||||
);
|
||||
}
|
||||
$deleted++;
|
||||
}
|
||||
return [
|
||||
'scanned' => $rows->count(),
|
||||
'deleted' => $deleted,
|
||||
'skipped' => $skipped,
|
||||
'blocked' => array_keys($blocked),
|
||||
];
|
||||
}, 3);
|
||||
}, 3);
|
||||
}
|
||||
|
||||
private static function rowBlocker($row, CloudInstance $instance,
|
||||
$dailyRows, $periods, $anchors): ?string
|
||||
{
|
||||
if ((int) $row->user_id !== (int) $instance->user_id) {
|
||||
return 'traffic_checkpoint_owner_mismatch';
|
||||
}
|
||||
$observedAt = (int) $row->first_observed_at;
|
||||
$download = (int) $row->download_rx_bytes;
|
||||
$upload = (int) $row->upload_tx_bytes;
|
||||
$day = intdiv($observedAt, 86400) * 86400;
|
||||
$daily = $dailyRows->get($day);
|
||||
if ($daily === null
|
||||
|| (int) $daily->user_id !== (int) $instance->user_id
|
||||
|| (int) $daily->first_observed_at > $observedAt
|
||||
|| (int) $daily->last_observed_at < $observedAt
|
||||
|| (int) $daily->first_download_rx_bytes > $download
|
||||
|| (int) $daily->last_download_rx_bytes < $download
|
||||
|| (int) $daily->first_upload_tx_bytes > $upload
|
||||
|| (int) $daily->last_upload_tx_bytes < $upload) {
|
||||
return 'traffic_checkpoint_daily_evidence_missing';
|
||||
}
|
||||
foreach ($periods as $period) {
|
||||
if ((int) $period->starts_at >= $observedAt
|
||||
|| ($period->download_base_bytes !== null
|
||||
&& $period->upload_base_bytes !== null)) {
|
||||
continue;
|
||||
}
|
||||
$anchor = $anchors->get((int) $period->id);
|
||||
if ($anchor === null
|
||||
|| (int) $anchor->instance_id !== (int) $instance->id
|
||||
|| (int) $anchor->user_id !== (int) $instance->user_id
|
||||
|| (int) $anchor->boundary_at !== (int) $period->starts_at
|
||||
|| (int) $anchor->observed_at <= (int) $period->starts_at
|
||||
|| (int) $anchor->download_rx_bytes < 0
|
||||
|| (int) $anchor->upload_tx_bytes < 0
|
||||
|| (int) $anchor->download_rx_bytes
|
||||
> (int) $instance->lifetime_download_bytes
|
||||
|| (int) $anchor->upload_tx_bytes
|
||||
> (int) $instance->lifetime_upload_bytes
|
||||
|| !in_array((string) $anchor->source_kind,
|
||||
['hourly_checkpoint', 'metric_sample'], true)) {
|
||||
return 'traffic_checkpoint_period_boundary_unfrozen';
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @return array{scanned:int,deleted:int,skipped:int,blocked:list<string>} */
|
||||
private static function blockedResult(string $code): array
|
||||
{
|
||||
return [
|
||||
'scanned' => 0,
|
||||
'deleted' => 0,
|
||||
'skipped' => 1,
|
||||
'blocked' => [$code],
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,211 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Services\Cloud\CloudLogIdentity;
|
||||
use App\Services\Cloud\CloudTrafficCheckpointRetention;
|
||||
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->addConnection([
|
||||
'driver' => 'sqlite', 'database' => ':memory:',
|
||||
], 'log');
|
||||
$capsule->setAsGlobal();
|
||||
$capsule->bootEloquent();
|
||||
|
||||
$main = $capsule->schema('default');
|
||||
$main->create('cloud_instances', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->integer('user_id');
|
||||
$table->integer('lifetime_download_bytes')->default(0);
|
||||
$table->integer('lifetime_upload_bytes')->default(0);
|
||||
$table->integer('traffic_synced_at')->default(0);
|
||||
});
|
||||
$main->create('cloud_service_periods', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->integer('instance_id');
|
||||
$table->integer('user_id');
|
||||
$table->integer('starts_at');
|
||||
$table->integer('download_base_bytes')->nullable();
|
||||
$table->integer('upload_base_bytes')->nullable();
|
||||
$table->string('status');
|
||||
});
|
||||
$main->create('cloud_traffic_instance_cursors',
|
||||
static function (Blueprint $table): void {
|
||||
$table->integer('instance_id')->primary();
|
||||
$table->integer('user_id');
|
||||
$table->string('state');
|
||||
});
|
||||
|
||||
$logSchema = $capsule->schema('log');
|
||||
$logSchema->create('cloud_vm_traffic_checkpoints',
|
||||
static function (Blueprint $table): void {
|
||||
$table->integer('instance_id');
|
||||
$table->integer('host_id');
|
||||
$table->binary('vm_uuid');
|
||||
$table->integer('checkpoint_hour');
|
||||
$table->integer('user_id');
|
||||
$table->integer('first_observed_at');
|
||||
$table->integer('download_rx_bytes');
|
||||
$table->integer('upload_tx_bytes');
|
||||
$table->primary(['host_id', 'vm_uuid', 'checkpoint_hour']);
|
||||
});
|
||||
$logSchema->create('cloud_vm_traffic_daily_checkpoints',
|
||||
static function (Blueprint $table): void {
|
||||
$table->integer('instance_id');
|
||||
$table->integer('user_id');
|
||||
$table->integer('checkpoint_day');
|
||||
$table->integer('first_observed_at');
|
||||
$table->integer('first_download_rx_bytes');
|
||||
$table->integer('first_upload_tx_bytes');
|
||||
$table->integer('last_observed_at');
|
||||
$table->integer('last_download_rx_bytes');
|
||||
$table->integer('last_upload_tx_bytes');
|
||||
$table->integer('sample_count');
|
||||
$table->primary(['instance_id', 'checkpoint_day']);
|
||||
});
|
||||
$logSchema->create('cloud_vm_traffic_boundary_anchors',
|
||||
static function (Blueprint $table): void {
|
||||
$table->integer('service_period_id')->primary();
|
||||
$table->integer('instance_id');
|
||||
$table->integer('user_id');
|
||||
$table->integer('boundary_at');
|
||||
$table->integer('observed_at');
|
||||
$table->string('source_kind');
|
||||
$table->integer('download_rx_bytes');
|
||||
$table->integer('upload_tx_bytes');
|
||||
});
|
||||
|
||||
$now = 10 * 86400;
|
||||
$cutoff = $now - CloudTrafficCheckpointRetention::RETENTION_SECONDS;
|
||||
$uuid = CloudLogIdentity::uuid('11111111-1111-4111-8111-111111111111');
|
||||
$log = $capsule->connection('log');
|
||||
|
||||
$insertInstance = static function (int $id, string $cursorState = 'ready')
|
||||
use ($capsule, $now): void {
|
||||
$capsule->connection('default')->table('cloud_instances')->insert([
|
||||
'id' => $id,
|
||||
'user_id' => 7,
|
||||
'lifetime_download_bytes' => 1000,
|
||||
'lifetime_upload_bytes' => 500,
|
||||
'traffic_synced_at' => $now,
|
||||
]);
|
||||
$capsule->connection('default')
|
||||
->table('cloud_traffic_instance_cursors')->insert([
|
||||
'instance_id' => $id,
|
||||
'user_id' => 7,
|
||||
'state' => $cursorState,
|
||||
]);
|
||||
};
|
||||
$insertCheckpoint = static function (int $instanceId, int $observedAt,
|
||||
bool $withDaily = true) use ($log, $uuid): void {
|
||||
$day = intdiv($observedAt, 86400) * 86400;
|
||||
$log->table('cloud_vm_traffic_checkpoints')->insert([
|
||||
'instance_id' => $instanceId,
|
||||
'host_id' => $instanceId,
|
||||
'vm_uuid' => $uuid,
|
||||
'checkpoint_hour' => intdiv($observedAt, 3600) * 3600,
|
||||
'user_id' => 7,
|
||||
'first_observed_at' => $observedAt,
|
||||
'download_rx_bytes' => 400,
|
||||
'upload_tx_bytes' => 200,
|
||||
]);
|
||||
if ($withDaily) {
|
||||
$log->table('cloud_vm_traffic_daily_checkpoints')->insert([
|
||||
'instance_id' => $instanceId,
|
||||
'user_id' => 7,
|
||||
'checkpoint_day' => $day,
|
||||
'first_observed_at' => $day + 60,
|
||||
'first_download_rx_bytes' => 300,
|
||||
'first_upload_tx_bytes' => 100,
|
||||
'last_observed_at' => $day + 23 * 3600,
|
||||
'last_download_rx_bytes' => 800,
|
||||
'last_upload_tx_bytes' => 400,
|
||||
'sample_count' => 10,
|
||||
]);
|
||||
}
|
||||
};
|
||||
|
||||
// Fully covered rows are safely removable and repeated cleanup is idempotent.
|
||||
$insertInstance(1);
|
||||
$insertCheckpoint(1, $cutoff - 3600);
|
||||
$capsule->connection('default')->table('cloud_service_periods')->insert([
|
||||
'id' => 1, 'instance_id' => 1, 'user_id' => 7,
|
||||
'starts_at' => $cutoff - 7200,
|
||||
'download_base_bytes' => 300, 'upload_base_bytes' => 100,
|
||||
'status' => 'active',
|
||||
]);
|
||||
$first = CloudTrafficCheckpointRetention::prune(20, $now);
|
||||
$assert($first['deleted'] === 1 && $first['blocked'] === []
|
||||
&& !$log->table('cloud_vm_traffic_checkpoints')
|
||||
->where('instance_id', 1)->exists(),
|
||||
'Verified hourly checkpoint was not pruned.');
|
||||
$repeat = CloudTrafficCheckpointRetention::prune(20, $now);
|
||||
$assert($repeat['deleted'] === 0,
|
||||
'Repeated hourly checkpoint pruning was not idempotent.');
|
||||
|
||||
// Missing daily evidence is retained rather than guessed away.
|
||||
$insertInstance(2);
|
||||
$insertCheckpoint(2, $cutoff - 7200, false);
|
||||
$missingDaily = CloudTrafficCheckpointRetention::prune(20, $now);
|
||||
$assert($log->table('cloud_vm_traffic_checkpoints')
|
||||
->where('instance_id', 2)->exists()
|
||||
&& in_array('traffic_checkpoint_daily_evidence_missing',
|
||||
array_column($missingDaily['blocked'], 'code'), true),
|
||||
'Checkpoint without daily evidence was deleted or not quarantined.');
|
||||
|
||||
// An unresolved service boundary blocks deletion until its immutable anchor
|
||||
// exists; the anchor then makes the old hourly row disposable.
|
||||
$insertInstance(3);
|
||||
$observedAt = $cutoff - 10_800;
|
||||
$insertCheckpoint(3, $observedAt);
|
||||
$capsule->connection('default')->table('cloud_service_periods')->insert([
|
||||
'id' => 3, 'instance_id' => 3, 'user_id' => 7,
|
||||
'starts_at' => $observedAt - 60,
|
||||
'download_base_bytes' => null, 'upload_base_bytes' => null,
|
||||
'status' => 'scheduled',
|
||||
]);
|
||||
$unfrozen = CloudTrafficCheckpointRetention::prune(20, $now);
|
||||
$assert($log->table('cloud_vm_traffic_checkpoints')
|
||||
->where('instance_id', 3)->exists()
|
||||
&& in_array('traffic_checkpoint_period_boundary_unfrozen',
|
||||
array_column($unfrozen['blocked'], 'code'), true),
|
||||
'Unfrozen service-period boundary did not retain its hourly evidence.');
|
||||
$log->table('cloud_vm_traffic_boundary_anchors')->insert([
|
||||
'service_period_id' => 3,
|
||||
'instance_id' => 3,
|
||||
'user_id' => 7,
|
||||
'boundary_at' => $observedAt - 60,
|
||||
'observed_at' => $observedAt,
|
||||
'source_kind' => 'hourly_checkpoint',
|
||||
'download_rx_bytes' => 400,
|
||||
'upload_tx_bytes' => 200,
|
||||
]);
|
||||
$anchored = CloudTrafficCheckpointRetention::prune(20, $now);
|
||||
$assert($anchored['deleted'] === 1
|
||||
&& !$log->table('cloud_vm_traffic_checkpoints')
|
||||
->where('instance_id', 3)->exists(),
|
||||
'Frozen service-period boundary did not release old hourly evidence.');
|
||||
|
||||
// Attention is a fail-closed accounting state, so no historical evidence is
|
||||
// removed until the original cursor is reconciled.
|
||||
$insertInstance(4, 'attention');
|
||||
$insertCheckpoint(4, $cutoff - 14_400);
|
||||
$attention = CloudTrafficCheckpointRetention::prune(20, $now);
|
||||
$assert($log->table('cloud_vm_traffic_checkpoints')
|
||||
->where('instance_id', 4)->exists()
|
||||
&& in_array('traffic_checkpoint_cursor_attention',
|
||||
array_column($attention['blocked'], 'code'), true),
|
||||
'Attention cursor did not retain its hourly checkpoint evidence.');
|
||||
|
||||
echo "Traffic checkpoint retention contracts passed.\n";
|
||||
Loading…
Reference in New Issue