-
Notifications
You must be signed in to change notification settings - Fork 1
/
providers.ts
96 lines (87 loc) · 2.72 KB
/
providers.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import {
ChangeMessageVisibilityCommand,
DeleteMessageCommand,
ReceiveMessageCommand
} from '@aws-sdk/client-sqs';
import AbstractProvider from '../../providers';
import { calculateBackoffMultiplier } from '../../utils';
import { BaseSQS } from './base';
import {
DEFAULT_MAX_NUMBER_OF_MESSAGES,
DEFAULT_VISIBILITY_TIMEOUT,
DEFAULT_WAIT_TIME_SECONDS
} from './constants';
import { SQSClientOptions } from './types';
export class SQSProvider extends AbstractProvider {
queueName: string;
clientOptions: SQSClientOptions;
client: BaseSQS;
constructor(queueName: string, clientOptions: SQSClientOptions) {
super();
this.queueName = queueName;
this.clientOptions = clientOptions;
this.client = new BaseSQS(clientOptions);
}
async confirmMessage(message: object) {
const receipt = message['ReceiptHandle'];
const queueUrl = await this.client.queueUrl(this.queueName);
try {
return await this.client.client.send(
new DeleteMessageCommand({
QueueUrl: queueUrl,
ReceiptHandle: receipt
})
);
} catch (error) {
if (error.response && error.response.status === 404) {
return Promise.resolve();
}
throw error;
}
}
async messageNotProcessed(message: object) {
if (!this.clientOptions.backoffFactor) return Promise.resolve();
const backoffMultiplier = calculateBackoffMultiplier(
parseInt(message['Attributes']['ApproximateReceiveCount'], 10),
this.clientOptions.backoffFactor
);
const customVisibilityTimeout = Math.round(
backoffMultiplier * this.clientOptions.visibilityTimeout
);
const queueUrl = await this.client.queueUrl(this.queueName);
const receipt = message['ReceiptHandle'];
try {
return await this.client.client.send(
new ChangeMessageVisibilityCommand({
QueueUrl: queueUrl,
ReceiptHandle: receipt,
VisibilityTimeout: customVisibilityTimeout
})
);
} catch (error) {
if (error.name !== 'InvalidParameterValue') {
return Promise.resolve();
}
throw error;
}
}
async fetchMessages(): Promise<object[]> {
const queueUrl = await this.client.queueUrl(this.queueName);
const messages = await this.client.client.send(
new ReceiveMessageCommand({
QueueUrl: queueUrl,
MaxNumberOfMessages:
this.clientOptions.maxNumberOfMessages ||
DEFAULT_MAX_NUMBER_OF_MESSAGES,
VisibilityTimeout:
this.clientOptions.visibilityTimeout || DEFAULT_VISIBILITY_TIMEOUT,
WaitTimeSeconds:
this.clientOptions.waitTimeSeconds || DEFAULT_WAIT_TIME_SECONDS
})
);
return messages.Messages;
}
stop() {
this.client.stop();
}
}