npm.io
3.5.0 • Published 2 weeks ago

@fgiova/fastify-sqs-consumer

Licence
MIT
Version
3.5.0
Deps
3
Size
32 kB
Vulns
0
Weekly
0
Stars
5

fastify sqs-consumer

NPM version CI workflow TypeScript Linted with Biome Maintainability Code Coverage

Description

This plugin for fastify 5.x (for fastify 4.x use 1.x ver) allows you to consume messages from AWS SQS queues. On fastify shutdown a simple wait function is called to wait for the end of the processing of the messages in progress.

Warning
To use this plugin, you must have correctly configured your AWS credentials.
This plugin uses @fgiova/mini-sqs-client and @fgiova/sqs-consumer to interact with SQS service.

Install

npm i @fgiova/fastify-sqs-consumer

Usage

ESM
import fastify from "fastify";
import sqsConsumer from "@fgiova/fastify-sqs-consumer";

const app = fastify();

app.register(sqsConsumer, [
    {
        arn: "arn:aws:sqs:eu-central-1:000000000000:MyQueue",
        waitTimeSeconds: 20,
        timeout: 10_000,
        batchSize: 10,
        handlerFunction: async (message, fastify) => {
            return true;
        }
    }
]);
CommonJS
const fastify = require("fastify")();

fastify.register(require("@fgiova/fastify-sqs-consumer").default, [
    {
        arn: "arn:aws:sqs:eu-central-1:000000000000:MyQueue",
        waitTimeSeconds: 20,
        timeout: 10_000,
        batchSize: 10,
        handlerFunction: async (message, fastify) => {
            return true;
        }
    }
]);

Options

Options are an array of objects with the following properties (one for each queue):

Option Type Description
arn* string The ARN of the Amazon SQS queue from which messages are received.
handlerFunction* function The function that will be called for each message.
name string An optional name for the consumer (useful for add hooks post config). If not provided, uuid is assigned.
waitTimeSeconds number The duration (in seconds, default 20s) for which the call waits for a message to arrive in the queue before returning. If a message is available, the call returns sooner than WaitTimeSeconds. If no messages are available and the wait time expires, the call returns successfully with an empty list of messages.
timeout number The duration before the message is considered as failed: default 90000ms.
batchSize number The maximum number of messages to return. Amazon SQS never returns more messages than this value (however, fewer messages might be returned). Valid values: 1 to 10. Default: 1.
attributeNames string[] Array of message system attributes to retrieve for each message.
messageAttributeNames string[] Array of custom message attributes to retrieve for each message.
parallelExecution boolean Enable parallel execution of message handlers.
credentials {accessKeyId, secretAccessKey} Explicit AWS credentials (alternative to environment configuration).
backoff number | (attempt: number, message: Message) => number Delay (in seconds, 0-43200) before a failed message becomes visible again. A number sets a fixed delay; a function receives the attempt number (ApproximateReceiveCount, requested automatically) and the message, and returns the delay. Default: 0 (immediate retry).
maxRetries number | (attempt: number, message: Message) => number Maximum receive count before giving up on a failed message. When ApproximateReceiveCount (requested automatically) reaches this value, the onMaxReceiveCountExceeded event is fired and the message is deleted unless the event returns false (also when no event is registered). A function receives the attempt number and the message, and returns the limit. Default: unlimited.
events object Events functions for the consumer (detail in next table).
sqs MiniSQSClient | SQSOptions Either an initialized @fgiova/mini-sqs-client instance (useful for testing sessions) or an options object used to build the client (see below).

* required

sqs options object

Instead of passing a pre-built MiniSQSClient, you can pass an options object so the plugin builds the client for you:

Option Type Description
endpoint string Custom SQS endpoint (e.g. a local LocalStack/ElasticMQ instance).
undiciOptions Pool.Options undici Pool options for the underlying HTTP client.
credentials {accessKeyId, secretAccessKey} Explicit AWS credentials. The top-level credentials option takes precedence over this one.
app.register(sqsConsumer, [
    {
        arn: "arn:aws:sqs:eu-central-1:000000000000:MyQueue",
        sqs: {
            endpoint: "http://localhost:4566",
            undiciOptions: { connections: 1 },
            credentials: {
                accessKeyId: "AWS_ACCESS_KEY_ID",
                secretAccessKey: "AWS_SECRET_ACCESS_KEY"
            }
        },
        handlerFunction: async (message, fastify) => {
            return true;
        }
    }
]);

Decorators

sqsConsumers

sqsConsumers is a Record<string, { consumer: SQSConsumer, meta: { pendingMessages: number }, ownedClient?: MiniSQSClient }> that provides access to the registered consumers and their metadata, keyed by consumer name. It is a null-prototype object (Object.create(null)): use Object.hasOwn(app.sqsConsumers, name) or name in app.sqsConsumers instead of app.sqsConsumers.hasOwnProperty(name).

The consumer lifecycle (start/stop) is managed by the plugin: do not call start() or stop() on these instances directly.

addSQSConsumer

addSQSConsumer(options: ConsumerOptions): string | null adds a consumer at runtime. options accepts the same object used for each entry of the plugin options array (see Options); the ConsumerOptions type is exported by the package.

  • Returns the consumer name (the generated uuid when name is not provided), or null if the consumer was not created.
  • Before the server is ready, the consumer is started together with the others in the onReady hook; after that, it is started immediately.
  • Returns null (and logs a warning) when a consumer with the same name already exists or when the server is closing.
import fastify from "fastify";
import sqsConsumer from "@fgiova/fastify-sqs-consumer";

const app = fastify();
await app.register(sqsConsumer, []);
await app.listen({ port: 3000 });

const name = app.addSQSConsumer({
    arn: "arn:aws:sqs:eu-central-1:000000000000:MyOtherQueue",
    handlerFunction: async (message, fastify) => {
        return true;
    }
});

handlerFunction

Handler function is an async function called for each message received from the queue. Each Error thrown by the function is caught and the message is not deleted from the queue. Otherwise, the message is deleted from the queue.

Events
Option Type Description
onPoll (messages: Message[]) => Promise<Message[]> Called when the consumer polls for messages
onMessage (message: Message) => Promise Called when the consumer receives a message
onHandle (message: Message) => Promise Called when the consumer handles a message
onHandlerSuccess (message: Message) => Promise Called when the consumer handles a message successfully
onHandlerTimeout (message: Message) => Promise Called when the consumer handler execution exceed executionTimeout
onHandlerError (message: Message, error: Error) => Promise Called when the consumer handler execution throws an error
onMaxReceiveCountExceeded (message: Message, count: number) => Promise Called when a failed message reaches maxRetries; return false to keep it (released with the usual backoff)
onSuccess (message: Message) => Promise Called when the consumer handler execution finishes successfully
onError ( hook: HookName, message: Message, error: Error) => Promise Called when the consumer handler execution throws an uncaught error
onSQSError (error: Error, message?: Message) => Promise Called when the consumer receives an error from the SQS service

License

Licensed under MIT.

Keywords