All files / src/lib/queue emailWorker.ts

0% Statements 0/202
100% Branches 0/0
0% Functions 0/1
0% Lines 0/202

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203                                                                                                                                                                                                                                                                                                                                                                                                                     
/**
 * Email Worker
 *
 * Processes email jobs from the queue.
 * Handles rendering, sending, and logging.
 */

import { Worker, Job } from 'bullmq';
import { redisConnection, queueConfig, workerConcurrency, rateLimits } from './config';
import { EmailJobData, EmailJobResult } from './types';
import { setMemoryQueueProcessor } from './emailQueue';
import { renderEmailTemplate } from '@/lib/email/templates';
import { sendEmail } from '@/lib/integrations/email';
import { logger } from '@/lib/logging';

// Worker instance
let emailWorker: Worker<EmailJobData, EmailJobResult> | null = null;

/**
 * Process a single email job
 */
async function processEmailJob(
  job: Job<EmailJobData> | EmailJobData,
  attemptsMade: number = 0
): Promise<EmailJobResult> {
  // Handle both BullMQ Job and raw data (for memory queue)
  const data = 'data' in job && 'id' in job ? job.data : (job as EmailJobData);
  const jobId = 'id' in job ? (job as Job).id : 'memory-job';
  const { to, subject, template, data: templateData, html: prerenderedHtml } = data;

  logger.info('Processing email job', {
    category: 'EXTERNAL',
    jobId,
    template,
    to,
    attempt: attemptsMade + 1,
  });

  try {
    // Use pre-rendered HTML or render template
    const html = prerenderedHtml || await renderEmailTemplate(template, templateData);

    // Send email
    const result = await sendEmail({
      to,
      subject,
      html,
    });

    const sentAt = new Date();

    // Log successful delivery
    // Note: EmailLog model will be available after prisma generate
    // if (userId) {
    //   await prisma.emailLog.create({
    //     data: {
    //       userId,
    //       to,
    //       subject,
    //       template,
    //       status: 'SENT',
    //       messageId: result ? 'sent' : undefined,
    //       sentAt,
    //     },
    //   }).catch((error: Error) => {
    //     logger.error('EMAIL_WORKER', 'Failed to log email', error);
    //   });
    // }

    logger.info('Email sent successfully', {
      category: 'EXTERNAL',
      jobId,
      to,
    });

    return {
      messageId: result ? 'sent' : 'dev-mode',
      status: 'sent',
      sentAt,
    };
  } catch (error) {
    // Log failure
    // Note: EmailLog model will be available after prisma generate
    // if (userId) {
    //   await prisma.emailLog.create({
    //     data: {
    //       userId,
    //       to,
    //       subject,
    //       template,
    //       status: 'FAILED',
    //       error: errorMessage,
    //       attemptCount: attemptsMade + 1,
    //     },
    //   }).catch((logError: Error) => {
    //     logger.error('EMAIL_WORKER', 'Failed to log email failure', logError);
    //   });
    // }

    logger.error('Email send failed', error as Error, { category: 'EXTERNAL' });

    throw error;
  }
}

/**
 * Start the email worker
 */
export async function startEmailWorker(): Promise<Worker<EmailJobData, EmailJobResult> | null> {
  // Set up memory queue processor for development fallback
  setMemoryQueueProcessor(async (data) => {
    return processEmailJob(data);
  });

  // Check if Redis is available
  const { isRedisAvailable } = await import('./config');
  const redisAvailable = await isRedisAvailable();

  if (!redisAvailable) {
    logger.info('Redis not available, using memory queue processor', { category: 'EXTERNAL' });
    return null;
  }

  if (emailWorker) {
    logger.warn('Email worker already running', { category: 'EXTERNAL' });
    return emailWorker;
  }

  emailWorker = new Worker<EmailJobData, EmailJobResult>(
    queueConfig.email.name,
    async (job) => {
      return processEmailJob(job, job.attemptsMade);
    },
    {
      connection: redisConnection,
      concurrency: workerConcurrency.email,
      limiter: rateLimits.email,
    }
  );

  // Event handlers
  emailWorker.on('completed', (job, result) => {
    logger.info('Job completed', {
      category: 'EXTERNAL',
      jobId: job.id,
      status: result.status,
    });
  });

  emailWorker.on('failed', (job, error) => {
    logger.error(`Job ${job?.id} failed after ${job?.attemptsMade} attempts`, error, { category: 'EXTERNAL' });
  });

  emailWorker.on('error', (error) => {
    logger.error('Worker error', error, { category: 'EXTERNAL' });
  });

  emailWorker.on('stalled', (jobId) => {
    logger.warn('Job stalled', { category: 'EXTERNAL', jobId });
  });

  logger.info('Email worker started', {
    category: 'EXTERNAL',
    concurrency: workerConcurrency.email,
    rateLimit: `${rateLimits.email.max}/${rateLimits.email.duration}ms`,
  });

  return emailWorker;
}

/**
 * Stop the email worker
 */
export async function stopEmailWorker(): Promise<void> {
  if (emailWorker) {
    await emailWorker.close();
    emailWorker = null;
    logger.info('Email worker stopped', { category: 'EXTERNAL' });
  }
}

/**
 * Check if worker is running
 */
export function isWorkerRunning(): boolean {
  return emailWorker !== null && !emailWorker.closing;
}

/**
 * Get worker status
 */
export function getWorkerStatus(): {
  running: boolean;
  concurrency: number;
  rateLimit: { max: number; duration: number };
} {
  return {
    running: isWorkerRunning(),
    concurrency: workerConcurrency.email,
    rateLimit: rateLimits.email,
  };
}