fix(api): 修复邮件队列超时并补齐调度进程

延长 SendEmailJob 超时并改为超时直接失败,补充重试退避、
失败日志与收件人脱敏,避免 send_email 队列批量超时重试。

新增 MAIL_TIMEOUT 与 QUEUE_RETRY_AFTER 配置,并抽出邮件运行时
配置与 HTML 内容服务,确保 Horizon 常驻进程使用最新邮件配置。

为 Docker、supervisor 与 compose 样例补齐 scheduler 进程,并在
节点管理端开启墙检测托管时立即触发一次检测,保证定时任务持续生效。
This commit is contained in:
yinjianm
2026-04-28 13:32:58 +08:00
parent 329d52f89f
commit a4e78b864a
36 changed files with 1359 additions and 107 deletions
+96
View File
@@ -0,0 +1,96 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\Mail;
use RuntimeException;
class MailHtmlContent
{
/**
* Build the inline HTML body used by notification emails.
*/
public static function buildModernNotifyHtml(array $templateValue, string $subject, string $appName): string
{
$title = self::escapeHtml($subject);
$brand = self::escapeHtml((string) ($templateValue['name'] ?? $appName));
$content = self::escapeHtml((string) ($templateValue['content'] ?? ''));
$content = nl2br($content, false);
$sendTime = self::escapeHtml(now()->format('Y-m-d H:i:s'));
$cta = '';
$url = isset($templateValue['url']) ? (string) $templateValue['url'] : '';
if (filter_var($url, FILTER_VALIDATE_URL)) {
$safeUrl = self::escapeHtml($url);
$cta = '<a href="' . $safeUrl . '" style="display:inline-block;padding:12px 20px;border-radius:10px;background:#111827;color:#ffffff;text-decoration:none;font-weight:600;">Open Link</a>';
}
return '<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>' . $title . '</title>
</head>
<body style="margin:0;padding:0;background:linear-gradient(135deg,#f8fafc 0%,#eef2ff 100%);font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica,Arial,sans-serif;">
<div style="max-width:680px;margin:0 auto;padding:32px 16px;">
<div style="background:#ffffff;border:1px solid #e5e7eb;border-radius:20px;overflow:hidden;box-shadow:0 16px 40px rgba(15,23,42,.08);">
<div style="padding:24px 24px 16px;background:radial-gradient(80% 120% at 0% 0%,#dbeafe 0%,#ffffff 100%);border-bottom:1px solid #e5e7eb;">
<div style="font-size:12px;color:#64748b;letter-spacing:.06em;text-transform:uppercase;">Message</div>
<h1 style="margin:8px 0 0;font-size:24px;line-height:1.3;color:#0f172a;">' . $title . '</h1>
</div>
<div style="padding:24px;">
<div style="font-size:15px;line-height:1.8;color:#334155;">' . $content . '</div>
<div style="margin-top:20px;">' . $cta . '</div>
</div>
<div style="padding:14px 24px;border-top:1px solid #e5e7eb;background:#f8fafc;font-size:12px;color:#64748b;">
<div>Sender: ' . $brand . '</div>
<div>Sent at: ' . $sendTime . '</div>
</div>
</div>
</div>
</body>
</html>';
}
/**
* Send a pre-rendered HTML email using the available Laravel mail API.
*/
public static function sendHtmlMail(string $email, string $subject, string $html): void
{
$mailer = Mail::getFacadeRoot();
if ($mailer && method_exists($mailer, 'html')) {
Mail::html($html, function ($message) use ($email, $subject) {
$message->to($email)->subject($subject);
});
return;
}
Mail::send([], [], function ($message) use ($email, $subject, $html) {
$message->to($email)->subject($subject);
if (method_exists($message, 'getSymfonyMessage')) {
$symfonyMessage = $message->getSymfonyMessage();
if ($symfonyMessage && method_exists($symfonyMessage, 'html')) {
$symfonyMessage->html($html);
return;
}
}
if (method_exists($message, 'setBody')) {
$message->setBody($html, 'text/html');
return;
}
throw new RuntimeException('Unsupported mail message driver for html body.');
});
}
/**
* Escape text before inserting it into an HTML email template.
*/
private static function escapeHtml(string $text): string
{
return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}
}
+110
View File
@@ -0,0 +1,110 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Mail;
class MailRuntimeConfig
{
private const DEFAULT_MAIL_TIMEOUT = 30;
private const MAX_MAIL_TIMEOUT = 120;
/**
* Apply the current runtime mail configuration before sending.
*/
public static function apply(string $appName): void
{
$timeout = self::normalizeTimeout(config('mail.timeout', self::DEFAULT_MAIL_TIMEOUT));
$smtpConfig = ['timeout' => $timeout];
if (admin_setting('email_host')) {
Config::set('mail.default', 'smtp');
Config::set('mail.driver', 'smtp');
$smtpConfig = [
'host' => admin_setting('email_host', config('mail.host')),
'port' => admin_setting('email_port', config('mail.port')),
'encryption' => admin_setting('email_encryption', config('mail.encryption')),
'username' => admin_setting('email_username', config('mail.username')),
'password' => admin_setting('email_password', config('mail.password')),
'timeout' => self::normalizeTimeout(admin_setting('email_timeout', $timeout)),
];
foreach ($smtpConfig as $key => $value) {
Config::set("mail.{$key}", $value);
}
Config::set('mail.from.address', admin_setting('email_from_address', config('mail.from.address')));
} else {
Config::set('mail.timeout', $timeout);
}
Config::set('mail.from.name', $appName);
self::setSmtpMailerConfig($smtpConfig);
self::forgetResolvedMailers();
}
/**
* Return a mail configuration snapshot safe for persistence.
*/
public static function configForLog(array $config): array
{
foreach ($config as $key => $value) {
if (is_array($value)) {
$config[$key] = self::configForLog($value);
continue;
}
if (self::isSensitiveMailConfigKey((string) $key) && $value !== null && $value !== '') {
$config[$key] = '******';
}
}
return $config;
}
/**
* Normalize a user-provided timeout into the supported range.
*/
private static function normalizeTimeout(mixed $timeout): int
{
$timeout = (int) $timeout;
if ($timeout <= 0) {
return self::DEFAULT_MAIL_TIMEOUT;
}
return min($timeout, self::MAX_MAIL_TIMEOUT);
}
/**
* Mirror legacy SMTP settings into Laravel's modern mailer config shape.
*/
private static function setSmtpMailerConfig(array $smtpConfig): void
{
Config::set('mail.mailers.smtp.transport', 'smtp');
foreach ($smtpConfig as $key => $value) {
Config::set("mail.mailers.smtp.{$key}", $value);
}
}
/**
* Clear resolved mailers so long-running workers use fresh settings.
*/
private static function forgetResolvedMailers(): void
{
$mailManager = Mail::getFacadeRoot();
if ($mailManager && method_exists($mailManager, 'forgetMailers')) {
$mailManager->forgetMailers();
}
}
/**
* Determine whether a mail config key contains sensitive material.
*/
private static function isSensitiveMailConfigKey(string $key): bool
{
return in_array(strtolower($key), ['password', 'secret', 'token', 'key'], true);
}
}
+4 -90
View File
@@ -8,7 +8,6 @@ use App\Models\MailTemplate;
use App\Models\User;
use App\Utils\CacheKey;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
@@ -236,15 +235,7 @@ class MailService
$appName = 'Notification Service';
}
if (admin_setting('email_host')) {
Config::set('mail.host', admin_setting('email_host', config('mail.host')));
Config::set('mail.port', admin_setting('email_port', config('mail.port')));
Config::set('mail.encryption', admin_setting('email_encryption', config('mail.encryption')));
Config::set('mail.username', admin_setting('email_username', config('mail.username')));
Config::set('mail.password', admin_setting('email_password', config('mail.password')));
Config::set('mail.from.address', admin_setting('email_from_address', config('mail.from.address')));
}
Config::set('mail.from.name', $appName);
MailRuntimeConfig::apply($appName);
$params['template_value'] = isset($params['template_value']) && is_array($params['template_value'])
? $params['template_value']
@@ -301,8 +292,8 @@ class MailService
$logTemplateName = $params['template_name'];
try {
if ($originTemplateName === 'notify') {
$html = self::buildModernNotifyHtml($params['template_value'], $subject, $appName);
self::sendHtmlMail($email, $subject, $html);
$html = MailHtmlContent::buildModernNotifyHtml($params['template_value'], $subject, $appName);
MailHtmlContent::sendHtmlMail($email, $subject, $html);
$logTemplateName = 'mail.modern.notify';
} else {
Mail::send(
@@ -324,7 +315,7 @@ class MailService
'subject' => $subject,
'template_name' => $logTemplateName,
'error' => $error,
'config' => config('mail'),
'config' => MailRuntimeConfig::configForLog((array) config('mail', [])),
];
MailLog::create($log);
@@ -339,81 +330,4 @@ class MailService
return trim((string) $cleaned);
}
private static function escapeHtml(string $text): string
{
return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}
private static function buildModernNotifyHtml(array $templateValue, string $subject, string $appName): string
{
$title = self::escapeHtml($subject);
$brand = self::escapeHtml((string) ($templateValue['name'] ?? $appName));
$content = self::escapeHtml((string) ($templateValue['content'] ?? ''));
$content = nl2br($content, false);
$sendTime = self::escapeHtml(now()->format('Y-m-d H:i:s'));
$cta = '';
$url = isset($templateValue['url']) ? (string) $templateValue['url'] : '';
if (filter_var($url, FILTER_VALIDATE_URL)) {
$safeUrl = self::escapeHtml($url);
$cta = '<a href="' . $safeUrl . '" style="display:inline-block;padding:12px 20px;border-radius:10px;background:#111827;color:#ffffff;text-decoration:none;font-weight:600;">Open Link</a>';
}
return '<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>' . $title . '</title>
</head>
<body style="margin:0;padding:0;background:linear-gradient(135deg,#f8fafc 0%,#eef2ff 100%);font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica,Arial,sans-serif;">
<div style="max-width:680px;margin:0 auto;padding:32px 16px;">
<div style="background:#ffffff;border:1px solid #e5e7eb;border-radius:20px;overflow:hidden;box-shadow:0 16px 40px rgba(15,23,42,.08);">
<div style="padding:24px 24px 16px;background:radial-gradient(80% 120% at 0% 0%,#dbeafe 0%,#ffffff 100%);border-bottom:1px solid #e5e7eb;">
<div style="font-size:12px;color:#64748b;letter-spacing:.06em;text-transform:uppercase;">Message</div>
<h1 style="margin:8px 0 0;font-size:24px;line-height:1.3;color:#0f172a;">' . $title . '</h1>
</div>
<div style="padding:24px;">
<div style="font-size:15px;line-height:1.8;color:#334155;">' . $content . '</div>
<div style="margin-top:20px;">' . $cta . '</div>
</div>
<div style="padding:14px 24px;border-top:1px solid #e5e7eb;background:#f8fafc;font-size:12px;color:#64748b;">
<div>Sender: ' . $brand . '</div>
<div>Sent at: ' . $sendTime . '</div>
</div>
</div>
</div>
</body>
</html>';
}
private static function sendHtmlMail(string $email, string $subject, string $html): void
{
$mailer = Mail::getFacadeRoot();
if ($mailer && method_exists($mailer, 'html')) {
Mail::html($html, function ($message) use ($email, $subject) {
$message->to($email)->subject($subject);
});
return;
}
Mail::send([], [], function ($message) use ($email, $subject, $html) {
$message->to($email)->subject($subject);
if (method_exists($message, 'getSymfonyMessage')) {
$symfonyMessage = $message->getSymfonyMessage();
if ($symfonyMessage && method_exists($symfonyMessage, 'html')) {
$symfonyMessage->html($html);
return;
}
}
if (method_exists($message, 'setBody')) {
$message->setBody($html, 'text/html');
return;
}
throw new \RuntimeException('Unsupported mail message driver for html body.');
});
}
}