@fgiova/fastify-sqs-consumer 1.1.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,12 +2,17 @@
2
2
  [![NPM version](https://img.shields.io/npm/v/@fgiova/fastify-sqs-consumer.svg?style=flat)](https://www.npmjs.com/package/@fgiova/fastify-rest-gateway)
3
3
  ![CI workflow](https://github.com/fgiova/fastify-sqs-consumer/actions/workflows/node.js.yml/badge.svg)
4
4
  [![TypeScript](https://img.shields.io/badge/%3C%2F%3E-TypeScript-%230074c1.svg)](http://www.typescriptlang.org/)
5
+ [![Linted with Biome](https://img.shields.io/badge/Linted_with-Biome-60a5fa?style=flat&logo=biome)](https://biomejs.dev)
6
+ [![Maintainability](https://qlty.sh/gh/fgiova/projects/fastify-sqs-consumer/maintainability.svg)](https://qlty.sh/gh/fgiova/projects/fastify-sqs-consumer)
7
+ [![Code Coverage](https://qlty.sh/gh/fgiova/projects/fastify-sqs-consumer/coverage.svg)](https://qlty.sh/gh/fgiova/projects/fastify-sqs-consumer)
8
+
5
9
  ## Description
6
- This plugin for fastify 4.x allows you to consume messages from AWS SQS queues.
10
+ This plugin for fastify 5.x (for fastify 4.x use 1.x ver) allows you to consume messages from AWS SQS queues.
7
11
  On fastify shutdown a simple wait function is called to wait for the end of the processing of the messages in progress.
8
12
 
9
13
  **Warning**<br>
10
- To use this plugin, you must have correctly configured your [AWS credentials](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html).
14
+ To use this plugin, you must have correctly configured your [AWS credentials](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html).<br>
15
+ This plugin uses [@fgiova/mini-sqs-client](https://www.npmjs.com/package/@fgiova/mini-sqs-client) and [@fgiova/sqs-consumer](https://www.npmjs.com/package/@fgiova/sqs-consumer) to interact with SQS service.
11
16
 
12
17
  ## Install
13
18
  ```bash
@@ -19,7 +24,7 @@ const fastify = require("fastify")()
19
24
 
20
25
  fastify.register(require("fastify-sqs-consumer"), [
21
26
  {
22
- url: "https://sqs.us-east-1.amazonaws.com/123456789012/MyQueue",
27
+ arn: "arn:aws:sqs:eu-central-1:000000000000:MyQueue",
23
28
  waitTimeSeconds: 20,
24
29
  timeout: 10_000,
25
30
  batchSize: 10,
@@ -32,17 +37,19 @@ fastify.register(require("fastify-sqs-consumer"), [
32
37
  ### Options
33
38
  Options are an array of objects with the following properties (one more for each queue):
34
39
 
35
- | Option | Type | Description |
36
- |------------------------|-----------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
37
- | url* | string | The URL of the Amazon SQS queue from which messages are received. |
38
- | 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. |
39
- | timeout | number | The duration before the message is considered as failed: default 90000ms. |
40
- | 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. |
41
- | handlerFunction* | function | The function that will be called for each message. |
42
- | messageAttributeNames | string[] | Array of caught message's attributes for each message |
43
- | attributeNames | string[] | Array of caught queue's attributes for each message |
44
- | events | object | Events functions for the consumer (detail in next table) |
45
- | sqs | SQSClient | Initialized SQS Client (useful for testing sessions) |
40
+ | Option | Type | Description |
41
+ |-----------------------|-----------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
42
+ | arn* | string | The ARN of the Amazon SQS queue from which messages are received. |
43
+ | handlerFunction* | function | The function that will be called for each message. |
44
+ | name | string | An optional name for the consumer (useful for add [hooks](https://github.com/fgiova/sqs-consumer?tab=readme-ov-file#hooks) post config). If not provided, uuid is assigned. |
45
+ | 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. |
46
+ | timeout | number | The duration before the message is considered as failed: default 90000ms. |
47
+ | 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. |
48
+ | messageAttributeNames | string[] | Array of caught message's attributes for each message |
49
+ | events | object | Events functions for the consumer (detail in next table) |
50
+ | sqs | SQSClient | Initialized SQS Client (useful for testing sessions) |
51
+
52
+ * required
46
53
 
47
54
  ### handlerFunction
48
55
 
@@ -52,19 +59,17 @@ Otherwise, the message is deleted from the queue.
52
59
 
53
60
  #### Events
54
61
 
55
- | Event name | Arguments | Description |
56
- |-------------------|-----------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------|
57
- | error | error Object | Fired when a general error occurs |
58
- | processingError | error Object, message SQS.Message | Fired when an error occurs pending message handling |
59
- | timeoutError | error Object, message SQS.Message | Fired when processing of message exceed timeout duration<br/> If function return false message are discarded, otherwise message is bounced to queue. |
60
- | messageReceived | message SQS.Message | Fired when message is received |
61
- | messageProcessed | message SQS.Message | Fired when message is successfully processed |
62
- | responseProcessed | void | Fired after one batch of items (up to batchSize) has been successfully processed. |
63
- | stopped | void | Fired when the consumer finally stops its work. |
64
- | empty | void | Fired when the queue is empty (All messages have been consumed). |
62
+ | Option | Type | Description |
63
+ |------------------|-----------------------------------------------------------------------|---------------------------------------------------------------------|
64
+ | onPoll | (messages: Message[]) => Promise<Message[]> | Called when the consumer polls for messages |
65
+ | onMessage | (message: Message) => Promise<Message> | Called when the consumer receives a message |
66
+ | onHandle | (message: Message) => Promise<Message> | Called when the consumer handles a message |
67
+ | onHandlerSuccess | (message: Message) => Promise<Message> | Called when the consumer handles a message successfully |
68
+ | onHandlerTimeout | (message: Message) => Promise<Message> | Called when the consumer handler execution exceed executionTimeout |
69
+ | onHandlerError | (message: Message, error: Error) => Promise<Boolean> | Called when the consumer handler execution throws an error |
70
+ | onSuccess | (message: Message) => Promise<Message> | Called when the consumer handler execution finishes successfully |
71
+ | onError | ( hook: HookName, message: Message, error: Error) => Promise<Boolean> | Called when the consumer handler execution throws an uncaught error |
72
+ | onSQSError | (error: Error, message?: Message) => Promise<void> | Called when the consumer receives an error from the SQS service |
65
73
 
66
74
  ## License
67
75
  Licensed under [MIT](./LICENSE).
68
-
69
- ### Acknowledgements
70
- This project is kindly sponsored by: isendu Srl [www.isendu.com](https://www.isendu.com)
@@ -0,0 +1,23 @@
1
+ import type { Message, MiniSQSClient } from "@fgiova/mini-sqs-client";
2
+ import { type HooksOptions, SQSConsumer } from "@fgiova/sqs-consumer";
3
+ import type { FastifyInstance } from "fastify";
4
+ declare module "fastify" {
5
+ interface FastifyInstance {
6
+ sqsConsumers: Record<string, SQSConsumer>;
7
+ }
8
+ }
9
+ declare function sqsConsumerPlugin(fastify: FastifyInstance, options: {
10
+ arn: string;
11
+ name?: string;
12
+ handlerFunction: (message: Message, fastify: FastifyInstance) => Promise<unknown>;
13
+ timeout?: number;
14
+ waitTimeSeconds?: number;
15
+ batchSize?: number;
16
+ messageAttributeNames?: string[];
17
+ attributeNames?: string[];
18
+ events?: HooksOptions;
19
+ parallelExecution?: boolean;
20
+ sqs?: MiniSQSClient;
21
+ }[], done: (err?: Error) => void): void;
22
+ declare const _default: typeof sqsConsumerPlugin;
23
+ export = _default;
@@ -0,0 +1,94 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ const node_crypto_1 = require("node:crypto");
6
+ const sqs_consumer_1 = require("@fgiova/sqs-consumer");
7
+ const fastify_plugin_1 = __importDefault(require("fastify-plugin"));
8
+ function createConsumer(fastify, queueArn, handlerFunction, meta, timeout = 90000, waitTimeSeconds = 20, batchSize = 1, attributeNames = [], messageAttributeNames = [], parallelExecution, hooks, sqs) {
9
+ return new sqs_consumer_1.SQSConsumer({
10
+ queueARN: queueArn,
11
+ autostart: false,
12
+ consumerOptions: {
13
+ waitTimeSeconds,
14
+ itemsPerRequest: batchSize,
15
+ attributeNames,
16
+ messageAttributeNames,
17
+ visibilityTimeout: timeout / 1000,
18
+ },
19
+ handlerOptions: {
20
+ executionTimeout: timeout,
21
+ parallelExecution,
22
+ },
23
+ hooks,
24
+ clientOptions: {
25
+ sqsClient: sqs,
26
+ },
27
+ handler: async function handleMessageFunction(message) {
28
+ meta.pendingMessages++;
29
+ try {
30
+ await handlerFunction(message, fastify);
31
+ meta.pendingMessages--;
32
+ }
33
+ catch (e) {
34
+ meta.pendingMessages--;
35
+ fastify.log.error(e);
36
+ throw e;
37
+ }
38
+ return;
39
+ },
40
+ });
41
+ }
42
+ function sqsConsumerPlugin(fastify, options, done) {
43
+ const metaData = {
44
+ pendingMessages: 0,
45
+ };
46
+ const consumers = {};
47
+ fastify.decorate("sqsConsumers", consumers);
48
+ for (const handler of options) {
49
+ const { name, arn: queueArn, handlerFunction, timeout, waitTimeSeconds, batchSize, attributeNames, messageAttributeNames, events, sqs, parallelExecution, } = handler;
50
+ try {
51
+ consumers[name || (0, node_crypto_1.randomUUID)()] = createConsumer(fastify, queueArn, handlerFunction, metaData, timeout, waitTimeSeconds, batchSize, attributeNames, messageAttributeNames, parallelExecution, events, sqs);
52
+ } /* c8 ignore next 3 */
53
+ catch (e) {
54
+ fastify.log.error(e);
55
+ }
56
+ }
57
+ fastify.addHook("onReady", (done) => {
58
+ for (const consumer of Object.values(consumers)) {
59
+ consumer.start().catch((e) => fastify.log.error(e));
60
+ }
61
+ done();
62
+ });
63
+ let allStopped = false;
64
+ fastify.addHook("onClose", async (fastify) => {
65
+ const arrayConsumers = Object.values(consumers);
66
+ for (const consumer of arrayConsumers) {
67
+ await consumer.stop();
68
+ }
69
+ const interval = setInterval(() => {
70
+ const isRunning = arrayConsumers.some((consumer) => consumer.isRunning);
71
+ /* c8 ignore next 5 */
72
+ if (isRunning) {
73
+ fastify.log.debug("[fastify-sqs-consumer] Some consumers still running... please wait");
74
+ return null;
75
+ }
76
+ else if (!allStopped) {
77
+ allStopped = true;
78
+ fastify.log.debug("[fastify-sqs-consumer] All consumers are stopped");
79
+ }
80
+ if (metaData.pendingMessages <= 0) {
81
+ clearInterval(interval);
82
+ return done();
83
+ }
84
+ else {
85
+ fastify.log.debug(`[fastify-sqs-consumer] ${metaData.pendingMessages} pending messages`);
86
+ }
87
+ }, 50);
88
+ });
89
+ done();
90
+ }
91
+ module.exports = (0, fastify_plugin_1.default)(sqsConsumerPlugin, {
92
+ name: "fastify-sqs-consumer",
93
+ fastify: ">=5.x",
94
+ });
@@ -0,0 +1,23 @@
1
+ import type { Message, MiniSQSClient } from "@fgiova/mini-sqs-client";
2
+ import { type HooksOptions, SQSConsumer } from "@fgiova/sqs-consumer";
3
+ import type { FastifyInstance } from "fastify";
4
+ declare module "fastify" {
5
+ interface FastifyInstance {
6
+ sqsConsumers: Record<string, SQSConsumer>;
7
+ }
8
+ }
9
+ declare function sqsConsumerPlugin(fastify: FastifyInstance, options: {
10
+ arn: string;
11
+ name?: string;
12
+ handlerFunction: (message: Message, fastify: FastifyInstance) => Promise<unknown>;
13
+ timeout?: number;
14
+ waitTimeSeconds?: number;
15
+ batchSize?: number;
16
+ messageAttributeNames?: string[];
17
+ attributeNames?: string[];
18
+ events?: HooksOptions;
19
+ parallelExecution?: boolean;
20
+ sqs?: MiniSQSClient;
21
+ }[], done: (err?: Error) => void): void;
22
+ declare const _default: typeof sqsConsumerPlugin;
23
+ export = _default;
@@ -0,0 +1,86 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { SQSConsumer } from "@fgiova/sqs-consumer";
3
+ import fp from "fastify-plugin";
4
+ function createConsumer(fastify, queueArn, handlerFunction, meta, timeout = 90000, waitTimeSeconds = 20, batchSize = 1, attributeNames = [], messageAttributeNames = [], parallelExecution, hooks, sqs) {
5
+ return new SQSConsumer({
6
+ queueARN: queueArn,
7
+ autostart: false,
8
+ consumerOptions: {
9
+ waitTimeSeconds,
10
+ itemsPerRequest: batchSize,
11
+ attributeNames,
12
+ messageAttributeNames,
13
+ visibilityTimeout: timeout / 1000,
14
+ },
15
+ handlerOptions: {
16
+ executionTimeout: timeout,
17
+ parallelExecution,
18
+ },
19
+ hooks,
20
+ clientOptions: {
21
+ sqsClient: sqs,
22
+ },
23
+ handler: async function handleMessageFunction(message) {
24
+ meta.pendingMessages++;
25
+ try {
26
+ await handlerFunction(message, fastify);
27
+ meta.pendingMessages--;
28
+ }
29
+ catch (e) {
30
+ meta.pendingMessages--;
31
+ fastify.log.error(e);
32
+ throw e;
33
+ }
34
+ return;
35
+ },
36
+ });
37
+ }
38
+ function sqsConsumerPlugin(fastify, options, done) {
39
+ const metaData = {
40
+ pendingMessages: 0,
41
+ };
42
+ const consumers = {};
43
+ fastify.decorate("sqsConsumers", consumers);
44
+ for (const handler of options) {
45
+ const { name, arn: queueArn, handlerFunction, timeout, waitTimeSeconds, batchSize, attributeNames, messageAttributeNames, events, sqs, parallelExecution, } = handler;
46
+ try {
47
+ consumers[name || randomUUID()] = createConsumer(fastify, queueArn, handlerFunction, metaData, timeout, waitTimeSeconds, batchSize, attributeNames, messageAttributeNames, parallelExecution, events, sqs);
48
+ } /* c8 ignore next 3 */
49
+ catch (e) {
50
+ fastify.log.error(e);
51
+ }
52
+ }
53
+ fastify.addHook("onReady", (done) => {
54
+ for (const consumer of Object.values(consumers)) {
55
+ consumer.start().catch((e) => fastify.log.error(e));
56
+ }
57
+ done();
58
+ });
59
+ let allStopped = false;
60
+ fastify.addHook("onClose", async (fastify) => {
61
+ const arrayConsumers = Object.values(consumers);
62
+ for (const consumer of arrayConsumers) {
63
+ await consumer.stop();
64
+ }
65
+ const interval = setInterval(() => {
66
+ const isRunning = arrayConsumers.some((consumer) => consumer.isRunning);
67
+ /* c8 ignore next 5 */
68
+ if (isRunning) {
69
+ fastify.log.debug("[fastify-sqs-consumer] Some consumers still running... please wait");
70
+ return null;
71
+ }
72
+ else if (!allStopped) {
73
+ allStopped = true;
74
+ fastify.log.debug("[fastify-sqs-consumer] All consumers are stopped");
75
+ }
76
+ if (metaData.pendingMessages <= 0) {
77
+ clearInterval(interval);
78
+ return done();
79
+ }
80
+ else {
81
+ fastify.log.debug(`[fastify-sqs-consumer] ${metaData.pendingMessages} pending messages`);
82
+ }
83
+ }, 50);
84
+ });
85
+ done();
86
+ }
package/package.json CHANGED
@@ -1,18 +1,35 @@
1
1
  {
2
2
  "name": "@fgiova/fastify-sqs-consumer",
3
3
  "description": "sqs-consumer fastify plugin",
4
- "version": "1.1.0",
5
- "main": "dist/index.js",
4
+ "version": "2.0.0",
5
+ "main": "./dist/index.js",
6
+ "types": "./dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "import": {
10
+ "types": "./dist/esm/index.d.mts",
11
+ "default": "./dist/esm/index.mjs"
12
+ },
13
+ "require": {
14
+ "types": "./dist/cjs/index.d.ts",
15
+ "default": "./dist/cjs/index.js"
16
+ }
17
+ }
18
+ },
6
19
  "files": [
7
20
  "dist"
8
21
  ],
9
22
  "scripts": {
10
- "lint": "eslint 'src/**/*.ts'",
11
23
  "clean": "rimraf dist",
12
- "build": "tsc",
13
- "test": "tap -t90 --before=test/scripts/executors/before.js --after=test/scripts/executors/after.js",
14
- "test:local": "TEST_LOCAL=true tap -t90",
15
- "test:debug": "tap -T -O --before=test/scripts/executors/before.js --after=test/scripts/executors/after.js"
24
+ "preBuild": "npm run clean",
25
+ "build": "esmBuilder",
26
+ "lint": "biome ci ./src ./test",
27
+ "fix": "biome check --write ./src ./test",
28
+ "test": "tap --timeout=90",
29
+ "test:debug": "tap --only --timeout=0",
30
+ "test:local": "TEST_LOCAL=true tap",
31
+ "test:local:debug": "TEST_LOCAL=true tap --only --timeout=0",
32
+ "test:coverage": "tap --coverage-report=lcovonly --coverage-report=text"
16
33
  },
17
34
  "repository": {
18
35
  "type": "git",
@@ -32,39 +49,41 @@
32
49
  "access": "public"
33
50
  },
34
51
  "engines": {
35
- "node": ">=18.0.0"
52
+ "node": ">=20.14.1"
36
53
  },
37
54
  "tap": {
38
- "node-arg": "--require=ts-node/register",
39
- "ts": true,
40
- "lines": 100,
41
- "branches": 100,
42
- "statements": 100,
43
- "functions": 100
55
+ "show-full-coverage": true,
56
+ "before": "./test/scripts/executors/before.js",
57
+ "after": "./test/scripts/executors/teardown.js",
58
+ "exclude": [
59
+ "test/helpers/**/*",
60
+ "test/scripts/**/*"
61
+ ]
62
+ },
63
+ "peerDependencies": {
64
+ "fastify": ">=5.0.0",
65
+ "p-map": ">=7.0.0"
44
66
  },
45
67
  "devDependencies": {
46
68
  "@aws-sdk/client-sqs": "^3.398.0",
69
+ "@biomejs/biome": "2.2.2",
70
+ "@fgiova/cjs-esm-ts-builder": "^1.2.0",
47
71
  "@semantic-release/changelog": "^6.0.3",
48
72
  "@semantic-release/git": "^10.0.1",
49
- "@types/node": "^18.17.1",
50
- "@types/tap": "^15.0.5",
51
- "@typescript-eslint/eslint-plugin": "^6.4.1",
52
- "@typescript-eslint/parser": "^6.4.1",
53
- "conventional-changelog-conventionalcommits": "^6.1.0",
54
- "cross-env": "^7.0.3",
73
+ "@tsconfig/node20": "^20.1.6",
74
+ "@types/dotenv": "^6.1.1",
75
+ "@types/node": "^20.19.11",
76
+ "conventional-changelog-conventionalcommits": "^8.0.0",
55
77
  "dotenv": "^10.0.0",
56
- "eslint": "^8.1.0",
57
- "eslint-plugin-import": "^2.25.2",
58
- "fastify": "^4.21.0",
59
- "nodemon": "^2.0.14",
60
- "semantic-release": "^21.1.0",
61
- "tap": "^16.3.8",
62
- "testcontainers": "^10.2.1",
63
- "ts-node": "^10.9.1",
78
+ "fastify": "^5.5.0",
79
+ "semantic-release": "^24.2.3",
80
+ "tap": "^21.1.0",
81
+ "testcontainers": "^11.5.1",
82
+ "ts-node": "^10.9.2",
64
83
  "typescript": "^5.1.6"
65
84
  },
66
85
  "dependencies": {
67
- "fastify-plugin": "^4.5.1",
68
- "sqs-consumer": "^7.2.2"
86
+ "@fgiova/sqs-consumer": "^2.1.1",
87
+ "fastify-plugin": "^5.0.1"
69
88
  }
70
89
  }
package/dist/index.d.ts DELETED
@@ -1,32 +0,0 @@
1
- import { Consumer } from "sqs-consumer";
2
- import type { FastifyInstance } from "fastify";
3
- import type { Message } from "@aws-sdk/client-sqs";
4
- import type { SQSClient } from "@aws-sdk/client-sqs";
5
- declare module "fastify" {
6
- interface FastifyInstance {
7
- sqsConsumers: Consumer[];
8
- }
9
- }
10
- type eventsHandlers = {
11
- error?: (error: Error, message: void | Message | Message[]) => void;
12
- processingError?: (error: Error, message: Message) => void;
13
- timeoutError?: (error: Error, message: Message) => void | boolean;
14
- messageReceived?: (message: Message) => void;
15
- messageProcessed?: (message: Message) => void;
16
- responseProcessed?: () => void;
17
- stopped?: () => void;
18
- empty?: () => void;
19
- };
20
- declare function sqsConsumerPlugin(fastify: FastifyInstance, options: {
21
- queueUrl: string;
22
- handlerFunction: (message: Message, fastify: FastifyInstance) => Promise<any>;
23
- timeout?: number;
24
- waitTimeSeconds?: number;
25
- batchSize?: number;
26
- attributeNames?: string[];
27
- messageAttributeNames?: string[];
28
- events?: eventsHandlers;
29
- sqs?: SQSClient;
30
- }[], done: any): void;
31
- declare const _default: typeof sqsConsumerPlugin;
32
- export = _default;
package/dist/index.js DELETED
@@ -1,134 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- const fastify_plugin_1 = __importDefault(require("fastify-plugin"));
6
- const sqs_consumer_1 = require("sqs-consumer");
7
- const promises_1 = require("timers/promises");
8
- ;
9
- function createConsumer(fastify, queueUrl, handlerFunction, meta, timeout = 90000, waitTimeSeconds = 20, batchSize = 1, attributeNames = [], messageAttributeNames = [], events, sqs) {
10
- return sqs_consumer_1.Consumer.create({
11
- queueUrl,
12
- handleMessageTimeout: 0,
13
- waitTimeSeconds,
14
- visibilityTimeout: timeout / 1000,
15
- batchSize,
16
- sqs,
17
- attributeNames,
18
- messageAttributeNames,
19
- handleMessage: async function handleMessageFunction(message) {
20
- meta.pendingMessages++;
21
- try {
22
- const result = await Promise.race([
23
- (0, promises_1.setTimeout)(timeout, "timeout"),
24
- handlerFunction(message, fastify),
25
- ]);
26
- if (result === "timeout") {
27
- const TimeoutError = new Error(`Message ${message.MessageId} Timeout after ${timeout}ms`);
28
- if (events?.timeoutError && typeof events.timeoutError === "function") {
29
- const timeout = events.timeoutError(TimeoutError, message);
30
- /* istanbul ignore else */
31
- if (timeout === false) {
32
- meta.pendingMessages--;
33
- return;
34
- }
35
- }
36
- throw TimeoutError;
37
- }
38
- meta.pendingMessages--;
39
- }
40
- catch (e) {
41
- meta.pendingMessages--;
42
- fastify.log.error(e);
43
- throw e;
44
- }
45
- return;
46
- }
47
- })
48
- .on("error", (err, message) => {
49
- /* istanbul ignore else */
50
- if (events?.error) {
51
- events.error(err, message);
52
- }
53
- else {
54
- fastify.log.error(`[fastify-sqs-consumer] ${err.message}`);
55
- }
56
- })
57
- .on("processing_error", (err, message) => {
58
- /* istanbul ignore else */
59
- if (events?.processingError) {
60
- events.processingError(err, message);
61
- }
62
- else {
63
- fastify.log.error(`[fastify-sqs-consumer] ${err.message}`);
64
- }
65
- })
66
- .on("message_received", (message) => {
67
- if (events?.messageReceived)
68
- events.messageReceived(message);
69
- })
70
- .on("message_processed", (message) => {
71
- if (events?.messageProcessed)
72
- events.messageProcessed(message);
73
- })
74
- .on("response_processed", () => {
75
- if (events?.responseProcessed)
76
- events.responseProcessed();
77
- }).on("stopped", () => {
78
- if (events?.stopped)
79
- events.stopped();
80
- })
81
- .on("empty", () => {
82
- /* istanbul ignore next */
83
- if (events?.empty)
84
- events.empty();
85
- });
86
- }
87
- function sqsConsumerPlugin(fastify, options, done) {
88
- const metaData = {
89
- pendingMessages: 0
90
- };
91
- const consumers = [];
92
- fastify.decorate("sqsConsumers", consumers);
93
- for (const handler of options) {
94
- const { queueUrl, handlerFunction, timeout, waitTimeSeconds, batchSize, attributeNames, messageAttributeNames, events, sqs } = handler;
95
- consumers.push(createConsumer(fastify, queueUrl, handlerFunction, metaData, timeout, waitTimeSeconds, batchSize, attributeNames, messageAttributeNames, events, sqs));
96
- }
97
- fastify.addHook("onReady", (done) => {
98
- for (const consumer of consumers) {
99
- consumer.start();
100
- }
101
- done();
102
- });
103
- let allStopped = false;
104
- fastify.addHook("onClose", (fastify, done) => {
105
- for (const consumer of consumers) {
106
- consumer.stop();
107
- consumer.removeAllListeners();
108
- }
109
- const interval = setInterval(() => {
110
- const isRunning = consumers.some((consumer) => consumer.isRunning);
111
- /* istanbul ignore next */
112
- if (isRunning) {
113
- fastify.log.debug("[fastify-sqs-consumer] Some consumers still running... please wait");
114
- return null;
115
- }
116
- else if (!allStopped) {
117
- allStopped = true;
118
- fastify.log.debug("[fastify-sqs-consumer] All consumers are stopped");
119
- }
120
- if (metaData.pendingMessages <= 0) {
121
- clearInterval(interval);
122
- return done();
123
- }
124
- else {
125
- fastify.log.debug(`[fastify-sqs-consumer] ${metaData.pendingMessages} pending messages`);
126
- }
127
- }, 50);
128
- });
129
- done();
130
- }
131
- module.exports = (0, fastify_plugin_1.default)(sqsConsumerPlugin, {
132
- name: "fastify-sqs-consumer",
133
- fastify: ">=4.x"
134
- });