copy()->subDay(); $report = MailDailyReport::where('report_date', $start->toDateString())->first(); if ($report) { return $report; } $rows = MailMessage::whereIn('direction', ['in', 'out']) ->whereRaw('COALESCE(submitted_at, first_attempt_at, created_at) >= ?', [$start->copy()->setTimezone(config('app.timezone'))->toDateTimeString()]) ->whereRaw('COALESCE(submitted_at, first_attempt_at, created_at) < ?', [$end->copy()->setTimezone(config('app.timezone'))->toDateTimeString()])->get(['direction', 'purpose', 'channel', 'status', 'fallback_reason']); $totals = []; foreach ($rows as $row) { $key = $row->direction . '/' . ($row->channel ?: ($row->status === 'policy_blocked' ? 'policy' : 'pending')) . '/' . $row->status; $totals[$key] = ($totals[$key] ?? 0) + 1; } $usage = null; if (Settings::get('resend_enabled') && Settings::get('resend_key')) { try { $usage = $this->resend->usage(); } catch (\Throwable $e) { /* report local records with an explicit unavailable marker */ } } $summary = [ 'resend_usage' => $usage, 'resend_usage_checked_at' => $usage ? now()->toIso8601String() : null, 'from' => $start->toIso8601String(), 'to' => $end->toIso8601String(), 'counts' => $totals, 'fallbacks' => $rows->whereNotNull('fallback_reason')->count(), 'backlog' => MailMessage::where('direction', 'out')->whereIn('status', ['pending', 'sending', 'unknown'])->count(), 'quota' => MailQuotaBucket::where('resets_at', '>', now())->get(['period', 'limit', 'used', 'reserved', 'synced_at'])->toArray(), ]; return MailDailyReport::firstOrCreate(['report_date' => $start->toDateString()], ['summary' => $summary]); } private const TERMINAL = ['sent', 'failed', 'uncertain', 'cancelled']; public function send(MailDailyReport $report): void { if (!config('mail_report.enabled', false) || config('app.env') !== 'production' || !Settings::get('enabled') || !Settings::get('report_enabled')) return; $startDate = (string) config('mail_report.start_date'); if (!preg_match('/\A\d{4}-\d{2}-\d{2}\z/D', $startDate)) throw new \RuntimeException('mail_report_start_required'); if (substr((string) $report->report_date, 0, 10) < $startDate) return; $lock = Cache::lock('mailflow:report:' . $report->id, 60); if (!$lock->get()) return; try { $report->refresh(); $summary = $report->summary; $event = $summary['_telehub'] ?? null; if ($event === null) { // A legacy submission, failed attempt or unknown result must never become a new TeleHub delivery. if ($report->status !== 'pending' || (int) $report->attempts !== 0) return; $event = ['version' => 1, 'identity' => $this->identity(), 'key' => 'xb.mail.daily.' . $this->identity() . '.' . substr((string) $report->report_date, 0, 10), 'bot' => 'info', 'target' => 'base', 'text' => $this->text($report), 'retry_at' => 0]; $summary['_telehub'] = $event; $report->update(['summary' => $summary]); // Freeze identity/key/body before the first HTTP attempt. } if (!is_array($event) || ($event['version'] ?? null) !== 1 || ($event['identity'] ?? null) !== $this->identity() || ($event['bot'] ?? null) !== 'info' || ($event['target'] ?? null) !== 'base' || !is_string($event['key'] ?? null) || !preg_match('/\A[A-Za-z0-9._:-]{1,128}\z/D', $event['key']) || !is_string($event['text'] ?? null) || (isset($event['receipt_id']) && !$this->uuid($event['receipt_id']))) { throw new \RuntimeException('mail_report_state_invalid'); } if (in_array($report->status, self::TERMINAL, true) || ($event['blocked'] ?? false)) return; if (now()->timestamp < ($event['retry_at'] ?? 0)) return; $base = rtrim((string) config('mail_report.telehub_url'), '/'); $key = (string) config('mail_report.telehub_key'); if (!$key || parse_url($base, PHP_URL_SCHEME) !== 'https' || !parse_url($base, PHP_URL_HOST) || parse_url($base, PHP_URL_USER) || parse_url($base, PHP_URL_PASS)) { $report->update(['error_code' => 'telehub_configuration_required']); return; } $event['retry_at'] = now()->timestamp + max(60, (int) config('mail_report.retry_seconds', 300)); $summary['_telehub'] = $event; $report->update(['summary' => $summary, 'attempts' => (int) $report->attempts + 1]); try { $client = Http::withoutRedirecting()->connectTimeout(5)->timeout(15)->withToken($key); $response = isset($event['receipt_id']) ? $client->get($base . '/api/v1/messages/' . $event['receipt_id']) : $client->withHeaders(['Idempotency-Key' => $event['key']])->post($base . '/api/v1/messages', [ 'bot' => 'info', 'target' => 'base', 'text' => $event['text'], ]); } catch (\Throwable $e) { $report->update(['error_code' => 'telehub_transport_unknown']); return; // Same immutable key/body is safe to retry; never fall back to master or direct Telegram. } if (!in_array($response->status(), [200, 202], true)) { $updates = ['error_code' => 'telehub_http_' . $response->status()]; if ($response->status() === 429) { $event['retry_at'] = now()->timestamp + max(60, min(86400, (int) $response->header('Retry-After', 300))); } elseif (in_array($response->status(), [400, 401, 403, 404, 409, 422], true)) { $event['blocked'] = true; $updates['status'] = 'failed'; } $summary['_telehub'] = $event; $report->update($updates + ['summary' => $summary]); return; } $data = $response->json('data'); $id = is_array($data) ? ($data['id'] ?? null) : null; $status = is_array($data) ? ($data['status'] ?? null) : null; if (!$this->uuid($id) || !in_array($status, ['queued', 'sending', ...self::TERMINAL], true) || isset($event['receipt_id']) && $event['receipt_id'] !== $id) { $report->update(['error_code' => 'telehub_response_invalid']); return; } $event['receipt_id'] = $id; $summary['_telehub'] = $event; $updates = ['summary' => $summary, 'status' => $status, 'error_code' => in_array($status, ['failed', 'uncertain'], true) ? 'telehub_delivery_' . $status : null]; if (!$report->submitted_at) $updates['submitted_at'] = now(); $report->update($updates); } finally { $lock->release(); } } private function identity(): string { $driver = (string) config('database.default'); return substr(hash('sha256', implode('|', [(string) config('app.env'), (string) config('mail_report.project'), (string) config('app.url'), $driver, (string) config('database.connections.' . $driver . '.database')])), 0, 24); } private function uuid(mixed $id): bool { return is_string($id) && preg_match('/\A[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\z/iD', $id) === 1; } private function text(MailDailyReport $report): string { $project = trim(preg_replace('/[\x00-\x1f\x7f]+/u', ' ', (string) config('mail_report.project'))); if ($project === '' || mb_strlen($project) > 100) throw new \RuntimeException('mail_report_project_invalid'); $summary = $report->summary; $from = Carbon::parse($summary['from'])->setTimezone('Asia/Shanghai')->format('Y-m-d H:i'); $to = Carbon::parse($summary['to'])->setTimezone('Asia/Shanghai')->format('Y-m-d H:i'); $text = '【' . $project . '/' . config('app.env') . ' - 邮件与Resend用量日报】'; $text .= "\n统计区间:" . $from . '–' . $to . '(北京时间)'; $labels = ['out' => '发送', 'in' => '收件', 'policy' => '邮件策略', 'resend' => 'Resend', 'conventional' => '常规邮箱', 'pending' => '待处理', 'submitted' => '已提交', 'delivered' => '已投递', 'delayed' => '投递延迟', 'bounced' => '退信', 'complained' => '投诉', 'suppressed' => '停止投递', 'failed' => '失败', 'unknown' => '结果未知', 'sending' => '提交中', 'received' => '已接收', 'simulated' => '模拟发送', 'expired' => '已过期', 'policy_blocked' => '因档位或套餐状态取消']; foreach ($summary['counts'] as $key => $count) { [$direction, $channel, $status] = explode('/', $key); $text .= "\n" . ($labels[$direction] ?? $direction) . ' / ' . ($labels[$channel] ?? $channel) . ' / ' . ($labels[$status] ?? $status) . ':' . $count; } if (!$summary['counts']) $text .= "\n期间邮件记录:0"; $text .= "\n回退常规邮箱:" . $summary['fallbacks'] . "\n待处理/结果未知:" . $summary['backlog']; if ($summary['resend_usage'] ?? null) { foreach (['daily' => '今日', 'monthly' => '本月'] as $period => $label) { $usage = $summary['resend_usage'][$period] ?? []; if (isset($usage['used'], $usage['limit'])) $text .= "\nResend 官方" . $label . '已用:' . $usage['used'] . ' / ' . $usage['limit']; } } else { $text .= "\nResend 官方额度未能实时核对,以下为本地记录。"; } foreach ($summary['quota'] as $quota) { $period = ['daily' => '日', 'monthly' => '月'][$quota['period']] ?? $quota['period']; $text .= "\nResend " . $period . '保守剩余额度:' . max(0, $quota['limit'] - $quota['used'] - $quota['reserved']); } if (mb_strlen($text) > 4096) throw new \RuntimeException('mail_report_text_too_long'); return $text; } }