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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@amqp-contract/worker

v3.1.0

Published

Worker utilities for consuming messages using amqp-contract

Readme

@amqp-contract/worker

Type-safe AMQP worker for consuming messages using amqp-contract with AsyncResult/Result error handling.

CI npm version npm downloads TypeScript License: MIT

📖 Full documentation →

Installation

pnpm add @amqp-contract/worker

Features

  • ✅ Type-safe message consumption — Handlers are fully typed based on your contract
  • ✅ Automatic validation — Messages are validated before reaching your handlers
  • ✅ Automatic retry mechanism — Built-in immediate or exponential backoff retry mechanisms
  • ✅ Prefetch configuration — Control message flow with per-consumer prefetch settings
  • ✅ Automatic reconnection — Built-in connection management with failover support

Usage

Basic Usage

import { TypedAmqpWorker, RetryableError, type Logger } from "@amqp-contract/worker";
import { fromPromise } from "unthrown";

import { contract } from "./contract.js";

// Optional: Create a logger implementation
const logger: Logger = {
  debug: (message, context) => console.debug(message, context),
  info: (message, context) => console.info(message, context),
  warn: (message, context) => console.warn(message, context),
  error: (message, context) => console.error(message, context),
};

// Create worker from contract with handlers (automatically connects and starts consuming)
const worker = await TypedAmqpWorker.create({
  contract,
  handlers: {
    processOrder: ({ input: { payload } }) => {
      console.log("Processing order:", payload.orderId);

      // Your business logic here
      return fromPromise(
        Promise.all([processPayment(payload), updateInventory(payload)]),
        (error) => new RetryableError("Order processing failed", error),
      ).map(() => undefined);
    },
  },
  urls: ["amqp://localhost"],
  logger, // Optional: logs message consumption and errors
}).getOrThrow();

// Worker is already consuming messages

// Clean up when needed
// await worker.close().get();

Advanced Features

For advanced features like prefetch configuration and automatic retry, see the Consume Messages Guide.

Retry configuration

Retry is configured at the queue level in your contract definition. Add retry to your queue definition:

import { defineExchange, defineQueue, defineQueueBinding } from "@amqp-contract/contract";

const dlx = defineExchange("orders-dlx");

// Configure retry at queue level
const orderQueue = defineQueue("order-processing", {
  deadLetter: { exchange: dlx },
  retry: {
    mode: "ttl-backoff",
    maxRetries: 3, // Retry up to 3 times (default: 3)
    initialDelayMs: 1000, // Start with 1 second delay (default: 1000)
    maxDelayMs: 30000, // Max 30 seconds between retries (default: 30000)
    backoffMultiplier: 2, // Double the delay each time (default: 2)
    jitter: true, // Add randomness to prevent thundering herd (default: true)
  },
});

// A dead-letter exchange with nothing bound to it discards every rejected
// message, and `defineContract` rejects that. Declare the dead-letter queue and
// bind it; `orders-dlx` is topic, so `#` catches whatever routing key the
// message arrived with.
const orderDlq = defineQueue("order-processing-dlq");
const orderDlqBinding = defineQueueBinding(orderDlq, dlx, { routingKey: "#" });

// …then pass both through:
//   defineContract({ …, queues: { orderDlq }, bindings: { orderDlqBinding } })

Then use RetryableError in your handlers:

import { TypedAmqpWorker, RetryableError } from "@amqp-contract/worker";
import { fromPromise } from "unthrown";

const worker = await TypedAmqpWorker.create({
  contract,
  handlers: {
    processOrder: ({ input: { payload } }) =>
      // If this fails with RetryableError, message is automatically retried
      fromPromise(
        processPayment(payload),
        (error) => new RetryableError("Payment failed", error),
      ).map(() => undefined),
  },
  urls: ["amqp://localhost"],
}).getOrThrow();

See Retry Failed Messages for complete details.

RPC handlers never retry: a RetryableError from one dead-letters the request, since the caller has stopped waiting long before a backoff ends.

Connection and topology options

  • topology: "assert" | "passive" | "none" — declare the worker's slice of the contract (its consumed queues with their bindings, retry wait queues, dead-letter exchanges and DLQs), only check it exists, or touch nothing. Default "assert".
  • connection — an AmqpConnectionManager you own, instead of urls; borrowed, never closed. With urls, the worker uses its own connection pool and never shares a TCP connection with a client.
  • maxMessageBytes — cap on an inbound body, plain or decompressed (default 16 MiB); over-cap messages are dead-lettered. Replaces the deprecated maxDecompressedBytes.
  • rpc.allowReplyTo — predicate for the replyTo addresses an RPC handler may answer (default: direct reply-to only); a refused request is dead-lettered.
  • worker.isConnected() — whether the broker connection is up, for readiness probes.

Defining Handlers Externally

You can define handlers outside of the worker creation using declareHandler and declareHandlers for better code organization. See the Worker API documentation for details.

Error Handling

Worker handlers return AsyncResult<void, HandlerError> for explicit error handling:

import { RetryableError, NonRetryableError } from "@amqp-contract/worker";
import { ErrAsync, fromPromise } from "unthrown";

handlers: {
  processOrder: ({ input: { payload } }) => {
    // Validation errors - non-retryable
    if (payload.amount <= 0) {
      return ErrAsync(new NonRetryableError("Invalid amount"));
    }

    // Transient errors - retryable
    return fromPromise(process(payload), (error) => new RetryableError("Processing failed", error))
      .map(() => undefined);
  },
}

Error Types:

Worker defines error classes:

  • MessageValidationError - Message fails schema validation (a modeled Err)
  • RetryableError - Signals that the error is transient and should be retried
  • NonRetryableError - Signals permanent failure, message is sent to DLQ (if configured) or dropped
  • TechnicalError - Runtime failures (parsing, processing), surfaced as a defect (handled in the defect arm of match, or via recoverDefect / tapDefect), never a modeled error

API

For complete API documentation, see the Worker API Reference.

Documentation

📖 Read the full documentation →

License

MIT