You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/Cloud/CloudDailyTrafficLedger.php

245 lines
10 KiB
PHP

<?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;
}
}