import { Injectable, Logger, OnModuleDestroy, OnModuleInit, } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import type { AppConfig } from '../config/app-config.schema.js'; import { retryDelayMs } from '../jobs/backoff.js'; import { JobsRepository } from '../jobs/jobs.repository.js'; import { MetricsService } from '../metrics/metrics.service.js'; const REAP_BATCH = 20; /** * The reaper is the backstop for a worker that was killed mid-job: the lease * expires and the job returns to `queued` without waiting for the broker's * delivery limit. */ @Injectable() export class LeaseReaper implements OnModuleInit, OnModuleDestroy { private readonly logger = new Logger(LeaseReaper.name); private timer: NodeJS.Timeout | undefined; private running = false; constructor( private readonly config: ConfigService, private readonly jobs: JobsRepository, private readonly metrics: MetricsService, ) {} onModuleInit(): void { const interval = this.config.getOrThrow('LEASE_REAPER_INTERVAL_MS'); const base = this.config.getOrThrow('JOB_RETRY_BASE_MS'); const cap = this.config.getOrThrow('JOB_RETRY_MAX_MS'); this.timer = setInterval(() => { if (this.running) return; this.running = true; this.jobs .reapExpiredLeases(REAP_BATCH, (attempt) => retryDelayMs(attempt, base, cap), ) .then((count) => { if (count > 0) this.metrics.add('worker.leases.reaped', count); }) .catch((error: unknown) => { this.metrics.increment('worker.leases.reap_error'); this.logger.warn( `Lease reaper failed: ${error instanceof Error ? error.message : 'unknown error'}`, ); }) .finally(() => { this.running = false; }); }, interval); this.timer.unref(); } onModuleDestroy(): void { clearInterval(this.timer); this.timer = undefined; } }