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

558 lines
23 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudMaintenanceNotice;
use App\Models\CloudMaintenanceNoticeInstance;
use App\Models\CloudMaintenanceNoticeRecipient;
use Illuminate\Database\Capsule\Manager as DB;
use Illuminate\Database\QueryException;
/** Owns maintenance-notice validation, audience freezing and state changes. */
final class CloudMaintenanceNoticeService
{
private const IMPACTS = [
'network_interruption', 'instance_restart',
'service_interruption', 'no_interruption',
];
private readonly \Closure $clock;
public function __construct(
private readonly CloudMaintenanceNoticeAudience $audience =
new CloudMaintenanceNoticeAudience(),
?callable $clock = null
) {
$this->clock = $clock === null
? static fn (): int => time()
: \Closure::fromCallable($clock);
}
public function preview(string $scopeType, int $scopeId): array
{
return $this->audience->preview($scopeType, $scopeId);
}
/** Return the immutable identifiers administrators may preview. */
public function catalog(): array
{
$hosts = DB::table('cloud_hosts')->orderBy('name')->orderBy('id')
->get(['id', 'name', 'region', 'enabled'])
->map(static fn ($host): array => [
'id' => (int) $host->id,
'name' => (string) $host->name,
'region' => (string) $host->region,
'enabled' => (bool) $host->enabled,
])->all();
$pools = DB::table('cloud_public_ip_pools as pool')
->join('cloud_hosts as host', 'host.id', '=', 'pool.host_id')
->orderBy('host.name')->orderBy('pool.address_family')
->orderBy('pool.name')->orderBy('pool.id')
->get([
'pool.id', 'pool.pool_key', 'pool.host_id',
'pool.address_family', 'pool.name', 'pool.cidr', 'pool.state',
'host.name as host_name',
])->map(static fn ($pool): array => [
'id' => (int) $pool->id,
'pool_key' => (string) $pool->pool_key,
'host_id' => (int) $pool->host_id,
'host_name' => (string) $pool->host_name,
'address_family' => (int) $pool->address_family,
'name' => (string) $pool->name,
'cidr' => (string) $pool->cidr,
'state' => (string) $pool->state,
])->all();
return ['hosts' => $hosts, 'pools' => $pools];
}
/** Resolve URL shortcuts only against the current server-owned catalog. */
public function prefill(array $query, array $catalog): array
{
$scopeType = trim((string) ($query['scope_type'] ?? ''));
if ($scopeType === 'host') {
$hostId = filter_var($query['host_id'] ?? $query['scope_id'] ?? null,
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
foreach ($catalog['hosts'] ?? [] as $host) {
if ($hostId !== false && (int) $host['id'] === (int) $hostId) {
return ['scope_type' => 'host', 'scope_id' => (int) $hostId];
}
}
}
if ($scopeType === 'public_ip_pool') {
$poolKey = strtolower(trim((string) ($query['pool_key'] ?? '')));
$hostId = filter_var($query['host_id'] ?? null,
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
foreach ($catalog['pools'] ?? [] as $pool) {
if (preg_match('/^[0-9a-f]{32}$/D', $poolKey) === 1
&& hash_equals((string) $pool['pool_key'], $poolKey)
&& $hostId !== false
&& (int) $pool['host_id'] === (int) $hostId) {
return [
'scope_type' => 'public_ip_pool',
'scope_id' => (int) $pool['id'],
];
}
}
}
return [];
}
public function schedule(int $actorId, string $idempotencyKey,
array $input): array
{
if ($actorId < 1) {
throw new CloudError('管理员身份无效', 403);
}
$idempotencyKey = trim($idempotencyKey);
if (preg_match('/^[A-Za-z0-9._:-]{16,128}$/D',
$idempotencyKey) !== 1) {
throw new CloudError('幂等键无效', 422);
}
$request = $this->validateRequest($input);
$fingerprint = hash('sha256', self::json($request));
$existing = $this->requestNotice($actorId, $idempotencyKey);
if ($existing !== null) {
return $this->idempotentResult($existing, $fingerprint);
}
try {
return DB::connection('default')->transaction(function () use (
$actorId,
$idempotencyKey,
$request,
$fingerprint
): array {
$existing = $this->requestNotice(
$actorId,
$idempotencyKey,
true
);
if ($existing !== null) {
return $this->idempotentResult($existing, $fingerprint);
}
$audience = $this->audience->preview(
$request['scope_type'],
$request['scope_id']
);
if (!hash_equals(
$request['audience_digest'],
$audience['audience_digest']
)) {
throw new CloudError(
'受影响实例或用户已变化,请重新预览后再发送',
409
);
}
if ($audience['instance_count'] < 1) {
throw new CloudError('当前范围没有受影响实例', 409);
}
if ($audience['recipient_count'] < 1) {
throw new CloudError('当前范围没有可投递的用户邮箱', 409);
}
$now = $this->now();
$notice = new CloudMaintenanceNotice();
$notice->notice_key = bin2hex(random_bytes(16));
$notice->requested_by_user_id = $actorId;
$notice->request_idempotency_key = $idempotencyKey;
$notice->request_fingerprint = $fingerprint;
$notice->scope_type = $request['scope_type'];
$notice->scope_id = $request['scope_id'];
$notice->scope_snapshot_json = self::json($audience['scope']);
$notice->subject = $request['subject'];
$notice->message_text = $request['message_text'];
$notice->impact = $request['impact'];
$notice->maintenance_starts_at =
$request['maintenance_starts_at'];
$notice->maintenance_ends_at =
$request['maintenance_ends_at'];
$notice->scheduled_at = $request['scheduled_at'];
$notice->audience_digest = $audience['audience_digest'];
$notice->instance_count = $audience['instance_count'];
$notice->recipient_count = $audience['recipient_count'];
$notice->skipped_count = $audience['skipped_count'];
$notice->status = 'scheduled';
$notice->last_error_code = '';
$notice->terminal_at = null;
$notice->created_at = $now;
$notice->updated_at = $now;
if (!$notice->save()) {
throw new CloudError('维护通知保存失败', 500);
}
$poolId = $request['scope_type'] === 'public_ip_pool'
? $request['scope_id'] : null;
foreach ($audience['instances'] as $instance) {
CloudMaintenanceNoticeInstance::insert([
'notice_id' => (int) $notice->id,
'instance_id' => $instance['id'],
'user_id' => $instance['user_id'],
'host_id' => $instance['host_id'],
'public_ip_pool_id' => $poolId,
'instance_name' => $instance['name'],
'ipv4' => $instance['ipv4'],
'ipv6' => $instance['ipv6'],
'evidence_json' => self::json($instance['evidence']),
'created_at' => $now,
]);
}
foreach ($audience['recipients'] as $recipient) {
$pending = $recipient['deliverable'] === true;
CloudMaintenanceNoticeRecipient::insert([
'notice_id' => (int) $notice->id,
'user_id' => $recipient['user_id'],
'email_snapshot' => $recipient['email'],
'status' => $pending ? 'pending' : 'skipped',
'attempts' => 0,
'available_at' => $request['scheduled_at'],
'lease_token' => null,
'lease_until' => 0,
'sent_at' => null,
'last_error_code' => $pending ? ''
: $recipient['skip_reason'],
'last_error' => '',
'created_at' => $now,
'updated_at' => $now,
]);
}
return $this->detailModel($notice);
}, 3);
} catch (QueryException $error) {
$existing = $this->requestNotice($actorId, $idempotencyKey);
if ($existing !== null) {
return $this->idempotentResult($existing, $fingerprint);
}
throw $error;
}
}
public function cancel(string $noticeKey): array
{
$noticeKey = $this->noticeKey($noticeKey);
return DB::connection('default')->transaction(function () use (
$noticeKey
): array {
$notice = CloudMaintenanceNotice::where('notice_key', $noticeKey)
->lockForUpdate()->first();
if ($notice === null) {
throw new CloudError('维护通知不存在', 404);
}
if (in_array((string) $notice->status,
['completed', 'cancelled'], true)) {
return $this->detailModel($notice);
}
$now = $this->now();
CloudMaintenanceNoticeRecipient::where('notice_id', $notice->id)
->where('status', 'pending')->update([
'status' => 'cancelled',
'last_error_code' => 'admin_cancelled',
'last_error' => '',
'updated_at' => $now,
]);
$this->recalculateLocked($notice, $now);
return $this->detailModel($notice->fresh());
}, 3);
}
public function detail(string $noticeKey): array
{
$notice = CloudMaintenanceNotice::where(
'notice_key',
$this->noticeKey($noticeKey)
)->first();
if ($notice === null) {
throw new CloudError('维护通知不存在', 404);
}
return $this->detailModel($notice);
}
public function page(array $query = []): array
{
$page = filter_var($query['page'] ?? 1, FILTER_VALIDATE_INT,
['options' => ['min_range' => 1]]) ?: 1;
$perPage = filter_var($query['per_page'] ?? 20, FILTER_VALIDATE_INT,
['options' => ['min_range' => 1, 'max_range' => 100]]) ?: 20;
$builder = CloudMaintenanceNotice::query();
$status = trim((string) ($query['status'] ?? ''));
if ($status !== '') {
if (!in_array($status, [
'scheduled', 'sending', 'completed', 'attention', 'cancelled',
], true)) {
throw new CloudError('维护通知状态筛选无效', 422);
}
$builder->where('status', $status);
}
$scopeType = trim((string) ($query['scope_type'] ?? ''));
if ($scopeType !== '') {
if (!in_array($scopeType, ['host', 'public_ip_pool'], true)) {
throw new CloudError('维护通知范围筛选无效', 422);
}
$builder->where('scope_type', $scopeType);
}
$total = (clone $builder)->count();
$rows = $builder->orderByDesc('id')
->forPage((int) $page, (int) $perPage)->get();
$ids = $rows->pluck('id')->map(static fn ($id): int => (int) $id)
->all();
$delivery = [];
if ($ids !== []) {
$counts = CloudMaintenanceNoticeRecipient::whereIn(
'notice_id', $ids
)->selectRaw('notice_id, status, COUNT(*) AS aggregate')
->groupBy('notice_id')->groupBy('status')->get();
foreach ($counts as $count) {
$delivery[(int) $count->notice_id][(string) $count->status]
= (int) $count->aggregate;
}
}
$items = $rows->map(static function ($notice) use ($delivery): array {
return [
'notice_key' => (string) $notice->notice_key,
'scope' => self::decode((string) $notice->scope_snapshot_json),
'subject' => (string) $notice->subject,
'impact' => (string) $notice->impact,
'maintenance_starts_at' =>
(int) $notice->maintenance_starts_at,
'maintenance_ends_at' => (int) $notice->maintenance_ends_at,
'scheduled_at' => (int) $notice->scheduled_at,
'instance_count' => (int) $notice->instance_count,
'recipient_count' => (int) $notice->recipient_count,
'skipped_count' => (int) $notice->skipped_count,
'status' => (string) $notice->status,
'last_error_code' => (string) $notice->last_error_code,
'terminal_at' => $notice->terminal_at === null
? null : (int) $notice->terminal_at,
'created_at' => (int) $notice->created_at,
'delivery' => $delivery[(int) $notice->id] ?? [],
];
})->all();
return [
'page' => (int) $page,
'per_page' => (int) $perPage,
'total' => (int) $total,
'items' => $items,
];
}
public function recalculate(int $noticeId): void
{
if ($noticeId < 1) {
throw new \InvalidArgumentException('Notice id is invalid.');
}
DB::connection('default')->transaction(function () use ($noticeId): void {
$notice = CloudMaintenanceNotice::where('id', $noticeId)
->lockForUpdate()->first();
if ($notice !== null) {
$this->recalculateLocked($notice, $this->now());
}
}, 3);
}
private function validateRequest(array $input): array
{
foreach (['scope_type', 'subject', 'message_text', 'impact',
'audience_digest'] as $key) {
if (!array_key_exists($key, $input)
|| !is_string($input[$key])) {
throw new CloudError('维护通知内容无效', 422);
}
}
$scopeType = trim((string) ($input['scope_type'] ?? ''));
$scopeId = filter_var($input['scope_id'] ?? null,
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
$subject = trim((string) ($input['subject'] ?? ''));
$message = trim((string) ($input['message_text'] ?? ''));
$impact = trim((string) ($input['impact'] ?? ''));
$digest = strtolower(trim((string) (
$input['audience_digest'] ?? ''
)));
if (!in_array($scopeType, ['host', 'public_ip_pool'], true)
|| $scopeId === false
|| $subject === '' || mb_strlen($subject) > 180
|| preg_match('/[\x00-\x1F\x7F]/', $subject) === 1
|| $message === '' || mb_strlen($message) > 5000
|| preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/',
$message) === 1
|| !in_array($impact, self::IMPACTS, true)
|| preg_match('/^[a-f0-9]{64}$/D', $digest) !== 1) {
throw new CloudError('维护通知内容无效', 422);
}
$startsAt = $this->positiveInt($input, 'maintenance_starts_at');
$endsAt = $this->positiveInt($input, 'maintenance_ends_at');
$scheduledAt = $this->positiveInt($input, 'scheduled_at');
$now = $this->now();
if ($scheduledAt < $now || $endsAt <= $startsAt
|| $endsAt <= $now || $scheduledAt > $endsAt
|| $startsAt > $now + 366 * 86400
|| $endsAt - $startsAt > 31 * 86400) {
throw new CloudError('维护通知时间范围无效', 422);
}
return [
'scope_type' => $scopeType,
'scope_id' => (int) $scopeId,
'subject' => $subject,
'message_text' => $message,
'impact' => $impact,
'maintenance_starts_at' => $startsAt,
'maintenance_ends_at' => $endsAt,
'scheduled_at' => $scheduledAt,
'audience_digest' => $digest,
];
}
private function positiveInt(array $input, string $key): int
{
$value = filter_var($input[$key] ?? null, FILTER_VALIDATE_INT,
['options' => ['min_range' => 1]]);
if ($value === false) {
throw new CloudError('维护通知时间无效', 422);
}
return (int) $value;
}
private function requestNotice(int $actorId, string $key,
bool $lock = false): ?CloudMaintenanceNotice
{
$query = CloudMaintenanceNotice::where('requested_by_user_id', $actorId)
->where('request_idempotency_key', $key);
return ($lock ? $query->lockForUpdate() : $query)->first();
}
private function idempotentResult(CloudMaintenanceNotice $notice,
string $fingerprint): array
{
if (!hash_equals((string) $notice->request_fingerprint, $fingerprint)) {
throw new CloudError('幂等键已用于其他维护通知请求', 409);
}
return $this->detailModel($notice);
}
private function detailModel(CloudMaintenanceNotice $notice): array
{
$instances = CloudMaintenanceNoticeInstance::where(
'notice_id', $notice->id
)->orderBy('id')->get()->map(static function ($instance): array {
return [
'instance_id' => (int) $instance->instance_id,
'user_id' => (int) $instance->user_id,
'host_id' => (int) $instance->host_id,
'instance_name' => (string) $instance->instance_name,
'ipv4' => (string) $instance->ipv4,
'ipv6' => (string) $instance->ipv6,
'evidence' => self::decode((string) $instance->evidence_json),
];
})->all();
$recipients = CloudMaintenanceNoticeRecipient::where(
'notice_id', $notice->id
)->orderBy('id')->get()->map(static fn ($recipient): array => [
'user_id' => (int) $recipient->user_id,
'email' => (string) $recipient->email_snapshot,
'status' => (string) $recipient->status,
'attempts' => (int) $recipient->attempts,
'sent_at' => $recipient->sent_at === null
? null : (int) $recipient->sent_at,
'last_error_code' => (string) $recipient->last_error_code,
])->all();
return [
'notice_key' => (string) $notice->notice_key,
'scope' => self::decode((string) $notice->scope_snapshot_json),
'subject' => (string) $notice->subject,
'message_text' => (string) $notice->message_text,
'impact' => (string) $notice->impact,
'maintenance_starts_at' => (int) $notice->maintenance_starts_at,
'maintenance_ends_at' => (int) $notice->maintenance_ends_at,
'scheduled_at' => (int) $notice->scheduled_at,
'audience_digest' => (string) $notice->audience_digest,
'instance_count' => (int) $notice->instance_count,
'recipient_count' => (int) $notice->recipient_count,
'skipped_count' => (int) $notice->skipped_count,
'status' => (string) $notice->status,
'last_error_code' => (string) $notice->last_error_code,
'terminal_at' => $notice->terminal_at === null
? null : (int) $notice->terminal_at,
'created_at' => (int) $notice->created_at,
'instances' => $instances,
'recipients' => $recipients,
];
}
private function recalculateLocked(CloudMaintenanceNotice $notice,
int $now): void
{
$counts = CloudMaintenanceNoticeRecipient::where(
'notice_id', $notice->id
)->selectRaw('status, COUNT(*) AS aggregate')
->groupBy('status')->pluck('aggregate', 'status')->all();
$count = static fn (string $status): int =>
(int) ($counts[$status] ?? 0);
$pending = $count('pending');
$sending = $count('sending');
$sent = $count('sent');
$unknown = $count('unknown');
$failed = $count('failed');
$cancelled = $count('cancelled');
$total = array_sum(array_map('intval', $counts));
if ($total === 0) {
$status = 'cancelled';
$terminalAt = $now;
$errorCode = 'audience_deleted';
} elseif ($pending > 0 || $sending > 0) {
$status = ($sending > 0 || $sent > 0
|| $unknown > 0 || $failed > 0) ? 'sending' : 'scheduled';
$terminalAt = null;
$errorCode = '';
} elseif ($unknown > 0 || $failed > 0
|| ($cancelled > 0 && $sent > 0)) {
$status = 'attention';
$terminalAt = $now;
$errorCode = $unknown > 0 ? 'delivery_effect_unknown'
: ($failed > 0 ? 'delivery_failed' : 'partially_cancelled');
} elseif ($sent > 0) {
$status = 'completed';
$terminalAt = $now;
$errorCode = '';
} elseif ($cancelled > 0) {
$status = 'cancelled';
$terminalAt = $now;
$errorCode = 'admin_cancelled';
} else {
$status = 'completed';
$terminalAt = $now;
$errorCode = '';
}
$notice->status = $status;
$notice->terminal_at = $terminalAt;
$notice->last_error_code = $errorCode;
$notice->updated_at = $now;
if (!$notice->save()) {
throw new CloudError('维护通知状态保存失败', 500);
}
}
private function noticeKey(string $noticeKey): string
{
$noticeKey = strtolower(trim($noticeKey));
if (preg_match('/^[a-f0-9]{32}$/D', $noticeKey) !== 1) {
throw new CloudError('维护通知编号无效', 422);
}
return $noticeKey;
}
private function now(): int
{
return (int) ($this->clock)();
}
private static function json(array $value): string
{
return json_encode($value, JSON_THROW_ON_ERROR
| JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
private static function decode(string $value): array
{
$decoded = json_decode($value, true, 64, JSON_THROW_ON_ERROR);
return is_array($decoded) ? $decoded : [];
}
}