All files / src/metrics bullmq.metrics.ts

76.92% Statements 20/26
76.19% Branches 16/21
66.66% Functions 4/6
80.95% Lines 17/21

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 5613x 13x 13x 13x     13x         2x 2x 2x 2x   2x                 1x         1x                 6x 6x 5x 5x 5x                        
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import { Gauge, register } from 'prom-client';
import { InjectQueue } from '@nestjs/bullmq';
import { Queue } from 'bullmq';
 
@Injectable()
export class BullMetricsService implements OnModuleInit, OnModuleDestroy {
  private readonly gauge: Gauge<string>;
  private timer!: NodeJS.Timeout;
 
  constructor(
    @InjectQueue('listingIndex') private readonly listingIndex: Queue,
    @InjectQueue('media') private readonly media: Queue,
    @InjectQueue('media-gc') private readonly mediaGc: Queue,
    @InjectQueue('boost-expiry') private readonly boostExpiry: Queue,
  ) {
    this.gauge = (register.getSingleMetric('bull_queue_lag_seconds') as Gauge<string>) ?? new Gauge({
      name: 'bull_queue_lag_seconds',
      help: 'Time in seconds between now and the oldest waiting job (per queue)',
      labelNames: ['queue'] as const,
      registers: [register],
    });
  }
 
  onModuleInit() {
    if (process.env.NODE_ENV === 'test') return; // skip in tests
    this.timer = setInterval(() => this.sample(), 5000).unref();
  }
 
  async sample() {
    await Promise.all([
      this.observeQueue(this.listingIndex, 'listingIndex'),
      this.observeQueue(this.media, 'media'),
      this.observeQueue(this.mediaGc, 'media-gc'),
      this.observeQueue(this.boostExpiry, 'boost-expiry'),
    ]);
  }
 
  async observeQueue(queue: Queue, name: string) {
    try {
      const jobs = await queue.getJobs(['waiting'], 0, 0, true);
      if (jobs.length === 0) {
        this.gauge.set({ queue: name }, 0);
        return;
      }
      const lagSec = (Date.now() - jobs[0].timestamp) / 1000;
      this.gauge.set({ queue: name }, lagSec);
    } catch (_err) {
      // ignore errors (e.g., NullQueue in dev)
    }
  }
 
  onModuleDestroy() {
    Iif (this.timer) clearInterval(this.timer);
  }
}