fix(traffic): 持久化跨迁移每日流量

go
codex 3 weeks ago
parent 2b248fadcc
commit d1288edcef

@ -32,7 +32,7 @@ PHP workers ──> 持久 task/operation_id ──一次派发──> 本机 Ga
| 任务状态、操作者、`operation_id`、绝对截止和终态回执 | PHP | 业务库 |
| libvirt、宿主机磁盘、网络、防火墙、快照、救援 | Go Agent | 本机 libvirt 与受管存储 |
| 已派发操作、永久防重放 tombstone 与有界完成 outbox | Go Agent | `journal_path` 指定的本机 bbolt 持久库,以及权限为 `0700` 的隔离 worker 状态目录 |
| 指标样本、持久流量累计和账期基线 | PHP 协调、Agent 采集 | 日志库与业务库 |
| 指标样本、持久流量累计、实例 UTC 每日流量和账期基线 | PHP 协调、Agent 采集 | 日志库与业务库 |
PHP 不打开 libvirt 连接,不接收任意宿主机命令,也不把 Agent 密钥返回浏览器。Agent 不连接面板数据库,不处理用户会话、余额或支付。

@ -8,7 +8,7 @@ use App\Services\Config;
/** Initializes only the clean-break PHP business and Agent log schemas. */
final class CloudSetup
{
private const SCHEMA_VERSION = 'go-agent-wss-v23-traffic-admin';
private const SCHEMA_VERSION = 'go-agent-wss-v24-daily-traffic';
private const MAIN_TABLES = [
'cloud_regions', 'cloud_traffic_pool_groups',
'cloud_network_lines', 'cloud_resource_pools',
@ -48,7 +48,8 @@ final class CloudSetup
];
private const LOG_TABLES = [
'cloud_vm_metric_samples', 'cloud_vm_traffic_checkpoints',
'cloud_vm_traffic_totals',
'cloud_vm_traffic_totals', 'cloud_vm_daily_traffic_cursors',
'cloud_vm_daily_traffic',
];
/** Refusal-only denylist: never read, import, rename or migrate these rows. */
private const RETIRED_LOG_TABLES = [
@ -333,6 +334,15 @@ final class CloudSetup
'user_id', 'first_observed_at', 'download_rx_bytes',
'upload_tx_bytes',
],
'cloud_vm_daily_traffic_cursors' => [
'instance_id', 'user_id', 'last_observed_at',
'download_total_bytes', 'upload_total_bytes', 'updated_at',
],
'cloud_vm_daily_traffic' => [
'instance_id', 'user_id', 'day_start', 'download_bytes',
'upload_bytes', 'sample_count', 'first_observed_at',
'last_observed_at', 'created_at', 'updated_at',
],
];
private const REQUIRED_CHECKS = [
'cloud_traffic_pool_groups' => [

@ -22,6 +22,7 @@ use App\Services\Cloud\CloudDeploymentPageService;
use App\Services\Cloud\CloudDeploymentSnapshotService;
use App\Services\Cloud\CloudAgentSettingsService;
use App\Services\Cloud\CloudConsoleTicketService;
use App\Services\Cloud\CloudDailyTrafficLedger;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudFirewallService;
use App\Services\Cloud\CloudInput;
@ -514,56 +515,6 @@ final class CloudApiController
'points' => $points];
}
/** Keep daily traffic to UTC day buckets and bounded byte counters. */
private function publicDailyTraffic($value, string $uuid, int $days): array
{
$result = is_array($value) ? $value : [];
$points = [];
foreach (is_array($result['traffic'] ?? null) ? $result['traffic'] : [] as $point) {
if (!is_array($point) || array_is_list($point)) {
continue;
}
$date = $point['date'] ?? null;
if (!is_string($date)
|| preg_match('/^\d{4}-\d{2}-\d{2}$/D', $date) !== 1) {
continue;
}
$parsed = \DateTimeImmutable::createFromFormat('!Y-m-d', $date,
new \DateTimeZone('UTC'));
if ($parsed === false || $parsed->format('Y-m-d') !== $date) {
continue;
}
$bytesByDirection = [];
foreach (['download_bytes' => 'rx_bytes', 'upload_bytes' => 'tx_bytes']
as $publicKey => $agentKey) {
$bytes = $point[$agentKey] ?? null;
if (is_string($bytes) && preg_match('/^[0-9]+$/D', $bytes) !== 1) {
$bytes = null;
}
if (is_bool($bytes) || (!is_int($bytes) && !is_string($bytes))
|| (int) $bytes < 0 || (int) $bytes > 9000000000000000) {
$bytes = null;
}
$bytesByDirection[$publicKey] = $bytes === null ? null : (int) $bytes;
}
$safe = ['date' => $date, 'day_start' => $parsed->getTimestamp()]
+ $bytesByDirection;
$safe['total_bytes'] = $safe['download_bytes'] === null
|| $safe['upload_bytes'] === null
? null : $safe['download_bytes'] + $safe['upload_bytes'];
$points[] = $safe;
if (count($points) >= $days) {
break;
}
}
$from = $points === [] ? null : $points[0]['day_start'];
$until = $points === [] ? null
: $points[count($points) - 1]['day_start'] + 86400;
return ['vm_id' => $uuid, 'days' => $days, 'timezone' => 'UTC',
'from' => $from, 'until' => $until,
'points' => $points];
}
/**
* Resolve list-only VM dependencies in fixed-size database queries and
* targeted Agent reads. The database collection is authoritative; a
@ -1358,12 +1309,8 @@ final class CloudApiController
if ($days === false) {
throw new CloudError('流量统计天数必须为 1 至 30');
}
$value = CloudAgentSettingsService::clientForHost(
(int) $instance->host_id
)->request('GET', '/v1/vms/' . rawurlencode((string) $instance->uuid)
. '/traffic/daily?days=' . (int) $days, $actor);
return $this->json($response, $this->publicDailyTraffic($value,
strtolower((string) $instance->uuid), (int) $days));
return $this->json($response,
CloudDailyTrafficLedger::read($instance, (int) $days));
}
public function credential($request, $response, $args)

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

@ -161,6 +161,17 @@ final class CloudTrafficService
->chunkById($batchSize, function ($instances) use (&$updated) {
$updated += self::syncBatch($instances);
});
try {
$log = User::getConnectionResolver()->connection('log');
if ($log->getSchemaBuilder()->hasTable(
'cloud_vm_daily_traffic'
)) {
CloudDailyTrafficLedger::prune();
}
} catch (\Throwable $error) {
error_log('cloud daily traffic retention unavailable: '
. get_class($error));
}
return $updated;
}
@ -479,6 +490,11 @@ final class CloudTrafficService
}
$updated = 0;
$log = User::getConnectionResolver()->connection('log');
$dailyReady = $log->getSchemaBuilder()->hasTable(
'cloud_vm_daily_traffic_cursors'
) && $log->getSchemaBuilder()->hasTable(
'cloud_vm_daily_traffic'
);
foreach ($groups as $hostId => $owned) {
$scope = self::hostScope($hostId);
$uuids = array_map(static fn ($instance) => (string) $instance->uuid, $owned);
@ -512,6 +528,23 @@ final class CloudTrafficService
->update(['lifetime_download_bytes' => $download,
'lifetime_upload_bytes' => $upload, 'traffic_synced_at' => $observed]);
$updated += $changed;
if ($dailyReady) {
try {
// The ledger locks and rechecks the current host/UUID
// after the monotonic main-database sync. A migration
// cutover therefore either sees this total in its base
// or rejects this source generation as stale.
CloudDailyTrafficLedger::record(
$instance, $observed, $download, $upload
);
} catch (\Throwable $error) {
// Daily charts are non-critical. The unchanged cursor
// lets the next successful sync catch up without
// rolling back billing totals.
error_log('cloud daily traffic write unavailable: '
. get_class($error));
}
}
}
}
return $updated;

@ -50,3 +50,34 @@ CREATE TABLE cloud_vm_traffic_checkpoints (
PRIMARY KEY (host_scope, vm_uuid, checkpoint_hour),
KEY vm_traffic_checkpoint_owner (user_id, host_id, first_observed_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- Logical-instance daily traffic survives maintenance migration because its
-- identity does not depend on the current host or libvirt UUID. The cursor is
-- retained beyond the 30-day chart window so an old cumulative total can
-- never be charged into a new day after pruning.
CREATE TABLE cloud_vm_daily_traffic_cursors (
instance_id BIGINT UNSIGNED NOT NULL,
user_id BIGINT UNSIGNED NOT NULL,
last_observed_at BIGINT UNSIGNED NOT NULL,
download_total_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0,
upload_total_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0,
updated_at BIGINT UNSIGNED NOT NULL,
PRIMARY KEY (instance_id),
KEY cloud_daily_traffic_cursor_owner (user_id, updated_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE cloud_vm_daily_traffic (
instance_id BIGINT UNSIGNED NOT NULL,
user_id BIGINT UNSIGNED NOT NULL,
day_start BIGINT UNSIGNED NOT NULL,
download_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0,
upload_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0,
sample_count INT UNSIGNED NOT NULL DEFAULT 0,
first_observed_at BIGINT UNSIGNED NOT NULL,
last_observed_at BIGINT UNSIGNED NOT NULL,
created_at BIGINT UNSIGNED NOT NULL,
updated_at BIGINT UNSIGNED NOT NULL,
PRIMARY KEY (instance_id, day_start),
KEY cloud_daily_traffic_retention (day_start),
KEY cloud_daily_traffic_owner (user_id, day_start)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

@ -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";

@ -22,7 +22,7 @@ $assert(stripos($schema, 'compatibility import') === false
$assert(!preg_match('/\bengine_[A-Za-z0-9_]*\b/', $schema),
'cloud.sql retained an engine-prefixed identifier.');
$assert(str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v23-traffic-admin'")
"SCHEMA_VERSION = 'go-agent-wss-v24-daily-traffic'")
&& !str_contains($setup, "SCHEMA_VERSION = 'go-v1'"),
'Outbound Agent schema must reject the incompatible earlier Go database.');
$assert(str_contains($schema,

@ -27,6 +27,8 @@ $routes = file_get_contents($root . '/config/routes_cloud.php');
$worker = file_get_contents($root . '/app/Services/Cloud/CloudWorkerService.php');
$pageService = $section($service, 'public static function forActor(',
'public static function detailForActor(');
$dailyTrafficApi = $section($api, 'public function dailyTraffic(',
'public function credential(');
$assert(str_contains($service, "CloudInstance::where('status', '<>', 'deleted')")
&& str_contains($service, "if (!(\$actor['is_admin'] ?? false))")
@ -177,9 +179,10 @@ $assert(str_contains($vmData, "'name' => (string) \$instance->name")
&& str_contains($api, 'private function publicVmMetadata(')
&& str_contains($api, 'private function publicVmSpec(')
&& str_contains($api, 'private function publicMetrics(')
&& str_contains($api, 'private function publicDailyTraffic(')
&& str_contains($api, '$this->publicMetrics($value')
&& str_contains($api, '$this->publicDailyTraffic($value')
&& str_contains($dailyTrafficApi, 'CloudDailyTrafficLedger::read(')
&& !str_contains($dailyTrafficApi, 'CloudAgentSettingsService')
&& !str_contains($dailyTrafficApi, "->request(")
&& !str_contains($vmData, "'host_id' =>")
&& !str_contains($vmData, 'host?->region')
&& !str_contains($vmData, 'CloudInput::safeResult($vm)'),

@ -56,7 +56,7 @@ $assert($replica !== ''
&& str_contains($replica, 'cleanup_resolved_at BIGINT UNSIGNED'),
'Rescue replica cannot prove exact identity or retain cleanup debt.');
$assert(str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v23-traffic-admin'")
"SCHEMA_VERSION = 'go-agent-wss-v24-daily-traffic'")
&& str_contains($setup, "'cloud_rescue_artifact_delete_due'")
&& str_contains($setup, "'cloud_rescue_replica_cleanup'"),
'CloudSetup version or rescue catalog indexes are incomplete.');

@ -63,7 +63,7 @@ $assert(str_contains($schema,
&& str_contains($schema,
'CONSTRAINT chk_cloud_template_import_completion CHECK (')
&& str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v23-traffic-admin'"),
"SCHEMA_VERSION = 'go-agent-wss-v24-daily-traffic'"),
'Template imports are missing durable identity or terminal-state constraints.');
$assert(str_contains($routes, "'/admin/cloud-template-imports'")
&& str_contains($routes, "'/admin/cloud-template-imports/{id}'")

@ -120,6 +120,29 @@ namespace {
$table->integer('upload_tx_bytes');
$table->primary(['host_scope', 'vm_uuid', 'checkpoint_hour']);
});
$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']);
});
$now = time();
$secondInHour = $now % 3600;
@ -194,10 +217,13 @@ namespace {
'test-gateway-secret-at-least-32-bytes');
$first = CloudTrafficService::collect(1, $agent);
$firstSyncCount = CloudTrafficService::sync(1);
$total = $log->table('cloud_vm_traffic_totals')->first();
$firstSample = $log->table('cloud_vm_metric_samples')
->where('sampled_at', $firstAt)->first();
$checkpoint = $log->table('cloud_vm_traffic_checkpoints')->first();
$dailyCursor = $log->table('cloud_vm_daily_traffic_cursors')->first();
$daily = $log->table('cloud_vm_daily_traffic')->first();
$baseline = json_decode((string) $total->network_baseline_json, true,
flags: JSON_THROW_ON_ERROR);
$assert($first === [
@ -205,6 +231,7 @@ namespace {
'errors' => [],
]
&& count($history) === 1
&& $firstSyncCount === 1
&& $history[0]['request']->getMethod() === 'POST'
&& (($firstEnvelope = json_decode(
(string) $history[0]['request']->getBody(), true,
@ -225,6 +252,12 @@ namespace {
&& (float) $firstSample->memory_total_mib === 2048.0
&& (int) $checkpoint->download_rx_bytes === 100_000
&& (int) $checkpoint->upload_tx_bytes === 50_000
&& (int) $dailyCursor->instance_id === (int) $instance->id
&& (int) $dailyCursor->download_total_bytes === 100_000
&& (int) $dailyCursor->upload_total_bytes === 50_000
&& (int) $daily->download_bytes === 0
&& (int) $daily->upload_bytes === 0
&& (int) $daily->sample_count === 1
&& !$log->table('cloud_vm_metric_samples')
->where('sampled_at', $now - 31 * 86400)->exists(),
'First signed Agent Metrics DTO did not restore its durable Agent total or prune old samples.');
@ -424,6 +457,39 @@ namespace {
'instance' => $migratedInstance->toArray(),
], JSON_THROW_ON_ERROR));
// A staggered deployment must keep cumulative billing alive even before
// the optional daily-log tables have been installed.
$logSchema->drop('cloud_vm_daily_traffic');
$logSchema->drop('cloud_vm_daily_traffic_cursors');
$log->table('cloud_vm_traffic_totals')
->where('vm_uuid', $migratedUuid)->update(['last_observed_at' => 0]);
$withoutDailyMetrics = $metrics(
$now + 1, 110_000_000, 524_288, 110, 55, 1_350, 800
);
$withoutDailyMetrics['uuid'] = $migratedUuid;
$withoutDailyMock = new MockHandler([
new Response(200, ['Content-Type' => 'application/json'],
json_encode($withoutDailyMetrics, JSON_THROW_ON_ERROR)),
]);
$withoutDailyAgent = new CloudAgentClient('8',
'metric-test-secret-at-least-32-bytes', new Client([
'handler' => HandlerStack::create($withoutDailyMock),
'http_errors' => false,
]), 20.0, 'http://127.0.0.1:8001/internal/agent/request',
'test-gateway-secret-at-least-32-bytes');
$withoutDaily = CloudTrafficService::collect(1, $withoutDailyAgent);
$withoutDailySyncCount = CloudTrafficService::sync(1);
$withoutDailyTotal = $log->table('cloud_vm_traffic_totals')
->where('vm_uuid', $migratedUuid)->first();
$assert($withoutDaily === [
'observed' => 1, 'unavailable' => 0, 'skipped' => 0,
'errors' => [],
]
&& $withoutDailySyncCount === 1
&& (int) $withoutDailyTotal->download_rx_bytes === 114_850
&& (int) $withoutDailyTotal->upload_tx_bytes === 57_500,
'Missing daily-log tables blocked the core cumulative traffic write.');
$controller = file_get_contents(dirname(__DIR__)
. '/app/Controllers/CloudApiController.php');
$lifecycle = file_get_contents(dirname(__DIR__)

@ -71,7 +71,7 @@ $assert(str_contains($schema,
'Service-period traffic-pool identity is not frozen or indexed.');
$assert(str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v23-traffic-admin'")
"SCHEMA_VERSION = 'go-agent-wss-v24-daily-traffic'")
&& str_contains($setup, "'chk_cloud_traffic_entitlement_balance'")
&& str_contains($setup, "'cloud_traffic_ledger_sequence'"),
'CloudSetup schema version or named-object validation is incomplete.');

@ -101,7 +101,7 @@ $assert(str_contains($jobs, 'vpc_id BIGINT UNSIGNED DEFAULT NULL')
'Cloud jobs cannot be correlated to VPC or VPC-port work.');
$assert(str_contains($setup,
"private const SCHEMA_VERSION = 'go-agent-wss-v23-traffic-admin'")
"private const SCHEMA_VERSION = 'go-agent-wss-v24-daily-traffic'")
&& str_contains($setup, "'name' => 'cloud_vpc_enabled'")
&& str_contains($setup, "'value' => 'false'")
&& str_contains($setup,

@ -29,6 +29,20 @@ foreach ([
'checkpoint_hour BIGINT UNSIGNED', 'first_observed_at BIGINT UNSIGNED',
'vm_traffic_checkpoint_owner (user_id, host_id, first_observed_at)',
],
'cloud_vm_daily_traffic_cursors' => [
'instance_id BIGINT UNSIGNED', 'user_id BIGINT UNSIGNED',
'last_observed_at BIGINT UNSIGNED',
'download_total_bytes BIGINT UNSIGNED',
'upload_total_bytes BIGINT UNSIGNED',
'cloud_daily_traffic_cursor_owner (user_id, updated_at)',
],
'cloud_vm_daily_traffic' => [
'instance_id BIGINT UNSIGNED', 'user_id BIGINT UNSIGNED',
'day_start BIGINT UNSIGNED', 'download_bytes BIGINT UNSIGNED',
'upload_bytes BIGINT UNSIGNED', 'sample_count INT UNSIGNED',
'cloud_daily_traffic_retention (day_start)',
'cloud_daily_traffic_owner (user_id, day_start)',
],
] as $table => $required) {
$assert(preg_match('/CREATE TABLE ' . preg_quote($table, '/')
. '\s*\((.*?)\) ENGINE=/s', $sql, $match) === 1,

Loading…
Cancel
Save