import dns from 'dns/promises'; import { topicManager } from './topicManager.js'; async function getMxDomain(email) { const domain = email.split('@')[1]; try { const mxRecords = await dns.resolveMx(domain); if (mxRecords && mxRecords.length > 0) { // Берём самый приоритетный MX return mxRecords.sort((a, b) => a.priority - b.priority)[0].exchange; } } catch (e) {} return domain; } export async function fillQueueForCampaign(campaign, subscribers, smtpServers) { // Группируем подписчиков по домену const domainMap = {}; for (const sub of subscribers) { const domain = sub.email.split('@')[1]; if (!domainMap[domain]) domainMap[domain] = []; domainMap[domain].push(sub); } // Обрабатываем каждый домен и SMTP сервер for (const [domain, subs] of Object.entries(domainMap)) { for (const smtp of smtpServers) { const topicName = `mail-send-${domain}-${smtp.id}`; // Создаем топик если его нет const topicCreated = await topicManager.createTopic(topicName); if (!topicCreated) { console.error(`[queueFiller] Failed to create topic: ${topicName}`); continue; } // Отправляем сообщения в топик const messages = subs.map(sub => ({ campaignId: campaign.id, subject: campaign.subject, text: campaign.text, html: campaign.html, mx: domain, // для обратной совместимости subscriberId: sub.id, email: sub.email, smtpServerId: smtp.id, })); for (const message of messages) { const sent = await topicManager.sendMessage(topicName, message); if (!sent) { console.error(`[queueFiller] Failed to send message to topic: ${topicName}`); } } console.log(`[queueFiller] Sent ${messages.length} messages to topic: ${topicName}`); } } }