All files / src/infrastructure/queue reminder-worker.ts

86.66% Statements 13/15
50% Branches 2/4
80% Functions 4/5
86.66% Lines 13/15

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                                  1x         1x                     1x     3x 2x 2x               1x 1x         1x       1x   1x 1x                                   1x    
import { Worker } from 'bullmq';
import Redis from 'ioredis';
import { env } from '../../shared/config/env';
import { logger } from '../../shared/logging/logger';
import { prisma } from '../database/prisma-client';
import { PrismaBabyRepository } from '../database/repositories/prisma-baby.repository';
import { PrismaVaccineRepository } from '../database/repositories/prisma-vaccine.repository';
import { PrismaBabyVaccineRecordRepository } from '../database/repositories/prisma-baby-vaccine-record.repository';
import { PrismaAppointmentRepository } from '../database/repositories/prisma-appointment.repository';
import { PrismaNotificationRepository } from '../database/repositories/prisma-notification.repository';
import { PrismaBabyGuardianRepository } from '../database/repositories/prisma-baby-guardian.repository';
import { PrismaUserRepository } from '../database/repositories/prisma-user.repository';
import { emailService } from '../email/email-service.instance';
import { GenerateReminderNotificationsUseCase } from '../../application/notification/generate-reminder-notifications.use-case';
import { REMINDER_QUEUE_NAME, reminderDeadLetterQueue } from './reminder-queue';
import { routeToDeadLetter } from './dead-letter';
 
const connection = new Redis(env.REDIS_URL, { maxRetriesPerRequest: null });
 
export function createReminderWorker(): Worker {
  // Uses the plain (non-cached) vaccine repository so the daily sweep always
  // sees the catalog as it is right now, regardless of the HTTP-facing cache TTL.
  const generateReminderNotificationsUseCase = new GenerateReminderNotificationsUseCase(
    new PrismaBabyRepository(prisma),
    new PrismaVaccineRepository(prisma),
    new PrismaBabyVaccineRecordRepository(prisma),
    new PrismaAppointmentRepository(prisma),
    new PrismaNotificationRepository(prisma),
    new PrismaBabyGuardianRepository(prisma),
    new PrismaUserRepository(prisma),
    emailService,
  );
 
  const worker = new Worker(
    REMINDER_QUEUE_NAME,
    async () => {
      const result = await generateReminderNotificationsUseCase.execute();
      logger.info({ createdCount: result.createdCount }, 'reminders.generated');
      return result;
    },
    { connection },
  );
 
  // Fires after every failed attempt, not just the last — routeToDeadLetter
  // no-ops while BullMQ still intends to retry, so the log line below is the
  // record of each attempt and the dead letter entry is the record of giving up.
  worker.on('failed', (job, error) => {
    logger.error(
      { err: error, jobId: job?.id, attemptsMade: job?.attemptsMade },
      'reminders.job_failed',
    );
 
    Iif (!job) {
      return;
    }
 
    void routeToDeadLetter(reminderDeadLetterQueue, job, error)
      .then((deadLettered) => {
        Eif (deadLettered) {
          logger.error(
            { jobId: job.id, attemptsMade: job.attemptsMade },
            'reminders.job_dead_lettered',
          );
        }
      })
      .catch((deadLetterError: unknown) => {
        // Redis is almost certainly the reason the job failed in the first
        // place, so this write can fail too. Losing the dead letter copy must
        // not take the worker process down — the original job is still in
        // BullMQ's failed set with its stack trace.
        logger.error(
          { err: deadLetterError, jobId: job.id },
          'reminders.dead_letter_write_failed',
        );
      });
  });
 
  return worker;
}