|
| 1 | +import { logger, queue, schemaTask } from '@trigger.dev/sdk'; |
| 2 | +import { z } from 'zod'; |
| 3 | +import { resend } from '../../email/resend'; |
| 4 | +import { generateUnsubscribeToken } from '@trycompai/email'; |
| 5 | + |
| 6 | +const RESEND_BATCH_LIMIT = 100; |
| 7 | + |
| 8 | +const batchEmailQueue = queue({ |
| 9 | + name: 'send-batch-email', |
| 10 | + concurrencyLimit: 5, |
| 11 | +}); |
| 12 | + |
| 13 | +const batchEmailItemSchema = z.object({ |
| 14 | + to: z.string(), |
| 15 | + subject: z.string(), |
| 16 | + html: z.string(), |
| 17 | + from: z.string().optional(), |
| 18 | + cc: z.union([z.string(), z.array(z.string())]).optional(), |
| 19 | +}); |
| 20 | + |
| 21 | +export const sendBatchEmailTask = schemaTask({ |
| 22 | + id: 'send-batch-email', |
| 23 | + queue: batchEmailQueue, |
| 24 | + retry: { |
| 25 | + maxAttempts: 3, |
| 26 | + }, |
| 27 | + schema: z.object({ |
| 28 | + emails: z.array(batchEmailItemSchema).min(1), |
| 29 | + }), |
| 30 | + run: async (params) => { |
| 31 | + if (!resend) { |
| 32 | + logger.error('Resend not initialized - missing RESEND_API_KEY'); |
| 33 | + throw new Error('Resend not initialized - missing API key'); |
| 34 | + } |
| 35 | + |
| 36 | + const fromDefault = |
| 37 | + process.env.RESEND_FROM_SYSTEM ?? process.env.RESEND_FROM_DEFAULT; |
| 38 | + |
| 39 | + if (!fromDefault) { |
| 40 | + throw new Error('Missing FROM address in environment variables'); |
| 41 | + } |
| 42 | + |
| 43 | + const toTest = process.env.RESEND_TO_TEST; |
| 44 | + const apiBaseUrl = |
| 45 | + process.env.NEXT_PUBLIC_API_URL || 'https://api.trycomp.ai'; |
| 46 | + |
| 47 | + let totalSent = 0; |
| 48 | + let totalFailed = 0; |
| 49 | + |
| 50 | + for (let i = 0; i < params.emails.length; i += RESEND_BATCH_LIMIT) { |
| 51 | + const chunk = params.emails.slice(i, i + RESEND_BATCH_LIMIT); |
| 52 | + |
| 53 | + const payload = chunk.map((email) => { |
| 54 | + const token = generateUnsubscribeToken(email.to); |
| 55 | + const oneClickUrl = `${apiBaseUrl}/v1/email/unsubscribe?email=${encodeURIComponent(email.to)}&token=${encodeURIComponent(token)}`; |
| 56 | + |
| 57 | + return { |
| 58 | + from: email.from ?? fromDefault, |
| 59 | + to: toTest ?? email.to, |
| 60 | + cc: email.cc, |
| 61 | + subject: email.subject, |
| 62 | + html: email.html, |
| 63 | + headers: { |
| 64 | + 'List-Unsubscribe': `<${oneClickUrl}>`, |
| 65 | + 'List-Unsubscribe-Post': 'List-Unsubscribe=One-Click', |
| 66 | + }, |
| 67 | + }; |
| 68 | + }); |
| 69 | + |
| 70 | + const { data, error } = await resend.batch.send(payload, { |
| 71 | + batchValidation: 'permissive', |
| 72 | + }); |
| 73 | + |
| 74 | + if (error) { |
| 75 | + logger.error('Resend batch API error', { |
| 76 | + error, |
| 77 | + chunkIndex: i, |
| 78 | + chunkSize: chunk.length, |
| 79 | + }); |
| 80 | + totalFailed += chunk.length; |
| 81 | + continue; |
| 82 | + } |
| 83 | + |
| 84 | + const sent = data?.data?.length ?? 0; |
| 85 | + totalSent += sent; |
| 86 | + |
| 87 | + if ('errors' in data && Array.isArray(data.errors)) { |
| 88 | + for (const err of data.errors) { |
| 89 | + logger.warn('Batch email failed for recipient', { |
| 90 | + index: err.index, |
| 91 | + message: err.message, |
| 92 | + to: chunk[err.index]?.to, |
| 93 | + }); |
| 94 | + totalFailed += 1; |
| 95 | + } |
| 96 | + } |
| 97 | + |
| 98 | + logger.info('Batch chunk sent', { |
| 99 | + chunkIndex: i, |
| 100 | + chunkSize: chunk.length, |
| 101 | + sent, |
| 102 | + }); |
| 103 | + } |
| 104 | + |
| 105 | + logger.info('Batch email task complete', { totalSent, totalFailed }); |
| 106 | + return { totalSent, totalFailed }; |
| 107 | + }, |
| 108 | +}); |
0 commit comments