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/tests/CloudServiceCompensationPla...

440 lines
17 KiB
PHP

<?php
declare(strict_types=1);
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudServiceCompensationPlanner;
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);
}
};
$expectCloudError = static function (
callable $callback,
int $status,
string $message
) use ($assert): void {
try {
$callback();
} catch (CloudError $error) {
$assert($error->httpStatus === $status, $message);
return;
}
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_hosts', static function (Blueprint $table): void {
$table->increments('id');
$table->string('name');
$table->string('region')->default('');
});
$schema->create(
'cloud_public_ip_pools',
static function (Blueprint $table): void {
$table->increments('id');
$table->string('pool_key');
$table->integer('host_id');
$table->integer('address_family');
$table->string('name');
$table->string('cidr');
}
);
$schema->create('user', static function (Blueprint $table): void {
$table->increments('id');
$table->string('email');
});
$schema->create('cloud_instances', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('user_id');
$table->integer('host_id');
$table->integer('reservation_id')->nullable();
$table->string('name');
$table->string('status');
$table->string('service_status');
$table->string('network_status');
$table->integer('expires_at')->nullable();
$table->integer('current_period_id')->nullable();
$table->integer('plan_id')->nullable();
$table->integer('offer_id')->nullable();
$table->string('renewal_price')->nullable();
$table->integer('renewal_days')->default(0);
$table->integer('renewal_traffic_bytes')->default(0);
$table->integer('lifetime_download_bytes')->default(0);
$table->integer('lifetime_upload_bytes')->default(0);
$table->text('spec_json');
$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('traffic_pool_group_id')->nullable();
$table->string('traffic_quota_mode');
$table->integer('starts_at');
$table->integer('ends_at');
$table->integer('traffic_quota_bytes');
$table->string('status');
$table->integer('created_at');
$table->integer('updated_at');
}
);
$schema->create(
'cloud_resource_reservations',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('instance_id')->nullable();
$table->integer('host_id');
$table->integer('user_id');
$table->string('state');
}
);
$schema->create(
'cloud_resource_reservation_ips',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('reservation_id');
$table->integer('address_family');
$table->integer('claim_generation');
$table->integer('active_claim')->nullable();
$table->integer('public_ip_pool_id');
$table->integer('public_ip_id');
$table->string('operation_id');
$table->string('state');
}
);
$now = 1800000000;
Capsule::table('cloud_hosts')->insert([
['id' => 1, 'name' => 'HKG-A', 'region' => 'HongKong'],
['id' => 2, 'name' => 'HKG-B', 'region' => 'HongKong'],
]);
Capsule::table('cloud_public_ip_pools')->insert([
['id' => 10, 'pool_key' => str_repeat('a', 32), 'host_id' => 1,
'address_family' => 4, 'name' => 'HKG IPv4',
'cidr' => '192.0.2.0/24'],
]);
Capsule::table('user')->insert([
['id' => 1, 'email' => ' OWNER@Example.COM '],
['id' => 2, 'email' => 'invalid'],
['id' => 3, 'email' => 'third@example.com'],
]);
$instance = static function (
int $id,
int $userId,
string $serviceStatus,
?int $expiresAt,
string $status = 'active',
string $networkStatus = 'active',
?int $reservationId = null
) use ($now): array {
return [
'id' => $id,
'user_id' => $userId,
'host_id' => 1,
'reservation_id' => $reservationId,
'name' => 'vm-' . $id,
'status' => $status,
'service_status' => $serviceStatus,
'network_status' => $networkStatus,
'expires_at' => $expiresAt,
'current_period_id' => null,
'plan_id' => 7,
'offer_id' => 9,
'renewal_price' => '10.00',
'renewal_days' => 30,
'renewal_traffic_bytes' => 2147483648,
'lifetime_download_bytes' => 0,
'lifetime_upload_bytes' => 0,
'spec_json' => '{}',
'updated_at' => $now,
];
};
// Deliberately insert out of ID order. Canonical output must sort by ID.
Capsule::table('cloud_instances')->insert([
$instance(110, 2, 'active', $now + 10000),
$instance(103, 2, 'exempt', $now + 5000, 'active', 'active', 203),
$instance(101, 1, 'active', $now + 3600, 'active',
'blocked_traffic', 201),
$instance(112, 3, 'active', $now + 4000),
$instance(106, 3, 'active', $now + 4000),
$instance(102, 1, 'active', $now + 7200),
$instance(109, 3, 'active', $now + 9000),
$instance(104, 2, 'expired_grace', $now + 6000),
$instance(108, 3, 'active', $now + 8000),
$instance(111, 1, 'active', $now + 11000, 'deleted',
'active', 211),
$instance(105, 2, 'active', $now),
$instance(107, 3, 'active', $now + 7000),
$instance(114, 2, 'active', null),
$instance(115, 2, 'active', $now - 1),
]);
Capsule::table('cloud_instances')->where('id', 102)
->update(['current_period_id' => 1002]);
$period = static function (
int $id,
int $instanceId,
int $userId,
int $startsAt,
int $endsAt,
string $status
) use ($now): array {
return [
'id' => $id,
'instance_id' => $instanceId,
'user_id' => $userId,
'plan_id' => 7,
'traffic_pool_group_id' => 5,
'traffic_quota_mode' => 'finite',
'starts_at' => $startsAt,
'ends_at' => $endsAt,
'traffic_quota_bytes' => 2147483648,
'status' => $status,
'created_at' => $now - 1000,
'updated_at' => $now,
];
};
Capsule::table('cloud_service_periods')->insert([
$period(1010, 110, 2, $now + 5000, $now + 10000, 'scheduled'),
$period(1003, 102, 1, $now + 3600, $now + 7200, 'scheduled'),
$period(1001, 101, 1, $now - 100, $now + 3600, 'active'),
$period(1012, 112, 3, $now - 100, $now + 3900, 'active'),
$period(1008, 108, 3, $now + 8000, $now + 8000, 'active'),
$period(1002, 102, 1, $now - 100, $now + 3600, 'active'),
$period(1011, 111, 1, $now - 100, $now + 11000, 'active'),
$period(1007, 107, 3, $now - 100, $now + 7000, 'finished'),
$period(1009, 109, 3, $now - 100, $now + 9000, 'exhausted'),
]);
Capsule::table('cloud_resource_reservations')->insert([
['id' => 201, 'instance_id' => 101, 'host_id' => 1,
'user_id' => 1, 'state' => 'committed'],
['id' => 203, 'instance_id' => 103, 'host_id' => 1,
'user_id' => 2, 'state' => 'committed'],
['id' => 211, 'instance_id' => 111, 'host_id' => 1,
'user_id' => 1, 'state' => 'committed'],
]);
Capsule::table('cloud_resource_reservation_ips')->insert([
['id' => 301, 'reservation_id' => 201, 'address_family' => 4,
'claim_generation' => 1, 'active_claim' => 1,
'public_ip_pool_id' => 10, 'public_ip_id' => 401,
'operation_id' => str_repeat('1', 32), 'state' => 'committed'],
['id' => 303, 'reservation_id' => 203, 'address_family' => 4,
'claim_generation' => 1, 'active_claim' => 1,
'public_ip_pool_id' => 10, 'public_ip_id' => 403,
'operation_id' => str_repeat('3', 32), 'state' => 'committed'],
['id' => 311, 'reservation_id' => 211, 'address_family' => 4,
'claim_generation' => 1, 'active_claim' => 1,
'public_ip_pool_id' => 10, 'public_ip_id' => 411,
'operation_id' => str_repeat('1', 32), 'state' => 'committed'],
]);
$planner = new CloudServiceCompensationPlanner(
clock: static fn (): int => $now
);
$preview = $planner->preview('host', 1);
$assert($preview['instance_count'] === 13
&& $preview['eligible_count'] === 4
&& $preview['rejected_count'] === 5
&& $preview['attention_count'] === 4,
'Host preview did not preserve the eligibility matrix.');
$assert($preview['eligible_count'] + $preview['rejected_count']
+ $preview['attention_count'] === $preview['instance_count'],
'Every affected instance must have exactly one disposition.');
$assert(array_column($preview['instances'], 'id') === [
101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 112, 114, 115,
],
'Canonical instances must be sorted by numeric ID.');
$byId = [];
foreach ($preview['instances'] as $row) {
$byId[$row['id']] = $row;
}
$assert($byId[101]['eligibility']['state'] === 'eligible'
&& $byId[101]['status'] === 'active',
'A network-blocked active service must remain compensable.');
$assert($byId[102]['eligibility']['state'] === 'eligible'
&& $byId[102]['tail_period']['id'] === 1003
&& $byId[102]['tail_period']['status'] === 'scheduled',
'The planner must choose the latest scheduled tail, not current_period_id.');
$assert($byId[109]['eligibility']['state'] === 'eligible'
&& $byId[109]['tail_period']['status'] === 'exhausted'
&& $byId[110]['eligibility']['state'] === 'eligible',
'Exhausted and scheduled unexpired tails must remain eligible.');
$assert($byId[103]['eligibility'] === [
'state' => 'rejected', 'code' => 'service_not_active',
] && $byId[104]['eligibility']['state'] === 'rejected'
&& $byId[105]['eligibility'] === [
'state' => 'rejected', 'code' => 'service_expired',
] && $byId[114]['eligibility']['code'] === 'service_expired'
&& $byId[115]['eligibility']['code'] === 'service_expired',
'Inactive service and every non-future expiry must be rejected.');
$assert($byId[106]['eligibility']['code'] === 'service_period_missing'
&& $byId[107]['eligibility']['code']
=== 'service_period_state_invalid'
&& $byId[108]['eligibility']['code']
=== 'service_period_window_invalid'
&& $byId[112]['eligibility']['code']
=== 'service_period_expiry_mismatch',
'Broken tail-period ledgers must require attention.');
$assert($preview['recipient_count'] === 2
&& $preview['skipped_count'] === 1,
'Only eligible owners must contribute notification recipients.');
$assert($preview['recipients'][0]['user_id'] === 1
&& $preview['recipients'][0]['email'] === 'owner@example.com'
&& $preview['recipients'][0]['instance_ids'] === [101, 102]
&& $preview['recipients'][1]['user_id'] === 2
&& $preview['recipients'][1]['deliverable'] === false
&& $preview['recipients'][1]['instance_ids'] === [110]
&& $preview['recipients'][2]['user_id'] === 3
&& $preview['recipients'][2]['instance_ids'] === [109],
'Recipients must be normalized and grouped in user/instance order.');
$instancePreview = $planner->preview('instance', 101);
$assert($instancePreview['scope']['type'] === 'instance'
&& $instancePreview['scope']['instance_id'] === 101
&& $instancePreview['scope']['label'] === '单实例 #101'
&& !array_key_exists('user_id', $instancePreview['scope'])
&& !str_contains(
json_encode($instancePreview['scope'], JSON_THROW_ON_ERROR),
'vm-101'
)
&& $instancePreview['instance_count'] === 1
&& $instancePreview['eligible_count'] === 1,
'Instance scope must produce one eligible preview without tenant PII.');
$deletedPreview = $planner->preview('instance', 111);
$assert($deletedPreview['scope']['instance_id'] === 111
&& $deletedPreview['instance_count'] === 0
&& $deletedPreview['eligible_count'] === 0,
'A retained deleted instance is an empty scope, not a missing scope.');
$emptyHost = $planner->preview('host', 2);
$assert($emptyHost['instance_count'] === 0
&& $emptyHost['audience_digest'] !== '',
'An empty existing scope must remain previewable.');
$rejectedOnly = $planner->preview('instance', 103);
$assert($rejectedOnly['instance_count'] === 1
&& $rejectedOnly['eligible_count'] === 0
&& $rejectedOnly['rejected_count'] === 1
&& $rejectedOnly['recipients'] === [],
'An all-ineligible scope must remain previewable without recipients.');
$poolPreview = $planner->preview('public_ip_pool', 10);
$assert($poolPreview['instance_count'] === 2
&& $poolPreview['eligible_count'] === 1
&& array_column($poolPreview['instances'], 'id') === [101, 103],
'Pool scope must use only committed active live claims.');
$expectCloudError(
static fn () => $planner->preview('instance', 999),
404,
'A missing instance scope must return 404.'
);
$expectCloudError(
static fn () => $planner->preview('host', 999),
404,
'A missing host scope must return 404.'
);
$expectCloudError(
static fn () => $planner->preview('public_ip_pool', 999),
404,
'A missing pool scope must return 404.'
);
$expectCloudError(
static fn () => $planner->preview('unsupported', 1),
422,
'An unsupported compensation scope must return 422.'
);
$digest = $preview['audience_digest'];
$assert($planner->preview('host', 1)['audience_digest'] === $digest,
'Repeated previews must have a deterministic digest.');
$assert($digest
=== 'a98a3183f6e41723dc6a6b2d82a7af20291997dead28423b52782b354078d5bd',
'Planner DTO golden digest drifted; actual=' . $digest);
Capsule::table('cloud_instances')->where('id', 101)->update([
'network_status' => 'active',
'current_period_id' => 999999,
'lifetime_download_bytes' => 123456,
'lifetime_upload_bytes' => 654321,
'updated_at' => $now + 100,
]);
$assert($planner->preview('host', 1)['audience_digest'] === $digest,
'Runtime, counter and updated-at projections must not affect the digest.');
Capsule::table('cloud_instances')->where('id', 101)
->update(['service_status' => 'expired_grace']);
$assert($planner->preview('host', 1)['audience_digest'] !== $digest,
'Service-status drift must invalidate the reviewed digest.');
Capsule::table('cloud_instances')->where('id', 101)
->update(['service_status' => 'active']);
Capsule::table('cloud_instances')->where('id', 101)
->update(['expires_at' => $now + 3700]);
$assert($planner->preview('host', 1)['audience_digest'] !== $digest,
'Expiry drift must invalidate the reviewed digest.');
Capsule::table('cloud_instances')->where('id', 101)
->update(['expires_at' => $now + 3600]);
Capsule::table('cloud_instances')->where('id', 101)
->update(['renewal_price' => '12.00']);
$assert($planner->preview('host', 1)['audience_digest'] !== $digest,
'Commercial snapshot drift must invalidate the reviewed digest.');
Capsule::table('cloud_instances')->where('id', 101)
->update(['renewal_price' => '10.00']);
Capsule::table('cloud_service_periods')->where('id', 1003)
->update(['ends_at' => $now + 7300]);
$assert($planner->preview('host', 1)['audience_digest'] !== $digest,
'Tail-period drift must invalidate the reviewed digest.');
Capsule::table('cloud_service_periods')->where('id', 1003)
->update(['ends_at' => $now + 7200]);
Capsule::table('user')->where('id', 1)
->update(['email' => 'changed@example.com']);
$assert($planner->preview('host', 1)['audience_digest'] !== $digest,
'Recipient-email drift must invalidate the reviewed digest.');
Capsule::table('user')->where('id', 1)
->update(['email' => ' OWNER@Example.COM ']);
Capsule::table('cloud_instances')->where('id', 101)
->update(['name' => 'renamed-instance']);
$assert($planner->preview('host', 1)['audience_digest'] !== $digest,
'Instance identity drift must invalidate the reviewed digest.');
Capsule::table('cloud_instances')->where('id', 101)
->update(['name' => 'vm-101']);
$poolDigest = $poolPreview['audience_digest'];
Capsule::table('cloud_resource_reservation_ips')->where('id', 301)
->update(['active_claim' => null, 'state' => 'released']);
$assert($planner->preview('public_ip_pool', 10)['audience_digest']
!== $poolDigest,
'Pool membership drift must invalidate the reviewed digest.');
$newInstance = $instance(113, 1, 'active', $now + 12000);
Capsule::table('cloud_instances')->insert($newInstance);
Capsule::table('cloud_service_periods')->insert(
$period(1013, 113, 1, $now - 100, $now + 12000, 'active')
);
$assert($planner->preview('host', 1)['audience_digest'] !== $digest,
'Host membership drift must invalidate the reviewed digest.');
echo "Service compensation planner tests passed.\n";