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 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | /**
* Email Queue
*
* Manages email job queuing with BullMQ.
* Falls back to direct sending in development when Redis is unavailable.
*/
import { Queue, Job } from 'bullmq';
import { redisConnection, queueConfig, isRedisAvailable } from './config';
import { EmailJobData, EmailJobResult, priorityMap, QueueStats } from './types';
import { logger } from '@/lib/logging';
// Queue instance (lazily initialized)
let emailQueue: Queue<EmailJobData, EmailJobResult> | null = null;
let redisAvailable: boolean | null = null;
/**
* Get or create the email queue
*/
async function getQueue(): Promise<Queue<EmailJobData, EmailJobResult> | null> {
// Check Redis availability once
if (redisAvailable === null) {
redisAvailable = await isRedisAvailable();
if (!redisAvailable) {
logger.warn('Redis not available, using direct email sending', { category: 'EXTERNAL' });
}
}
if (!redisAvailable) {
return null;
}
if (!emailQueue) {
emailQueue = new Queue<EmailJobData, EmailJobResult>(
queueConfig.email.name,
{
connection: redisConnection,
defaultJobOptions: queueConfig.email.defaultJobOptions,
}
);
logger.info('Email queue initialized', { category: 'EXTERNAL' });
}
return emailQueue;
}
/**
* In-memory queue for development fallback
*/
const memoryQueue: Array<{ data: EmailJobData; id: string }> = [];
let memoryQueueProcessor: ((job: EmailJobData) => Promise<EmailJobResult>) | null = null;
/**
* Set the processor for memory queue (used in development)
*/
export function setMemoryQueueProcessor(
processor: (job: EmailJobData) => Promise<EmailJobResult>
): void {
memoryQueueProcessor = processor;
}
/**
* Process memory queue items
*/
async function processMemoryQueue(): Promise<void> {
if (!memoryQueueProcessor || memoryQueue.length === 0) return;
const job = memoryQueue.shift();
if (job) {
try {
await memoryQueueProcessor(job.data);
logger.info(`Memory queue job ${job.id} processed`, { category: 'EXTERNAL' });
} catch (error) {
logger.error(`Memory queue job ${job.id} failed`, error as Error, { category: 'EXTERNAL' });
}
}
}
/**
* Add email to queue
*/
export async function queueEmail(
data: EmailJobData,
options?: {
delay?: number;
priority?: 'high' | 'normal' | 'low';
}
): Promise<{ id: string; queued: boolean }> {
const queue = await getQueue();
const priority = options?.priority || data.priority || 'normal';
if (queue) {
// Use BullMQ queue
const job = await queue.add(
`email:${data.template}`,
data,
{
delay: options?.delay || data.delay,
priority: priorityMap[priority],
}
);
logger.info('Email queued', {
category: 'EXTERNAL',
jobId: job.id,
template: data.template,
to: data.to,
priority,
});
return { id: job.id || 'unknown', queued: true };
}
// Fallback: Use memory queue (processes immediately in dev)
const jobId = `mem-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
memoryQueue.push({ data, id: jobId });
logger.info('Email added to memory queue', {
category: 'EXTERNAL',
jobId,
template: data.template,
to: data.to,
});
// Process immediately in development
setImmediate(() => processMemoryQueue());
return { id: jobId, queued: false };
}
/**
* Queue bulk emails
*/
export async function queueBulkEmails(
emails: EmailJobData[],
options?: { batchSize?: number }
): Promise<{ count: number; queued: boolean }> {
const queue = await getQueue();
const batchSize = options?.batchSize || 100;
if (queue) {
// Use BullMQ bulk add
for (let i = 0; i < emails.length; i += batchSize) {
const batch = emails.slice(i, i + batchSize);
await queue.addBulk(
batch.map((data) => ({
name: `email:${data.template}`,
data,
opts: {
priority: priorityMap[data.priority || 'low'],
},
}))
);
}
logger.info('Bulk emails queued', {
category: 'EXTERNAL',
total: emails.length,
batches: Math.ceil(emails.length / batchSize),
});
return { count: emails.length, queued: true };
}
// Fallback: Add to memory queue
emails.forEach((data) => {
const jobId = `mem-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
memoryQueue.push({ data, id: jobId });
});
logger.info('Bulk emails added to memory queue', {
category: 'EXTERNAL',
total: emails.length,
});
// Process immediately
setImmediate(() => {
emails.forEach(() => processMemoryQueue());
});
return { count: emails.length, queued: false };
}
/**
* Get queue statistics
*/
export async function getEmailQueueStats(): Promise<QueueStats> {
const queue = await getQueue();
if (!queue) {
// Return memory queue stats
return {
waiting: memoryQueue.length,
active: 0,
completed: 0,
failed: 0,
delayed: 0,
paused: false,
};
}
const [waiting, active, completed, failed, delayed] = await Promise.all([
queue.getWaitingCount(),
queue.getActiveCount(),
queue.getCompletedCount(),
queue.getFailedCount(),
queue.getDelayedCount(),
]);
const isPaused = await queue.isPaused();
return { waiting, active, completed, failed, delayed, paused: isPaused };
}
/**
* Pause the queue
*/
export async function pauseEmailQueue(): Promise<boolean> {
const queue = await getQueue();
if (queue) {
await queue.pause();
logger.info('Queue paused', { category: 'EXTERNAL' });
return true;
}
return false;
}
/**
* Resume the queue
*/
export async function resumeEmailQueue(): Promise<boolean> {
const queue = await getQueue();
if (queue) {
await queue.resume();
logger.info('Queue resumed', { category: 'EXTERNAL' });
return true;
}
return false;
}
/**
* Get a specific job by ID
*/
export async function getEmailJob(jobId: string): Promise<Job<EmailJobData, EmailJobResult> | null> {
const queue = await getQueue();
if (!queue) return null;
const job = await queue.getJob(jobId);
return job || null;
}
/**
* Retry a failed job
*/
export async function retryEmailJob(jobId: string): Promise<boolean> {
const queue = await getQueue();
if (!queue) return false;
const job = await queue.getJob(jobId);
if (job) {
await job.retry();
logger.info('Job retry initiated', { category: 'EXTERNAL', jobId });
return true;
}
return false;
}
/**
* Clean up completed jobs older than specified age
*/
export async function cleanEmailQueue(
status: 'completed' | 'failed' = 'completed',
gracePeriodMs: number = 24 * 60 * 60 * 1000 // 24 hours
): Promise<number> {
const queue = await getQueue();
if (!queue) return 0;
const removed = await queue.clean(gracePeriodMs, 1000, status);
logger.info('Queue cleaned', { category: 'EXTERNAL', status, removed: removed.length });
return removed.length;
}
/**
* Close the queue connection
*/
export async function closeEmailQueue(): Promise<void> {
if (emailQueue) {
await emailQueue.close();
emailQueue = null;
logger.info('Queue closed', { category: 'EXTERNAL' });
}
}
|