fix(traffic): 持久化跨迁移每日流量
parent
2b248fadcc
commit
d1288edcef
@ -0,0 +1,244 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
use App\Models\CloudInstance;
|
||||
use App\Models\User;
|
||||
|
||||
/**
|
||||
* PHP-owned UTC daily traffic for one logical instance across host/UUID
|
||||
* generations. The first observation establishes a clean baseline; historical
|
||||
* Agent-local buckets are deliberately not imported.
|
||||
*/
|
||||
final class CloudDailyTrafficLedger
|
||||
{
|
||||
private const MAX_DAYS = 30;
|
||||
private const RETENTION_DAYS = 30;
|
||||
|
||||
/** Record one monotonic panel total without coupling chart writes to billing. */
|
||||
public static function record(CloudInstance $instance, int $observedAt,
|
||||
int $downloadTotal, int $uploadTotal): bool
|
||||
{
|
||||
$instanceId = (int) $instance->id;
|
||||
$userId = (int) $instance->user_id;
|
||||
if ($instanceId < 1 || $userId < 1 || $observedAt < 1
|
||||
|| $downloadTotal < 0 || $uploadTotal < 0) {
|
||||
throw new CloudError('每日流量采样参数无效', 503);
|
||||
}
|
||||
$sampledHostId = (int) $instance->host_id;
|
||||
$sampledUuid = strtolower((string) $instance->uuid);
|
||||
$main = User::getConnectionResolver()->connection('default');
|
||||
return $main->transaction(static function () use (
|
||||
$instanceId, $userId, $observedAt, $downloadTotal,
|
||||
$uploadTotal, $sampledHostId, $sampledUuid
|
||||
): bool {
|
||||
$current = CloudInstance::where('id', $instanceId)
|
||||
->lockForUpdate()->first([
|
||||
'id', 'host_id', 'user_id', 'uuid',
|
||||
'lifetime_download_bytes', 'lifetime_upload_bytes',
|
||||
'traffic_synced_at',
|
||||
]);
|
||||
if ($current === null
|
||||
|| (int) $current->user_id !== $userId
|
||||
|| (int) $current->host_id !== $sampledHostId
|
||||
|| !hash_equals(
|
||||
strtolower((string) $current->uuid), $sampledUuid
|
||||
)
|
||||
|| (int) $current->lifetime_download_bytes
|
||||
!== $downloadTotal
|
||||
|| (int) $current->lifetime_upload_bytes !== $uploadTotal
|
||||
|| (int) $current->traffic_synced_at < $observedAt) {
|
||||
// A maintenance cutover or a newer sync won the instance-row
|
||||
// race. Its generation will own the next daily observation.
|
||||
return false;
|
||||
}
|
||||
|
||||
$log = User::getConnectionResolver()->connection('log');
|
||||
return $log->transaction(static function () use (
|
||||
$log, $instanceId, $userId, $observedAt,
|
||||
$downloadTotal, $uploadTotal
|
||||
): bool {
|
||||
$cursor = $log->table('cloud_vm_daily_traffic_cursors')
|
||||
->where('instance_id', $instanceId)->lockForUpdate()->first();
|
||||
if ($cursor === null) {
|
||||
$inserted = $log->table('cloud_vm_daily_traffic_cursors')
|
||||
->insertOrIgnore([
|
||||
'instance_id' => $instanceId,
|
||||
'user_id' => $userId,
|
||||
'last_observed_at' => $observedAt,
|
||||
'download_total_bytes' => $downloadTotal,
|
||||
'upload_total_bytes' => $uploadTotal,
|
||||
'updated_at' => time(),
|
||||
]);
|
||||
if ($inserted === 1) {
|
||||
self::writeDay($log, $instanceId, $userId,
|
||||
self::dayStart($observedAt), $observedAt, 0, 0);
|
||||
return true;
|
||||
}
|
||||
$cursor = $log->table('cloud_vm_daily_traffic_cursors')
|
||||
->where('instance_id', $instanceId)
|
||||
->lockForUpdate()->first();
|
||||
if ($cursor === null) {
|
||||
throw new CloudError(
|
||||
'每日流量游标暂时无法建立', 503
|
||||
);
|
||||
}
|
||||
}
|
||||
if ((int) $cursor->user_id !== $userId) {
|
||||
throw new CloudError('每日流量归属与实例不一致', 409);
|
||||
}
|
||||
|
||||
$previousDownload = max(0,
|
||||
(int) $cursor->download_total_bytes);
|
||||
$previousUpload = max(0, (int) $cursor->upload_total_bytes);
|
||||
if ($downloadTotal < $previousDownload
|
||||
|| $uploadTotal < $previousUpload) {
|
||||
throw new CloudError('每日流量累计计数发生回退', 503);
|
||||
}
|
||||
$previousObservedAt = max(0,
|
||||
(int) $cursor->last_observed_at);
|
||||
$download = $downloadTotal - $previousDownload;
|
||||
$upload = $uploadTotal - $previousUpload;
|
||||
if ($observedAt <= $previousObservedAt
|
||||
&& $download === 0 && $upload === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// A corrected host clock may move backwards while the durable
|
||||
// counters continue increasing. Keep the logical observation
|
||||
// monotonic so it cannot reopen or rewrite an older UTC bucket.
|
||||
$effectiveAt = max($observedAt, $previousObservedAt);
|
||||
self::writeDay($log, $instanceId, $userId,
|
||||
self::dayStart($effectiveAt), $effectiveAt,
|
||||
$download, $upload);
|
||||
$log->table('cloud_vm_daily_traffic_cursors')
|
||||
->where('instance_id', $instanceId)
|
||||
->where('user_id', $userId)->update([
|
||||
'last_observed_at' => $effectiveAt,
|
||||
'download_total_bytes' => $downloadTotal,
|
||||
'upload_total_bytes' => $uploadTotal,
|
||||
'updated_at' => time(),
|
||||
]);
|
||||
return true;
|
||||
}, 3);
|
||||
}, 3);
|
||||
}
|
||||
|
||||
/** Return a fixed UTC window; missing days remain null, never fabricated 0. */
|
||||
public static function read(CloudInstance $instance, int $days): array
|
||||
{
|
||||
if ($days < 1 || $days > self::MAX_DAYS) {
|
||||
throw new CloudError('流量统计天数必须为 1 至 30');
|
||||
}
|
||||
$instanceId = (int) $instance->id;
|
||||
$userId = (int) $instance->user_id;
|
||||
if ($instanceId < 1 || $userId < 1) {
|
||||
throw new CloudError('实例标识无效', 409);
|
||||
}
|
||||
$today = self::dayStart(time());
|
||||
$from = $today - ($days - 1) * 86400;
|
||||
$until = $today + 86400;
|
||||
try {
|
||||
$log = User::getConnectionResolver()->connection('log');
|
||||
if (!$log->getSchemaBuilder()->hasTable(
|
||||
'cloud_vm_daily_traffic'
|
||||
)) {
|
||||
throw new CloudError('每日流量日志库尚未初始化', 503);
|
||||
}
|
||||
$rows = $log->table('cloud_vm_daily_traffic')
|
||||
->where('instance_id', $instanceId)
|
||||
->where('user_id', $userId)
|
||||
->where('day_start', '>=', $from)
|
||||
->where('day_start', '<', $until)
|
||||
->orderBy('day_start')->get()->keyBy('day_start');
|
||||
} catch (CloudError $error) {
|
||||
throw $error;
|
||||
} catch (\Throwable $error) {
|
||||
throw new CloudError('每日流量记录暂时无法读取', 503);
|
||||
}
|
||||
|
||||
$points = [];
|
||||
for ($day = $from; $day < $until; $day += 86400) {
|
||||
$row = $rows->get($day);
|
||||
$sampled = $row !== null && (int) $row->sample_count > 0;
|
||||
$download = $sampled
|
||||
? max(0, (int) $row->download_bytes) : null;
|
||||
$upload = $sampled
|
||||
? max(0, (int) $row->upload_bytes) : null;
|
||||
$points[] = [
|
||||
'date' => gmdate('Y-m-d', $day),
|
||||
'day_start' => $day,
|
||||
'download_bytes' => $download,
|
||||
'upload_bytes' => $upload,
|
||||
'total_bytes' => $sampled ? $download + $upload : null,
|
||||
];
|
||||
}
|
||||
return [
|
||||
'vm_id' => strtolower((string) $instance->uuid),
|
||||
'days' => $days,
|
||||
'timezone' => 'UTC',
|
||||
'from' => $from,
|
||||
'until' => $until,
|
||||
'points' => $points,
|
||||
];
|
||||
}
|
||||
|
||||
/** Delete expired daily buckets while retaining the continuity cursor. */
|
||||
public static function prune(?int $now = null): int
|
||||
{
|
||||
$cutoff = self::dayStart($now ?? time())
|
||||
- (self::RETENTION_DAYS - 1) * 86400;
|
||||
return User::getConnectionResolver()->connection('log')
|
||||
->table('cloud_vm_daily_traffic')
|
||||
->where('day_start', '<', $cutoff)->delete();
|
||||
}
|
||||
|
||||
private static function writeDay($log, int $instanceId, int $userId,
|
||||
int $dayStart, int $observedAt, int $download, int $upload): void
|
||||
{
|
||||
$row = $log->table('cloud_vm_daily_traffic')
|
||||
->where('instance_id', $instanceId)
|
||||
->where('day_start', $dayStart)->lockForUpdate()->first();
|
||||
if ($row === null) {
|
||||
$log->table('cloud_vm_daily_traffic')->insert([
|
||||
'instance_id' => $instanceId,
|
||||
'user_id' => $userId,
|
||||
'day_start' => $dayStart,
|
||||
'download_bytes' => $download,
|
||||
'upload_bytes' => $upload,
|
||||
'sample_count' => 1,
|
||||
'first_observed_at' => $observedAt,
|
||||
'last_observed_at' => $observedAt,
|
||||
'created_at' => time(),
|
||||
'updated_at' => time(),
|
||||
]);
|
||||
return;
|
||||
}
|
||||
if ((int) $row->user_id !== $userId) {
|
||||
throw new CloudError('每日流量日桶归属与实例不一致', 409);
|
||||
}
|
||||
$currentDownload = max(0, (int) $row->download_bytes);
|
||||
$currentUpload = max(0, (int) $row->upload_bytes);
|
||||
if ($download > PHP_INT_MAX - $currentDownload
|
||||
|| $upload > PHP_INT_MAX - $currentUpload) {
|
||||
throw new CloudError('每日流量超出可记录范围', 503);
|
||||
}
|
||||
$log->table('cloud_vm_daily_traffic')
|
||||
->where('instance_id', $instanceId)
|
||||
->where('day_start', $dayStart)
|
||||
->where('user_id', $userId)->update([
|
||||
'download_bytes' => $currentDownload + $download,
|
||||
'upload_bytes' => $currentUpload + $upload,
|
||||
'sample_count' => max(0, (int) $row->sample_count) + 1,
|
||||
'last_observed_at' => max(
|
||||
(int) $row->last_observed_at, $observedAt
|
||||
),
|
||||
'updated_at' => time(),
|
||||
]);
|
||||
}
|
||||
|
||||
private static function dayStart(int $timestamp): int
|
||||
{
|
||||
return intdiv(max(0, $timestamp), 86400) * 86400;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,210 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Models\CloudInstance;
|
||||
use App\Services\Cloud\CloudDailyTrafficLedger;
|
||||
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);
|
||||
}
|
||||
};
|
||||
$expect = static function (callable $callable, int $status,
|
||||
string $message) use ($assert): void {
|
||||
try {
|
||||
$callable();
|
||||
} catch (CloudError $error) {
|
||||
$assert($error->httpStatus === $status,
|
||||
$message . ' Unexpected status: ' . $error->httpStatus);
|
||||
return;
|
||||
}
|
||||
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();
|
||||
|
||||
$capsule->schema('default')->create('cloud_instances',
|
||||
static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->integer('host_id');
|
||||
$table->integer('user_id');
|
||||
$table->string('uuid');
|
||||
$table->integer('lifetime_download_bytes')->default(0);
|
||||
$table->integer('lifetime_upload_bytes')->default(0);
|
||||
$table->integer('traffic_synced_at')->default(0);
|
||||
$table->integer('created_at');
|
||||
$table->integer('updated_at');
|
||||
});
|
||||
$logSchema = $capsule->schema('log');
|
||||
$logSchema->create('cloud_vm_daily_traffic_cursors',
|
||||
static function (Blueprint $table): void {
|
||||
$table->integer('instance_id')->primary();
|
||||
$table->integer('user_id');
|
||||
$table->integer('last_observed_at');
|
||||
$table->integer('download_total_bytes');
|
||||
$table->integer('upload_total_bytes');
|
||||
$table->integer('updated_at');
|
||||
});
|
||||
$logSchema->create('cloud_vm_daily_traffic',
|
||||
static function (Blueprint $table): void {
|
||||
$table->integer('instance_id');
|
||||
$table->integer('user_id');
|
||||
$table->integer('day_start');
|
||||
$table->integer('download_bytes')->default(0);
|
||||
$table->integer('upload_bytes')->default(0);
|
||||
$table->integer('sample_count')->default(0);
|
||||
$table->integer('first_observed_at');
|
||||
$table->integer('last_observed_at');
|
||||
$table->integer('created_at');
|
||||
$table->integer('updated_at');
|
||||
$table->primary(['instance_id', 'day_start']);
|
||||
});
|
||||
|
||||
$today = intdiv(time(), 86400) * 86400;
|
||||
$firstAt = $today - 120;
|
||||
$secondAt = $today + 60;
|
||||
$instance = new CloudInstance();
|
||||
$instance->host_id = 1;
|
||||
$instance->user_id = 17;
|
||||
$instance->uuid = '11111111-1111-4111-8111-111111111111';
|
||||
$instance->lifetime_download_bytes = 0;
|
||||
$instance->lifetime_upload_bytes = 0;
|
||||
$instance->traffic_synced_at = 0;
|
||||
$instance->created_at = $instance->updated_at = time();
|
||||
$instance->save();
|
||||
$record = static function (CloudInstance $instance, int $observedAt,
|
||||
int $download, int $upload): bool {
|
||||
$current = CloudInstance::findOrFail($instance->id);
|
||||
$syncedAt = max((int) $current->traffic_synced_at, $observedAt);
|
||||
CloudInstance::where('id', $instance->id)->update([
|
||||
'host_id' => (int) $instance->host_id,
|
||||
'user_id' => (int) $instance->user_id,
|
||||
'uuid' => (string) $instance->uuid,
|
||||
'lifetime_download_bytes' => $download,
|
||||
'lifetime_upload_bytes' => $upload,
|
||||
'traffic_synced_at' => $syncedAt,
|
||||
]);
|
||||
$instance->lifetime_download_bytes = $download;
|
||||
$instance->lifetime_upload_bytes = $upload;
|
||||
$instance->traffic_synced_at = $syncedAt;
|
||||
return CloudDailyTrafficLedger::record(
|
||||
$instance, $observedAt, $download, $upload
|
||||
);
|
||||
};
|
||||
|
||||
$assert($record(
|
||||
$instance, $firstAt, 1_000, 500
|
||||
), 'First daily observation did not establish the clean baseline.');
|
||||
$log = $capsule->connection('log');
|
||||
$firstDay = $log->table('cloud_vm_daily_traffic')->where(
|
||||
'day_start', $today - 86400
|
||||
)->first();
|
||||
$assert($firstDay !== null
|
||||
&& (int) $firstDay->download_bytes === 0
|
||||
&& (int) $firstDay->upload_bytes === 0
|
||||
&& (int) $firstDay->sample_count === 1,
|
||||
'First daily observation backfilled traffic that predates deployment.');
|
||||
|
||||
$assert($record(
|
||||
$instance, $secondAt, 1_300, 600
|
||||
), 'Second daily observation was not recorded.');
|
||||
$assert(!$record(
|
||||
$instance, $secondAt, 1_300, 600
|
||||
), 'An exact daily observation replay was counted twice.');
|
||||
$assert($record(
|
||||
$instance, $secondAt - 30, 1_400, 650
|
||||
), 'A clock rollback froze an increasing cumulative total.');
|
||||
|
||||
// Maintenance migration changes host/UUID but retains the logical instance id.
|
||||
$staleSource = clone $instance;
|
||||
$instance->host_id = 2;
|
||||
$instance->uuid = '22222222-2222-4222-8222-222222222222';
|
||||
CloudInstance::where('id', $instance->id)->update([
|
||||
'host_id' => 2,
|
||||
'uuid' => $instance->uuid,
|
||||
'traffic_synced_at' => $secondAt + 30,
|
||||
]);
|
||||
$instance->traffic_synced_at = $secondAt + 30;
|
||||
$assert(!CloudDailyTrafficLedger::record(
|
||||
$staleSource, $secondAt + 45, 1_500, 675
|
||||
), 'A stale source-host sample advanced the post-cutover daily cursor.');
|
||||
$assert($record(
|
||||
$instance, $secondAt + 60, 1_600, 700
|
||||
), 'A maintenance migration reset the logical-instance daily cursor.');
|
||||
$assert($record(
|
||||
$instance, $secondAt + 120, 1_600, 700
|
||||
), 'A real zero-traffic observation was discarded.');
|
||||
$assert(!$record(
|
||||
$instance, $secondAt + 120, 1_600, 700
|
||||
), 'A repeated zero-traffic observation inflated the sample count.');
|
||||
|
||||
$todayRow = $log->table('cloud_vm_daily_traffic')
|
||||
->where('instance_id', $instance->id)
|
||||
->where('day_start', $today)->first();
|
||||
$assert($todayRow !== null
|
||||
&& (int) $todayRow->download_bytes === 600
|
||||
&& (int) $todayRow->upload_bytes === 200
|
||||
&& (int) $todayRow->sample_count === 4,
|
||||
'Daily deltas did not survive UTC rollover, replay or migration.');
|
||||
|
||||
$assert(!CloudDailyTrafficLedger::record(
|
||||
$instance, $secondAt + 180, 1_599, 700
|
||||
), 'A stale smaller cumulative total passed the main-instance fence.');
|
||||
$todayAfterRegression = $log->table('cloud_vm_daily_traffic')
|
||||
->where('instance_id', $instance->id)
|
||||
->where('day_start', $today)->first();
|
||||
$assert((int) $todayAfterRegression->download_bytes === 600
|
||||
&& (int) $todayAfterRegression->sample_count === 4,
|
||||
'A rejected cumulative regression changed the daily ledger.');
|
||||
|
||||
$window = CloudDailyTrafficLedger::read($instance, 3);
|
||||
$assert(count($window['points']) === 3
|
||||
&& $window['from'] === $today - 2 * 86400
|
||||
&& $window['until'] === $today + 86400
|
||||
&& $window['points'][0]['download_bytes'] === null
|
||||
&& $window['points'][0]['upload_bytes'] === null
|
||||
&& $window['points'][1]['download_bytes'] === 0
|
||||
&& $window['points'][1]['upload_bytes'] === 0
|
||||
&& $window['points'][2]['download_bytes'] === 600
|
||||
&& $window['points'][2]['upload_bytes'] === 200,
|
||||
'Daily read fabricated missing samples or lost a genuine zero sample.');
|
||||
|
||||
$log->table('cloud_vm_daily_traffic')->insert([
|
||||
'instance_id' => 999,
|
||||
'user_id' => 17,
|
||||
'day_start' => $today - 30 * 86400,
|
||||
'download_bytes' => 1,
|
||||
'upload_bytes' => 1,
|
||||
'sample_count' => 1,
|
||||
'first_observed_at' => $today - 30 * 86400,
|
||||
'last_observed_at' => $today - 30 * 86400,
|
||||
'created_at' => time(),
|
||||
'updated_at' => time(),
|
||||
]);
|
||||
$assert(CloudDailyTrafficLedger::prune($today + 3600) === 1
|
||||
&& $log->table('cloud_vm_daily_traffic_cursors')
|
||||
->where('instance_id', $instance->id)->exists(),
|
||||
'Thirty-day pruning removed the continuity cursor or retained expired data.');
|
||||
|
||||
$log->table('cloud_vm_daily_traffic_cursors')
|
||||
->where('instance_id', $instance->id)->update(['user_id' => 18]);
|
||||
CloudInstance::where('id', $instance->id)->update([
|
||||
'traffic_synced_at' => $secondAt + 240,
|
||||
]);
|
||||
$expect(static fn () => CloudDailyTrafficLedger::record(
|
||||
$instance, $secondAt + 240, 1_600, 700
|
||||
), 409, 'A cursor bound to another owner was accepted.');
|
||||
|
||||
echo "Logical-instance daily traffic ledger contracts passed.\n";
|
||||
Loading…
Reference in New Issue