r4bbit Documentation

website·Indexed 31 days ago

http://r4bbit.io/

A library built on top of amqplib for simplified RabbitMQ integration. It provides tools for server-client and RPC communication patterns, featuring a built-in logger, request tracer, and automatic reconnection. Includes API references for setupR4bbit(), getClient(), and getServer().

Tokens
6.9K
Snippets
48
Records
53
Agent score
52%

What's inside r4bbit

  1. Overview of r4bbit features and amqplib integration

    r4bbit is a highly opinionated, 'batteries included' library built on top of amqplib. It simplifies RabbitMQ integration by providing sensible defaults and built-in functionality such as automatic reconnection after connection failures, an out-of-the-box logger, and a request tracer. Because it is built on amqplib, it remains extendable via all standard amqplib options.
  2. Implement Multiple RPC communication pattern

    The Multiple RPC pattern allows a client to publish a single RPC message to an exchange with a topic name and receive multiple replies from different servers. This is achieved by having multiple servers register RPC routes that match the same routing key (e.g., using wildcards). To distinguish which server sent which reply, servers can provide a replySignature in their route configuration.
  3. Understand r4bbit Request Tracing

    Request tracers in r4bbit are used to separate and track individual requests as they move through multiple microservices (e.g., client -> server -> client). A request tracer consists of two primary functions: one to assign a unique identifier to a request and another to retrieve that identifier. This ensures the same ID persists throughout the entire journey of the request.
  4. Publish Multiple RPC messages with Limited Replies strategy

    Use the waitedReplies option in publishMultipleRPC when the client knows exactly how many responses to expect. The promise will resolve when either all waitedReplies are received or the timeout is reached. If the timeout occurs first, the client returns all replies received up to that point; if no replies are received, it returns an empty array.
    await client.publishMultipleRPC(objectMessage, {
      exchangeName: "test-exchange",
      routingKey: "my.routing-key",
      replyQueueName: "multiple-rpc-client-reply-queue",
      timeout: 5_000,
      waitedReplies: 2,
      responseContains: {
        content: true,
        headers: true,
        signature: true,
      },
    });
  5. Send an RPC message as a client

    Use publishRPCMessage to send a request to the server. You must specify the exchange, routing key, and a reply queue name where the server will send the response. You can also define a timeout and specify which metadata (headers, signature) should be included in the response.
    await client.publishRPCMessage(
      { message: "OurMessage", nested: { value: 15 } },
      {
        exchangeName: "my-exchange",
        routingKey: "my.routing-key",
        replyQueueName: "simple-rpc-reply",
        timeout: 5_000,
        responseContains: {
          content: true,
          headers: true,
          signature: true,
        },
      }
    );
  6. Register a route to listen for messages

    Use the server.registerRoute method to define which queue, exchange, and routing key the server should listen to. The routing key supports wildcards (e.g., my.* matches any key starting with my.).
    await server.registerRoute(
      {
        queueName: "my-queue",
        exchangeName: "my-exchange",
        routingKey: "my.*",
      },
      handlerFunc
    );
  7. Initialize a RabbitMQ client and publish messages

    Use getClient to create a client instance. Use the publishMessage method to send a message by providing the content, exchange name, and routing key.
    import { getClient } from "r4bbit";
    
    const localRabbitUrl = "amqp://guest:guest@localhost:5672/";
    const client = await getClient(localRabbitUrl);
    
    await client.publishMessage(
      { content: "hello world!!!" },
      {
        exchangeName: "my-exchange",
        routingKey: "my.routing-key",
      }
    );
  8. Set up RPC servers for multiple replies

    To enable multiple servers to respond to a single client request, use registerRPCRoute on each server with routing keys that overlap. Use the replySignature option to allow the client to identify the source of each response.
    const server = await getServer("amqp://guest:guest@localhost:5672/");
    
    const handler: ServerTypes.RpcHandler = 
      (reply) => (msg: Record<string, unknown> | string) => {
        reply(msg);
      };
    
    const objectMessage = { message: "OurMessage" };
    
    // Server 1 listens to 'my.*'
    await server.registerRPCRoute(
      {
        queueName: "queue-1",
        routingKey: "my.*",
        exchangeName: "test-exchange",
      },
      handler,
      {
        replySignature: "server-1",
      }
    );
    
    // Server 2 listens to '*.routing-key'
    await server.registerRPCRoute(
      {
        queueName: "queue-2",
        routingKey: "*.routing-key",
        exchangeName: "test-exchange",
      },
      handler,
      {
        replySignature: "server-2",
      }
    );
  9. Close r4bbit server or client connections

    While servers typically run for the lifetime of an application, you can gracefully close the connection to the RabbitMQ broker using the .close() method available on both client and server instances.
    await client.close();
    await server.close();
  10. Initialize r4bbit server and client instances

    Create server and client instances by providing a RabbitMQ connection URL. If no additional options are provided, default values are used.
    const server = await getServer("amqp://guest:guest@localhost:5672/");
    const client = await getClient("amqp://guest:guest@localhost:5672/");
  11. Initialize a RabbitMQ server with r4bbit

    Use the getServer function to create a server instance. This instance acts as a router for receiving messages from a RabbitMQ broker. A running RabbitMQ broker is required.
    import { getServer } from "r4bbit";
    
    const localRabbitUrl = "amqp://guest:guest@localhost:5672/";
    const server = await getServer(localRabbitUrl);
  12. Contribute to R4bbit documentation

    The documentation is maintained in a separate repository. Use pnpm for dependency management. To start developing a new feature or fix in the docs, clone the repository, set up your environment variables, and run the development server.
    # Clone the documentation repository
    git clone git@github.com:r4bbitjs/r4bbitjs.github.io.git
    cd r4bbitjs.github.io
    
    # Create a feature branch
    git checkout -b my-new-feature
    
    # Setup environment and dependencies
    cp .env.example .env
    pnpm i
    
    # Start development server
    pnpm start