npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@betsys-nestjs/rabbit-mq

v5.0.0

Published

This library is responsible for handling RabbitMQ.

Downloads

38

Readme

RabbitMQ library

This library is responsible for handling RabbitMQ connection, message production and consumption.

Dependencies

| Package | Version | | ---------------- | ------- | | amqplib | ^0.10.3 | | @nestjs/common | ^10.0.0 | | @nestjs/core | ^10.0.0 | | @nestjs/terminus | ^10.0.0 | | reflect-metadata | <1.0.0 | | rxjs | ^7.0.0 |

Usage

  • To start using this library simply import RabbitMqModule to your module.
@Module({
    imports: [
        RabbitMqModule.forFeature({
          uri: 'amqp://test:test@localhost:5672/',
          prefetchSize: 10,
          parser: ProtoMessageParserService,
        }, 'my-handle'),
    ]
})
export class AppModule {
    // ...
}
  • Prepare rabbit environment setup
import { Injectable } from '@nestjs/common';
import { InjectConfig, InjectConnectionUtils } from '@betsys-nestjs/rabbit-mq';
import { RabbitMqConfig } from '@betsys-nestjs/rabbit-mq';
import { AbstractSetupRabbitEnvironmentService } from '@betsys-nestjs/rabbit-mq';
import { RabbitMqConnectionUtils } from '@betsys-nestjs/rabbit-mq';

@Injectable()
export class SetupRabbitEnvironmentService extends AbstractSetupRabbitEnvironmentService {
  constructor(
    @InjectConnectionUtils()
    private readonly rabbitMqConnectionUtils: RabbitMqConnectionUtils,
    @InjectConfig() private config: RabbitMqConfig,
  ) {
    super();
  }

  protected async setup(): Promise<void> {
    await this.rabbitMqConnectionUtils.createExchange(
      'my-exchange',
      'direct',
      {
        durable: true,
        autoDelete: false,
        internal: false,
        arguments: {},
      },
    );

    await this.rabbitMqConnectionUtils.createQueue(
      'my-queue',
      {
        durable: true,
        autoDelete: false,
        maxLength: 100000,
      },
    );

    await this.rabbitMqConnectionUtils.bindQueue(
      'result-queue',
      'result-exchange',
      'my-routing-key',
    );
  }
}

and set it up

    async onApplicationBootstrap(): Promise<void> {
        await this.setupRabbit.execute();
    }

Proto message parser

Furthermore you need to implement proto-message parser class that extends AbstractProtoMessageParserService, and implements MessageParser and pass it to the forFeature static method to the parser property of RabbitMqModule.

Example of implementing ProtoMessageParser:

import path from 'path';
import { Injectable } from '@nestjs/common';
import { loadSync, Type } from 'protobufjs';
import { AbstractProtoMessageParserService } from '@betsys-nestjs/rabbit-mq';
import { InjectLogger } from '@betsys-nestjs/rabbit-mq';
import { RabbitMqLoggerInterface } from '@betsys-nestjs/rabbit-mq';
import { MessageParser } from '@betsys-nestjs/rabbit-mq';

export interface UpdateMessage {
  table: string;
  uuid: string;
  timestamp: bigint;
}

export interface ProtoMessage {
  table: string | null;
  uuid: string | null;
  timestamp: number | null;
}

export interface ProtoMessageBulk {
  messages: ProtoMessage[];
}

@Injectable()
export class ProtoMessageParserService extends AbstractProtoMessageParserService<
  UpdateMessage,
  ProtoMessage,
  ProtoMessageBulk,
  Type
> implements MessageParser {
  constructor(@InjectLogger() protected logger: RabbitMqLoggerInterface) {
    super(logger);
  }

  protected createRowMessageBulkDecoder(): Type {
    const protoRoot = loadSync(path.join(__dirname, './update_message.proto'));

    return protoRoot.lookupType('updatemessage.RowMessageBulk');
  }

  protected transformPayload(protoMessage: ProtoMessage): UpdateMessage {
    return {
      table: protoMessage.table || '',
      uuid: protoMessage.uuid || '',
      // timestamp after decoding has inaccuracy 100 nanoseconds (it means 2 last places are replaced by zeroes)
      timestamp: protoMessage.timestamp || 0n,
    } as UpdateMessage;
  }
}
  • Then you can produce messages:
await rabbitMqProduceUtils.publishToExchange(
    'test-exchange',
    'test-routing-key',
    Buffer.from(
        JSON.stringify({
            message: 'My message',
        }),
    ),
);
  • Or consume messages:
await rabbitMqConsumeUtils.consumeQueueSync('my-queue', async (message: ConsumeMessage) => {
        // do something with message
});

Monitoring and Logger

The library is ready to work with monitoring and logger. To enable it you need to implement your own monitoring and logger service based on abstraction provided by this library.

Monitoring

There are three different monitoring parts that can be independently set in the config:

Time monitoring - used for monitoring of operation time and message time, your provided service must implement RabbitMqTimeMonitoringInterface. Implementation of startTimerOperationTime starts your custom timer returning a function which stops the timer, similarly the implementation of startTimerMessageTime.

Connection monitoring - used for observing count of connections to rabbit-mq via this library. To use this monitoring type, you must implement RabbitMqConnectionMonitoringInterface.

Message count monitoring - used for observing counts of messages. To use this monitoring type, you must implement RabbitMqMessageCountMonitoringInterface.

Example of connection monitoring using @betsys-nestjs/monitoring:

import cluster from 'cluster';
import {
  Gauge,
  InjectMonitoringConfig,
  InjectMonitoringRegistry,
  Registry,
  AbstractMonitoringService,
  MonitoringConfigInterface,
} from '@betsys-nestjs/monitoring';
import { RabbitMqConnectionMonitoringInterface } from '@betsys-nestjs/rabbit-mq';

export class RabbitMqMonitoringService extends AbstractMonitoringService implements
  RabbitMqConnectionMonitoringInterface {
  private readonly SYSTEM_LABEL = 'rabbitmq';

  private readonly connectionGauge: Gauge<string>;

  private readonly workerId: number;

  constructor(
    @InjectMonitoringConfig() private readonly config: MonitoringConfigInterface,
    @InjectMonitoringRegistry() protected readonly registry: Registry,
  ) {
    super(registry);
    this.connectionGauge = super.createMetric(Gauge, {
      name: this.config.getMetricsName('open_connection'),
      help: 'count of currently open connections to rabbitmq',
      labelNames: ['system', 'handle'],
      registers: [registry],
    });

    this.workerId = RabbitMqMonitoringService.getWorkerId();
  }

  private static getWorkerId(): number {
    return cluster.isMaster ? 0 : cluster.worker?.id ?? -1;
  }

  connectionOpened(handle: string): void {
    this.connectionGauge.inc({ system: this.SYSTEM_LABEL, handle }, 1);
  }

  connectionClosed(handle: string): void {
    this.connectionGauge.dec({ system: this.SYSTEM_LABEL, handle }, 1);
  }
}

Logger

Similarly to monitoring you can simply implement custom service following RabbitMqLoggerInterface.

import { RabbitMqLoggerInterface } from '@betsys-nestjs/rabbit-mq';
import { Logger as NestLogger } from '@betsys-nestjs/logger';
export class RabbitLoggerService implements RabbitMqLoggerInterface {
  constructor(private readonly logger: NestLogger) {}

  setContext(context: string): void {
    this.logger.setContext(context);
  }
  debug(message: string) {
    this.logger.debug(message);
  }
  error(message: string) {
    this.logger.error(message);
  }
}

To start using Logger or Monitoring service, you simply insert class references to forFeature method of PostgresModule like this:

RabbitMqModule.forFeature({
  // other config values, 
  logger: RabbitMqTestLogger,
  monitoring: {
    connection: TestConnectionMonitoringService,
    time: TestTimeMonitoringService,
    messageCount: TestMessageCountMonitoringService,
  },
})