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

354 lines
12 KiB
PHP

<?php
namespace App\Services\Cloud;
use Illuminate\Database\Capsule\Manager as DB;
/** Build one deterministic, read-only service-compensation audience plan. */
final class CloudServiceCompensationPlanner
{
private const SCOPE_INSTANCE = 'instance';
private const SCOPE_HOST = 'host';
private const SCOPE_PUBLIC_IP_POOL = 'public_ip_pool';
private readonly \Closure $clock;
public function __construct(
private readonly CloudAffectedInstanceResolver $affectedInstances =
new CloudAffectedInstanceResolver(),
?callable $clock = null
) {
$this->clock = $clock === null
? static fn (): int => time()
: \Closure::fromCallable($clock);
}
public function preview(string $scopeType, int $scopeId): array
{
$scopeType = trim($scopeType);
if (!in_array($scopeType, [
self::SCOPE_INSTANCE,
self::SCOPE_HOST,
self::SCOPE_PUBLIC_IP_POOL,
], true) || $scopeId < 1) {
throw new CloudError('实例补偿范围无效', 422);
}
$scope = $this->scope($scopeType, $scopeId);
$candidates = $this->affectedInstances->resolve(
$scopeType,
$scopeId
);
$candidateIds = array_values(array_unique(array_map(
static fn (object $candidate): int => (int) $candidate->id,
$candidates
)));
sort($candidateIds, SORT_NUMERIC);
$rows = $this->instances($candidateIds);
$tails = $this->tailPeriods($candidateIds);
$now = ($this->clock)();
$instances = [];
$eligible = 0;
$rejected = 0;
$attention = 0;
$recipientInstanceIds = [];
foreach ($candidateIds as $instanceId) {
$instance = $rows[$instanceId] ?? null;
if ($instance === null) {
// A concurrent delete after scope resolution is represented as
// attention instead of silently changing the reviewed count.
$instances[] = [
'id' => $instanceId,
'user_id' => 0,
'host_id' => 0,
'name' => '',
'status' => 'missing',
'service_status' => '',
'expires_at' => null,
'commercial' => $this->emptyCommercialSnapshot(),
'tail_period' => null,
'eligibility' => [
'state' => 'attention',
'code' => 'instance_snapshot_missing',
],
];
$attention++;
continue;
}
$tail = $tails[$instanceId] ?? null;
$eligibility = $this->eligibility($instance, $tail, $now);
$state = $eligibility['state'];
if ($state === 'eligible') {
$eligible++;
$recipientInstanceIds[(int) $instance->user_id][] =
$instanceId;
} elseif ($state === 'rejected') {
$rejected++;
} else {
$attention++;
}
$instances[] = [
'id' => $instanceId,
'user_id' => (int) $instance->user_id,
'host_id' => (int) $instance->host_id,
'name' => (string) $instance->name,
'status' => (string) $instance->status,
'service_status' => (string) $instance->service_status,
'expires_at' => $instance->expires_at === null
? null : (int) $instance->expires_at,
'commercial' => [
'plan_id' => $instance->plan_id === null
? null : (int) $instance->plan_id,
'offer_id' => $instance->offer_id === null
? null : (int) $instance->offer_id,
'renewal_price' => $instance->renewal_price === null
? null : (string) $instance->renewal_price,
'renewal_days' => (int) $instance->renewal_days,
'renewal_traffic_bytes' =>
(int) $instance->renewal_traffic_bytes,
],
'tail_period' => $this->periodSnapshot($tail),
'eligibility' => $eligibility,
];
}
usort($instances, static fn (array $left, array $right): int =>
$left['id'] <=> $right['id']);
$recipients = $this->recipients($recipientInstanceIds);
$recipientCount = count(array_filter(
$recipients,
static fn (array $recipient): bool => $recipient['deliverable']
));
$canonical = [
'scope' => $scope,
'instances' => $instances,
'recipients' => $recipients,
];
return $canonical + [
'instance_count' => count($instances),
'eligible_count' => $eligible,
'rejected_count' => $rejected,
'attention_count' => $attention,
'recipient_count' => $recipientCount,
'skipped_count' => count($recipients) - $recipientCount,
'audience_digest' => hash('sha256', self::json($canonical)),
];
}
private function scope(string $scopeType, int $scopeId): array
{
if ($scopeType === self::SCOPE_INSTANCE) {
$instance = DB::table('cloud_instances')
->where('id', $scopeId)->first();
if ($instance === null) {
throw new CloudError('虚拟机不存在', 404);
}
return [
'type' => $scopeType,
'id' => $scopeId,
// The per-instance rows already freeze the tenant-owned name
// and owner. Keep the long-lived batch scope free of tenant
// PII so account deletion can retain aggregate audit safely.
'label' => '单实例 #' . $scopeId,
'instance_id' => $scopeId,
'host_id' => (int) $instance->host_id,
];
}
if ($scopeType === self::SCOPE_HOST) {
$host = DB::table('cloud_hosts')->where('id', $scopeId)->first();
if ($host === null) {
throw new CloudError('计算节点不存在', 404);
}
return [
'type' => $scopeType,
'id' => $scopeId,
'label' => (string) $host->name,
'host_id' => $scopeId,
'region' => (string) ($host->region ?? ''),
];
}
$pool = DB::table('cloud_public_ip_pools')
->where('id', $scopeId)->first();
if ($pool === null) {
throw new CloudError('公网地址池不存在', 404);
}
return [
'type' => $scopeType,
'id' => $scopeId,
'label' => (string) $pool->name,
'pool_key' => (string) $pool->pool_key,
'host_id' => (int) $pool->host_id,
'address_family' => (int) $pool->address_family,
'cidr' => (string) $pool->cidr,
];
}
/** @return array<int, object> */
private function instances(array $instanceIds): array
{
if ($instanceIds === []) {
return [];
}
return DB::table('cloud_instances')->whereIn('id', $instanceIds)
->get([
'id', 'user_id', 'host_id', 'name', 'status',
'service_status', 'expires_at', 'plan_id', 'offer_id',
'renewal_price', 'renewal_days', 'renewal_traffic_bytes',
])->keyBy('id')->all();
}
/** @return array<int, object> */
private function tailPeriods(array $instanceIds): array
{
if ($instanceIds === []) {
return [];
}
$tails = [];
$periods = DB::table('cloud_service_periods')
->whereIn('instance_id', $instanceIds)
->orderBy('instance_id')->orderByDesc('ends_at')
->orderByDesc('id')->get([
'id', 'instance_id', 'plan_id', 'traffic_pool_group_id',
'traffic_quota_mode', 'starts_at', 'ends_at',
'traffic_quota_bytes', 'status',
]);
foreach ($periods as $period) {
$instanceId = (int) $period->instance_id;
if (!isset($tails[$instanceId])) {
$tails[$instanceId] = $period;
}
}
return $tails;
}
private function eligibility(
object $instance,
?object $tail,
int $now
): array {
if ((string) $instance->status === 'deleted') {
return ['state' => 'rejected', 'code' => 'instance_deleted'];
}
if ((string) $instance->service_status !== 'active') {
return [
'state' => 'rejected',
'code' => 'service_not_active',
];
}
if ($instance->expires_at === null
|| (int) $instance->expires_at <= $now) {
return ['state' => 'rejected', 'code' => 'service_expired'];
}
if ($tail === null) {
return [
'state' => 'attention',
'code' => 'service_period_missing',
];
}
if (!in_array((string) $tail->status, [
'active', 'exhausted', 'scheduled',
], true)) {
return [
'state' => 'attention',
'code' => 'service_period_state_invalid',
];
}
if ((int) $tail->starts_at >= (int) $tail->ends_at) {
return [
'state' => 'attention',
'code' => 'service_period_window_invalid',
];
}
if ((int) $tail->ends_at !== (int) $instance->expires_at) {
return [
'state' => 'attention',
'code' => 'service_period_expiry_mismatch',
];
}
return ['state' => 'eligible', 'code' => ''];
}
private function periodSnapshot(?object $period): ?array
{
if ($period === null) {
return null;
}
return [
'id' => (int) $period->id,
'plan_id' => $period->plan_id === null
? null : (int) $period->plan_id,
'traffic_pool_group_id' => $period->traffic_pool_group_id === null
? null : (int) $period->traffic_pool_group_id,
'traffic_quota_mode' => (string) $period->traffic_quota_mode,
'starts_at' => (int) $period->starts_at,
'ends_at' => (int) $period->ends_at,
'traffic_quota_bytes' => (int) $period->traffic_quota_bytes,
'status' => (string) $period->status,
];
}
/** @param array<int, list<int>> $instanceIdsByUser */
private function recipients(array $instanceIdsByUser): array
{
if ($instanceIdsByUser === []) {
return [];
}
ksort($instanceIdsByUser, SORT_NUMERIC);
$users = DB::table('user')->whereIn(
'id',
array_keys($instanceIdsByUser)
)->get(['id', 'email'])->keyBy('id')->all();
$recipients = [];
foreach ($instanceIdsByUser as $userId => $instanceIds) {
sort($instanceIds, SORT_NUMERIC);
$user = $users[$userId] ?? null;
$email = strtolower(trim((string) ($user->email ?? '')));
[$deliverable, $reason] = $this->emailDisposition($user, $email);
$recipients[] = [
'user_id' => (int) $userId,
'email' => $email,
'deliverable' => $deliverable,
'skip_reason' => $reason,
'instance_ids' => $instanceIds,
];
}
return $recipients;
}
private function emailDisposition(?object $user, string $email): array
{
if ($user === null) {
return [false, 'user_missing'];
}
if ($email === '' || strlen($email) > 254
|| preg_match('/^[\x21-\x7e]+$/D', $email) !== 1
|| filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
return [false, 'email_invalid'];
}
return [true, ''];
}
private function emptyCommercialSnapshot(): array
{
return [
'plan_id' => null,
'offer_id' => null,
'renewal_price' => null,
'renewal_days' => 0,
'renewal_traffic_bytes' => 0,
];
}
private static function json(array $value): string
{
return json_encode($value, JSON_THROW_ON_ERROR
| JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
}