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.
472 lines
17 KiB
PHP
472 lines
17 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Cloud;
|
|
|
|
use App\Models\CloudServiceCompensation;
|
|
use App\Models\CloudServiceCompensationItem;
|
|
use App\Models\CloudServiceCompensationRecipient;
|
|
use App\Models\User;
|
|
use App\Services\Mail;
|
|
use Illuminate\Database\Capsule\Manager as DB;
|
|
|
|
/** Freezes terminal compensation mail and delivers it without blind replay. */
|
|
final class CloudServiceCompensationNotificationService
|
|
{
|
|
public const LEASE_SECONDS = 300;
|
|
private const EXPIRED_LEASE_LIMIT = 10;
|
|
|
|
private readonly \Closure $clock;
|
|
private readonly \Closure $sender;
|
|
private readonly \Closure $blacklist;
|
|
|
|
public function __construct(
|
|
?callable $sender = null,
|
|
?callable $blacklist = null,
|
|
?callable $clock = null
|
|
) {
|
|
$this->clock = \Closure::fromCallable(
|
|
$clock ?? static fn (): int => time()
|
|
);
|
|
$this->sender = \Closure::fromCallable(
|
|
$sender ?? static fn (
|
|
string $to,
|
|
string $subject,
|
|
array $variables
|
|
): bool => Mail::send(
|
|
$to,
|
|
$subject,
|
|
'cloud/service-compensation.tpl',
|
|
$variables,
|
|
[],
|
|
'service_compensation'
|
|
)
|
|
);
|
|
$this->blacklist = \Closure::fromCallable(
|
|
$blacklist ?? static fn (string $email): bool =>
|
|
Mail::isRecipientBlacklisted($email)
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Freeze one immutable recipient row per applied owner.
|
|
*
|
|
* The caller already holds the batch and every item row in the same
|
|
* transaction. No recipient exists while business work is still open.
|
|
*/
|
|
public function freezeLocked(
|
|
CloudServiceCompensation $batch,
|
|
int $now
|
|
): void {
|
|
if (!$batch->exists || (int) $batch->id < 1
|
|
|| !in_array((string) $batch->state,
|
|
['completed', 'partial', 'attention'], true)
|
|
|| $batch->terminal_at === null) {
|
|
throw new CloudError('补偿通知只能在业务批次终态后冻结', 409);
|
|
}
|
|
if (!(bool) $batch->notify_users) {
|
|
$batch->recipient_count = 0;
|
|
$batch->updated_at = $now;
|
|
$batch->save();
|
|
return;
|
|
}
|
|
$existing = CloudServiceCompensationRecipient::where(
|
|
'batch_id', (int) $batch->id
|
|
)->orderBy('id')->lockForUpdate()->get();
|
|
|
|
$items = CloudServiceCompensationItem::where(
|
|
'batch_id', (int) $batch->id
|
|
)->where('state', 'applied')->orderBy('user_id')->orderBy('id')->get();
|
|
$byUser = [];
|
|
foreach ($items as $item) {
|
|
$byUser[(int) $item->user_id][] = $item;
|
|
}
|
|
$existingByUser = $existing->keyBy('user_id');
|
|
foreach ($existingByUser->keys() as $existingUserId) {
|
|
if (!array_key_exists((int) $existingUserId, $byUser)) {
|
|
throw new CloudError(
|
|
'补偿通知收件人与已应用实例不一致',
|
|
409
|
|
);
|
|
}
|
|
}
|
|
foreach ($byUser as $userId => $userItems) {
|
|
$payload = $this->payload($batch, $userItems);
|
|
$payloadJson = self::json($payload);
|
|
$payloadHash = hash('sha256', $payloadJson);
|
|
$recipient = $existingByUser->get($userId);
|
|
if ($recipient !== null) {
|
|
if ((int) $recipient->instance_count !== count($userItems)
|
|
|| !hash_equals(
|
|
(string) $recipient->payload_sha256,
|
|
$payloadHash
|
|
)
|
|
|| !hash_equals(
|
|
(string) $recipient->payload_json,
|
|
$payloadJson
|
|
)) {
|
|
throw new CloudError('补偿通知冻结内容发生冲突', 409);
|
|
}
|
|
continue;
|
|
}
|
|
$user = User::where('id', $userId)->first(['email']);
|
|
$email = strtolower(trim((string) ($user->email ?? '')));
|
|
if ($user === null || !self::validEmail($email)) {
|
|
continue;
|
|
}
|
|
$recipient = new CloudServiceCompensationRecipient();
|
|
$recipient->batch_id = (int) $batch->id;
|
|
$recipient->user_id = $userId;
|
|
$recipient->email_snapshot = $email;
|
|
$recipient->instance_count = count($userItems);
|
|
$recipient->payload_json = $payloadJson;
|
|
$recipient->payload_sha256 = $payloadHash;
|
|
$recipient->status = 'pending';
|
|
$recipient->attempts = 0;
|
|
$recipient->available_at = max(1, $now);
|
|
$recipient->lease_token = null;
|
|
$recipient->lease_until = 0;
|
|
$recipient->sent_at = null;
|
|
$recipient->last_error_code = '';
|
|
$recipient->last_error = '';
|
|
$recipient->created_at = $recipient->updated_at = $now;
|
|
$recipient->save();
|
|
}
|
|
$batch->recipient_count = CloudServiceCompensationRecipient::where(
|
|
'batch_id', (int) $batch->id
|
|
)->count();
|
|
$batch->updated_at = $now;
|
|
$batch->save();
|
|
}
|
|
|
|
public function tick(): bool
|
|
{
|
|
$worked = $this->convergeExpiredLeases();
|
|
$claim = $this->claim();
|
|
if ($claim === null) {
|
|
return $worked;
|
|
}
|
|
if (isset($claim['cancelled'])) {
|
|
return true;
|
|
}
|
|
$recipient = $claim['recipient'];
|
|
$token = (string) $claim['token'];
|
|
$recipientId = (int) $recipient->id;
|
|
try {
|
|
$user = User::where('id', (int) $recipient->user_id)
|
|
->first(['email']);
|
|
if ($user === null) {
|
|
$this->finalize(
|
|
$recipientId,
|
|
$token,
|
|
'skipped',
|
|
'user_deleted',
|
|
''
|
|
);
|
|
return true;
|
|
}
|
|
$currentEmail = strtolower(trim((string) $user->email));
|
|
if (!hash_equals(
|
|
(string) $recipient->email_snapshot,
|
|
$currentEmail
|
|
)) {
|
|
$this->finalize(
|
|
$recipientId,
|
|
$token,
|
|
'skipped',
|
|
'recipient_email_changed',
|
|
''
|
|
);
|
|
return true;
|
|
}
|
|
if (($this->blacklist)($currentEmail)) {
|
|
$this->finalize(
|
|
$recipientId,
|
|
$token,
|
|
'skipped',
|
|
'recipient_blacklisted',
|
|
''
|
|
);
|
|
return true;
|
|
}
|
|
$mail = $this->mail($recipient);
|
|
} catch (\Throwable $error) {
|
|
$this->finalize(
|
|
$recipientId,
|
|
$token,
|
|
'failed',
|
|
'delivery_preflight_failed',
|
|
get_class($error)
|
|
);
|
|
return true;
|
|
}
|
|
|
|
try {
|
|
$accepted = ($this->sender)(
|
|
(string) $recipient->email_snapshot,
|
|
(string) $mail['subject'],
|
|
$mail['variables']
|
|
) === true;
|
|
} catch (\Throwable $error) {
|
|
$this->finalize(
|
|
$recipientId,
|
|
$token,
|
|
'unknown',
|
|
'delivery_effect_unknown',
|
|
get_class($error)
|
|
);
|
|
return true;
|
|
}
|
|
$this->finalize(
|
|
$recipientId,
|
|
$token,
|
|
$accepted ? 'sent' : 'unknown',
|
|
$accepted ? '' : 'delivery_effect_unknown',
|
|
''
|
|
);
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* @return array{recipient:CloudServiceCompensationRecipient,token:string}
|
|
* |array{cancelled:true}|null
|
|
*/
|
|
private function claim(): ?array
|
|
{
|
|
$hint = CloudServiceCompensationRecipient::where('status', 'pending')
|
|
->where('available_at', '<=', $this->now())
|
|
->orderBy('available_at')->orderBy('id')->first(['id', 'batch_id']);
|
|
if ($hint === null) {
|
|
return null;
|
|
}
|
|
return DB::connection('default')->transaction(
|
|
function () use ($hint): ?array {
|
|
$now = $this->now();
|
|
$batch = CloudServiceCompensation::where(
|
|
'id', (int) $hint->batch_id
|
|
)->lockForUpdate()->first();
|
|
$recipient = CloudServiceCompensationRecipient::where(
|
|
'id', (int) $hint->id
|
|
)->lockForUpdate()->first();
|
|
if ($recipient === null
|
|
|| (string) $recipient->status !== 'pending'
|
|
|| (int) $recipient->available_at > $now) {
|
|
return null;
|
|
}
|
|
if ($batch === null || !(bool) $batch->notify_users
|
|
|| !in_array((string) $batch->state,
|
|
['completed', 'partial', 'attention'], true)
|
|
|| $batch->terminal_at === null) {
|
|
$recipient->status = 'cancelled';
|
|
$recipient->last_error_code = 'batch_not_deliverable';
|
|
$recipient->last_error = '';
|
|
$recipient->updated_at = $now;
|
|
$recipient->save();
|
|
return ['cancelled' => true];
|
|
}
|
|
$token = bin2hex(random_bytes(16));
|
|
$recipient->status = 'sending';
|
|
$recipient->attempts = (int) $recipient->attempts + 1;
|
|
$recipient->lease_token = $token;
|
|
$recipient->lease_until = $now + self::LEASE_SECONDS;
|
|
$recipient->last_error_code = '';
|
|
$recipient->last_error = '';
|
|
$recipient->updated_at = $now;
|
|
$recipient->save();
|
|
return ['recipient' => $recipient, 'token' => $token];
|
|
},
|
|
3
|
|
);
|
|
}
|
|
|
|
private function convergeExpiredLeases(): bool
|
|
{
|
|
$now = $this->now();
|
|
$ids = CloudServiceCompensationRecipient::where('status', 'sending')
|
|
->where('lease_until', '>', 0)
|
|
->where('lease_until', '<=', $now)
|
|
->orderBy('lease_until')->orderBy('id')
|
|
->limit(self::EXPIRED_LEASE_LIMIT)->pluck('id')->map(
|
|
static fn ($id): int => (int) $id
|
|
)->all();
|
|
$changed = false;
|
|
foreach ($ids as $id) {
|
|
$updated = CloudServiceCompensationRecipient::where('id', $id)
|
|
->where('status', 'sending')
|
|
->where('lease_until', '<=', $now)
|
|
->update([
|
|
'status' => 'unknown',
|
|
'lease_token' => null,
|
|
'lease_until' => 0,
|
|
'last_error_code' => 'delivery_lease_expired',
|
|
'last_error' => '',
|
|
'updated_at' => $now,
|
|
]);
|
|
$changed = $changed || $updated === 1;
|
|
}
|
|
return $changed;
|
|
}
|
|
|
|
/** @return array{subject:string,variables:array<string,mixed>} */
|
|
private function mail(CloudServiceCompensationRecipient $recipient): array
|
|
{
|
|
$payloadJson = (string) $recipient->payload_json;
|
|
if (!hash_equals(
|
|
(string) $recipient->payload_sha256,
|
|
hash('sha256', $payloadJson)
|
|
)) {
|
|
throw new \RuntimeException('Compensation payload digest mismatch.');
|
|
}
|
|
$payload = json_decode(
|
|
$payloadJson,
|
|
true,
|
|
64,
|
|
JSON_THROW_ON_ERROR
|
|
);
|
|
if (!is_array($payload)
|
|
|| !is_array($payload['instances'] ?? null)
|
|
|| count($payload['instances']) !== (int) $recipient->instance_count
|
|
|| !is_string($payload['reason_text'] ?? null)
|
|
|| !is_int($payload['compensation_seconds'] ?? null)) {
|
|
throw new \RuntimeException('Compensation payload is invalid.');
|
|
}
|
|
return [
|
|
'subject' => 'Service Time Compensation Applied',
|
|
'variables' => [
|
|
'reason_text' => $payload['reason_text'],
|
|
'scope_label' => self::scopeLabel(
|
|
(string) ($payload['scope_label'] ?? '')
|
|
),
|
|
'compensation_duration' => self::duration(
|
|
$payload['compensation_seconds']
|
|
),
|
|
'incident_window_utc' => self::incidentWindow($payload),
|
|
'instances' => $payload['instances'],
|
|
],
|
|
];
|
|
}
|
|
|
|
/** @param list<CloudServiceCompensationItem> $items */
|
|
private function payload(
|
|
CloudServiceCompensation $batch,
|
|
array $items
|
|
): array {
|
|
$scope = json_decode(
|
|
(string) $batch->scope_snapshot_json,
|
|
true,
|
|
32,
|
|
JSON_THROW_ON_ERROR
|
|
);
|
|
$instances = [];
|
|
foreach ($items as $item) {
|
|
if ((string) $item->state !== 'applied'
|
|
|| $item->before_expires_at === null
|
|
|| $item->after_expires_at === null
|
|
|| (int) $item->after_expires_at
|
|
!== (int) $item->before_expires_at
|
|
+ (int) $item->requested_seconds) {
|
|
throw new CloudError('补偿通知实例证据不完整', 409);
|
|
}
|
|
$instances[] = [
|
|
'instance_id' => (int) $item->instance_id,
|
|
'instance_name' => (string) $item->instance_name,
|
|
'seconds_added' => (int) $item->requested_seconds,
|
|
'previous_expires_utc' => gmdate(
|
|
'Y-m-d H:i:s \U\T\C',
|
|
(int) $item->before_expires_at
|
|
),
|
|
'new_expires_utc' => gmdate(
|
|
'Y-m-d H:i:s \U\T\C',
|
|
(int) $item->after_expires_at
|
|
),
|
|
];
|
|
}
|
|
return [
|
|
'compensation_key' => (string) $batch->compensation_key,
|
|
'incident_key' => (string) $batch->incident_key,
|
|
'scope_label' => (string) ($scope['label'] ?? ''),
|
|
'reason_text' => (string) $batch->reason_text,
|
|
'incident_starts_at' => $batch->incident_starts_at === null
|
|
? null : (int) $batch->incident_starts_at,
|
|
'incident_ends_at' => $batch->incident_ends_at === null
|
|
? null : (int) $batch->incident_ends_at,
|
|
'compensation_seconds' => (int) $batch->compensation_seconds,
|
|
'instances' => $instances,
|
|
];
|
|
}
|
|
|
|
private function finalize(
|
|
int $recipientId,
|
|
string $token,
|
|
string $status,
|
|
string $errorCode,
|
|
string $error
|
|
): void {
|
|
CloudServiceCompensationRecipient::where('id', $recipientId)
|
|
->where('status', 'sending')
|
|
->where('lease_token', $token)
|
|
->update([
|
|
'status' => $status,
|
|
'lease_token' => null,
|
|
'lease_until' => 0,
|
|
'sent_at' => $status === 'sent' ? $this->now() : null,
|
|
'last_error_code' => $errorCode,
|
|
'last_error' => mb_substr($error, 0, 500),
|
|
'updated_at' => $this->now(),
|
|
]);
|
|
}
|
|
|
|
private static function duration(int $seconds): string
|
|
{
|
|
if ($seconds % 86400 === 0) {
|
|
$value = (int) ($seconds / 86400);
|
|
return $value . ($value === 1 ? ' day' : ' days');
|
|
}
|
|
if ($seconds % 3600 === 0) {
|
|
$value = (int) ($seconds / 3600);
|
|
return $value . ($value === 1 ? ' hour' : ' hours');
|
|
}
|
|
if ($seconds % 60 === 0) {
|
|
$value = (int) ($seconds / 60);
|
|
return $value . ($value === 1 ? ' minute' : ' minutes');
|
|
}
|
|
return $seconds . ($seconds === 1 ? ' second' : ' seconds');
|
|
}
|
|
|
|
private static function scopeLabel(string $label): string
|
|
{
|
|
if (preg_match('/^单实例\s*#(\d+)$/u', $label, $matches) === 1) {
|
|
return 'Instance #' . $matches[1];
|
|
}
|
|
return $label;
|
|
}
|
|
|
|
private static function incidentWindow(array $payload): string
|
|
{
|
|
$start = $payload['incident_starts_at'] ?? null;
|
|
$end = $payload['incident_ends_at'] ?? null;
|
|
if (!is_int($start) || !is_int($end)) {
|
|
return 'Not recorded separately';
|
|
}
|
|
return gmdate('Y-m-d H:i:s \U\T\C', $start)
|
|
. ' — ' . gmdate('Y-m-d H:i:s \U\T\C', $end);
|
|
}
|
|
|
|
private static function validEmail(string $email): bool
|
|
{
|
|
return $email !== '' && strlen($email) <= 254
|
|
&& preg_match('/^[\x21-\x7e]+$/D', $email) === 1
|
|
&& filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
|
|
}
|
|
|
|
private static function json(array $value): string
|
|
{
|
|
return json_encode($value, JSON_THROW_ON_ERROR
|
|
| JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
|
|
}
|
|
|
|
private function now(): int
|
|
{
|
|
return max(1, (int) ($this->clock)());
|
|
}
|
|
}
|