├── CHANGELOG.md ├── CONTRIBUTORS.md ├── .mocharc.yml ├── .whitesource ├── src ├── Utils.ts ├── test │ ├── stubs │ │ ├── SquissStub.ts │ │ ├── S3Stub.ts │ │ └── SQSStub.ts │ ├── setup.ts │ └── src │ │ ├── gzipUtils.spec.ts │ │ ├── messageSizeUtils.spec.ts │ │ ├── TimeoutExtender.spec.ts │ │ ├── Message.spec.ts │ │ └── index.spec.ts ├── index.ts ├── gzipUtils.ts ├── messageSizeUtils.ts ├── s3Utils.ts ├── attributeUtils.ts ├── EventEmitterTypesHelper.ts ├── Types.ts ├── TimeoutExtender.ts ├── Message.ts └── Squiss.ts ├── e2e ├── docker-compose.yml └── flow.ts ├── tsconfig.json ├── .github ├── ISSUE_TEMPLATE │ ├── feature_request.md │ └── bug_report.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ └── ci.yml ├── .gitignore ├── .npmignore ├── package.json ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── README.md ├── eslint.config.js └── LICENSE /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Squiss-TS Change Log 2 | 3 | Please see here 4 | -------------------------------------------------------------------------------- /CONTRIBUTORS.md: -------------------------------------------------------------------------------- 1 | # Squiss-TS contributors 2 | 3 | Please see here 4 | -------------------------------------------------------------------------------- /.mocharc.yml: -------------------------------------------------------------------------------- 1 | require: 2 | - 'ts-node/register' 3 | - 'source-map-support/register' 4 | - 'src/test/setup.ts' 5 | recursive: true 6 | reporter: 'spec' 7 | exit: true 8 | spec: 9 | - 'src/test/**/*.ts' 10 | -------------------------------------------------------------------------------- /.whitesource: -------------------------------------------------------------------------------- 1 | { 2 | "scanSettings": { 3 | "baseBranches": [] 4 | }, 5 | "checkRunSettings": { 6 | "vulnerableCheckRunConclusionLevel": "failure", 7 | "displayMode": "diff" 8 | }, 9 | "issueSettings": { 10 | "minSeverityLevel": "LOW" 11 | } 12 | } -------------------------------------------------------------------------------- /src/Utils.ts: -------------------------------------------------------------------------------- 1 | export const removeEmptyKeys = (obj: T): T => { 2 | (Object.keys(obj) as (keyof typeof obj)[]).forEach((key) => { 3 | if (obj[key] === undefined) { 4 | delete obj[key]; 5 | } 6 | }); 7 | return obj; 8 | }; 9 | -------------------------------------------------------------------------------- /src/test/stubs/SquissStub.ts: -------------------------------------------------------------------------------- 1 | import {EventEmitter} from 'events'; 2 | 3 | export class SquissStub extends EventEmitter { 4 | public changeMessageVisibility() { 5 | return Promise.resolve(); 6 | } 7 | public handledMessage() { 8 | return Promise.resolve(); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /e2e/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | services: 3 | queue: 4 | image: softwaremill/elasticmq 5 | ports: 6 | - "9324:9324" 7 | - "9325:9325" 8 | 9 | s3: 10 | image: scireum/s3-ninja 11 | ports: 12 | - "9000:9000" 13 | environment: 14 | root: elasticmq 15 | initialBuckets: test 16 | 17 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | /* istanbul ignore file */ 2 | import {SQS, QueueAttributeName} from '@aws-sdk/client-sqs' 3 | export {SQS, QueueAttributeName} 4 | import {S3} from '@aws-sdk/client-s3' 5 | export {S3} 6 | export {Squiss} from './Squiss'; 7 | export { 8 | BodyFormat, 9 | IMessageDeletedEventPayload, 10 | IMessageDeleteErrorEventPayload, 11 | IMessageErrorEventPayload, 12 | IMessageS3EventPayload, 13 | IMessageToSend, 14 | IObject, 15 | ISendMessageRequest, 16 | ISquissOptions, 17 | } from './Types'; 18 | export {IMessageAttributes} from './attributeUtils'; 19 | export {Message} from './Message'; 20 | -------------------------------------------------------------------------------- /src/test/setup.ts: -------------------------------------------------------------------------------- 1 | import * as chai from 'chai'; 2 | // @ts-ignore 3 | import * as dirtyChai from 'dirty-chai'; 4 | import * as chaiAsPromised from 'chai-as-promised'; 5 | import * as path from 'path'; 6 | // @ts-ignore 7 | import * as mod from 'module'; 8 | // @ts-ignore 9 | import * as sinon from 'sinon'; 10 | // @ts-ignore 11 | import * as sinonChai from 'sinon-chai'; 12 | 13 | chai.use(sinonChai); 14 | chai.use(chaiAsPromised); 15 | chai.use(dirtyChai); 16 | 17 | (global as any).should = chai.should(); 18 | (global as any).sinon = sinon; 19 | 20 | // importing files with ../../../../../.. makes my brain hurt 21 | process.env.NODE_PATH = path.join(__dirname, '..') + path.delimiter + (process.env.NODE_PATH || ''); 22 | // @ts-ignore 23 | mod._initPaths(); 24 | -------------------------------------------------------------------------------- /src/gzipUtils.ts: -------------------------------------------------------------------------------- 1 | import {brotliCompress, brotliDecompress} from 'zlib'; 2 | import {promisify }from 'util'; 3 | 4 | const compress =promisify(brotliCompress); 5 | const decompress= promisify(brotliDecompress); 6 | 7 | export const GZIP_MARKER = '__SQS_GZIP__'; 8 | 9 | export const compressMessage = (message: string): Promise => { 10 | return compress(Buffer.from(message)) 11 | .then((buffer): Promise => { 12 | return Promise.resolve(Buffer.from(buffer).toString('base64')); 13 | }); 14 | }; 15 | 16 | export const decompressMessage = (body: string): Promise => { 17 | return decompress(Buffer.from(body, 'base64')) 18 | .then((bufferUnziped) => { 19 | return Promise.resolve(bufferUnziped.toString('utf8')); 20 | }); 21 | }; 22 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES2020", 4 | "module": "commonjs", 5 | "moduleResolution": "node", 6 | "declaration": true, 7 | "checkJs": false, 8 | "allowJs": false, 9 | "outDir": "./dist", 10 | "strict": true, 11 | "noImplicitAny": true, 12 | "noImplicitThis": true, 13 | "noUnusedLocals": true, 14 | "noUnusedParameters": false, 15 | "noImplicitReturns": true, 16 | "resolveJsonModule": true, 17 | "strictFunctionTypes": true, 18 | "alwaysStrict": true, 19 | "noImplicitUseStrict": false, 20 | "preserveSymlinks": true, 21 | "rootDir": "src", 22 | "sourceMap": true, 23 | "lib": [ 24 | "ES2022", 25 | "dom" 26 | ] 27 | }, 28 | "include": [ 29 | "src/**/*.ts" 30 | ], 31 | "exclude": [ 32 | "dist" 33 | ] 34 | } 35 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: enhancement 6 | assignees: regevbr 7 | 8 | --- 9 | 10 | 13 | **Is your feature request related to a problem? Please describe.** 14 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 15 | 16 | **Describe the solution you'd like** 17 | A clear and concise description of what you want to happen. 18 | 19 | **Describe alternatives you've considered** 20 | A clear and concise description of any alternative solutions or features you've considered. 21 | 22 | **Additional context** 23 | Add any other context or screenshots about the feature request here. 24 | -------------------------------------------------------------------------------- /src/test/src/gzipUtils.spec.ts: -------------------------------------------------------------------------------- 1 | import {decompressMessage, compressMessage} from '../../gzipUtils'; 2 | 3 | describe('gzip utils', () => { 4 | 5 | it('should compress message', () => { 6 | return compressMessage('{"i": 1}') 7 | .then((gzipped) => { 8 | gzipped.should.eql('iwOAeyJpIjogMX0D'); 9 | }); 10 | }); 11 | 12 | it('should decompress message', () => { 13 | return decompressMessage('iwOAeyJpIjogMX0D') 14 | .then((parsed) => { 15 | parsed.should.eql('{"i": 1}'); 16 | }); 17 | }); 18 | 19 | it('compressed and decompressed valued should be equal', () => { 20 | const message = '{"i": 1}'; 21 | return compressMessage(message) 22 | .then((gzipped) => { 23 | return decompressMessage(gzipped); 24 | }) 25 | .then((parsed) => { 26 | parsed.should.eql(message); 27 | }); 28 | }); 29 | }); 30 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 9 | **Summary** 10 | 11 | 12 | 13 | This PR fixes/implements the following **bugs/features** 14 | 15 | * [ ] Bug 1 16 | * [ ] Bug 2 17 | * [ ] Feature 1 18 | * [ ] Feature 2 19 | * [ ] Breaking changes 20 | 21 | 22 | 23 | Explain the **motivation** for making this change. What existing problem does the pull request solve? 24 | 25 | 26 | 27 | **Test plan (required)** 28 | 29 | 30 | -------------------------------------------------------------------------------- /src/test/src/messageSizeUtils.spec.ts: -------------------------------------------------------------------------------- 1 | import {getMessageSize} from '../../messageSizeUtils'; 2 | 3 | describe('message size utils', () => { 4 | 5 | it('should get message size with no attributes', () => { 6 | getMessageSize({ 7 | MessageBody: 'sss', 8 | }).should.eql(3); 9 | }); 10 | 11 | it('should get message size with attributes', () => { 12 | getMessageSize({ 13 | MessageBody: 'sss', 14 | MessageAttributes: { 15 | a: { 16 | StringValue: 'b', 17 | DataType: 'String', 18 | }, 19 | }, 20 | }).should.eql(11); 21 | }); 22 | 23 | it('should get message size with attributes and not count non enumerable values', () => { 24 | function DummyConstructor() { 25 | // @ts-ignore 26 | this.a = { 27 | StringValue: 'b', 28 | DataType: 'String', 29 | }; 30 | } 31 | 32 | DummyConstructor.prototype.pAttr = 1; 33 | // @ts-ignore 34 | const attributes: any = new DummyConstructor(); 35 | getMessageSize({ 36 | MessageBody: 'sss', 37 | // tslint-disable-next-line 38 | MessageAttributes: attributes, 39 | }).should.eql(11); 40 | }); 41 | 42 | }); 43 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | packages 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | package-lock.json 14 | 15 | # Directory for instrumented libs generated by jscoverage/JSCover 16 | lib-cov 17 | 18 | # Coverage directory used by tools like istanbul 19 | coverage 20 | 21 | # nyc test coverage 22 | .nyc_output 23 | 24 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 25 | .grunt 26 | 27 | # Bower dependency directory (https://bower.io/) 28 | bower_components 29 | 30 | # node-waf configuration 31 | .lock-wscript 32 | 33 | # Compiled binary addons (http://nodejs.org/api/addons.html) 34 | build/Release 35 | 36 | # Dependency directories 37 | node_modules/ 38 | .idea/ 39 | dist/ 40 | build/ 41 | jspm_packages/ 42 | 43 | # Typescript v1 declaration files 44 | typings/ 45 | 46 | # Optional npm cache directory 47 | .npm 48 | 49 | # Optional eslint cache 50 | .eslintcache 51 | 52 | # Optional REPL history 53 | .node_repl_history 54 | 55 | # Output of 'npm pack' 56 | *.tgz 57 | 58 | # Yarn Integrity file 59 | .yarn-integrity 60 | 61 | # dotenv environment variables file 62 | .env 63 | -------------------------------------------------------------------------------- /src/messageSizeUtils.ts: -------------------------------------------------------------------------------- 1 | import {ISendMessageRequest} from './index'; 2 | import {MessageBodyAttributeMap} from './Types'; 3 | 4 | export const getMessageSize = (message: ISendMessageRequest): number => { 5 | const msgAttributesSize = getMsgAttributesSize(message.MessageAttributes); 6 | const msgBodySize = getSizeInBytes(message.MessageBody); 7 | return msgAttributesSize + msgBodySize; 8 | }; 9 | 10 | export const getSizeInBytes = (obj?: string | NodeJS.TypedArray | DataView | ArrayBuffer | SharedArrayBuffer) 11 | : number => { 12 | return obj ? Buffer.byteLength(obj) : 0; 13 | }; 14 | 15 | const getMsgAttributesSize = (attributes?: MessageBodyAttributeMap): number => { 16 | let totalMsgAttributesSize = 0; 17 | attributes = attributes || {}; 18 | for (const attribute in attributes) { 19 | if (Object.hasOwn(attributes, attribute)) { 20 | totalMsgAttributesSize += getSizeInBytes(attribute); 21 | const val = attributes[attribute]; 22 | totalMsgAttributesSize += getSizeInBytes(val.DataType); 23 | totalMsgAttributesSize += getSizeInBytes(val.StringValue); 24 | // @ts-ignore 25 | totalMsgAttributesSize += getSizeInBytes(val.BinaryValue); 26 | } 27 | } 28 | return totalMsgAttributesSize; 29 | }; 30 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: bug 6 | assignees: regevbr 7 | 8 | --- 9 | 10 | 13 | ## Expected Behavior 14 | 15 | 16 | 17 | ## Current Behavior 18 | 19 | 20 | 21 | ## Possible Solution 22 | 23 | 24 | 25 | ## Steps to Reproduce (for bugs) 26 | 27 | 28 | 1. 29 | 2. 30 | 3. 31 | 4. 32 | 33 | ## Context 34 | 35 | 36 | 37 | ## Your Environment 38 | 39 | * Version used: 40 | * Node version: 41 | 42 | -------------------------------------------------------------------------------- /src/s3Utils.ts: -------------------------------------------------------------------------------- 1 | import {S3} from '@aws-sdk/client-s3'; 2 | import { v4 as uuidv4 } from 'uuid'; 3 | import {getSizeInBytes} from './messageSizeUtils'; 4 | import {Readable} from 'stream'; 5 | 6 | export const S3_MARKER = '__SQS_S3__'; 7 | 8 | export interface IS3Upload { 9 | bucket: string; 10 | key: string; 11 | uploadSize: number; 12 | } 13 | 14 | export const uploadBlob = (s3: S3, bucket: string, blob: string, prefix: string): Promise => { 15 | const key = `${prefix}${uuidv4()}`; 16 | const size = getSizeInBytes(blob); 17 | return s3.putObject({ 18 | Body: blob, 19 | Bucket: bucket, 20 | Key: key, 21 | ContentLength: size, 22 | }) 23 | .then(() => { 24 | return Promise.resolve({ 25 | uploadSize: size, 26 | bucket, 27 | key, 28 | }); 29 | }); 30 | }; 31 | 32 | export const getBlob = async (s3: S3, uploadData: IS3Upload): Promise => { 33 | const key = uploadData.key; 34 | const bucket = uploadData.bucket; 35 | const s3Result = await s3.getObject({ 36 | Key: key, 37 | Bucket: bucket, 38 | }); 39 | const s3ResponseStream = s3Result.Body as Readable; 40 | const chunks: any[] = []; 41 | for await (const chunk of s3ResponseStream) { 42 | chunks.push(chunk); 43 | } 44 | return Buffer.concat(chunks).toString('utf-8'); 45 | }; 46 | 47 | export const deleteBlob = (s3: S3, uploadData: IS3Upload): Promise => { 48 | const key = uploadData.key; 49 | const bucket = uploadData.bucket; 50 | return s3.deleteObject({ 51 | Key: key, 52 | Bucket: bucket, 53 | }) 54 | .then(() => { 55 | return Promise.resolve(); 56 | }); 57 | }; 58 | -------------------------------------------------------------------------------- /src/test/stubs/S3Stub.ts: -------------------------------------------------------------------------------- 1 | import {EventEmitter} from 'events'; 2 | import { 3 | DeleteObjectOutput, 4 | DeleteObjectRequest, 5 | GetObjectCommandInput, 6 | GetObjectOutput, 7 | PutObjectCommandInput, 8 | PutObjectOutput 9 | } from '@aws-sdk/client-s3'; 10 | import {Readable} from 'stream'; 11 | 12 | export interface Blobs { 13 | [k: string]: { [k: string]: string }; 14 | } 15 | 16 | export class S3Stub extends EventEmitter { 17 | 18 | private blobs: Blobs; 19 | 20 | constructor(blobs?: Blobs) { 21 | super(); 22 | this.blobs = blobs || {}; 23 | } 24 | 25 | public getObject({Key, Bucket}: GetObjectCommandInput): Promise { 26 | if (Bucket && Key && this.blobs[Bucket]?.[Key]) { 27 | const body = new Readable(); 28 | body.push(this.blobs[Bucket][Key]); 29 | body.push(null); 30 | return Promise.resolve({Body: body }); 31 | } else { 32 | return Promise.reject(new Error('Blob doesnt exist')); 33 | } 34 | } 35 | 36 | public putObject({Key, Bucket, Body}: PutObjectCommandInput): Promise { 37 | if (Bucket && !this.blobs[Bucket]) { 38 | this.blobs[Bucket] = {}; 39 | } 40 | if (Bucket && Key) { 41 | // @ts-ignore 42 | this.blobs[Bucket][Key] = Body; 43 | } 44 | return Promise.resolve({}); 45 | } 46 | 47 | public deleteObject({Key, Bucket}: DeleteObjectRequest): Promise { 48 | if (Bucket && Key && this.blobs[Bucket]?.[Key]) { 49 | delete this.blobs[Bucket][Key]; 50 | return Promise.resolve({}); 51 | } else { 52 | return Promise.reject(new Error('Blob doesnt exist')); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### Node template 3 | # Logs 4 | logs 5 | *.log 6 | npm-debug.log* 7 | yarn-debug.log* 8 | yarn-error.log* 9 | 10 | # Runtime data 11 | pids 12 | *.pid 13 | *.seed 14 | *.pid.lock 15 | 16 | # Directory for instrumented libs generated by jscoverage/JSCover 17 | lib-cov 18 | 19 | # Coverage directory used by tools like istanbul 20 | coverage 21 | 22 | # source files 23 | src 24 | test 25 | scripts 26 | src/test/ 27 | CHANGELOG.md 28 | 29 | # source maps 30 | 31 | **/*.js.map 32 | **/*.spec.* 33 | 34 | # config files 35 | tslint.json 36 | .gitignore 37 | .npmignore 38 | cc-test-reporter 39 | .editorconfig 40 | .jscs 41 | .jshintrc 42 | .prettierrc 43 | .gitlab-ci.yml 44 | tsconfig.json 45 | .github 46 | CONTRIBUTING.md 47 | CODE_OF_CONDUCT.md 48 | CONTRIBUTORS.md 49 | # nyc test coverage 50 | .nyc_output 51 | .nycrc 52 | 53 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 54 | .grunt 55 | 56 | # Bower dependency directory (https://bower.io/) 57 | bower_components 58 | 59 | # node-waf configuration 60 | .lock-wscript 61 | 62 | # Compiled binary addons (https://nodejs.org/api/addons.html) 63 | build/Release 64 | 65 | # Dependency directories 66 | node_modules/ 67 | jspm_packages/ 68 | 69 | # TypeScript v1 declaration files 70 | typings/ 71 | 72 | # Optional npm cache directory 73 | .npm 74 | 75 | # Optional eslint cache 76 | .eslintcache 77 | 78 | # Optional REPL history 79 | .node_repl_history 80 | 81 | # Output of 'npm pack' 82 | *.tgz 83 | 84 | # Yarn Integrity file 85 | .yarn-integrity 86 | 87 | # dotenv environment variables file 88 | .env 89 | 90 | # next.js build output 91 | .next 92 | 93 | -------------------------------------------------------------------------------- /e2e/flow.ts: -------------------------------------------------------------------------------- 1 | import {Squiss, Message} from '../src'; 2 | import {SQSClientConfig} from '@aws-sdk/client-sqs'; 3 | import {S3} from '@aws-sdk/client-s3'; 4 | 5 | const awsConfig: SQSClientConfig = { 6 | region: 'elasticmq', 7 | endpoint: 'http://localhost:9324', 8 | credentials: { 9 | accessKeyId: 'dummy', 10 | secretAccessKey: 'dummy', 11 | }, 12 | }; 13 | 14 | const s3 = new S3({ 15 | endpoint: 'http://localhost:9000/s3', 16 | credentials: { 17 | accessKeyId: 'AKIAIOSFODNN7EXAMPLE', 18 | secretAccessKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY', 19 | }, 20 | }) 21 | 22 | const squiss = new Squiss({ 23 | awsConfig, 24 | queueName: 'my-sqs-queue', 25 | bodyFormat: 'json', 26 | maxInFlight: 15, 27 | S3: s3, 28 | gzip: true, 29 | minGzipSize: 1, 30 | s3Fallback: true, 31 | s3Bucket: 'test', 32 | minS3Size: 1, 33 | correctQueueUrl: true, 34 | }); 35 | 36 | (async () => { 37 | await await s3.createBucket({ 38 | Bucket: 'test', 39 | }); 40 | await squiss.createQueue(); 41 | squiss.on('message', async (message: Message) => { 42 | console.log(`${message.body.name} says: ${JSON.stringify(message.body.message)} and has attripute p1 with value ${message.attributes.p1}`); 43 | await message.del(); 44 | }); 45 | squiss.on('error', (error: Error) => { 46 | console.log(`squiss error`, error); 47 | }); 48 | await squiss.start(); 49 | 50 | const messageToSend = { 51 | name: 'messageName', 52 | message: { 53 | a: 1, 54 | b: 2, 55 | }, 56 | }; 57 | 58 | const propsToSend = { 59 | p1: 1, 60 | p2: 2, 61 | }; 62 | 63 | await squiss.sendMessage(messageToSend, 0, propsToSend); 64 | })(); 65 | -------------------------------------------------------------------------------- /src/attributeUtils.ts: -------------------------------------------------------------------------------- 1 | import {MessageAttributeValue} from '@aws-sdk/client-sqs' 2 | import {isBoolean, isNumber, isString} from 'ts-type-guards'; 3 | import {MessageBodyAttributeMap} from './Types'; 4 | 5 | const EMPTY_OBJ = {}; 6 | const STRING_TYPE = 'String'; 7 | const NUMBER_TYPE = 'Number'; 8 | const BINARY_TYPE = 'Binary'; 9 | 10 | export type IMessageAttribute = number | string | Uint8Array | undefined | boolean; 11 | 12 | export interface IMessageAttributes { 13 | FIFO_MessageDeduplicationId?: string; 14 | FIFO_MessageGroupId?: string; 15 | 16 | [k: string]: IMessageAttribute; 17 | } 18 | 19 | export const parseMessageAttributes = (messageAttributes: MessageBodyAttributeMap | undefined) 20 | : IMessageAttributes => { 21 | const _messageAttributes = messageAttributes || EMPTY_OBJ as MessageBodyAttributeMap; 22 | return Object.keys(_messageAttributes).reduce((parsedAttributes: IMessageAttributes, name: string) => { 23 | parsedAttributes[name] = parseAttributeValue(_messageAttributes[name]); 24 | return parsedAttributes; 25 | }, {}); 26 | }; 27 | 28 | const parseAttributeValue = (unparsedAttribute: MessageAttributeValue): IMessageAttribute => { 29 | const type = unparsedAttribute.DataType; 30 | const stringValue = unparsedAttribute.StringValue; 31 | const binaryValue = unparsedAttribute.BinaryValue; 32 | 33 | switch (type) { 34 | case 'Number': 35 | return Number(stringValue); 36 | case 'Binary': 37 | return binaryValue; 38 | default: 39 | return stringValue || binaryValue; 40 | } 41 | }; 42 | 43 | export const createMessageAttributes = (messageAttributes: IMessageAttributes) 44 | : MessageBodyAttributeMap | undefined => { 45 | const keys = Object.keys(messageAttributes); 46 | if (keys.length === 0) { 47 | return ; 48 | } 49 | return Object.keys(messageAttributes).reduce((parsedAttributes: MessageBodyAttributeMap, name: string) => { 50 | parsedAttributes[name] = createAttributeValue(messageAttributes[name]); 51 | return parsedAttributes; 52 | }, {}); 53 | }; 54 | 55 | const createAttributeValue = (unparsedAttribute: IMessageAttribute): MessageAttributeValue => { 56 | if (unparsedAttribute === undefined || unparsedAttribute === null) { 57 | unparsedAttribute = ''; 58 | } 59 | if (isNumber(unparsedAttribute)) { 60 | return { 61 | DataType: NUMBER_TYPE, 62 | StringValue: String(unparsedAttribute), 63 | }; 64 | } else if (isString(unparsedAttribute)) { 65 | return { 66 | DataType: STRING_TYPE, 67 | StringValue: unparsedAttribute, 68 | }; 69 | } else if (isBoolean(unparsedAttribute)) { 70 | return { 71 | DataType: STRING_TYPE, 72 | StringValue: `${unparsedAttribute}`, 73 | }; 74 | } else { 75 | return { 76 | DataType: BINARY_TYPE, 77 | BinaryValue: unparsedAttribute, 78 | }; 79 | } 80 | }; 81 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "squiss-ts", 3 | "version": "5.6.0", 4 | "description": "High-volume SQS poller", 5 | "main": "dist/index.js", 6 | "types": "dist/index.d.ts", 7 | "engines": { 8 | "node": "^18 || ^20 || ^22 || ^24" 9 | }, 10 | "scripts": { 11 | "clean": "rm -rf .nyc_output coverage dist", 12 | "build": "yarn lint && yarn compile", 13 | "compile": "tsc", 14 | "test": "yarn lint && yarn mocha", 15 | "ci": "yarn build && yarn cover", 16 | "cover": "yarn clean && yarn nyc yarn mocha", 17 | "lint": "eslint \"src/**/*.ts\"", 18 | "benchmark": "tsc --extendedDiagnostics --incremental false", 19 | "e2e:start": "docker compose -f e2e/docker-compose.yml up &", 20 | "e2e:stop": "docker compose -f e2e/docker-compose.yml down &" 21 | }, 22 | "repository": { 23 | "type": "git", 24 | "url": "git+https://github.com/PruvoNet/squiss-ts.git" 25 | }, 26 | "files": [ 27 | "/dist/*.d.ts", 28 | "/dist/*.js" 29 | ], 30 | "keywords": [ 31 | "aws", 32 | "amazon", 33 | "sqs", 34 | "polling", 35 | "poll", 36 | "poller", 37 | "queue", 38 | "typescript", 39 | "sns", 40 | "s3", 41 | "extended", 42 | "client", 43 | "sdk" 44 | ], 45 | "author": "Regev Brody ", 46 | "license": "Apache-2.0", 47 | "bugs": { 48 | "url": "https://github.com/PruvoNet/squiss-ts/issues" 49 | }, 50 | "homepage": "https://github.com/PruvoNet/squiss-ts#readme", 51 | "dependencies": { 52 | "@aws-sdk/client-s3": "^3.927.0", 53 | "@aws-sdk/client-sqs": "^3.927.0", 54 | "@aws-sdk/types": "^3.922.0", 55 | "linked-list": "2.1.0", 56 | "ts-type-guards": "^0.7.0", 57 | "uuid": "11.1.0" 58 | }, 59 | "devDependencies": { 60 | "@istanbuljs/nyc-config-typescript": "1.0.2", 61 | "@types/chai": "4.3.20", 62 | "@types/chai-as-promised": "7.1.8", 63 | "@types/mocha": "^10.0.10", 64 | "@types/node": "^24.10.0", 65 | "@types/proxyquire": "^1.3.31", 66 | "@typescript-eslint/eslint-plugin": "^8.46.3", 67 | "@typescript-eslint/parser": "^8.46.3", 68 | "chai": "4.3.10", 69 | "chai-as-promised": "7.1.1", 70 | "delay": "5.0.0", 71 | "dirty-chai": "^2.0.1", 72 | "eslint": "^9.39.1", 73 | "eslint-config-prettier": "^10.1.8", 74 | "eslint-plugin-import": "^2.32.0", 75 | "eslint-plugin-jsdoc": "50.8.0", 76 | "eslint-plugin-prefer-arrow": "^1.2.3", 77 | "mocha": "^11.7.5", 78 | "nyc": "^17.1.0", 79 | "proxyquire": "^2.1.3", 80 | "sinon": "17.0.1", 81 | "sinon-chai": "3.7.0", 82 | "source-map-support": "^0.5.21", 83 | "ts-node": "^10.9.2", 84 | "typescript": "^5.9.3", 85 | "typescript-eslint": "^8.46.3" 86 | }, 87 | "nyc": { 88 | "extends": "@istanbuljs/nyc-config-typescript", 89 | "check-coverage": true, 90 | "all": true, 91 | "exclude": [ 92 | "src/test/**", 93 | "e2e**", 94 | "build**", 95 | "eslint.config.js" 96 | ], 97 | "reporter": [ 98 | "html", 99 | "lcov", 100 | "text", 101 | "text-summary" 102 | ], 103 | "report-dir": "coverage" 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at info@pruvo.net. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | release: 8 | types: [published] 9 | pull_request: 10 | branches: 11 | - '**' 12 | 13 | env: 14 | PRIMARY_NODE_VERSION: 18.x 15 | PRIMARY_OS: ubuntu-latest 16 | REGISTRY: https://registry.npmjs.org/ 17 | 18 | jobs: 19 | test: 20 | name: CI 21 | runs-on: ${{ matrix.os }} 22 | strategy: 23 | matrix: 24 | os: [ubuntu-latest, macos-latest, windows-latest] 25 | node-version: [18.x, 20.x, 22.x, 24.x] 26 | 27 | steps: 28 | - uses: actions/checkout@v5 29 | name: Checkout 30 | with: 31 | ref: ${{ github.event.client_payload.ref || github.ref }} 32 | 33 | - name: Use Node.js ${{ matrix.node-version }} 34 | uses: actions/setup-node@v6 35 | with: 36 | node-version: ${{ matrix.node-version }} 37 | 38 | - name: Get yarn cache directory 39 | id: yarn-cache-dir 40 | shell: bash 41 | run: | 42 | echo "dir=$(yarn cache dir)" >> $GITHUB_OUTPUT 43 | 44 | - uses: actions/cache@v4 45 | id: yarn-cache 46 | with: 47 | path: ${{ steps.yarn-cache-dir.outputs.dir }} 48 | key: ${{ matrix.os }}-${{ matrix.node-version }}-yarn-${{ hashFiles('**/yarn.lock') }} 49 | restore-keys: | 50 | ${{ matrix.os }}-${{ matrix.node-version }}-yarn- 51 | 52 | - name: Install dependencies and build 53 | run: | 54 | yarn install --frozen-lockfile 55 | yarn build 56 | 57 | - name: Snyk security check 58 | if: matrix.node-version == env.PRIMARY_NODE_VERSION && matrix.os == env.PRIMARY_OS && !github.event.pull_request.head.repo.fork 59 | uses: snyk/actions/node@master 60 | env: 61 | SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }} 62 | 63 | - name: Run unit tests with coverage 64 | if: matrix.node-version == env.PRIMARY_NODE_VERSION && matrix.os == env.PRIMARY_OS && !github.event.pull_request.head.repo.fork 65 | run: yarn cover 66 | 67 | - name: Upload coverage 68 | if: matrix.node-version == env.PRIMARY_NODE_VERSION && matrix.os == env.PRIMARY_OS 69 | uses: qltysh/qlty-action/coverage@v2 70 | with: 71 | token: ${{ secrets.QLTY_COVERAGE_TOKEN }} 72 | files: coverage/lcov.info 73 | 74 | - name: Run unit tests 75 | if: "!(matrix.node-version == env.PRIMARY_NODE_VERSION && matrix.os == env.PRIMARY_OS)" 76 | run: yarn test 77 | 78 | publish_version: 79 | name: Publish 80 | runs-on: ${{ matrix.os }} 81 | strategy: 82 | matrix: 83 | os: [ubuntu-latest] 84 | node-version: [18.x] 85 | needs: [test] 86 | if: github.event_name == 'release' && github.event.action == 'published' 87 | steps: 88 | 89 | - name: Checkout 90 | uses: actions/checkout@v5 91 | 92 | - name: fetch 93 | run: | 94 | git fetch --prune --unshallow 95 | 96 | - name: Use Node.js ${{ matrix.node-version }} 97 | uses: actions/setup-node@v6 98 | with: 99 | node-version: ${{ matrix.node-version }} 100 | registry-url: ${{ env.REGISTRY }} 101 | 102 | - name: Get yarn cache directory 103 | id: yarn-cache-dir 104 | shell: bash 105 | run: | 106 | echo "dir=$(yarn cache dir)" >> $GITHUB_OUTPUT 107 | 108 | - uses: actions/cache@v4 109 | id: yarn-cache 110 | with: 111 | path: ${{ steps.yarn-cache-dir.outputs.dir }} 112 | key: ${{ matrix.os }}-${{ matrix.node-version }}-yarn-${{ hashFiles('**/yarn.lock') }} 113 | restore-keys: | 114 | ${{ matrix.os }}-${{ matrix.node-version }}-yarn- 115 | 116 | - name: Install dependencies and build 117 | run: | 118 | yarn install --frozen-lockfile 119 | yarn build 120 | 121 | - name: Publish 122 | uses: JS-DevTools/npm-publish@v1 123 | with: 124 | token: ${{ secrets.NPM_AUTH_TOKEN }} 125 | registry: ${{ env.REGISTRY }} 126 | -------------------------------------------------------------------------------- /src/EventEmitterTypesHelper.ts: -------------------------------------------------------------------------------- 1 | // https://github.com/bterlson/strict-event-emitter-types 2 | 3 | declare const assignmentCompatibilityHack: unique symbol; 4 | 5 | interface TypeRecord { 6 | ' _emitterType'?: T; 7 | ' _eventsType'?: U; 8 | ' _emitType'?: V; 9 | } 10 | 11 | type InnerEEMethodReturnType = T extends ( 12 | ...args: any[] 13 | ) => any 14 | ? ReturnType extends void | undefined ? FValue : TValue 15 | : FValue; 16 | 17 | type EEMethodReturnType< 18 | T, 19 | S extends string, 20 | TValue, 21 | FValue = void 22 | > = S extends keyof T ? InnerEEMethodReturnType : FValue; 23 | 24 | type ListenerType = [T] extends [(...args: infer U) => any] 25 | ? U 26 | : [T] extends [void] ? [] : [T]; 27 | 28 | interface OverriddenMethods< 29 | TEmitter, 30 | TEventRecord, 31 | TEmitRecord = TEventRecord 32 | > { 33 | on

( 34 | this: T, 35 | event: P, 36 | listener: (...args: ListenerType) => void 37 | ): EEMethodReturnType; 38 | on( 39 | event: typeof assignmentCompatibilityHack, 40 | listener: (...args: any[]) => any 41 | ): void; 42 | 43 | addListener

( 44 | this: T, 45 | event: P, 46 | listener: (...args: ListenerType) => void 47 | ): EEMethodReturnType; 48 | addListener( 49 | event: typeof assignmentCompatibilityHack, 50 | listener: (...args: any[]) => any 51 | ): void; 52 | 53 | addEventListener

( 54 | this: T, 55 | event: P, 56 | listener: (...args: ListenerType) => void 57 | ): EEMethodReturnType; 58 | addEventListener( 59 | event: typeof assignmentCompatibilityHack, 60 | listener: (...args: any[]) => any 61 | ): void; 62 | 63 | removeListener

( 64 | this: T, 65 | event: P, 66 | listener: (...args: any[]) => any 67 | ): EEMethodReturnType; 68 | removeListener( 69 | event: typeof assignmentCompatibilityHack, 70 | listener: (...args: any[]) => any 71 | ): void; 72 | 73 | removeEventListener

( 74 | this: T, 75 | event: P, 76 | listener: (...args: any[]) => any 77 | ): EEMethodReturnType; 78 | removeEventListener( 79 | event: typeof assignmentCompatibilityHack, 80 | listener: (...args: any[]) => any 81 | ): void; 82 | 83 | once

( 84 | this: T, 85 | event: P, 86 | listener: (...args: ListenerType) => void 87 | ): EEMethodReturnType; 88 | once( 89 | event: typeof assignmentCompatibilityHack, 90 | listener: (...args: any[]) => any 91 | ): void; 92 | 93 | emit

( 94 | this: T, 95 | event: P, 96 | ...args: ListenerType 97 | ): EEMethodReturnType; 98 | emit(event: typeof assignmentCompatibilityHack, ...args: any[]): void; 99 | } 100 | 101 | type OverriddenKeys = keyof OverriddenMethods; 102 | 103 | export type StrictEventEmitter< 104 | TEmitterType, 105 | TEventRecord, 106 | TEmitRecord = TEventRecord, 107 | UnneededMethods extends Exclude = Exclude< 108 | OverriddenKeys, 109 | keyof TEmitterType 110 | >, 111 | NeededMethods extends Exclude = Exclude< 112 | OverriddenKeys, 113 | UnneededMethods 114 | > 115 | > = 116 | TypeRecord & 117 | Pick> & 118 | Pick< 119 | OverriddenMethods, 120 | NeededMethods 121 | >; 122 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | When contributing to this repository, please first discuss the change you wish to make via issue, 4 | email, or any other method with the owners of this repository before making a change. 5 | 6 | Please note we have a code of conduct, please follow it in all your interactions with the project. 7 | 8 | ## Pull Request Process 9 | 10 | 1. Ensure any install or build dependencies are removed before the end of the layer when doing a 11 | build. 12 | 2. Update the README.md with details of changes to the interface. 13 | 3. Update the CHANGELOG.md with details of changes. 14 | 4. You may merge the Pull Request in once you have the sign-off of another developers, or if you 15 | do not have permission to do that, you may request the reviewer to merge it for you. 16 | 17 | ## Code of Conduct 18 | 19 | ### Our Pledge 20 | 21 | In the interest of fostering an open and welcoming environment, we as 22 | contributors and maintainers pledge to making participation in our project and 23 | our community a harassment-free experience for everyone, regardless of age, body 24 | size, disability, ethnicity, gender identity and expression, level of experience, 25 | nationality, personal appearance, race, religion, or sexual identity and 26 | orientation. 27 | 28 | ### Our Standards 29 | 30 | Examples of behavior that contributes to creating a positive environment 31 | include: 32 | 33 | * Using welcoming and inclusive language 34 | * Being respectful of differing viewpoints and experiences 35 | * Gracefully accepting constructive criticism 36 | * Focusing on what is best for the community 37 | * Showing empathy towards other community members 38 | 39 | Examples of unacceptable behavior by participants include: 40 | 41 | * The use of sexualized language or imagery and unwelcome sexual attention or 42 | advances 43 | * Trolling, insulting/derogatory comments, and personal or political attacks 44 | * Public or private harassment 45 | * Publishing others' private information, such as a physical or electronic 46 | address, without explicit permission 47 | * Other conduct which could reasonably be considered inappropriate in a 48 | professional setting 49 | 50 | ### Our Responsibilities 51 | 52 | Project maintainers are responsible for clarifying the standards of acceptable 53 | behavior and are expected to take appropriate and fair corrective action in 54 | response to any instances of unacceptable behavior. 55 | 56 | Project maintainers have the right and responsibility to remove, edit, or 57 | reject comments, commits, code, wiki edits, issues, and other contributions 58 | that are not aligned to this Code of Conduct, or to ban temporarily or 59 | permanently any contributor for other behaviors that they deem inappropriate, 60 | threatening, offensive, or harmful. 61 | 62 | ### Scope 63 | 64 | This Code of Conduct applies both within project spaces and in public spaces 65 | when an individual is representing the project or its community. Examples of 66 | representing a project or community include using an official project e-mail 67 | address, posting via an official social media account, or acting as an appointed 68 | representative at an online or offline event. Representation of a project may be 69 | further defined and clarified by project maintainers. 70 | 71 | ### Enforcement 72 | 73 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 74 | reported by contacting the project team at dev@pruvo.net. All 75 | complaints will be reviewed and investigated and will result in a response that 76 | is deemed necessary and appropriate to the circumstances. The project team is 77 | obligated to maintain confidentiality with regard to the reporter of an incident. 78 | Further details of specific enforcement policies may be posted separately. 79 | 80 | Project maintainers who do not follow or enforce the Code of Conduct in good 81 | faith may face temporary or permanent repercussions as determined by other 82 | members of the project's leadership. 83 | 84 | ### Attribution 85 | 86 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 87 | available at [http://contributor-covenant.org/version/1/4][version] 88 | 89 | [homepage]: http://contributor-covenant.org 90 | [version]: http://contributor-covenant.org/version/1/4/ 91 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Npm Version](https://img.shields.io/npm/v/squiss-ts.svg?style=popout)](https://www.npmjs.com/package/squiss-ts) 2 | [![node](https://img.shields.io/node/v-lts/squiss-ts)](https://travis-ci.com/PruvoNet/squiss-ts) 3 | [![Build Status](https://github.com/PruvoNet/squiss-ts/actions/workflows/ci.yml/badge.svg?branch=master)](https://travis-ci.com/PruvoNet/squiss-ts) 4 | [![Code Coverage](https://qlty.sh/gh/PruvoNet/projects/squiss-ts/coverage.svg)](https://qlty.sh/gh/PruvoNet/projects/squiss-ts) 5 | [![Maintainability](https://qlty.sh/gh/PruvoNet/projects/squiss-ts/maintainability.svg)](https://qlty.sh/gh/PruvoNet/projects/squiss-ts) 6 | [![Known Vulnerabilities](https://snyk.io/test/github/PruvoNet/squiss-ts/badge.svg?targetFile=package.json)](https://snyk.io/test/github/PruvoNet/squiss-ts?targetFile=package.json) 7 | 8 |

9 | 10 |

11 | 12 | # Squiss-TS 13 | High-volume Amazon SQS Poller and single-queue client for Node.js 16 and up with full typescript support 14 | The library is production ready and is being stress used in a full blown production environment 15 | 16 | ## Main features 17 | - Control how many messages can be handled at any given point 18 | - Efficiently auto pull new messages when concurrency is not fully utilized 19 | - Easy message lifecycle management 20 | - Options to auto renew messages visibility timeout for long message processing 21 | - Option to automatically gzip incoming and outgoing messages (based on message size) to decrease message sizes and save SQS costs 22 | - Option to auto upload large messages to s3 and retrieve the message from s3 upon receive, in order to decrease message sizes, save SQS costs and be able to send messages bigger than SQS size limit 23 | - Full typescript support 24 | 25 | ## Documentation 26 | 27 | Please see full documentation here 28 | 29 | ## Quick example 30 | ```typescript 31 | import {Squiss, Message} from 'squiss-ts'; 32 | 33 | const awsConfig = { 34 | credentials: { 35 | accessKeyId: 'accessKeyId', 36 | secretAccessKey: 'secretAccessKey', 37 | }, 38 | region: '', 39 | }; 40 | 41 | const squiss = new Squiss({ 42 | awsConfig, 43 | queueName: 'my-sqs-queue', 44 | bodyFormat: 'json', 45 | maxInFlight: 15 46 | }); 47 | 48 | squiss.on('message', (message: Message) => { 49 | console.log(`${message.body.name} says: ${JSON.stringify(message.body.message)} and has attripute p1 with value ${message.attributes.p1}`); 50 | message.del(); 51 | }); 52 | 53 | squiss.start(); 54 | 55 | const messageToSend = { 56 | name: 'messageName', 57 | message: { 58 | a: 1, 59 | b: 2, 60 | }, 61 | }; 62 | 63 | const propsToSend = { 64 | p1: 1, 65 | p2: 2, 66 | }; 67 | 68 | squiss.sendMessage(messageToSend, 0, propsToSend); 69 | ``` 70 | 71 | ## Install 72 | ```bash 73 | npm install squiss-ts 74 | ``` 75 | 76 | ## How it works 77 | Squiss processes as many messages simultaneously as possible. 78 | Set the [maxInFlight](https://squiss-ts.pruvo.com/#squiss-class-constructor-options-polling-options-maxinflight) option to the number of messages your app can handle at one time without choking, and Squiss will keep 79 | that many messages flowing through your app, grabbing more as you mark each message as handled or ready for deletion. 80 | If the queue is empty, Squiss will maintain an open connection to SQS, waiting for any messages that appear in real time. 81 | Squiss can also handle renewing the visibility timeout for your messages until you handle the message, or message handling time 82 | (set up by you) has passed (see [autoExtendTimeout](https://squiss-ts.pruvo.com/#squiss-class-constructor-options-auto-extend-options-autoextendtimeout)). 83 | Bonus: Squiss will also automatically handle the message attributes formatting and parsing when receiving and sending messages. 84 | 85 | ## Versions 86 | Squiss supports Node 6 LTS and higher. 87 | 88 | ## Credits 89 | This project is a typescript port (with better performance, bug fixes and new features) of the wonderful and unmaintnaed project [TomFrost/Squiss](https://www.github.com/TomFrost/Squiss) 90 | Squiss was originally created at [TechnologyAdvice](http://www.technologyadvice.com) in Nashville, TN. 91 | 92 | ## Contributing 93 | 94 | All contributions are happily welcomed! 95 | Please make all pull requests to the `master` branch from your fork and ensure tests pass locally. 96 | -------------------------------------------------------------------------------- /src/Types.ts: -------------------------------------------------------------------------------- 1 | import {Message} from './Message'; 2 | import { 3 | SQSClientConfig, 4 | BatchResultErrorEntry, 5 | SQS, 6 | SQSServiceException, 7 | MessageAttributeValue, 8 | QueueAttributeName 9 | } from '@aws-sdk/client-sqs' 10 | import {S3, S3ClientConfig} from '@aws-sdk/client-s3' 11 | import {IS3Upload} from './s3Utils'; 12 | import {StrictEventEmitter} from './EventEmitterTypesHelper'; 13 | import {EventEmitter} from 'events'; 14 | 15 | export interface IMessageDeletedEventPayload { 16 | msg: Message; 17 | successId: string; 18 | } 19 | 20 | export interface IMessageErrorEventPayload { 21 | message: Message; 22 | error: SQSServiceException; 23 | } 24 | 25 | export interface IMessageDeleteErrorEventPayload { 26 | message: Message; 27 | error: BatchResultErrorEntry; 28 | } 29 | 30 | export interface IMessageS3EventPayload { 31 | message: Message; 32 | data: IS3Upload; 33 | } 34 | 35 | export type MessageBodyAttributeMap = Record; 36 | 37 | export interface ISendMessageRequest { 38 | MessageBody: string; 39 | DelaySeconds?: number; 40 | MessageAttributes?: MessageBodyAttributeMap; 41 | MessageDeduplicationId?: string; 42 | MessageGroupId?: string; 43 | } 44 | 45 | export interface IObject { 46 | [k: string]: any; 47 | } 48 | 49 | export type IMessageToSend = IObject | string; 50 | 51 | export type BodyFormat = 'json' | 'plain' | undefined; 52 | 53 | export interface ISquissOptions { 54 | receiveBatchSize?: number; 55 | receiveAttributes?: string[]; 56 | receiveSqsAttributes?: QueueAttributeName[]; 57 | minReceiveBatchSize?: number; 58 | receiveWaitTimeSecs?: number; 59 | deleteBatchSize?: number; 60 | deleteWaitMs?: number; 61 | maxInFlight?: number; 62 | unwrapSns?: boolean; 63 | bodyFormat?: BodyFormat; 64 | correctQueueUrl?: boolean; 65 | pollRetryMs?: number; 66 | activePollIntervalMs?: number; 67 | idlePollIntervalMs?: number; 68 | delaySecs?: number; 69 | gzip?: boolean; 70 | minGzipSize?: number; 71 | maxMessageBytes?: number; 72 | messageRetentionSecs?: number; 73 | autoExtendTimeout?: boolean; 74 | SQS?: SQS | typeof SQS; 75 | S3?: S3 | typeof S3; 76 | awsConfig?: SQSClientConfig & S3ClientConfig; 77 | queueUrl?: string; 78 | queueName?: string; 79 | visibilityTimeoutSecs?: number; 80 | queuePolicy?: string; 81 | accountNumber?: string | number; 82 | noExtensionsAfterSecs?: number; 83 | advancedCallMs?: number; 84 | s3Fallback?: boolean; 85 | s3Bucket?: string; 86 | s3Retain?: boolean; 87 | s3Prefix?: string; 88 | minS3Size?: number; 89 | } 90 | 91 | export interface IDeleteQueueItem { 92 | msg: Message; 93 | Id: string; 94 | ReceiptHandle: string; 95 | resolve: () => void; 96 | reject: (reason?: any) => void; 97 | } 98 | 99 | export interface IDeleteQueueItemById { 100 | [k: string]: IDeleteQueueItem; 101 | } 102 | 103 | export const optDefaults: ISquissOptions = { 104 | receiveBatchSize: 10, 105 | receiveAttributes: ['All'], 106 | receiveSqsAttributes: ['All'], 107 | minReceiveBatchSize: 1, 108 | receiveWaitTimeSecs: 20, 109 | deleteBatchSize: 10, 110 | deleteWaitMs: 2000, 111 | maxInFlight: 100, 112 | unwrapSns: false, 113 | bodyFormat: 'plain', 114 | correctQueueUrl: false, 115 | pollRetryMs: 2000, 116 | activePollIntervalMs: 0, 117 | idlePollIntervalMs: 0, 118 | delaySecs: 0, 119 | gzip: false, 120 | minGzipSize: 0, 121 | s3Fallback: false, 122 | s3Retain: false, 123 | s3Prefix: '', 124 | maxMessageBytes: 262144, 125 | messageRetentionSecs: 345600, 126 | autoExtendTimeout: false, 127 | }; 128 | 129 | export interface ISquissEvents { 130 | delQueued: Message; 131 | handled: Message; 132 | released: Message; 133 | timeoutReached: Message; 134 | extendingTimeout: Message; 135 | timeoutExtended: Message; 136 | message: Message; 137 | keep: Message; 138 | drained: void; 139 | queueEmpty: void; 140 | maxInFlight: void; 141 | deleted: IMessageDeletedEventPayload; 142 | gotMessages: number; 143 | error: Error; 144 | aborted: SQSServiceException; 145 | delError: IMessageDeleteErrorEventPayload; 146 | autoExtendFail: IMessageErrorEventPayload; 147 | autoExtendError: IMessageErrorEventPayload; 148 | s3Download: IMessageS3EventPayload; 149 | s3Delete: IMessageS3EventPayload; 150 | s3Upload: IS3Upload; 151 | } 152 | 153 | export type SquissEmitter = StrictEventEmitter; 154 | -------------------------------------------------------------------------------- /src/TimeoutExtender.ts: -------------------------------------------------------------------------------- 1 | import {Squiss} from './index'; 2 | import {Message} from './Message'; 3 | import * as LinkedList from 'linked-list'; 4 | import {Item} from 'linked-list'; 5 | import {SQSServiceException} from '@aws-sdk/client-sqs'; 6 | 7 | const MAX_MESSAGE_AGE_MS = 43200000; 8 | 9 | class Node extends Item { 10 | constructor(public message: Message, public receivedOn: number, public timerOn: number) { 11 | super(); 12 | } 13 | } 14 | 15 | export interface ITimeoutExtenderOptions { 16 | visibilityTimeoutSecs?: number; 17 | noExtensionsAfterSecs?: number; 18 | advancedCallMs?: number; 19 | } 20 | 21 | interface MessageIndex { 22 | [k: string]: Node; 23 | } 24 | 25 | const optDefaults: ITimeoutExtenderOptions = { 26 | visibilityTimeoutSecs: 30, 27 | noExtensionsAfterSecs: MAX_MESSAGE_AGE_MS / 1000, 28 | advancedCallMs: 5000, 29 | }; 30 | 31 | export class TimeoutExtender { 32 | 33 | public readonly _index: MessageIndex; 34 | public _linkedList: LinkedList; 35 | public _opts: ITimeoutExtenderOptions; 36 | private readonly _squiss: Squiss; 37 | private _timer: any; 38 | private readonly _visTimeout: number; 39 | private readonly _stopAfter: number; 40 | private readonly _apiLeadMs: number; 41 | 42 | constructor(squiss: Squiss, opts?: ITimeoutExtenderOptions) { 43 | this._opts = { 44 | ...optDefaults, 45 | ...(opts || {}), 46 | }; 47 | this._index = {}; 48 | this._timer = undefined; 49 | this._squiss = squiss; 50 | this._linkedList = new LinkedList(); 51 | this._squiss.on('handled', (msg: Message) => { 52 | return this.deleteMessage(msg); 53 | }); 54 | this._squiss.on('message', (msg: Message) => { 55 | return this.addMessage(msg); 56 | }); 57 | this._visTimeout = this._opts.visibilityTimeoutSecs! * 1000; 58 | this._stopAfter = Math.min(this._opts.noExtensionsAfterSecs! * 1000, MAX_MESSAGE_AGE_MS); 59 | this._apiLeadMs = Math.min(this._opts.advancedCallMs!, this._visTimeout); 60 | } 61 | 62 | public addMessage(message: Message) { 63 | const now = Date.now(); 64 | this._addNode(new Node(message, now, now + this._visTimeout - this._apiLeadMs)); 65 | } 66 | 67 | public deleteMessage(message: Message) { 68 | const node = this._index[message.raw.MessageId!]; 69 | if (node) { 70 | this._deleteNode(node); 71 | } 72 | } 73 | 74 | public _addNode(node: Node) { 75 | this._index[node.message.raw.MessageId!] = node; 76 | this._linkedList.append(node); 77 | if (!node.prev) { 78 | this._headChanged(); 79 | } 80 | } 81 | 82 | public _deleteNode(node: Node) { 83 | const msgId = node.message.raw.MessageId!; 84 | delete this._index[msgId]; 85 | const isFirst = !node.prev; 86 | node.detach(); 87 | if (isFirst) { 88 | this._headChanged(); 89 | } 90 | } 91 | 92 | public _getNodeAge(node: Node) { 93 | return Date.now() - node.receivedOn + this._apiLeadMs; 94 | } 95 | 96 | public _headChanged() { 97 | if (this._timer) { 98 | clearTimeout(this._timer); 99 | } 100 | if (!this._linkedList.head) { 101 | return false; 102 | } 103 | const node = this._linkedList.head; 104 | this._timer = setTimeout(() => { 105 | if (this._getNodeAge(node) >= this._stopAfter) { 106 | this._deleteNode(node); 107 | node.message.keep(); 108 | node.message.emit('keep'); 109 | this._squiss.emit('keep', node.message); 110 | node.message.emit('timeoutReached'); 111 | this._squiss.emit('timeoutReached', node.message); 112 | return; 113 | } 114 | return this._renewNode(node); 115 | }, node.timerOn - Date.now()); 116 | return true; 117 | } 118 | 119 | public _renewNode(node: Node) { 120 | const extendByMs = Math.min(this._visTimeout, MAX_MESSAGE_AGE_MS - this._getNodeAge(node)); 121 | const extendBySecs = Math.floor(extendByMs / 1000); 122 | node.message.emit('extendingTimeout'); 123 | this._squiss.emit('extendingTimeout', node.message); 124 | this._squiss.changeMessageVisibility(node.message, extendBySecs) 125 | .then(() => { 126 | node.message.emit('timeoutExtended'); 127 | this._squiss.emit('timeoutExtended', node.message); 128 | }) 129 | .catch((err: SQSServiceException) => { 130 | if (err.name === 'ReceiptHandleIsInvalid' || err.name === 'MessageNotInflight' || 131 | err.message.match(/message does not exist or is not available/i) || 132 | err.message.match(/the receipt handle has expired/i) || 133 | err.message.match(/not a valid receipt handle/i)) { 134 | this._deleteNode(node); 135 | node.message.emit('autoExtendFail', err); 136 | this._squiss.emit('autoExtendFail', {message: node.message, error: err}); 137 | } else { 138 | node.message.emit('autoExtendError', err); 139 | this._squiss.emit('autoExtendError', {message: node.message, error: err}); 140 | } 141 | }); 142 | this._deleteNode(node); 143 | node.timerOn = Date.now() + extendByMs - this._apiLeadMs; 144 | this._addNode(node); 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /src/test/stubs/SQSStub.ts: -------------------------------------------------------------------------------- 1 | import {EventEmitter} from 'events'; 2 | import { 3 | CreateQueueRequest, 4 | DeleteMessageBatchRequest, DeleteMessageBatchResult, 5 | GetQueueUrlRequest, 6 | Message as SQSMessage, ReceiveMessageRequest, SendMessageBatchRequest, SendMessageBatchResult, SendMessageRequest 7 | } from '@aws-sdk/client-sqs'; 8 | import {HttpHandlerOptions} from '@aws-sdk/types'; 9 | 10 | export class SQSStub extends EventEmitter { 11 | 12 | public msgs: SQSMessage[]; 13 | public timeout: number; 14 | public msgCount: number; 15 | public config: { 16 | region: string; 17 | endpoint: string; 18 | }; 19 | 20 | constructor(msgCount?: number, timeout?: number) { 21 | super(); 22 | this.msgs = []; 23 | this.timeout = timeout ?? 20; 24 | this.msgCount = msgCount ?? 0; 25 | this.config = { 26 | region: 'us-east-1', 27 | endpoint: 'http://foo.bar', 28 | }; 29 | for (let i = 0; i < this.msgCount; i++) { 30 | this._addMessage(i); 31 | } 32 | } 33 | 34 | public createQueue(params: CreateQueueRequest) { 35 | return this.getQueueUrl(params); 36 | } 37 | 38 | public deleteMessageBatch(params: DeleteMessageBatchRequest) { 39 | const res: DeleteMessageBatchResult = { 40 | Successful: [], 41 | Failed: [], 42 | }; 43 | params.Entries?.forEach((entry) => { 44 | if (parseInt(entry.ReceiptHandle ?? '', 10) < this.msgCount) { 45 | res.Successful?.push({Id: entry.Id}); 46 | } else { 47 | res.Failed?.push({ 48 | Id: entry.Id, 49 | SenderFault: true, 50 | Code: '404', 51 | Message: 'Does not exist', 52 | }); 53 | } 54 | }); 55 | return Promise.resolve(res); 56 | } 57 | 58 | public changeMessageVisibility() { 59 | return Promise.resolve(); 60 | } 61 | 62 | public deleteQueue() { 63 | return Promise.resolve({ResponseMetadata: {RequestId: 'd2206b43-df52-5161-a8e8-24dc83737962'}}); 64 | 65 | } 66 | 67 | public getQueueUrl(params: GetQueueUrlRequest) { 68 | return Promise.resolve({ 69 | QueueUrl: `http://localhost:9324/queues/${params.QueueName}`, 70 | }); 71 | } 72 | 73 | public getQueueAttributes() { 74 | return Promise.resolve({ 75 | Attributes: { 76 | VisibilityTimeout: '31', 77 | MaximumMessageSize: '200', 78 | }, 79 | }); 80 | } 81 | 82 | public receiveMessage(params?: ReceiveMessageRequest, opts?: HttpHandlerOptions) { 83 | if (opts?.abortSignal) { 84 | opts.abortSignal.onabort = () => { 85 | this.emit('abort'); 86 | }; 87 | } 88 | const msgs = this.msgs.splice(0, params ? params.MaxNumberOfMessages : undefined); 89 | return new Promise((resolve, reject) => { 90 | if (msgs.length) { 91 | return resolve({Messages: msgs}); 92 | } 93 | 94 | let removeListeners = () => { 95 | }; 96 | const timeout = setTimeout(() => { 97 | removeListeners(); 98 | resolve({}); 99 | }, this.timeout); 100 | const onAbort = () => { 101 | removeListeners(); 102 | const err = new Error('Request aborted by user'); 103 | (err as any).name = 'AbortError'; 104 | (err as any).retryable = false; 105 | (err as any).time = new Date(); 106 | reject(err); 107 | }; 108 | const onNewMessage = () => { 109 | removeListeners(); 110 | resolve(this.receiveMessage()); 111 | }; 112 | removeListeners = () => { 113 | clearTimeout(timeout); 114 | this.removeListener('newMessage', onNewMessage); 115 | this.removeListener('abort', onAbort); 116 | }; 117 | this.once('abort', onAbort); 118 | this.once('newMessage', onNewMessage); 119 | return undefined; 120 | }); 121 | } 122 | 123 | public purgeQueue() { 124 | this.msgs = []; 125 | this.msgCount = 0; 126 | return Promise.resolve({ 127 | RequestId: '6fde8d1e-52cd-4581-8cd9-c512f4c64223', 128 | }); 129 | } 130 | 131 | public sendMessage(params: SendMessageRequest) { 132 | this._addMessage(params.QueueUrl ?? '', params.MessageBody); 133 | return Promise.resolve({ 134 | MessageId: 'd2206b43-df52-5161-a8e8-24dc83737962', 135 | MD5OfMessageAttributes: 'deadbeefdeadbeefdeadbeefdeadbeef', 136 | MD5OfMessageBody: 'deadbeefdeadbeefdeadbeefdeadbeef', 137 | }); 138 | } 139 | 140 | public sendMessageBatch(params: SendMessageBatchRequest) { 141 | const res: SendMessageBatchResult = { 142 | Successful: [], 143 | Failed: [], 144 | }; 145 | params.Entries?.forEach((entry, idx) => { 146 | if (entry.MessageBody !== 'FAIL') { 147 | this._addMessage(entry.Id ?? '', entry.MessageBody); 148 | res.Successful?.push({ 149 | Id: entry.Id, 150 | MessageId: idx.toString(), 151 | MD5OfMessageAttributes: 'deadbeefdeadbeefdeadbeefdeadbeef', 152 | MD5OfMessageBody: 'deadbeefdeadbeefdeadbeefdeadbeef', 153 | }); 154 | } else { 155 | res.Failed?.push({ 156 | Id: entry.Id, 157 | SenderFault: true, 158 | Code: 'Message is empty', 159 | Message: '', 160 | }); 161 | } 162 | }); 163 | return Promise.resolve(res); 164 | } 165 | 166 | private _addMessage(id: number | string, body?: string) { 167 | this.msgs.push({ 168 | MessageId: `id_${id}`, 169 | ReceiptHandle: `${id}`, 170 | Body: body ?? `{"num": ${id}}`, 171 | }); 172 | this.emit('newMessage'); 173 | } 174 | 175 | } 176 | -------------------------------------------------------------------------------- /src/Message.ts: -------------------------------------------------------------------------------- 1 | import {BatchResultErrorEntry, Message as SQSMessage, SQSServiceException} from '@aws-sdk/client-sqs' 2 | import {S3} from '@aws-sdk/client-s3' 3 | import {BodyFormat, Squiss} from '.'; 4 | import {IMessageAttributes, parseMessageAttributes} from './attributeUtils'; 5 | import {EventEmitter} from 'events'; 6 | import {GZIP_MARKER, decompressMessage} from './gzipUtils'; 7 | import {deleteBlob, getBlob, IS3Upload, S3_MARKER} from './s3Utils'; 8 | import {StrictEventEmitter} from './EventEmitterTypesHelper'; 9 | 10 | const EMPTY_BODY = '{}'; 11 | 12 | export interface IMessageOpts { 13 | msg: SQSMessage; 14 | unwrapSns?: boolean; 15 | bodyFormat?: BodyFormat; 16 | squiss: Squiss; 17 | s3Retriever: () => S3; 18 | s3Retain: boolean; 19 | } 20 | 21 | interface SNSBody { 22 | Message?: string; 23 | Subject: string; 24 | TopicArn: string; 25 | } 26 | 27 | interface IMessageEvents { 28 | delQueued: void; 29 | handled: void; 30 | released: void; 31 | timeoutReached: void; 32 | extendingTimeout: void; 33 | timeoutExtended: void; 34 | keep: void; 35 | delError: BatchResultErrorEntry; 36 | deleted: string; 37 | autoExtendFail: SQSServiceException; 38 | autoExtendError: SQSServiceException; 39 | s3Download: IS3Upload; 40 | s3Delete: IS3Upload; 41 | } 42 | 43 | type MessageEmitter = StrictEventEmitter; 44 | 45 | export class Message extends (EventEmitter as new() => MessageEmitter) { 46 | 47 | private static formatMessage(msg: string | undefined, format: BodyFormat) { 48 | if (format === 'json') { 49 | return JSON.parse(msg || EMPTY_BODY); 50 | } else { 51 | return msg; 52 | } 53 | } 54 | 55 | public raw: SQSMessage; 56 | public body?: any; 57 | public subject?: string; 58 | public topicArn?: string; 59 | public topicName?: string; 60 | public attributes: IMessageAttributes; 61 | public sqsAttributes: { [k: string]: string }; 62 | private readonly _squiss: Squiss; 63 | private _handled: boolean; 64 | private readonly _opts: IMessageOpts; 65 | private _deleteCallback?: () => Promise; 66 | private readonly _s3Retriever: () => S3; 67 | private readonly _s3Retain: boolean; 68 | 69 | constructor(opts: IMessageOpts) { 70 | super(); 71 | this._opts = opts; 72 | this.raw = opts.msg; 73 | this.body = opts.msg.Body; 74 | if (opts.unwrapSns) { 75 | const unwrapped: SNSBody = JSON.parse(this.body || EMPTY_BODY); 76 | this.body = unwrapped.Message; 77 | this.subject = unwrapped.Subject; 78 | this.topicArn = unwrapped.TopicArn; 79 | if (this.topicArn) { 80 | this.topicName = unwrapped.TopicArn.substring(unwrapped.TopicArn.lastIndexOf(':') + 1); 81 | } 82 | } 83 | this._squiss = opts.squiss; 84 | this._handled = false; 85 | this.attributes = parseMessageAttributes(opts.msg.MessageAttributes); 86 | this.sqsAttributes = opts.msg.Attributes || {}; 87 | this._s3Retriever = opts.s3Retriever; 88 | this._s3Retain = opts.s3Retain; 89 | } 90 | 91 | public parse(): Promise { 92 | if (this.body === undefined || this.body === null) { 93 | return Promise.resolve(); 94 | } 95 | let promise = Promise.resolve(this.body); 96 | if (this.attributes[S3_MARKER]) { 97 | delete this.attributes[S3_MARKER]; 98 | promise = this._getBlobMessage(); 99 | } 100 | promise = promise 101 | .then((resolvedBody) => { 102 | if (this.attributes[GZIP_MARKER] === 1) { 103 | delete this.attributes[GZIP_MARKER]; 104 | return decompressMessage(resolvedBody); 105 | } else { 106 | return Promise.resolve(resolvedBody); 107 | } 108 | }); 109 | return promise 110 | .then((parsedBody) => { 111 | this.body = Message.formatMessage(parsedBody, this._opts.bodyFormat); 112 | }); 113 | } 114 | 115 | public isHandled() { 116 | return this._handled; 117 | } 118 | 119 | public del(): Promise { 120 | if (!this._handled) { 121 | this._handled = true; 122 | let promise: Promise; 123 | if (this._deleteCallback) { 124 | promise = this._deleteCallback(); 125 | } else { 126 | promise = Promise.resolve(); 127 | } 128 | return promise 129 | .then(() => { 130 | return this._squiss.deleteMessage(this); 131 | }) 132 | .catch(() => { 133 | this._handled = false; 134 | }); 135 | } else { 136 | return Promise.resolve(); 137 | } 138 | } 139 | 140 | public keep(): void { 141 | if (!this._handled) { 142 | this._squiss.handledMessage(this); 143 | this._handled = true; 144 | } 145 | } 146 | 147 | public release(): Promise { 148 | if (!this._handled) { 149 | this._handled = true; 150 | return this._squiss.releaseMessage(this) 151 | .catch(() => { 152 | this._handled = false; 153 | }); 154 | } 155 | return Promise.resolve(); 156 | } 157 | 158 | public changeVisibility(timeoutInSeconds: number): Promise { 159 | return this._squiss.changeMessageVisibility(this, timeoutInSeconds); 160 | } 161 | 162 | private _getBlobMessage() { 163 | const uploadData: IS3Upload = JSON.parse(this.body); 164 | const s3 = this._s3Retriever(); 165 | return getBlob(s3, uploadData) 166 | .then((resolvedBody) => { 167 | this.emit('s3Download', uploadData); 168 | this._squiss.emit('s3Download', {data: uploadData, message: this}); 169 | if (!this._s3Retain) { 170 | this._deleteCallback = () => { 171 | return deleteBlob(s3, uploadData) 172 | .then(() => { 173 | this.emit('s3Delete', uploadData); 174 | this._squiss.emit('s3Delete', {data: uploadData, message: this}); 175 | }); 176 | }; 177 | } 178 | return Promise.resolve(resolvedBody); 179 | }); 180 | } 181 | 182 | } 183 | -------------------------------------------------------------------------------- /eslint.config.js: -------------------------------------------------------------------------------- 1 | const eslint = require('@eslint/js'); 2 | const tseslint = require('typescript-eslint'); 3 | const prettierConfig = require('eslint-config-prettier'); 4 | const importPlugin = require('eslint-plugin-import'); 5 | const jsdocPlugin = require('eslint-plugin-jsdoc'); 6 | const preferArrowPlugin = require('eslint-plugin-prefer-arrow'); 7 | 8 | module.exports = tseslint.config( 9 | eslint.configs.recommended, 10 | ...tseslint.configs.recommendedTypeChecked, 11 | prettierConfig, 12 | { 13 | languageOptions: { 14 | globals: { 15 | // Node.js globals 16 | __dirname: 'readonly', 17 | __filename: 'readonly', 18 | Buffer: 'readonly', 19 | global: 'readonly', 20 | process: 'readonly', 21 | require: 'readonly', 22 | module: 'readonly', 23 | exports: 'readonly', 24 | console: 'readonly', 25 | // Browser globals 26 | document: 'readonly', 27 | navigator: 'readonly', 28 | window: 'readonly', 29 | }, 30 | parserOptions: { 31 | project: './tsconfig.json', 32 | sourceType: 'module', 33 | }, 34 | }, 35 | files: ['**/*.ts'], 36 | plugins: { 37 | import: importPlugin, 38 | jsdoc: jsdocPlugin, 39 | 'prefer-arrow': preferArrowPlugin, 40 | }, 41 | rules: { 42 | // TypeScript-specific rules (only non-deprecated ones from v8) 43 | '@typescript-eslint/adjacent-overload-signatures': 'error', 44 | '@typescript-eslint/array-type': [ 45 | 'error', 46 | { 47 | default: 'array', 48 | }, 49 | ], 50 | '@typescript-eslint/await-thenable': 'off', 51 | '@typescript-eslint/ban-ts-comment': 'off', 52 | '@typescript-eslint/consistent-type-assertions': 'error', 53 | '@typescript-eslint/dot-notation': 'error', 54 | '@typescript-eslint/explicit-function-return-type': 'off', 55 | '@typescript-eslint/explicit-module-boundary-types': 'off', 56 | '@typescript-eslint/naming-convention': [ 57 | 'off', 58 | { 59 | selector: 'variable', 60 | format: ['camelCase', 'UPPER_CASE'], 61 | leadingUnderscore: 'allow', 62 | trailingUnderscore: 'forbid', 63 | }, 64 | ], 65 | '@typescript-eslint/no-array-constructor': 'error', 66 | '@typescript-eslint/no-base-to-string': 'error', 67 | '@typescript-eslint/no-empty-function': 'off', 68 | '@typescript-eslint/no-explicit-any': 'off', 69 | '@typescript-eslint/no-floating-promises': 'off', 70 | '@typescript-eslint/no-for-in-array': 'error', 71 | '@typescript-eslint/no-implied-eval': 'error', 72 | '@typescript-eslint/no-misused-new': 'error', 73 | '@typescript-eslint/no-misused-promises': 'off', 74 | '@typescript-eslint/no-namespace': 'error', 75 | '@typescript-eslint/no-redundant-type-constituents': 'off', 76 | '@typescript-eslint/no-shadow': [ 77 | 'error', 78 | { 79 | hoist: 'all', 80 | }, 81 | ], 82 | '@typescript-eslint/no-this-alias': 'error', 83 | '@typescript-eslint/no-unnecessary-type-assertion': 'off', 84 | '@typescript-eslint/no-unsafe-argument': 'off', 85 | '@typescript-eslint/no-unsafe-assignment': 'off', 86 | '@typescript-eslint/no-unsafe-call': 'off', 87 | '@typescript-eslint/no-unsafe-member-access': 'off', 88 | '@typescript-eslint/no-unsafe-return': 'off', 89 | '@typescript-eslint/no-unused-expressions': 'off', 90 | '@typescript-eslint/no-unused-vars': 'off', 91 | '@typescript-eslint/no-use-before-define': 'off', 92 | '@typescript-eslint/prefer-as-const': 'error', 93 | '@typescript-eslint/prefer-for-of': 'error', 94 | '@typescript-eslint/prefer-function-type': 'error', 95 | '@typescript-eslint/prefer-namespace-keyword': 'error', 96 | '@typescript-eslint/require-await': 'off', 97 | '@typescript-eslint/restrict-plus-operands': 'error', 98 | '@typescript-eslint/restrict-template-expressions': 'error', 99 | '@typescript-eslint/triple-slash-reference': [ 100 | 'error', 101 | { 102 | path: 'always', 103 | types: 'prefer-import', 104 | lib: 'always', 105 | }, 106 | ], 107 | '@typescript-eslint/typedef': 'off', 108 | '@typescript-eslint/unbound-method': 'off', 109 | '@typescript-eslint/unified-signatures': 'error', 110 | 111 | // General ESLint rules 112 | 'comma-dangle': ['off'], 113 | complexity: 'off', 114 | 'constructor-super': 'off', 115 | 'dot-notation': 'off', 116 | eqeqeq: ['error', 'smart'], 117 | 'guard-for-in': 'error', 118 | 'id-denylist': [ 119 | 'error', 120 | 'any', 121 | 'Number', 122 | 'number', 123 | 'String', 124 | 'string', 125 | 'Boolean', 126 | 'boolean', 127 | 'Undefined', 128 | 'undefined', 129 | ], 130 | 'id-match': 'error', 131 | 'import/order': [ 132 | 'off', 133 | { 134 | alphabetize: { 135 | caseInsensitive: true, 136 | order: 'asc', 137 | }, 138 | 'newlines-between': 'ignore', 139 | groups: [['builtin', 'external', 'internal', 'unknown', 'object', 'type'], 'parent', ['sibling', 'index']], 140 | distinctGroup: false, 141 | pathGroupsExcludedImportTypes: [], 142 | pathGroups: [ 143 | { 144 | pattern: './', 145 | patternOptions: { 146 | nocomment: true, 147 | dot: true, 148 | }, 149 | group: 'sibling', 150 | position: 'before', 151 | }, 152 | { 153 | pattern: '.', 154 | patternOptions: { 155 | nocomment: true, 156 | dot: true, 157 | }, 158 | group: 'sibling', 159 | position: 'before', 160 | }, 161 | { 162 | pattern: '..', 163 | patternOptions: { 164 | nocomment: true, 165 | dot: true, 166 | }, 167 | group: 'parent', 168 | position: 'before', 169 | }, 170 | { 171 | pattern: '../', 172 | patternOptions: { 173 | nocomment: true, 174 | dot: true, 175 | }, 176 | group: 'parent', 177 | position: 'before', 178 | }, 179 | ], 180 | }, 181 | ], 182 | 'jsdoc/check-alignment': 'error', 183 | 'jsdoc/check-indentation': 'error', 184 | 'max-classes-per-file': 'off', 185 | 'max-len': [ 186 | 'error', 187 | { 188 | ignorePattern: '^import |^export \\{(.*?)\\}|class [a-zA-Z]+ implements |//', 189 | code: 120, 190 | }, 191 | ], 192 | 'new-parens': 'error', 193 | 'no-array-constructor': 'off', 194 | 'no-bitwise': 'error', 195 | 'no-caller': 'error', 196 | 'no-cond-assign': 'error', 197 | 'no-console': 'off', 198 | 'no-debugger': 'error', 199 | 'no-empty': 'off', 200 | 'no-empty-function': 'off', 201 | 'no-eval': 'error', 202 | 'no-fallthrough': 'off', 203 | 'no-implied-eval': 'off', 204 | 'no-invalid-this': 'off', 205 | 'no-loss-of-precision': 'off', 206 | 'no-new-wrappers': 'error', 207 | 'no-shadow': 'off', 208 | 'no-throw-literal': 'error', 209 | 'no-trailing-spaces': 'error', 210 | 'no-undef-init': 'error', 211 | 'no-underscore-dangle': 'off', 212 | 'no-unsafe-finally': 'error', 213 | 'no-unused-expressions': 'off', 214 | 'no-unused-labels': 'error', 215 | 'no-unused-vars': 'off', 216 | 'no-use-before-define': 'off', 217 | 'no-var': 'error', 218 | 'object-shorthand': 'error', 219 | 'one-var': ['error', 'never'], 220 | 'prefer-arrow/prefer-arrow-functions': 'off', 221 | 'prefer-const': 'error', 222 | radix: 'error', 223 | 'require-await': 'off', 224 | 'spaced-comment': [ 225 | 'error', 226 | 'always', 227 | { 228 | markers: ['/'], 229 | }, 230 | ], 231 | 'use-isnan': 'error', 232 | 'valid-typeof': 'off', 233 | }, 234 | } 235 | ); -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /src/test/src/TimeoutExtender.spec.ts: -------------------------------------------------------------------------------- 1 | import {Message, Squiss} from '../../'; 2 | import {TimeoutExtender} from '../../TimeoutExtender'; 3 | import {SquissStub} from '../stubs/SquissStub'; 4 | import delay from 'delay'; 5 | // @ts-ignore 6 | import * as sinon from 'sinon'; 7 | import {S3Stub} from '../stubs/S3Stub'; 8 | import {S3} from '@aws-sdk/client-s3'; 9 | 10 | const getSquissStub = () => { 11 | return new SquissStub() as any as Squiss; 12 | }; 13 | 14 | const getS3Stub = () => { 15 | return new S3Stub() as any as S3; 16 | }; 17 | 18 | let inst = null; 19 | let clock: any = null; 20 | const msgSquissStub = getSquissStub(); 21 | const fooMsg = new Message({ 22 | squiss: msgSquissStub, 23 | msg: {MessageId: 'foo', Body: 'foo'}, 24 | s3Retriever: getS3Stub, 25 | s3Retain: false, 26 | }); 27 | const barMsg = new Message({ 28 | squiss: msgSquissStub, 29 | msg: {MessageId: 'bar', Body: 'bar'}, 30 | s3Retriever: getS3Stub, 31 | s3Retain: false, 32 | }); 33 | const bazMsg = new Message({ 34 | squiss: msgSquissStub, 35 | msg: {MessageId: 'baz', Body: 'baz'}, 36 | s3Retriever: getS3Stub, 37 | s3Retain: false, 38 | }); 39 | 40 | describe('TimeoutExtender', () => { 41 | afterEach(() => { 42 | if (clock?.restore) { 43 | clock.restore(); 44 | } 45 | inst = null; 46 | }); 47 | it('adds and deletes a message through function calls', () => { 48 | inst = new TimeoutExtender(getSquissStub()); 49 | inst.addMessage(fooMsg); 50 | inst._index.should.have.property('foo'); 51 | inst.deleteMessage(fooMsg); 52 | inst._index.should.not.have.property('foo'); 53 | }); 54 | it('adds and deletes a message through events', () => { 55 | const squiss = getSquissStub(); 56 | inst = new TimeoutExtender(squiss); 57 | const addSpy = sinon.spy(inst, 'addMessage'); 58 | const delSpy = sinon.spy(inst, 'deleteMessage'); 59 | squiss.emit('message', fooMsg); 60 | return delay(5).then(() => { 61 | addSpy.should.be.calledOnce(); 62 | squiss.emit('handled', fooMsg); 63 | return delay(5); 64 | }).then(() => { 65 | delSpy.should.be.calledOnce(); 66 | }); 67 | }); 68 | it('fails silently when asked to delete a nonexistent message', () => { 69 | inst = new TimeoutExtender(getSquissStub()); 70 | inst.addMessage(fooMsg); 71 | inst.deleteMessage(barMsg); 72 | }); 73 | it('tracks multiple messages', () => { 74 | inst = new TimeoutExtender(getSquissStub()); 75 | inst.addMessage(fooMsg); 76 | inst.addMessage(barMsg); 77 | inst._index.should.have.property('foo'); 78 | inst._index.should.have.property('bar'); 79 | }); 80 | it('deletes a head node', () => { 81 | inst = new TimeoutExtender(getSquissStub()); 82 | inst.addMessage(fooMsg); 83 | inst.addMessage(barMsg); 84 | inst.addMessage(bazMsg); 85 | inst.deleteMessage(fooMsg); 86 | inst._linkedList.head!.message.raw.MessageId!.should.equal('bar'); 87 | }); 88 | it('deletes a tail node', () => { 89 | inst = new TimeoutExtender(getSquissStub()); 90 | inst.addMessage(fooMsg); 91 | inst.addMessage(barMsg); 92 | inst.addMessage(bazMsg); 93 | inst.deleteMessage(bazMsg); 94 | inst._linkedList.tail!.message.raw.MessageId!.should.equal('bar'); 95 | }); 96 | it('deletes a middle node', () => { 97 | inst = new TimeoutExtender(getSquissStub()); 98 | inst.addMessage(fooMsg); 99 | inst.addMessage(barMsg); 100 | inst.addMessage(bazMsg); 101 | inst.deleteMessage(barMsg); 102 | inst._linkedList.head!.next.message.raw.MessageId!.should.equal('baz'); 103 | }); 104 | it('renews a message approaching expiry', () => { 105 | clock = sinon.useFakeTimers(100000); 106 | const squiss = getSquissStub(); 107 | const spy = sinon.spy(squiss, 'changeMessageVisibility'); 108 | inst = new TimeoutExtender(squiss, {visibilityTimeoutSecs: 10}); 109 | inst.addMessage(fooMsg); 110 | spy.should.not.be.called(); 111 | clock.tick(6000); 112 | spy.should.be.calledOnce(); 113 | }); 114 | it('emits "timeoutExtended" on renewal', (done) => { 115 | clock = sinon.useFakeTimers(100000); 116 | const squiss = getSquissStub(); 117 | squiss.on('timeoutExtended', (msg: Message) => { 118 | msg.should.equal(fooMsg); 119 | done(); 120 | }); 121 | inst = new TimeoutExtender(squiss, {visibilityTimeoutSecs: 10}); 122 | inst.addMessage(fooMsg); 123 | clock.tick(6000); 124 | }); 125 | it('renews two messages approaching expiry', () => { 126 | clock = sinon.useFakeTimers(100000); 127 | const squiss = getSquissStub(); 128 | const spy = sinon.spy(squiss, 'changeMessageVisibility'); 129 | inst = new TimeoutExtender(squiss, {visibilityTimeoutSecs: 20}); 130 | inst.addMessage(fooMsg); 131 | clock.tick(10000); 132 | inst.addMessage(barMsg); 133 | spy.should.not.be.called(); 134 | clock.tick(10000); 135 | spy.should.be.calledOnce(); 136 | clock.tick(10000); 137 | spy.callCount.should.eql(3); 138 | clock.tick(10000); 139 | spy.callCount.should.eql(4); 140 | }); 141 | it('renews multiple times with proper advanced time', () => { 142 | clock = sinon.useFakeTimers(100000); 143 | const squiss = getSquissStub(); 144 | const spy = sinon.spy(squiss, 'changeMessageVisibility'); 145 | inst = new TimeoutExtender(squiss, {visibilityTimeoutSecs: 20}); 146 | inst.addMessage(fooMsg); 147 | clock.tick(10000); 148 | spy.should.not.be.called(); 149 | clock.tick(5000); 150 | spy.should.be.calledOnce(); 151 | clock.tick(15000); 152 | spy.should.be.calledTwice(); 153 | clock.tick(15000); 154 | spy.should.be.calledThrice(); 155 | }); 156 | it('renews only until the configured age limit', () => { 157 | const keepSpyMessage = sinon.spy(); 158 | const keepSpySquiss = sinon.spy(); 159 | const timeoutSpyMessage = sinon.spy(); 160 | const timeoutSpySquiss = sinon.spy(); 161 | clock = sinon.useFakeTimers(100000); 162 | const squiss = getSquissStub(); 163 | squiss.on('timeoutReached', timeoutSpySquiss); 164 | fooMsg.on('timeoutReached', timeoutSpyMessage); 165 | squiss.on('keep', keepSpySquiss); 166 | fooMsg.on('keep', keepSpyMessage); 167 | const spy = sinon.spy(squiss, 'changeMessageVisibility'); 168 | inst = new TimeoutExtender(squiss, {visibilityTimeoutSecs: 10, noExtensionsAfterSecs: 15}); 169 | inst.addMessage(fooMsg); 170 | clock.tick(10000); 171 | spy.should.be.calledOnce(); 172 | clock.tick(20000); 173 | spy.should.be.calledOnce(); 174 | fooMsg.isHandled().should.eql(true); 175 | keepSpyMessage.should.be.calledOnce(); 176 | keepSpySquiss.should.be.calledOnce(); 177 | keepSpySquiss.should.be.calledWith(fooMsg); 178 | timeoutSpyMessage.should.be.calledOnce(); 179 | timeoutSpySquiss.should.be.calledOnce(); 180 | timeoutSpySquiss.should.be.calledWith(fooMsg); 181 | }); 182 | it('emits error on the parent Squiss object in case of issue', (done) => { 183 | clock = sinon.useFakeTimers(100000); 184 | const squiss = getSquissStub(); 185 | squiss.on('autoExtendError', () => done()); 186 | squiss.changeMessageVisibility = sinon.stub().returns(Promise.reject(new Error('test'))); 187 | inst = new TimeoutExtender(squiss, {visibilityTimeoutSecs: 10}); 188 | inst.addMessage(fooMsg); 189 | clock.tick(6000); 190 | }); 191 | it('calls changeMessageVisibility with the appropriate timeout value', () => { 192 | clock = sinon.useFakeTimers(100000); 193 | const squiss = getSquissStub(); 194 | const spy = sinon.spy(squiss, 'changeMessageVisibility'); 195 | inst = new TimeoutExtender(squiss, {visibilityTimeoutSecs: 10}); 196 | inst.addMessage(fooMsg); 197 | clock.tick(6000); 198 | spy.should.be.calledWith(fooMsg, 10); 199 | }); 200 | it('emits autoExtendFail when an extended message has already been deleted', (done) => { 201 | clock = sinon.useFakeTimers(100000); 202 | const expectedError = new Error('Value AQEB5iHoiWO4nU0Tx3mGzJLdXNQ+fg3nadtYYTDoWMhuOiUOP7sjZTgC64MlRbSwFneA5+' + 203 | 'C+fS5DGRbiEC1VAF0KTMEBrgEOVAQpwRQo8yfie8ltzf+0LLasaHrTB1IFDIvQ0+wsrM4PxXiDJD1tzQ2kw89ijfP4W4tAy6Dqvd5mhlAn' + 204 | 'V+Gvq5IhSRrlzUx9ZOSZyoYPfWN7KwJVKrCWYIyGN3nkGaKwTc+HlJ3jABjTEWHULD9lZjWfBXMWY9bvIVvYuyg2BkSjqb/WKdM6eSPjIA' + 205 | 'UxPIeI6HlkCccfAr9i2GeRmUJp+29g6l0kw3WKJ8msybx1kRzZ11E9++pbhay62SAZKeHZ/E+KuV1jwCJ9nFYPPPk/SwsgUSO1Q4ULYc/0' + 206 | ' for parameter ReceiptHandle is invalid. Reason: Message does not exist or is not available for visibility ' + 207 | 'timeout change.'); 208 | const squiss = getSquissStub(); 209 | squiss.on('autoExtendFail', (obj: any) => { 210 | try { 211 | obj.should.deep.equal({ 212 | message: fooMsg, 213 | error: expectedError, 214 | }); 215 | } catch (e) { 216 | return done(e); 217 | } 218 | return done(); 219 | }); 220 | squiss.changeMessageVisibility = sinon.stub().returns(Promise.reject(expectedError)); 221 | inst = new TimeoutExtender(squiss, {visibilityTimeoutSecs: 10}); 222 | inst.addMessage(fooMsg); 223 | clock.tick(6000); 224 | }); 225 | it('emits autoExtendFail when an extended message receipt handle has expired', (done) => { 226 | clock = sinon.useFakeTimers(100000); 227 | const expectedError = new Error('Value AQEB5iHoiWO4nU0Tx3mGzJLdXNQ+fg3nadtYYTDoWMhuOiUOP7sjZTgC64MlRbSwFneA5+' + 228 | 'C+fS5DGRbiEC1VAF0KTMEBrgEOVAQpwRQo8yfie8ltzf+0LLasaHrTB1IFDIvQ0+wsrM4PxXiDJD1tzQ2kw89ijfP4W4tAy6Dqvd5mhlAn' + 229 | 'V+Gvq5IhSRrlzUx9ZOSZyoYPfWN7KwJVKrCWYIyGN3nkGaKwTc+HlJ3jABjTEWHULD9lZjWfBXMWY9bvIVvYuyg2BkSjqb/WKdM6eSPjIA' + 230 | 'UxPIeI6HlkCccfAr9i2GeRmUJp+29g6l0kw3WKJ8msybx1kRzZ11E9++pbhay62SAZKeHZ/E+KuV1jwCJ9nFYPPPk/SwsgUSO1Q4ULYc/0' + 231 | ' for parameter ReceiptHandle is invalid. Reason: The receipt handle has expired'); 232 | const squiss = getSquissStub(); 233 | squiss.on('autoExtendFail', (obj: any) => { 234 | try { 235 | obj.should.deep.equal({ 236 | message: fooMsg, 237 | error: expectedError, 238 | }); 239 | } catch (e) { 240 | return done(e); 241 | } 242 | return done(); 243 | }); 244 | squiss.changeMessageVisibility = sinon.stub().returns(Promise.reject(expectedError)); 245 | inst = new TimeoutExtender(squiss, {visibilityTimeoutSecs: 10}); 246 | inst.addMessage(fooMsg); 247 | clock.tick(6000); 248 | }); 249 | it('emits autoExtendFail when an extended message receipt handle is not valid', (done) => { 250 | clock = sinon.useFakeTimers(100000); 251 | const expectedError = new Error('Value AQEB5iHoiWO4nU0Tx3mGzJLdXNQ+fg3nadtYYTDoWMhuOiUOP7sjZTgC64MlRbSwFneA5+' + 252 | 'C+fS5DGRbiEC1VAF0KTMEBrgEOVAQpwRQo8yfie8ltzf+0LLasaHrTB1IFDIvQ0+wsrM4PxXiDJD1tzQ2kw89ijfP4W4tAy6Dqvd5mhlAn' + 253 | 'V+Gvq5IhSRrlzUx9ZOSZyoYPfWN7KwJVKrCWYIyGN3nkGaKwTc+HlJ3jABjTEWHULD9lZjWfBXMWY9bvIVvYuyg2BkSjqb/WKdM6eSPjIA' + 254 | 'UxPIeI6HlkCccfAr9i2GeRmUJp+29g6l0kw3WKJ8msybx1kRzZ11E9++pbhay62SAZKeHZ/E+KuV1jwCJ9nFYPPPk/SwsgUSO1Q4ULYc/0' + 255 | ' for parameter ReceiptHandle is invalid. Reason: Not a valid receipt handle'); 256 | const squiss = getSquissStub(); 257 | squiss.on('autoExtendFail', (obj: any) => { 258 | try { 259 | obj.should.deep.equal({ 260 | message: fooMsg, 261 | error: expectedError, 262 | }); 263 | } catch (e) { 264 | return done(e); 265 | } 266 | return done(); 267 | }); 268 | squiss.changeMessageVisibility = sinon.stub().returns(Promise.reject(expectedError)); 269 | inst = new TimeoutExtender(squiss, {visibilityTimeoutSecs: 10}); 270 | inst.addMessage(fooMsg); 271 | clock.tick(6000); 272 | }); 273 | it('emits autoExtendFail when an extended message receipt handle is not valid - by error name', (done) => { 274 | clock = sinon.useFakeTimers(100000); 275 | const expectedError = new Error('Value AQEB5iHoiWO4nU0Tx3mGzJLdXNQ+fg3nadtYYTDoWMhuOiUOP7sjZTgC64MlRbSwFneA5+' + 276 | 'C+fS5DGRbiEC1VAF0KTMEBrgEOVAQpwRQo8yfie8ltzf+0LLasaHrTB1IFDIvQ0+wsrM4PxXiDJD1tzQ2kw89ijfP4W4tAy6Dqvd5mhlAn' + 277 | 'V+Gvq5IhSRrlzUx9ZOSZyoYPfWN7KwJVKrCWYIyGN3nkGaKwTc+HlJ3jABjTEWHULD9lZjWfBXMWY9bvIVvYuyg2BkSjqb/WKdM6eSPjIA' + 278 | 'UxPIeI6HlkCccfAr9i2GeRmUJp+29g6l0kw3WKJ8msybx1kRzZ11E9++pbhay62SAZKeHZ/E+KuV1jwCJ9nFYPPPk/SwsgUSO1Q4ULYc/0' + 279 | ' for parameter ReceiptHandle is invalid'); 280 | expectedError.name = 'ReceiptHandleIsInvalid'; 281 | const squiss = getSquissStub(); 282 | squiss.on('autoExtendFail', (obj: any) => { 283 | try { 284 | obj.should.deep.equal({ 285 | message: fooMsg, 286 | error: expectedError, 287 | }); 288 | } catch (e) { 289 | return done(e); 290 | } 291 | return done(); 292 | }); 293 | squiss.changeMessageVisibility = sinon.stub().returns(Promise.reject(expectedError)); 294 | inst = new TimeoutExtender(squiss, {visibilityTimeoutSecs: 10}); 295 | inst.addMessage(fooMsg); 296 | clock.tick(6000); 297 | }); 298 | it('emits autoExtendFail when an extended message receipt handle is not in flight', (done) => { 299 | clock = sinon.useFakeTimers(100000); 300 | const expectedError = new Error('Value AQEB5iHoiWO4nU0Tx3mGzJLdXNQ+fg3nadtYYTDoWMhuOiUOP7sjZTgC64MlRbSwFneA5+' + 301 | 'C+fS5DGRbiEC1VAF0KTMEBrgEOVAQpwRQo8yfie8ltzf+0LLasaHrTB1IFDIvQ0+wsrM4PxXiDJD1tzQ2kw89ijfP4W4tAy6Dqvd5mhlAn' + 302 | 'V+Gvq5IhSRrlzUx9ZOSZyoYPfWN7KwJVKrCWYIyGN3nkGaKwTc+HlJ3jABjTEWHULD9lZjWfBXMWY9bvIVvYuyg2BkSjqb/WKdM6eSPjIA' + 303 | 'UxPIeI6HlkCccfAr9i2GeRmUJp+29g6l0kw3WKJ8msybx1kRzZ11E9++pbhay62SAZKeHZ/E+KuV1jwCJ9nFYPPPk/SwsgUSO1Q4ULYc/0' + 304 | ' for parameter ReceiptHandle is invalid'); 305 | expectedError.name = 'MessageNotInflight'; 306 | const squiss = getSquissStub(); 307 | squiss.on('autoExtendFail', (obj: any) => { 308 | try { 309 | obj.should.deep.equal({ 310 | message: fooMsg, 311 | error: expectedError, 312 | }); 313 | } catch (e) { 314 | return done(e); 315 | } 316 | return done(); 317 | }); 318 | squiss.changeMessageVisibility = sinon.stub().returns(Promise.reject(expectedError)); 319 | inst = new TimeoutExtender(squiss, {visibilityTimeoutSecs: 10}); 320 | inst.addMessage(fooMsg); 321 | clock.tick(6000); 322 | }); 323 | it('extends only to the message lifetime maximum', () => { 324 | clock = sinon.useFakeTimers(43200000); 325 | const squiss = getSquissStub(); 326 | const spy = sinon.spy(squiss, 'changeMessageVisibility'); 327 | inst = new TimeoutExtender(squiss, {visibilityTimeoutSecs: 10}); 328 | inst.addMessage(fooMsg); 329 | inst._linkedList.head!.receivedOn = 20000; 330 | clock.tick(6000); 331 | spy.should.be.calledWith(fooMsg, 10); 332 | }); 333 | }); 334 | -------------------------------------------------------------------------------- /src/test/src/Message.spec.ts: -------------------------------------------------------------------------------- 1 | import {IMessageAttributes, Message, Squiss, S3} from '../../'; 2 | import {Message as SQSMessage} from '@aws-sdk/client-sqs'; 3 | import {SquissStub} from '../stubs/SquissStub'; 4 | import {Blobs, S3Stub} from '../stubs/S3Stub'; 5 | import delay from 'delay'; 6 | 7 | const wait = (ms?: number) => delay(ms ?? 20 ); 8 | 9 | const getSquissStub = () => { 10 | return new SquissStub() as any as Squiss; 11 | }; 12 | 13 | const getS3Stub = (blobs?: Blobs) => { 14 | const stub = new S3Stub(blobs) as any as S3; 15 | return () => stub; 16 | }; 17 | 18 | function getSQSMsg(body?: string): SQSMessage { 19 | return { 20 | MessageId: 'msgId', 21 | ReceiptHandle: 'handle', 22 | MD5OfBody: 'abcdeabcdeabcdeabcdeabcdeabcde12', 23 | Body: body, 24 | MessageAttributes: { 25 | SomeNumber: { 26 | DataType: 'Number', 27 | StringValue: '1', 28 | }, 29 | SomeString: { 30 | DataType: 'String', 31 | StringValue: 's', 32 | }, 33 | SomeBinary: { 34 | DataType: 'Binary', 35 | BinaryValue: Buffer.from(['s'.charCodeAt(0)]), 36 | }, 37 | SomeCustomBinary: { 38 | DataType: 'CustomBinary', 39 | BinaryValue: Buffer.from(['c'.charCodeAt(0)]), 40 | }, 41 | }, 42 | }; 43 | } 44 | 45 | const snsMsg = { 46 | Type: 'Notification', 47 | MessageId: 'some-id', 48 | TopicArn: 'arn:aws:sns:us-east-1:1234567890:sns-topic-name', 49 | Subject: 'some-subject', 50 | Message: 'foo', 51 | Timestamp: '2015-11-25T04:17:37.741Z', 52 | SignatureVersion: '1', 53 | Signature: 'dGVzdAo=', 54 | SigningCertURL: 'https://sns.us-east-1.amazonaws.com/SimpleNotificationService-bb750dd426d95ee9390147a5624348ee.pem', 55 | UnsubscribeURL: 'https://sns.us-east-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-east-1:1234567890:sns-topic-name:12345678-1234-4321-1234-123456789012', 56 | }; 57 | 58 | describe('Message', () => { 59 | it('unwraps an SNS message', () => { 60 | const msg = new Message({ 61 | squiss: getSquissStub(), 62 | msg: getSQSMsg(JSON.stringify(snsMsg)), 63 | unwrapSns: true, 64 | bodyFormat: 'plain', 65 | s3Retriever: getS3Stub(), 66 | s3Retain: false, 67 | }); 68 | const attributes: IMessageAttributes = msg.attributes; 69 | attributes.should.have.property('SomeNumber').equal(1); 70 | attributes.should.have.property('SomeString').equal('s'); 71 | msg.should.have.property('body').equal('foo'); 72 | msg.should.have.property('subject').equal('some-subject'); 73 | msg.should.have.property('topicArn').equal(snsMsg.TopicArn); 74 | msg.should.have.property('topicName').equal('sns-topic-name'); 75 | }); 76 | it('unwraps an SNS message with empty body', () => { 77 | const msg = new Message({ 78 | squiss: getSquissStub(), 79 | msg: getSQSMsg(''), 80 | unwrapSns: true, 81 | bodyFormat: 'plain', 82 | s3Retriever: getS3Stub(), 83 | s3Retain: false, 84 | }); 85 | msg.should.have.property('body').equal(undefined); 86 | msg.should.have.property('subject').equal(undefined); 87 | msg.should.have.property('topicArn').equal(undefined); 88 | }); 89 | it('parses JSON', () => { 90 | const msg = new Message({ 91 | squiss: getSquissStub(), 92 | msg: getSQSMsg('{"Message":"foo","bar":"baz"}'), 93 | bodyFormat: 'json', 94 | s3Retriever: getS3Stub(), 95 | s3Retain: false, 96 | }); 97 | return msg.parse() 98 | .then(() => { 99 | msg.should.have.property('body'); 100 | msg.body!.should.be.an('object'); 101 | msg.body!.should.have.property('Message').equal('foo'); 102 | msg.body!.should.have.property('bar').equal('baz'); 103 | msg.attributes.should.be.eql({ 104 | SomeNumber: 1, 105 | SomeString: 's', 106 | SomeBinary: Buffer.from(['s'.charCodeAt(0)]), 107 | SomeCustomBinary: Buffer.from(['c'.charCodeAt(0)]), 108 | }); 109 | }); 110 | }); 111 | it('parses S3 JSON', () => { 112 | const bucket = 'my_bucket'; 113 | const key = 'my_key'; 114 | const blobs: Blobs = {}; 115 | blobs[bucket] = {}; 116 | blobs[bucket][key] = '{"i": 1}'; 117 | const rawMsg = getSQSMsg(JSON.stringify({bucket, key})); 118 | rawMsg.MessageAttributes!.__SQS_S3__ = { 119 | DataType: 'Number', 120 | StringValue: '1', 121 | }; 122 | const msg = new Message({ 123 | squiss: getSquissStub(), 124 | msg: rawMsg, 125 | bodyFormat: 'json', 126 | s3Retriever: getS3Stub(blobs), 127 | s3Retain: false, 128 | }); 129 | return msg.parse() 130 | .then(() => { 131 | msg.should.have.property('body'); 132 | msg.body!.should.be.an('object'); 133 | msg.body!.should.have.property('i').equal(1); 134 | }); 135 | }); 136 | it('parses gzipped JSON', () => { 137 | const rawMsg = getSQSMsg('iwOAeyJpIjogMX0D'); 138 | rawMsg.MessageAttributes!.__SQS_GZIP__ = { 139 | DataType: 'Number', 140 | StringValue: '1', 141 | }; 142 | const msg = new Message({ 143 | squiss: getSquissStub(), 144 | msg: rawMsg, 145 | bodyFormat: 'json', 146 | s3Retriever: getS3Stub(), 147 | s3Retain: false, 148 | }); 149 | return msg.parse() 150 | .then(() => { 151 | msg.should.have.property('body'); 152 | msg.body!.should.be.an('object'); 153 | msg.body!.should.have.property('i').equal(1); 154 | }); 155 | }); 156 | it('parses gzipped S3 JSON', () => { 157 | const bucket = 'my_bucket'; 158 | const key = 'my_key'; 159 | const blobs: Blobs = {}; 160 | blobs[bucket] = {}; 161 | blobs[bucket][key] = 'iwOAeyJpIjogMX0D'; 162 | const rawMsg = getSQSMsg(JSON.stringify({bucket, key})); 163 | rawMsg.MessageAttributes!.__SQS_S3__ = { 164 | DataType: 'Number', 165 | StringValue: '1', 166 | }; 167 | rawMsg.MessageAttributes!.__SQS_GZIP__ = { 168 | DataType: 'Number', 169 | StringValue: '1', 170 | }; 171 | const msg = new Message({ 172 | squiss: getSquissStub(), 173 | msg: rawMsg, 174 | bodyFormat: 'json', 175 | s3Retriever: getS3Stub(blobs), 176 | s3Retain: false, 177 | }); 178 | return msg.parse() 179 | .then(() => { 180 | msg.should.have.property('body'); 181 | msg.body!.should.be.an('object'); 182 | msg.body!.should.have.property('i').equal(1); 183 | }); 184 | }); 185 | it('parses gzipped plain', () => { 186 | const rawMsg = getSQSMsg('iwOAeyJpIjogMX0D'); 187 | rawMsg.MessageAttributes!.__SQS_GZIP__ = { 188 | DataType: 'Number', 189 | StringValue: '1', 190 | }; 191 | const msg = new Message({ 192 | squiss: getSquissStub(), 193 | msg: rawMsg, 194 | s3Retriever: getS3Stub(), 195 | s3Retain: false, 196 | }); 197 | return msg.parse() 198 | .then(() => { 199 | msg.should.have.property('body'); 200 | msg.body!.should.eql('{"i": 1}'); 201 | }); 202 | }); 203 | it('not parse empty gzipped body', () => { 204 | const rawMsg = getSQSMsg(); 205 | rawMsg.MessageAttributes!.__SQS_GZIP__ = { 206 | DataType: 'Number', 207 | StringValue: '1', 208 | }; 209 | const msg = new Message({ 210 | squiss: getSquissStub(), 211 | msg: rawMsg, 212 | s3Retriever: getS3Stub(), 213 | s3Retain: false, 214 | }); 215 | return msg.parse() 216 | .then(() => { 217 | msg.should.have.property('body').equals(undefined); 218 | }); 219 | }); 220 | it('parses empty string as json', () => { 221 | const msg = new Message({ 222 | squiss: getSquissStub(), 223 | msg: getSQSMsg(''), 224 | bodyFormat: 'json', 225 | s3Retriever: getS3Stub(), 226 | s3Retain: false, 227 | }); 228 | return msg.parse() 229 | .then(() => { 230 | msg.should.have.property('body'); 231 | msg.body!.should.be.an('object'); 232 | }); 233 | }); 234 | it('not parse empty body', () => { 235 | const msg = new Message({ 236 | squiss: getSquissStub(), 237 | msg: getSQSMsg(), 238 | bodyFormat: 'json', 239 | s3Retriever: getS3Stub(), 240 | s3Retain: false, 241 | }); 242 | return msg.parse() 243 | .then(() => { 244 | msg.should.have.property('body').equal(undefined); 245 | }); 246 | }); 247 | it('removes S3 on delete', (done) => { 248 | const bucket = 'my_bucket'; 249 | const key = 'my_key'; 250 | const uploadSize = 50; 251 | const blobs: Blobs = {}; 252 | blobs[bucket] = {}; 253 | blobs[bucket][key] = '{"i": 1}'; 254 | const rawMsg = getSQSMsg(JSON.stringify({bucket, key, uploadSize})); 255 | rawMsg.MessageAttributes!.__SQS_S3__ = { 256 | DataType: 'Number', 257 | StringValue: '1', 258 | }; 259 | let squissS3DeleteEventEmitted = false; 260 | let squissS3DownloadEventEmitted = false; 261 | let msgS3DeleteEventEmitted = false; 262 | let msgS3DownloadEventEmitted = false; 263 | const msg = new Message({ 264 | squiss: { 265 | deleteMessage: (toDel: Message) => { 266 | blobs[bucket].should.not.have.property(key); 267 | toDel.should.equal(msg); 268 | squissS3DeleteEventEmitted.should.eql(true); 269 | msgS3DeleteEventEmitted.should.eql(true); 270 | squissS3DownloadEventEmitted.should.eql(true); 271 | msgS3DownloadEventEmitted.should.eql(true); 272 | done(); 273 | }, 274 | emit: (event: string, data: any) => { 275 | console.log(event); 276 | data.data.bucket.should.eql(bucket); 277 | data.data.key.should.eql(key); 278 | data.data.uploadSize.should.eql(uploadSize); 279 | data.message.should.eql(msg); 280 | squissS3DeleteEventEmitted = squissS3DeleteEventEmitted || event === 's3Delete'; 281 | squissS3DownloadEventEmitted = squissS3DownloadEventEmitted || event === 's3Download'; 282 | }, 283 | } as any as Squiss, 284 | msg: rawMsg, 285 | bodyFormat: 'json', 286 | s3Retriever: getS3Stub(blobs), 287 | s3Retain: false, 288 | }); 289 | msg.on('s3Delete', (data) => { 290 | data.bucket.should.eql(bucket); 291 | data.key.should.eql(key); 292 | data.uploadSize.should.eql(uploadSize); 293 | msgS3DeleteEventEmitted = true; 294 | }); 295 | msg.on('s3Download', (data) => { 296 | data.bucket.should.eql(bucket); 297 | data.key.should.eql(key); 298 | data.uploadSize.should.eql(uploadSize); 299 | msgS3DownloadEventEmitted = true; 300 | }); 301 | msg.parse() 302 | .then(() => { 303 | msg.should.have.property('body'); 304 | msg.body!.should.be.an('object'); 305 | msg.body!.should.have.property('i').equal(1); 306 | msg.del(); 307 | }); 308 | }); 309 | it('does not removes S3 on delete when s3Retain is set', (done) => { 310 | const bucket = 'my_bucket'; 311 | const key = 'my_key'; 312 | const blobs: Blobs = {}; 313 | blobs[bucket] = {}; 314 | blobs[bucket][key] = '{"i": 1}'; 315 | const rawMsg = getSQSMsg(JSON.stringify({bucket, key})); 316 | rawMsg.MessageAttributes!.__SQS_S3__ = { 317 | DataType: 'Number', 318 | StringValue: '1', 319 | }; 320 | let squissS3DeleteEventEmitted = false; 321 | let squissS3DownloadEventEmitted = false; 322 | let msgS3DeleteEventEmitted = false; 323 | let msgS3DownloadEventEmitted = false; 324 | const msg = new Message({ 325 | squiss: { 326 | deleteMessage: (toDel: Message) => { 327 | blobs[bucket].should.have.property(key); 328 | toDel.should.equal(msg); 329 | squissS3DeleteEventEmitted.should.eql(false); 330 | msgS3DeleteEventEmitted.should.eql(false); 331 | squissS3DownloadEventEmitted.should.eql(true); 332 | msgS3DownloadEventEmitted.should.eql(true); 333 | done(); 334 | }, 335 | emit: (event: string, data: any) => { 336 | squissS3DeleteEventEmitted = squissS3DeleteEventEmitted || event === 's3Delete'; 337 | squissS3DownloadEventEmitted = squissS3DownloadEventEmitted || event === 's3Download'; 338 | }, 339 | } as any as Squiss, 340 | msg: rawMsg, 341 | bodyFormat: 'json', 342 | s3Retriever: getS3Stub(blobs), 343 | s3Retain: true, 344 | }); 345 | msg.on('s3Delete', () => { 346 | msgS3DeleteEventEmitted = true; 347 | }); 348 | msg.on('s3Download', () => { 349 | msgS3DownloadEventEmitted = true; 350 | }); 351 | msg.parse() 352 | .then(() => { 353 | msg.should.have.property('body'); 354 | msg.body!.should.be.an('object'); 355 | msg.body!.should.have.property('i').equal(1); 356 | msg.del(); 357 | }); 358 | }); 359 | it('calls Squiss.deleteMessage on delete', (done) => { 360 | const msg = new Message({ 361 | msg: getSQSMsg('{"Message":"foo","bar":"baz"}'), 362 | bodyFormat: 'json', 363 | squiss: { 364 | deleteMessage: (toDel: Message) => { 365 | toDel.should.equal(msg); 366 | done(); 367 | }, 368 | } as any as Squiss, 369 | s3Retriever: getS3Stub(), 370 | s3Retain: false, 371 | }); 372 | msg.del(); 373 | }); 374 | it('should not mark as handled if failed to delete message', () => { 375 | const msg = new Message({ 376 | msg: getSQSMsg('{"Message":"foo","bar":"baz"}'), 377 | bodyFormat: 'json', 378 | squiss: { 379 | deleteMessage: (toDel: Message) => { 380 | return Promise.reject(new Error('Delete failed')); 381 | }, 382 | } as any as Squiss, 383 | s3Retriever: getS3Stub(), 384 | s3Retain: false, 385 | }); 386 | return msg.del() 387 | .then(() => { 388 | msg.isHandled().should.eql(false); 389 | }); 390 | }); 391 | it('should not mark as handled if failed to release message', () => { 392 | const msg = new Message({ 393 | msg: getSQSMsg('{"Message":"foo","bar":"baz"}'), 394 | bodyFormat: 'json', 395 | squiss: { 396 | releaseMessage: (toDel: Message) => { 397 | return Promise.reject(new Error('Release failed')); 398 | }, 399 | } as any as Squiss, 400 | s3Retriever: getS3Stub(), 401 | s3Retain: false, 402 | }); 403 | return msg.release() 404 | .then(() => { 405 | msg.isHandled().should.eql(false); 406 | }); 407 | }); 408 | it('calls Squiss.handledMessage on keep', (done) => { 409 | const msg = new Message({ 410 | msg: getSQSMsg('{"Message":"foo","bar":"baz"}'), 411 | bodyFormat: 'json', 412 | squiss: { 413 | handledMessage: () => done(), 414 | } as any as Squiss, 415 | s3Retriever: getS3Stub(), 416 | s3Retain: false, 417 | }); 418 | msg.keep(); 419 | }); 420 | it('treats del(), keep(), and release() as idempotent', () => { 421 | let calls = 0; 422 | const msg = new Message({ 423 | msg: getSQSMsg('{"Message":"foo","bar":"baz"}'), 424 | bodyFormat: 'json', 425 | squiss: { 426 | deleteMessage: () => { 427 | calls += 1; 428 | }, 429 | handledMessage: () => { 430 | calls += 10; 431 | }, 432 | releaseMessage: () => { 433 | calls += 100; 434 | }, 435 | } as any as Squiss, 436 | s3Retriever: getS3Stub(), 437 | s3Retain: false, 438 | }); 439 | msg.del(); 440 | msg.keep(); 441 | msg.release(); 442 | msg.del(); 443 | return wait() 444 | .then(() => { 445 | calls.should.equal(1); 446 | }); 447 | }); 448 | it('calls Squiss.changeMessageVisibility on changeVisibility', (done) => { 449 | const timeout = 10; 450 | const message = new Message({ 451 | msg: getSQSMsg('{"Message":"foo","bar":"baz"}'), 452 | bodyFormat: 'json', 453 | squiss: { 454 | changeMessageVisibility: (msg: Message, timeoutInSeconds: number) => { 455 | msg.should.be.eql(message); 456 | timeoutInSeconds.should.be.eql(timeout); 457 | done(); 458 | }, 459 | } as any as Squiss, 460 | s3Retriever: getS3Stub(), 461 | s3Retain: false, 462 | }); 463 | message.changeVisibility(timeout); 464 | }); 465 | it('calls Squiss.releaseMessage on release', (done) => { 466 | const message = new Message({ 467 | msg: getSQSMsg('{"Message":"foo","bar":"baz"}'), 468 | bodyFormat: 'json', 469 | squiss: { 470 | releaseMessage: (msg: Message) => { 471 | msg.should.eql(message); 472 | return Promise.resolve(); 473 | }, 474 | } as any as Squiss, 475 | s3Retriever: getS3Stub(), 476 | s3Retain: false, 477 | }); 478 | message.release() 479 | .then(() => { 480 | done(); 481 | }); 482 | }); 483 | }); 484 | -------------------------------------------------------------------------------- /src/Squiss.ts: -------------------------------------------------------------------------------- 1 | import {EventEmitter} from 'events'; 2 | import {Message} from './Message'; 3 | import {ITimeoutExtenderOptions, TimeoutExtender} from './TimeoutExtender'; 4 | import {createMessageAttributes, IMessageAttributes} from './attributeUtils'; 5 | import {isString} from 'ts-type-guards'; 6 | import { ReceiveMessageCommandInput, 7 | BatchResultErrorEntry, 8 | SendMessageBatchRequestEntry, 9 | SendMessageBatchResult, 10 | SendMessageBatchResultEntry, 11 | SendMessageBatchCommandInput, 12 | SendMessageBatchCommandOutput, 13 | SendMessageCommandInput, 14 | SQSServiceException, 15 | ReceiveMessageCommandOutput, 16 | SQS, CreateQueueCommandInput, 17 | GetQueueUrlCommandInput, 18 | SendMessageCommandOutput, 19 | Message as SQSMessage,DeleteMessageBatchCommandOutput 20 | } from '@aws-sdk/client-sqs' 21 | import {S3} from '@aws-sdk/client-s3' 22 | import {GZIP_MARKER, compressMessage} from './gzipUtils'; 23 | import {S3_MARKER, uploadBlob} from './s3Utils'; 24 | import {getMessageSize} from './messageSizeUtils'; 25 | import { 26 | IMessageToSend, ISendMessageRequest, 27 | IDeleteQueueItem, IDeleteQueueItemById, optDefaults, SquissEmitter, ISquissOptions 28 | } from './Types'; 29 | import {removeEmptyKeys} from './Utils'; 30 | import { URL } from 'url'; 31 | import {Endpoint, EndpointV2} from '@aws-sdk/types'; 32 | 33 | const AWS_MAX_SEND_BATCH = 10; 34 | 35 | export class Squiss extends (EventEmitter as new() => SquissEmitter) { 36 | 37 | public get inFlight(): number { 38 | return this._inFlight; 39 | } 40 | 41 | public get running(): boolean { 42 | return this._running; 43 | } 44 | 45 | public sqs: SQS; 46 | public _timeoutExtender: TimeoutExtender | undefined; 47 | public _opts: ISquissOptions; 48 | private _s3?: S3; 49 | private _running = false; 50 | private _paused = true; 51 | private _inFlight = 0; 52 | private _queueVisibilityTimeout = 0; 53 | private _queueMaximumMessageSize = 0; 54 | private _queueUrl: string; 55 | private _delQueue = new Map(); 56 | private _delTimer: any; 57 | private _activeReq: AbortController | undefined; 58 | 59 | constructor(opts?: ISquissOptions ) { 60 | super(); 61 | this._opts = { 62 | ...optDefaults, 63 | ...(opts ?? {}), 64 | }; 65 | this._initOpts(); 66 | this._queueUrl = this._opts.queueUrl ?? ''; 67 | this.sqs = this._initSqs(); 68 | } 69 | 70 | public changeMessageVisibility(msg: Message | string, timeoutInSeconds: number): Promise { 71 | let receiptHandle: string; 72 | if (msg instanceof Message) { 73 | receiptHandle = msg.raw.ReceiptHandle!; 74 | } else { 75 | receiptHandle = msg; 76 | } 77 | return this.getQueueUrl() 78 | .then((queueUrl) => { 79 | return this.sqs.changeMessageVisibility({ 80 | QueueUrl: queueUrl, 81 | ReceiptHandle: receiptHandle, 82 | VisibilityTimeout: timeoutInSeconds, 83 | }); 84 | } 85 | ) 86 | .then(() => { 87 | return Promise.resolve(); 88 | }); 89 | } 90 | 91 | public createQueue(): Promise { 92 | if (!this._opts.queueName) { 93 | return Promise.reject(new Error('Squiss was not instantiated with a queueName')); 94 | } 95 | const params: CreateQueueCommandInput = { 96 | QueueName: this._opts.queueName, 97 | Attributes: { 98 | ReceiveMessageWaitTimeSeconds: this._opts.receiveWaitTimeSecs!.toString(), 99 | DelaySeconds: this._opts.delaySecs!.toString(), 100 | MaximumMessageSize: this._opts.maxMessageBytes!.toString(), 101 | MessageRetentionPeriod: this._opts.messageRetentionSecs!.toString(), 102 | }, 103 | }; 104 | if (this._opts.visibilityTimeoutSecs) { 105 | params.Attributes!.VisibilityTimeout = this._opts.visibilityTimeoutSecs.toString(); 106 | } 107 | if (this._opts.queuePolicy) { 108 | params.Attributes!.Policy = this._opts.queuePolicy; 109 | } 110 | return this.sqs.createQueue(params).then((res) => { 111 | this._queueUrl = res.QueueUrl!; 112 | return res.QueueUrl!; 113 | }); 114 | } 115 | 116 | public async deleteMessage(msg: Message): Promise { 117 | if (!msg.raw) { 118 | throw new Error('Squiss.deleteMessage requires a Message object'); 119 | } 120 | const promise = new Promise((resolve, reject) => { 121 | this._delQueue.set(msg.raw.MessageId!, 122 | {msg, Id: msg.raw.MessageId!, ReceiptHandle: msg.raw.ReceiptHandle!, resolve, reject}); 123 | }); 124 | msg.emit('delQueued'); 125 | this.emit('delQueued', msg); 126 | this.handledMessage(msg); 127 | if (this._delQueue.size >= this._opts.deleteBatchSize!) { 128 | if (this._delTimer) { 129 | clearTimeout(this._delTimer); 130 | this._delTimer = undefined; 131 | } 132 | await this._deleteXMessages(this._opts.deleteBatchSize); 133 | } else if (!this._delTimer) { 134 | this._delTimer = setTimeout(async () => { 135 | this._delTimer = undefined; 136 | await this._deleteXMessages(); 137 | }, this._opts.deleteWaitMs); 138 | } 139 | return promise; 140 | } 141 | 142 | public deleteQueue(): Promise { 143 | return this.getQueueUrl() 144 | .then((queueUrl) => { 145 | return this.sqs.deleteQueue({QueueUrl: queueUrl}); 146 | }) 147 | .then(() => { 148 | return Promise.resolve(); 149 | }); 150 | } 151 | 152 | public getQueueUrl(): Promise { 153 | if (this._queueUrl) { 154 | return Promise.resolve(this._queueUrl); 155 | } 156 | const params: GetQueueUrlCommandInput = {QueueName: this._opts.queueName!}; 157 | if (this._opts.accountNumber) { 158 | params.QueueOwnerAWSAccountId = this._opts.accountNumber.toString(); 159 | } 160 | return this.sqs.getQueueUrl(params).then(async (data) => { 161 | this._queueUrl = data.QueueUrl!; 162 | if (this._opts.correctQueueUrl) { 163 | let newUrl: URL | undefined; 164 | const endpoint = this.sqs.config.endpoint; 165 | /* istanbul ignore else */ 166 | if (typeof endpoint === 'string') { 167 | newUrl = new URL(endpoint); 168 | } else if (typeof endpoint === 'function') { 169 | const retrievedEndpoint = await endpoint(); 170 | if (retrievedEndpoint && typeof retrievedEndpoint === 'object') { 171 | if ('url' in retrievedEndpoint) { 172 | newUrl = new URL((retrievedEndpoint as EndpointV2).url.toString()); 173 | } 174 | if ('hostname' in retrievedEndpoint) { 175 | const { protocol, hostname, port, path } = retrievedEndpoint as Endpoint; 176 | // query params are ignored in setting endpoint. 177 | newUrl = new URL(`${protocol}//${hostname}${port ? ':' + port : ''}${path}`); 178 | } 179 | } 180 | } 181 | /* istanbul ignore if */ 182 | if (!newUrl) { 183 | throw new Error('Failed to get configured SQQ endpoint'); 184 | } 185 | const parsedQueueUrl = new URL(this._queueUrl); 186 | newUrl.pathname = parsedQueueUrl.pathname; 187 | this._queueUrl = newUrl.toString(); 188 | } 189 | return this._queueUrl; 190 | }); 191 | } 192 | 193 | public getQueueVisibilityTimeout(): Promise { 194 | if (this._queueVisibilityTimeout) { 195 | return Promise.resolve(this._queueVisibilityTimeout); 196 | } 197 | return this.getQueueUrl().then((queueUrl) => { 198 | return this.sqs.getQueueAttributes({ 199 | AttributeNames: ['VisibilityTimeout'], 200 | QueueUrl: queueUrl, 201 | }); 202 | }).then((res) => { 203 | if (!res.Attributes?.VisibilityTimeout) { 204 | throw new Error('SQS.GetQueueAttributes call did not return expected shape. Response: ' + 205 | JSON.stringify(res)); 206 | } 207 | this._queueVisibilityTimeout = parseInt(res.Attributes.VisibilityTimeout, 10); 208 | return this._queueVisibilityTimeout; 209 | }); 210 | } 211 | 212 | public getQueueMaximumMessageSize(): Promise { 213 | if (this._queueMaximumMessageSize) { 214 | return Promise.resolve(this._queueMaximumMessageSize); 215 | } 216 | return this.getQueueUrl().then((queueUrl) => { 217 | return this.sqs.getQueueAttributes({ 218 | AttributeNames: ['MaximumMessageSize'], 219 | QueueUrl: queueUrl, 220 | }); 221 | }).then((res) => { 222 | if (!res.Attributes?.MaximumMessageSize) { 223 | throw new Error('SQS.GetQueueAttributes call did not return expected shape. Response: ' + 224 | JSON.stringify(res)); 225 | } 226 | this._queueMaximumMessageSize = parseInt(res.Attributes.MaximumMessageSize, 10); 227 | return this._queueMaximumMessageSize; 228 | }); 229 | } 230 | 231 | public handledMessage(msg: Message): void { 232 | this._inFlight--; 233 | if (this._paused && this._slotsAvailable()) { 234 | this._paused = false; 235 | this._startPoller() 236 | .catch((e: Error) => { 237 | this.emit('error', e); 238 | }); 239 | } 240 | msg.emit('handled'); 241 | this.emit('handled', msg); 242 | if (!this._inFlight) { 243 | this.emit('drained'); 244 | } 245 | } 246 | 247 | public releaseMessage(msg: Message): Promise { 248 | this.handledMessage(msg); 249 | return this.changeMessageVisibility(msg, 0) 250 | .then((res) => { 251 | msg.emit('released'); 252 | this.emit('released', msg); 253 | return res; 254 | }); 255 | } 256 | 257 | public purgeQueue(): Promise { 258 | return this.getQueueUrl() 259 | .then((queueUrl) => { 260 | return this.sqs.purgeQueue({QueueUrl: queueUrl}); 261 | }) 262 | .then(() => { 263 | this._inFlight = 0; 264 | this._delQueue = new Map(); 265 | this._delTimer = undefined; 266 | return Promise.resolve(); 267 | }); 268 | } 269 | 270 | public sendMessage(message: IMessageToSend, delay?: number, attributes?: IMessageAttributes) 271 | : Promise { 272 | return Promise.all([ 273 | this._prepareMessageRequest(message, delay, attributes), 274 | this.getQueueUrl(), 275 | ]) 276 | .then((data) => { 277 | const rawParams = data[0]; 278 | const queueUrl = data[1]; 279 | const params: SendMessageCommandInput = { 280 | QueueUrl: queueUrl, 281 | ...rawParams, 282 | }; 283 | return this.sqs.sendMessage(params); 284 | }); 285 | } 286 | 287 | public sendMessages(messages: IMessageToSend[] | IMessageToSend, delay?: number, 288 | attributes?: IMessageAttributes | IMessageAttributes[]) 289 | : Promise { 290 | return this.getQueueMaximumMessageSize() 291 | .then((queueMaximumMessageSize) => { 292 | return this._prepareMessagesToSend(messages, queueMaximumMessageSize, delay, attributes); 293 | }) 294 | .then((batches) => { 295 | return Promise.all(batches.map((batch, idx) => { 296 | return this._sendMessageBatch(batch, delay, idx * AWS_MAX_SEND_BATCH); 297 | })); 298 | }) 299 | .then((results) => { 300 | const successful: SendMessageBatchResultEntry[] = []; 301 | const failed: BatchResultErrorEntry[] = []; 302 | results.forEach((res) => { 303 | res.Successful?.forEach((elem) => successful.push(elem)); 304 | res.Failed?.forEach((elem) => failed.push(elem)); 305 | }); 306 | return {Successful: successful, Failed: failed}; 307 | }); 308 | } 309 | 310 | public start(): Promise { 311 | if (this._running) { 312 | return Promise.resolve(); 313 | } 314 | this._running = true; 315 | return this._startPoller(); 316 | } 317 | 318 | public async stop(soft?: boolean, timeout?: number): Promise { 319 | if (!soft && this._activeReq) { 320 | this._activeReq.abort(); 321 | } 322 | this._running = this._paused = false; 323 | if (!this._inFlight) { 324 | await this._drainDeleteQueue(); 325 | return true; 326 | } 327 | let resolved = false; 328 | let timer: any; 329 | const result = await new Promise((resolve) => { 330 | this.on('drained',() => { 331 | if (!resolved) { 332 | resolved = true; 333 | if (timer) { 334 | clearTimeout(timer); 335 | timer = undefined; 336 | } 337 | resolve(true); 338 | } 339 | }); 340 | timer = timeout ? setTimeout(() => { 341 | resolved = true; 342 | resolve(false); 343 | }, timeout) : undefined; 344 | }); 345 | await this._drainDeleteQueue(); 346 | return result; 347 | } 348 | 349 | public getS3(): S3 { 350 | if (!this._s3) { 351 | this._s3 = this._initS3(); 352 | } 353 | return this._s3; 354 | } 355 | 356 | private async _drainDeleteQueue(): Promise { 357 | if (this._delTimer) { 358 | clearTimeout(this._delTimer); 359 | this._delTimer = undefined; 360 | } 361 | await this._deleteXMessages(); 362 | } 363 | 364 | private _initS3() { 365 | if (this._opts.S3) { 366 | if (typeof this._opts.S3 === 'function') { 367 | return new this._opts.S3(this._opts.awsConfig || {}); 368 | } else { 369 | return this._opts.S3; 370 | } 371 | } else { 372 | /* istanbul ignore next */ 373 | return new S3(this._opts.awsConfig || {}); 374 | } 375 | } 376 | 377 | private _initOpts() { 378 | if (!this._opts.queueUrl && !this._opts.queueName) { 379 | throw new Error('Squiss requires either the "queueUrl", or the "queueName".'); 380 | } 381 | if (this._opts.s3Fallback && !this._opts.s3Bucket) { 382 | throw new Error('Squiss requires "s3Bucket" to be defined is using s3 fallback'); 383 | } 384 | this._opts.deleteBatchSize = Math.min(this._opts.deleteBatchSize!, 10); 385 | this._opts.receiveBatchSize = Math.min(this._opts.receiveBatchSize!, 386 | this._opts.maxInFlight! > 0 ? this._opts.maxInFlight! : 10, 10); 387 | this._opts.minReceiveBatchSize = Math.min(this._opts.minReceiveBatchSize!, this._opts.receiveBatchSize); 388 | } 389 | 390 | private async _deleteMessages(batch: IDeleteQueueItem[]): Promise { 391 | if (batch.length === 0) { 392 | return; 393 | } 394 | return this.getQueueUrl().then((queueUrl) => { 395 | return this.sqs.deleteMessageBatch({ 396 | QueueUrl: queueUrl, 397 | Entries: batch.map((item) => { 398 | return { 399 | Id: item.Id, 400 | ReceiptHandle: item.ReceiptHandle, 401 | }; 402 | }), 403 | }); 404 | }).then(this._handleBatchDeleteResults(batch)) 405 | .catch((err: Error) => { 406 | this.emit('error', err); 407 | }); 408 | } 409 | 410 | private _emitMessages(messages: SQSMessage[]): void { 411 | messages.forEach((msg) => { 412 | const message = new Message({ 413 | squiss: this, 414 | unwrapSns: this._opts.unwrapSns, 415 | bodyFormat: this._opts.bodyFormat, 416 | msg, 417 | s3Retriever: this.getS3.bind(this), 418 | s3Retain: this._opts.s3Retain || false, 419 | }); 420 | this._inFlight++; 421 | message.parse() 422 | .then(() => { 423 | this.emit('message', message); 424 | }) 425 | .catch((e: Error) => { 426 | this.emit('error', e); 427 | message.release(); 428 | }); 429 | }); 430 | } 431 | 432 | private _getBatch(queueUrl: string): void { 433 | if (this._activeReq || !this._running) { 434 | return; 435 | } 436 | const maxMessagesToGet = this._getMaxMessagesToGet(); 437 | if (maxMessagesToGet < this._opts.minReceiveBatchSize!) { 438 | this._paused = true; 439 | return; 440 | } 441 | const params: ReceiveMessageCommandInput = removeEmptyKeys({ 442 | QueueUrl: queueUrl, MaxNumberOfMessages: maxMessagesToGet, 443 | WaitTimeSeconds: this._opts.receiveWaitTimeSecs, 444 | MessageAttributeNames: this._opts.receiveAttributes, 445 | AttributeNames: this._opts.receiveSqsAttributes, 446 | VisibilityTimeout: this._opts.visibilityTimeoutSecs, 447 | }); 448 | const controller = new AbortController(); 449 | this._activeReq = controller; 450 | this.sqs.receiveMessage(params, { 451 | abortSignal: controller.signal, 452 | }).then(this._handleGetBatchResult(queueUrl)).catch((err: SQSServiceException) => { 453 | this._activeReq = undefined; 454 | if (err.name === 'AbortError') { 455 | this.emit('aborted', err); 456 | } else { 457 | setTimeout(this._getBatch.bind(this, queueUrl), this._opts.pollRetryMs); 458 | this.emit('error', err); 459 | } 460 | }); 461 | } 462 | 463 | private _initTimeoutExtender(): Promise { 464 | if (!this._opts.autoExtendTimeout || this._timeoutExtender) { 465 | return Promise.resolve(); 466 | } 467 | return Promise.resolve().then(() => { 468 | if (this._opts.visibilityTimeoutSecs) { 469 | return this._opts.visibilityTimeoutSecs; 470 | } 471 | return this.getQueueVisibilityTimeout(); 472 | }).then((visibilityTimeoutSecs) => { 473 | const opts: ITimeoutExtenderOptions = {visibilityTimeoutSecs}; 474 | if (this._opts.noExtensionsAfterSecs) { 475 | opts.noExtensionsAfterSecs = this._opts.noExtensionsAfterSecs; 476 | } 477 | if (this._opts.advancedCallMs) { 478 | opts.advancedCallMs = this._opts.advancedCallMs; 479 | } 480 | this._timeoutExtender = new TimeoutExtender(this, opts); 481 | }); 482 | } 483 | 484 | private _sendMessageBatch(messages: ISendMessageRequest[], delay: number | undefined, startIndex: number): 485 | Promise { 486 | const start = startIndex || 0; 487 | return this.getQueueUrl().then((queueUrl) => { 488 | const entries: SendMessageBatchRequestEntry[] = []; 489 | const params: SendMessageBatchCommandInput = { 490 | QueueUrl: queueUrl, 491 | Entries: entries, 492 | }; 493 | const promises: Promise[] = []; 494 | messages.forEach((msg, idx) => { 495 | const entry: SendMessageBatchRequestEntry = { 496 | Id: (start + idx).toString(), 497 | ...msg, 498 | }; 499 | entries.push(entry); 500 | }); 501 | return Promise.all(promises) 502 | .then(() => { 503 | return this.sqs.sendMessageBatch(params); 504 | }); 505 | }); 506 | } 507 | 508 | private _slotsAvailable(): boolean { 509 | return !this._opts.maxInFlight || this._inFlight < this._opts.maxInFlight; 510 | } 511 | 512 | private _startPoller(): Promise { 513 | return this._initTimeoutExtender() 514 | .then(() => this.getQueueUrl()) 515 | .then((queueUrl): void => { 516 | this._getBatch(queueUrl); 517 | }) 518 | } 519 | 520 | private async _deleteXMessages(x?: number): Promise { 521 | const delQueue = this._delQueue; 522 | const iterator = delQueue.entries(); 523 | let length = x ?? delQueue.size; 524 | /* istanbul ignore next */ 525 | length = length <= delQueue.size ? length : delQueue.size 526 | const delBatch = Array.from({length}, function(this: typeof iterator) { 527 | const element = this.next().value; 528 | /* istanbul ignore next */ 529 | if (!element) { 530 | throw new Error('Unexpected undefined element in delete queue'); 531 | } 532 | delQueue.delete(element[0]); 533 | return element[1]; 534 | }, iterator); 535 | await this._deleteMessages(delBatch); 536 | } 537 | 538 | private _isLargeMessage(message: ISendMessageRequest, minSize?: number): Promise { 539 | const messageSize = getMessageSize(message); 540 | if (minSize) { 541 | return Promise.resolve(messageSize > minSize); 542 | } 543 | return this.getQueueMaximumMessageSize() 544 | .then((queueMaximumMessageSize) => { 545 | return messageSize >= queueMaximumMessageSize; 546 | }); 547 | } 548 | 549 | private _prepareMessageParams(message: IMessageToSend, delay?: number, attributes?: IMessageAttributes) { 550 | const messageStr = isString(message) ? message : JSON.stringify(message); 551 | const params: ISendMessageRequest = {MessageBody: messageStr, DelaySeconds: delay}; 552 | attributes = {...attributes}; 553 | params.MessageGroupId = attributes.FIFO_MessageGroupId; 554 | delete attributes.FIFO_MessageGroupId; 555 | params.MessageDeduplicationId = attributes.FIFO_MessageDeduplicationId; 556 | delete attributes.FIFO_MessageDeduplicationId; 557 | params.MessageAttributes = createMessageAttributes(attributes); 558 | let getMessagePromise = Promise.resolve(messageStr); 559 | if (this._opts.gzip && (!this._opts.minGzipSize || getMessageSize(params) >= this._opts.minGzipSize)) { 560 | getMessagePromise = compressMessage(messageStr); 561 | params.MessageAttributes = params.MessageAttributes || {}; 562 | params.MessageAttributes[GZIP_MARKER] = { 563 | StringValue: '1', 564 | DataType: 'Number', 565 | }; 566 | } 567 | return getMessagePromise.then((finalMessage) => { 568 | params.MessageBody = finalMessage; 569 | return {finalMessage, params}; 570 | }); 571 | } 572 | 573 | private _handleLargeMessagePrepare({finalMessage, params}: { finalMessage: string, params: ISendMessageRequest }) { 574 | if (!this._opts.s3Fallback) { 575 | return Promise.resolve(params); 576 | } 577 | return this._isLargeMessage(params, this._opts.minS3Size) 578 | .then((isLarge) => { 579 | if (!isLarge) { 580 | return Promise.resolve(params); 581 | } 582 | return uploadBlob(this.getS3(), this._opts.s3Bucket!, finalMessage, this._opts.s3Prefix || '') 583 | .then((uploadData) => { 584 | this.emit('s3Upload', uploadData); 585 | params.MessageBody = JSON.stringify(uploadData); 586 | params.MessageAttributes = params.MessageAttributes ?? {}; 587 | params.MessageAttributes[S3_MARKER] = { 588 | StringValue: `${uploadData.uploadSize}`, 589 | DataType: 'Number', 590 | }; 591 | return Promise.resolve(params); 592 | }); 593 | }); 594 | } 595 | 596 | private _prepareMessageRequest(message: IMessageToSend, delay?: number, attributes?: IMessageAttributes) 597 | : Promise { 598 | if (attributes?.[GZIP_MARKER]) { 599 | return Promise.reject(new Error(`Using of internal attribute ${GZIP_MARKER} is not allowed`)); 600 | } 601 | if (attributes?.[S3_MARKER]) { 602 | return Promise.reject(new Error(`Using of internal attribute ${S3_MARKER} is not allowed`)); 603 | } 604 | return this._prepareMessageParams(message, delay, attributes) 605 | .then(this._handleLargeMessagePrepare.bind(this)) 606 | .then((params) => { 607 | return removeEmptyKeys(params); 608 | }); 609 | } 610 | 611 | private _initSqs() { 612 | if (this._opts.SQS) { 613 | if (typeof this._opts.SQS === 'function') { 614 | return new this._opts.SQS(this._opts.awsConfig || {}); 615 | } else { 616 | return this._opts.SQS; 617 | } 618 | } else { 619 | return new SQS(this._opts.awsConfig || {}); 620 | } 621 | } 622 | 623 | private _handleBatchDeleteResults(batch: IDeleteQueueItem[]) { 624 | const itemById: IDeleteQueueItemById = batch.reduce((prevByValue, item) => { 625 | prevByValue[item.Id] = item; 626 | return prevByValue; 627 | }, {} as IDeleteQueueItemById); 628 | return (data: DeleteMessageBatchCommandOutput) => { 629 | if (data.Failed?.length) { 630 | data.Failed.forEach((fail) => { 631 | /* istanbul ignore next */ 632 | const item = itemById[fail.Id ?? '']; 633 | this.emit('delError', {error: fail, message: item.msg}); 634 | item.msg.emit('delError', fail); 635 | item.reject(fail); 636 | }); 637 | } 638 | if (data.Successful?.length) { 639 | data.Successful.forEach((success) => { 640 | /* istanbul ignore next */ 641 | const id = success.Id ?? ''; 642 | const item = itemById[id]; 643 | const msg = item.msg; 644 | this.emit('deleted', {msg, successId: id}); 645 | msg.emit('deleted', id); 646 | item.resolve(); 647 | }); 648 | } 649 | }; 650 | } 651 | 652 | private _prepareMessagesToSend(messages: IMessageToSend[] | IMessageToSend, queueMaximumMessageSize: number, 653 | delay?: number, attributes?: IMessageAttributes | IMessageAttributes[]) { 654 | const msgs: IMessageToSend[] = Array.isArray(messages) ? messages : [messages]; 655 | const defaultAttributes = (attributes && !Array.isArray(attributes)) ? attributes : undefined; 656 | const arrayAttributes = (attributes && Array.isArray(attributes)) ? attributes : []; 657 | const promises = msgs.map((msg, i) => { 658 | return this._prepareMessageRequest(msg, delay, defaultAttributes || arrayAttributes[i]); 659 | }); 660 | return Promise.all(promises) 661 | .then((requests) => { 662 | const batches: ISendMessageRequest[][] = []; 663 | let currentBatchSize = 0; 664 | let currentBatchLength = 0; 665 | requests.forEach((message) => { 666 | const messageSize = getMessageSize(message); 667 | if (currentBatchLength % AWS_MAX_SEND_BATCH === 0 || 668 | currentBatchSize + messageSize >= queueMaximumMessageSize) { 669 | currentBatchLength = currentBatchSize = 0; 670 | batches.push([]); 671 | } 672 | currentBatchSize += messageSize; 673 | currentBatchLength++; 674 | batches[batches.length - 1].push(message); 675 | }); 676 | return batches; 677 | }); 678 | } 679 | 680 | private _handleGetBatchResult(queueUrl: string) { 681 | return (data: ReceiveMessageCommandOutput) => { 682 | let gotMessages = true; 683 | this._activeReq = undefined; 684 | if (data?.Messages) { 685 | this.emit('gotMessages', data.Messages.length); 686 | this._emitMessages(data.Messages); 687 | } else { 688 | this.emit('queueEmpty'); 689 | gotMessages = false; 690 | } 691 | if (this._slotsAvailable()) { 692 | const next = this._getBatch.bind(this, queueUrl); 693 | if (gotMessages && this._opts.activePollIntervalMs) { 694 | setTimeout(next, this._opts.activePollIntervalMs); 695 | } else if (!gotMessages && this._opts.idlePollIntervalMs) { 696 | setTimeout(next, this._opts.idlePollIntervalMs); 697 | } else { 698 | next(); 699 | } 700 | } else { 701 | this._paused = true; 702 | this.emit('maxInFlight'); 703 | } 704 | }; 705 | } 706 | 707 | private _getMaxMessagesToGet() { 708 | return !this._opts.maxInFlight ? this._opts.receiveBatchSize! : 709 | Math.min(this._opts.maxInFlight - this._inFlight, this._opts.receiveBatchSize!); 710 | } 711 | } 712 | -------------------------------------------------------------------------------- /src/test/src/index.spec.ts: -------------------------------------------------------------------------------- 1 | import * as proxyquire from 'proxyquire'; 2 | 3 | const uuidStub = () => { 4 | return 'my_uuid'; 5 | }; 6 | const stubs = { 7 | 'uuid': { 8 | v4: uuidStub, 9 | '@global': true, 10 | }, 11 | }; 12 | 13 | const {Squiss: SquissPatched, Message: MessagePatched} = proxyquire('../../', stubs); 14 | 15 | import {ISquissOptions, Squiss, Message} from '../../'; 16 | import {SQSStub} from '../stubs/SQSStub'; 17 | import delay from 'delay'; 18 | import {IMessageOpts } from '../../Message'; 19 | // @ts-ignore 20 | import * as sinon from 'sinon'; 21 | import * as chai from 'chai'; 22 | import {GetQueueUrlCommandInput, ReceiveMessageRequest, SendMessageBatchResult, SQS} from '@aws-sdk/client-sqs' 23 | import {S3} from '@aws-sdk/client-s3' 24 | import {EventEmitter} from 'events'; 25 | import {Blobs, S3Stub} from '../stubs/S3Stub'; 26 | import {HttpHandlerOptions} from '@aws-sdk/types'; 27 | 28 | const should = chai.should(); 29 | let inst: Squiss | null = null; 30 | const wait = (ms?: number) => delay(ms ?? 20); 31 | 32 | const getS3Stub = (blobs?: Blobs) => { 33 | return new S3Stub(blobs) as any as S3; 34 | }; 35 | 36 | const generateLargeMessage = (length: number) => { 37 | let result = ''; 38 | for (let i = 0; i < length; i++) { 39 | result += 's'; 40 | } 41 | return result; 42 | }; 43 | 44 | describe('index', () => { 45 | afterEach(() => { 46 | if (inst) { 47 | inst.stop(); 48 | } 49 | inst = null; 50 | }); 51 | describe('constructor', () => { 52 | it('creates a new SquissPatched instance', () => { 53 | inst = new SquissPatched({ 54 | queueUrl: 'foo', 55 | unwrapSns: true, 56 | visibilityTimeoutSecs: 10, 57 | } as ISquissOptions); 58 | should.exist(inst); 59 | }); 60 | it('fails if queue is not specified', () => { 61 | let errored = false; 62 | try { 63 | new SquissPatched(); 64 | } catch (e: any) { 65 | should.exist(e); 66 | e.should.be.instanceOf(Error); 67 | errored = true; 68 | } 69 | errored.should.eql(true); 70 | }); 71 | it('fail if s3 but no bucket is not specified', () => { 72 | let errored = false; 73 | try { 74 | new SquissPatched({queueUrl: 'foo', s3Fallback: true}); 75 | } catch (e: any) { 76 | should.exist(e); 77 | e.should.be.instanceOf(Error); 78 | errored = true; 79 | } 80 | errored.should.eql(true); 81 | }); 82 | it('provides a configured sqs client instance', async () => { 83 | inst = new SquissPatched({ 84 | queueUrl: 'foo', 85 | awsConfig: { 86 | region: 'us-east-1', 87 | }, 88 | } as ISquissOptions); 89 | inst!.should.have.property('sqs'); 90 | inst!.sqs.should.be.an('object'); 91 | (await inst!.sqs.config.region()).should.equal('us-east-1'); 92 | }); 93 | it('provides a configured s3 client instance', async () => { 94 | inst = new SquissPatched({ 95 | queueUrl: 'foo', 96 | awsConfig: { 97 | region: 'us-east-1', 98 | }, 99 | } as ISquissOptions); 100 | const s3 = inst!.getS3(); 101 | s3.should.be.an('object'); 102 | (await s3.config.region()).should.equal('us-east-1'); 103 | }); 104 | it('accepts an sqs function for instantiation if one is provided', () => { 105 | const spy = sinon.spy(); 106 | inst = new SquissPatched({ 107 | queueUrl: 'foo', 108 | SQS: spy, 109 | } as ISquissOptions); 110 | inst!.should.have.property('sqs'); 111 | (inst!.sqs as any as SQSStub).should.be.an('object'); 112 | spy.should.be.calledOnce(); 113 | }); 114 | it('accepts an s3 function for instantiation if one is provided', () => { 115 | const spy = sinon.spy(); 116 | inst = new SquissPatched({ 117 | queueUrl: 'foo', 118 | S3: spy, 119 | } as ISquissOptions); 120 | const s3 = inst!.getS3(); 121 | s3.should.be.an('object'); 122 | inst!.getS3(); 123 | spy.should.be.calledOnce(); 124 | }); 125 | it('accepts an instance of sqs client if one is provided', () => { 126 | inst = new SquissPatched({ 127 | queueUrl: 'foo', 128 | SQS: {}, 129 | } as ISquissOptions); 130 | inst!.should.have.property('sqs'); 131 | (inst!.sqs as any as SQSStub).should.be.an('object'); 132 | }); 133 | it('accepts an instance of s3 client if one is provided', () => { 134 | inst = new SquissPatched({ 135 | queueUrl: 'foo', 136 | S3: {}, 137 | } as ISquissOptions); 138 | const s3 = inst!.getS3(); 139 | s3.should.be.an('object'); 140 | }); 141 | }); 142 | describe('Receiving', () => { 143 | it('reports the appropriate "running" status', () => { 144 | inst = new SquissPatched({queueUrl: 'foo'} as ISquissOptions); 145 | // @ts-ignore 146 | inst!._getBatch = () => { 147 | }; 148 | inst!.running.should.eq(false); 149 | inst!.start(); 150 | inst!.running.should.eq(true); 151 | }); 152 | it('treats start() as idempotent', () => { 153 | inst = new SquissPatched({queueUrl: 'foo'} as ISquissOptions); 154 | // @ts-ignore 155 | inst!._getBatch = () => { 156 | }; 157 | inst!.running.should.eq(false); 158 | inst!.start(); 159 | inst!.start(); 160 | inst!.running.should.eq(true); 161 | }); 162 | it('receives a batch of messages under the max', () => { 163 | const spy = sinon.spy(); 164 | inst = new SquissPatched({queueUrl: 'foo'} as ISquissOptions); 165 | inst!.sqs = new SQSStub(5) as any as SQS; 166 | inst!.on('gotMessages', spy); 167 | inst!.start(); 168 | return wait().then(() => { 169 | spy.should.be.calledOnce(); 170 | spy.should.be.calledWith(5); 171 | }); 172 | }); 173 | it('receives batches of messages', () => { 174 | const batches: any = []; 175 | const spy = sinon.spy(); 176 | inst = new SquissPatched({queueUrl: 'foo'} as ISquissOptions); 177 | inst!.sqs = new SQSStub(15, 0) as any as SQS; 178 | inst!.on('gotMessages', (count: number) => batches.push({total: count, num: 0})); 179 | inst!.on('message', () => batches[batches.length - 1].num++); 180 | inst!.once('queueEmpty', spy); 181 | inst!.start(); 182 | return wait().then(() => { 183 | spy.should.be.calledOnce(); 184 | batches.should.deep.equal([ 185 | {total: 10, num: 0}, 186 | {total: 5, num: 15}, 187 | ]); 188 | }); 189 | }); 190 | it('receives batches of messages when maxInflight = receiveBatchSize', () => { 191 | const batches: any = []; 192 | const spy = sinon.spy(); 193 | inst = new SquissPatched({queueUrl: 'foo', maxInFlight: 10, receiveBatchSize: 10} as ISquissOptions); 194 | inst!.sqs = new SQSStub(15, 0) as any as SQS; 195 | inst!.on('gotMessages', (count: number) => batches.push({total: count, num: 0})); 196 | inst!.on('message', (m: Message) => { 197 | batches[batches.length - 1].num++; 198 | m.del(); 199 | }); 200 | inst!.once('queueEmpty', spy); 201 | inst!.start(); 202 | return wait(40).then(() => { 203 | spy.should.be.calledOnce(); 204 | batches.should.deep.equal([ 205 | {total: 10, num: 10}, 206 | {total: 5, num: 5}, 207 | ]); 208 | }); 209 | }); 210 | it('receives batches of messages when maxInflight % receiveBatchSize != 0', () => { 211 | const batches: any = []; 212 | const spy = sinon.spy(); 213 | inst = new SquissPatched({queueUrl: 'foo', maxInFlight: 15, receiveBatchSize: 10} as ISquissOptions); 214 | inst!.sqs = new SQSStub(15, 0) as any as SQS; 215 | inst!.on('gotMessages', (count: number) => batches.push({total: count, num: 0})); 216 | inst!.once('queueEmpty', spy); 217 | inst!.on('message', (m: Message) => { 218 | batches[batches.length - 1].num++; 219 | }); 220 | inst!.start(); 221 | return wait().then(() => { 222 | spy.should.not.be.called(); 223 | batches.should.deep.equal([ 224 | {total: 10, num: 0}, 225 | {total: 5, num: 15}, 226 | ]); 227 | }); 228 | }); 229 | it('receives batches of messages as much as it can', () => { 230 | const batches: any = []; 231 | const spy = sinon.spy(); 232 | inst = new SquissPatched({queueUrl: 'foo', maxInFlight: 15, receiveBatchSize: 10} as ISquissOptions); 233 | inst!.sqs = new SQSStub(16, 0) as any as SQS; 234 | inst!.on('gotMessages', (count: number) => batches.push({total: count, num: 0})); 235 | inst!.once('queueEmpty', spy); 236 | inst!.on('message', (m: Message) => { 237 | batches[batches.length - 1].num++; 238 | if (batches.length === 2 && batches[batches.length - 1].num === 5) { 239 | m.del(); 240 | } 241 | }); 242 | inst!.start(); 243 | return wait().then(() => { 244 | spy.should.not.be.called(); 245 | batches.should.deep.equal([ 246 | {total: 10, num: 0}, 247 | {total: 5, num: 15}, 248 | {total: 1, num: 1}, 249 | ]); 250 | }); 251 | }); 252 | it('receives batches of messages as much as it can with min batch size', () => { 253 | const batches: any = []; 254 | const spy = sinon.spy(); 255 | inst = new SquissPatched({ 256 | queueUrl: 'foo', 257 | maxInFlight: 15, 258 | receiveBatchSize: 10, 259 | minReceiveBatchSize: 2, 260 | } as ISquissOptions); 261 | inst!.sqs = new SQSStub(16, 0) as any as SQS; 262 | inst!.on('gotMessages', (count: number) => batches.push({total: count, num: 0})); 263 | inst!.once('queueEmpty', spy); 264 | inst!.on('message', (m: Message) => { 265 | batches[batches.length - 1].num++; 266 | if (batches.length === 2 && batches[batches.length - 1].num >= 14) { 267 | m.del(); 268 | } 269 | }); 270 | inst!.start(); 271 | return wait().then(() => { 272 | spy.should.not.be.called(); 273 | batches.should.deep.equal([ 274 | {total: 10, num: 0}, 275 | {total: 5, num: 15}, 276 | {total: 1, num: 1}, 277 | ]); 278 | }); 279 | }); 280 | it('receives batches of messages as much as it can but with min batch size', () => { 281 | const batches: any = []; 282 | const spy = sinon.spy(); 283 | inst = new SquissPatched({ 284 | queueUrl: 'foo', 285 | maxInFlight: 15, 286 | receiveBatchSize: 10, 287 | minReceiveBatchSize: 2, 288 | } as ISquissOptions); 289 | inst!.sqs = new SQSStub(16, 0) as any as SQS; 290 | inst!.on('gotMessages', (count: number) => batches.push({total: count, num: 0})); 291 | inst!.once('queueEmpty', spy); 292 | inst!.on('message', (m: Message) => { 293 | batches[batches.length - 1].num++; 294 | if (batches.length === 2 && batches[batches.length - 1].num === 5) { 295 | m.del(); 296 | } 297 | }); 298 | inst!.start(); 299 | return wait().then(() => { 300 | spy.should.not.be.called(); 301 | batches.should.deep.equal([ 302 | {total: 10, num: 0}, 303 | {total: 5, num: 15}, 304 | ]); 305 | }); 306 | }); 307 | it('receives batches of messages as much as it can and gets empty', () => { 308 | const batches: any = []; 309 | const spy = sinon.spy(); 310 | inst = new SquissPatched({queueUrl: 'foo', maxInFlight: 15, receiveBatchSize: 10} as ISquissOptions); 311 | inst!.sqs = new SQSStub(15, 0) as any as SQS; 312 | inst!.on('gotMessages', (count: number) => batches.push({total: count, num: 0})); 313 | inst!.once('queueEmpty', spy); 314 | inst!.on('message', (m: Message) => { 315 | batches[batches.length - 1].num++; 316 | if (batches.length === 2 && batches[batches.length - 1].num === 5) { 317 | m.del(); 318 | } 319 | }); 320 | inst!.start(); 321 | return wait().then(() => { 322 | spy.should.be.calledOnce(); 323 | batches.should.deep.equal([ 324 | {total: 10, num: 0}, 325 | {total: 5, num: 15}, 326 | ]); 327 | }); 328 | }); 329 | it('emits error on message parse error', () => { 330 | const msgSpy = sinon.spy(); 331 | const errorSpy = sinon.spy(); 332 | inst = new SquissPatched({bodyFormat: 'json', queueUrl: 'foo', maxInFlight: 15, 333 | receiveBatchSize: 10} as ISquissOptions); 334 | inst!.sqs = new SQSStub(0, 0) as any as SQS; 335 | inst!.on('message', msgSpy); 336 | inst!.on('error', errorSpy); 337 | inst!.start(); 338 | inst!.sendMessage('{sdfsdf'); 339 | return wait().then(() => { 340 | msgSpy.should.not.be.called(); 341 | errorSpy.should.be.calledOnce(); 342 | errorSpy.should.be.calledWith(sinon.match.instanceOf(Error)); 343 | }); 344 | }); 345 | it('emits queueEmpty event with no messages', () => { 346 | const msgSpy = sinon.spy(); 347 | const qeSpy = sinon.spy(); 348 | inst = new SquissPatched({queueUrl: 'foo'} as ISquissOptions); 349 | inst!.sqs = new SQSStub(0, 0) as any as SQS; 350 | inst!.on('message', msgSpy); 351 | inst!.once('queueEmpty', qeSpy); 352 | inst!.start(); 353 | return wait().then(() => { 354 | msgSpy.should.not.be.called(); 355 | qeSpy.should.be.calledOnce(); 356 | }); 357 | }); 358 | it('emits aborted when stopped with an active message req', () => { 359 | const spy = sinon.spy(); 360 | inst = new SquissPatched({queueUrl: 'foo'} as ISquissOptions); 361 | inst!.sqs = new SQSStub(0, 1000) as any as SQS; 362 | inst!.on('aborted', spy); 363 | inst!.start(); 364 | return wait().then(() => { 365 | spy.should.not.be.called(); 366 | inst!.stop(); 367 | return wait(); 368 | }).then(() => { 369 | spy.should.be.calledOnce(); 370 | spy.should.be.calledWith(sinon.match.instanceOf(Error)); 371 | inst!.running.should.eq(false); 372 | }); 373 | }); 374 | it('should resolve when timeout exceeded and queue not drained', () => { 375 | const spy = sinon.spy(); 376 | inst = new SquissPatched({queueUrl: 'foo'} as ISquissOptions); 377 | inst!.sqs = new SQSStub(1, 1000) as any as SQS; 378 | inst!.on('aborted', spy); 379 | inst!.start(); 380 | return wait().then(() => { 381 | spy.should.not.be.called(); 382 | return inst!.stop(false, 1000); 383 | }).then((result: boolean) => { 384 | result.should.eq(false); 385 | }); 386 | }); 387 | it('should resolve when queue already drained', () => { 388 | const spy = sinon.spy(); 389 | const deleteSpy = sinon.spy(); 390 | inst = new SquissPatched({queueUrl: 'foo'} as ISquissOptions); 391 | inst!.sqs = new SQSStub(1, 1000) as any as SQS; 392 | inst!.on('aborted', spy); 393 | inst!.on('deleted', deleteSpy); 394 | inst!.on('message', (msg: Message) => { 395 | msg.del(); 396 | }); 397 | inst!.start(); 398 | return wait().then(() => { 399 | spy.should.not.be.called(); 400 | deleteSpy.should.not.be.called(); 401 | return inst!.stop(false, 1000); 402 | }).then((result: boolean) => { 403 | deleteSpy.should.be.called(); 404 | result.should.eq(true); 405 | }); 406 | }); 407 | it('should resolve when queue drained before timeout', () => { 408 | const spy = sinon.spy(); 409 | const deleteSpy = sinon.spy(); 410 | inst = new SquissPatched({queueUrl: 'foo'} as ISquissOptions); 411 | inst!.sqs = new SQSStub(1, 1000) as any as SQS; 412 | inst!.on('aborted', spy); 413 | inst!.on('deleted', deleteSpy); 414 | inst!.on('message', (msg: Message) => { 415 | setTimeout(() => { 416 | msg.del(); 417 | }, 1000); 418 | }); 419 | inst!.start(); 420 | return wait().then(() => { 421 | spy.should.not.be.called(); 422 | deleteSpy.should.not.be.called(); 423 | return inst!.stop(false, 10000); 424 | }).then((result: boolean) => { 425 | deleteSpy.should.be.called(); 426 | result.should.eq(true); 427 | }); 428 | }); 429 | it('should not double resolve if queue drained after timeout', function() { 430 | this.timeout(5000); 431 | const spy = sinon.spy(); 432 | inst = new SquissPatched({queueUrl: 'foo'} as ISquissOptions); 433 | inst!.sqs = new SQSStub(1, 1000) as any as SQS; 434 | inst!.on('aborted', spy); 435 | inst!.on('message', (msg: Message) => { 436 | setTimeout(() => { 437 | msg.del(); 438 | }, 1000); 439 | }); 440 | inst!.start(); 441 | return wait().then(() => { 442 | spy.should.not.be.called(); 443 | return inst!.stop(false, 50); 444 | }).then((result: boolean) => { 445 | result.should.eq(false); 446 | return wait(2000); 447 | }); 448 | }); 449 | it('observes the maxInFlight cap', () => { 450 | const msgSpy = sinon.spy(); 451 | const maxSpy = sinon.spy(); 452 | inst = new SquissPatched({queueUrl: 'foo', maxInFlight: 10} as ISquissOptions); 453 | inst!.sqs = new SQSStub(15) as any as SQS; 454 | inst!.on('message', msgSpy); 455 | inst!.on('maxInFlight', maxSpy); 456 | inst!.start(); 457 | return wait().then(() => { 458 | msgSpy.should.have.callCount(10); 459 | maxSpy.should.have.callCount(1); 460 | }); 461 | }); 462 | it('respects maxInFlight as 0 (no cap)', () => { 463 | const msgSpy = sinon.spy(); 464 | const qeSpy = sinon.spy(); 465 | const gmSpy = sinon.spy(); 466 | inst = new SquissPatched({queueUrl: 'foo', maxInFlight: 0} as ISquissOptions); 467 | inst!.sqs = new SQSStub(35, 0) as any as SQS; 468 | inst!.on('message', msgSpy); 469 | inst!.on('gotMessages', gmSpy); 470 | inst!.once('queueEmpty', qeSpy); 471 | inst!.start(); 472 | return wait(50).then(() => { 473 | msgSpy.should.have.callCount(35); 474 | gmSpy.should.have.callCount(4); 475 | qeSpy.should.have.callCount(1); 476 | }); 477 | }); 478 | it('reports the correct number of inFlight messages', () => { 479 | const msgs: Message[] = []; 480 | inst = new SquissPatched({queueUrl: 'foo', deleteWaitMs: 1} as ISquissOptions); 481 | inst!.sqs = new SQSStub(5) as any as SQS; 482 | inst!.on('message', (msg: Message) => msgs.push(msg)); 483 | inst!.start(); 484 | return wait().then(() => { 485 | inst!.inFlight.should.equal(5); 486 | inst!.deleteMessage(msgs.pop()!); 487 | inst!.handledMessage(new EventEmitter() as any); 488 | return wait(1); 489 | }).then(() => { 490 | inst!.inFlight.should.equal(3); 491 | }); 492 | }); 493 | it('emits error when start polling fails', () => { 494 | const errorSpy = sinon.spy(); 495 | inst = new SquissPatched({queueUrl: 'foo', deleteWaitMs: 1, maxInFlight: 5} as ISquissOptions); 496 | const sqsStub = new SQSStub(5); 497 | inst!.sqs = sqsStub as any as SQS; 498 | let receiveMessageCallCount = 0; 499 | const originalReceiveMessage = sqsStub.receiveMessage; 500 | sqsStub.receiveMessage = (params?: ReceiveMessageRequest, opts?: HttpHandlerOptions) => { 501 | receiveMessageCallCount++; 502 | if (receiveMessageCallCount === 2) { 503 | throw new Error('test'); 504 | } 505 | return originalReceiveMessage.call(sqsStub, params, opts); 506 | }; 507 | inst!.on('error', errorSpy); 508 | return inst!.start() 509 | .then(() => wait()) 510 | .then(async () => { 511 | inst!.inFlight.should.equal(5); 512 | inst!.handledMessage(new EventEmitter() as any); 513 | await wait(1); 514 | }).then(() => { 515 | inst!.inFlight.should.equal(4); 516 | errorSpy.should.be.calledOnce(); 517 | errorSpy.should.be.calledWith(sinon.match.instanceOf(Error)); 518 | }); 519 | }); 520 | it('pauses polling when maxInFlight is reached; resumes after', () => { 521 | const msgSpy = sinon.spy(); 522 | const maxSpy = sinon.spy(); 523 | inst = new SquissPatched({queueUrl: 'foo', maxInFlight: 10} as ISquissOptions); 524 | inst!.sqs = new SQSStub(11, 1000) as any as SQS; 525 | inst!.on('message', msgSpy); 526 | inst!.on('maxInFlight', maxSpy); 527 | inst!.start(); 528 | return wait().then(() => { 529 | msgSpy.should.have.callCount(10); 530 | maxSpy.should.be.calledOnce(); 531 | for (let i = 0; i < 10; i++) { 532 | inst!.handledMessage(new EventEmitter() as any); 533 | } 534 | return wait(); 535 | }).then(() => { 536 | msgSpy.should.have.callCount(11); 537 | }); 538 | }); 539 | it('observes the visibilityTimeout setting', () => { 540 | inst = new SquissPatched({queueUrl: 'foo', visibilityTimeoutSecs: 10} as ISquissOptions); 541 | inst!.sqs = new SQSStub() as any as SQS; 542 | const spy = sinon.spy(inst!.sqs, 'receiveMessage'); 543 | inst!.start(); 544 | return wait().then(() => { 545 | spy.should.be.calledWith({ 546 | QueueUrl: 'foo', 547 | AttributeNames: ['All'], 548 | MessageAttributeNames: ['All'], 549 | MaxNumberOfMessages: 10, 550 | WaitTimeSeconds: 20, 551 | VisibilityTimeout: 10, 552 | }); 553 | }); 554 | }); 555 | it('observes activePollIntervalMs', () => { 556 | const abortSpy = sinon.spy(); 557 | const gmSpy = sinon.spy(); 558 | inst = new SquissPatched({queueUrl: 'foo', activePollIntervalMs: 1000} as ISquissOptions); 559 | inst!.sqs = new SQSStub(1, 0) as any as SQS; 560 | inst!.on('aborted', abortSpy); 561 | inst!.on('gotMessages', gmSpy); 562 | inst!.start(); 563 | return wait().then(() => { 564 | gmSpy.should.be.calledOnce(); 565 | abortSpy.should.not.be.called(); 566 | }); 567 | }); 568 | it('observes idlePollIntervalMs', () => { 569 | const abortSpy = sinon.spy(); 570 | const qeSpy = sinon.spy(); 571 | inst = new SquissPatched({queueUrl: 'foo', idlePollIntervalMs: 1000} as ISquissOptions); 572 | inst!.sqs = new SQSStub(1, 0) as any as SQS; 573 | inst!.on('aborted', abortSpy); 574 | inst!.on('queueEmpty', qeSpy); 575 | inst!.start(); 576 | return wait().then(() => { 577 | qeSpy.should.be.calledOnce(); 578 | abortSpy.should.not.be.called(); 579 | }); 580 | }); 581 | it('receiveAttributes defaults to all', () => { 582 | inst = new SquissPatched({queueUrl: 'foo'}); 583 | inst!.sqs = new SQSStub() as any as SQS; 584 | const spy = sinon.spy(inst!.sqs, 'receiveMessage'); 585 | inst!.start(); 586 | return wait().then(() => { 587 | spy.should.be.calledWith({ 588 | QueueUrl: 'foo', 589 | MaxNumberOfMessages: 10, 590 | WaitTimeSeconds: 20, 591 | AttributeNames: ['All'], 592 | MessageAttributeNames: ['All'], 593 | }); 594 | }); 595 | }); 596 | it('observes receiveAttributes', () => { 597 | inst = new SquissPatched({queueUrl: 'foo', receiveAttributes: ['a']}); 598 | inst!.sqs = new SQSStub() as any as SQS; 599 | const spy = sinon.spy(inst!.sqs, 'receiveMessage'); 600 | inst!.start(); 601 | return wait().then(() => { 602 | spy.should.be.calledWith({ 603 | QueueUrl: 'foo', 604 | MaxNumberOfMessages: 10, 605 | WaitTimeSeconds: 20, 606 | AttributeNames: ['All'], 607 | MessageAttributeNames: ['a'], 608 | }); 609 | }); 610 | }); 611 | it('observes receiveSqsAttributes', () => { 612 | inst = new SquissPatched({queueUrl: 'foo', receiveSqsAttributes: ['a']}); 613 | inst!.sqs = new SQSStub() as any as SQS; 614 | const spy = sinon.spy(inst!.sqs, 'receiveMessage'); 615 | inst!.start(); 616 | return wait().then(() => { 617 | spy.should.be.calledWith({ 618 | QueueUrl: 'foo', 619 | MaxNumberOfMessages: 10, 620 | WaitTimeSeconds: 20, 621 | AttributeNames: ['a'], 622 | MessageAttributeNames: ['All'], 623 | }); 624 | }); 625 | }); 626 | }); 627 | describe('Deleting', () => { 628 | it('deletes messages using internal API', () => { 629 | const msgs: Message[] = []; 630 | inst = new SquissPatched({queueUrl: 'foo', deleteWaitMs: 1} as ISquissOptions); 631 | inst!.sqs = new SQSStub(5) as any as SQS; 632 | const spy = sinon.spy(inst!.sqs, 'deleteMessageBatch'); 633 | inst!.on('message', (msg: Message) => msgs.push(msg)); 634 | inst!.start(); 635 | let promise: Promise; 636 | return wait().then(() => { 637 | msgs.should.have.length(5); 638 | promise = inst!.deleteMessage(msgs.pop()!); 639 | return wait(10); 640 | }).then(() => { 641 | spy.should.be.calledOnce(); 642 | return promise!.should.be.fulfilled('should be fullfiled'); 643 | }); 644 | }); 645 | it('deletes messages using Message API', () => { 646 | const msgs: Message[] = []; 647 | inst = new SquissPatched({queueUrl: 'foo', deleteWaitMs: 1} as ISquissOptions); 648 | inst!.sqs = new SQSStub(5) as any as SQS; 649 | const spy = sinon.spy(inst!.sqs, 'deleteMessageBatch'); 650 | inst!.on('message', (msg: Message) => msgs.push(msg)); 651 | inst!.start(); 652 | return wait().then(() => { 653 | msgs.should.have.length(5); 654 | msgs.pop()!.del(); 655 | return wait(10); 656 | }).then(() => { 657 | spy.should.be.calledOnce(); 658 | }); 659 | }); 660 | it('deletes messages in batches', () => { 661 | inst = new SquissPatched({queueUrl: 'foo', deleteWaitMs: 10} as ISquissOptions); 662 | inst!.sqs = new SQSStub(15) as any as SQS; 663 | const spy = sinon.spy(inst!.sqs, 'deleteMessageBatch'); 664 | inst!.on('message', (msg: Message) => msg.del()); 665 | inst!.start(); 666 | return wait().then(() => { 667 | spy.should.be.calledTwice(); 668 | }); 669 | }); 670 | it('deletes messages in batches without duplicates', () => { 671 | inst = new SquissPatched({queueUrl: 'foo', deleteWaitMs: 10} as ISquissOptions); 672 | inst!.sqs = new SQSStub(15) as any as SQS; 673 | const spy = sinon.spy(inst!.sqs, 'deleteMessageBatch'); 674 | inst!.on('message', (msg: Message) => { 675 | inst!.deleteMessage(msg); 676 | inst!.deleteMessage(msg); 677 | }); 678 | inst!.start(); 679 | return wait().then(() => { 680 | spy.should.be.calledTwice(); 681 | }); 682 | }); 683 | it('deletes immediately with batch size=1', () => { 684 | inst = new SquissPatched({queueUrl: 'foo', deleteBatchSize: 1} as ISquissOptions); 685 | inst!.sqs = new SQSStub(5) as any as SQS; 686 | const spy = sinon.spy(inst!.sqs, 'deleteMessageBatch'); 687 | inst!.on('message', (msg: Message) => msg.del()); 688 | inst!.start(); 689 | return wait().then(() => { 690 | spy.should.have.callCount(5); 691 | }); 692 | }); 693 | it('emits deleted event', () => { 694 | const msgSpyMessage = sinon.spy(); 695 | const msgSpySquiss = sinon.spy(); 696 | inst = new SquissPatched({queueUrl: 'foo', deleteBatchSize: 1} as ISquissOptions); 697 | inst!.sqs = new SQSStub(1) as any as SQS; 698 | let message: Message; 699 | inst!.on('message', (msg: Message) => { 700 | message = msg; 701 | msg.on('deleted', msgSpyMessage); 702 | msg.del(); 703 | }); 704 | inst!.on('deleted', msgSpySquiss); 705 | inst!.start(); 706 | return wait().then(() => { 707 | msgSpyMessage.should.be.calledOnce(); 708 | msgSpyMessage.should.be.calledWith('id_0'); 709 | msgSpySquiss.should.be.calledOnce(); 710 | msgSpySquiss.should.be.calledWith({successId: 'id_0', msg: message}); 711 | }); 712 | }); 713 | it('delWaitTime timeout should be cleared after timeout runs', () => { 714 | const msgs: Message[] = []; 715 | inst = new SquissPatched({queueUrl: 'foo', deleteBatchSize: 10, deleteWaitMs: 10} as ISquissOptions); 716 | inst!.sqs = new SQSStub(2) as any as SQS; 717 | const spy = sinon.spy(inst, '_deleteMessages'); 718 | inst!.on('message', (msg: Message) => msgs.push(msg)); 719 | inst!.start(); 720 | return wait().then(() => { 721 | inst!.stop(); 722 | msgs[0].del(); 723 | return wait(15); 724 | }).then(() => { 725 | spy.should.be.calledOnce(); 726 | msgs[1].del(); 727 | return wait(15); 728 | }).then(() => { 729 | spy.should.be.calledTwice(); 730 | }); 731 | }); 732 | it('should not call delete api if no messages after stop', () => { 733 | inst = new SquissPatched({queueUrl: 'foo', deleteBatchSize: 10, deleteWaitMs: 10} as ISquissOptions); 734 | inst!.sqs = new SQSStub() as any as SQS; 735 | const spy = sinon.spy(inst!.sqs, 'deleteMessageBatch'); 736 | inst!.start(); 737 | return wait().then(() => { 738 | return inst!.stop(); 739 | }).then(() => { 740 | spy.should.not.be.called(); 741 | }); 742 | }); 743 | it('requires a Message object be sent to deleteMessage', () => { 744 | inst = new SquissPatched({queueUrl: 'foo', deleteBatchSize: 1} as ISquissOptions); 745 | const promise = inst!.deleteMessage('foo' as any); 746 | return promise.should.be.rejectedWith(/Message/); 747 | }); 748 | }); 749 | describe('Failures', () => { 750 | it('emits delError when a message fails to delete', () => { 751 | const spy = sinon.spy(); 752 | inst = new SquissPatched({queueUrl: 'foo', deleteBatchSize: 1} as ISquissOptions); 753 | inst!.sqs = new SQSStub(1) as any as SQS; 754 | inst!.on('delError', spy); 755 | const msg = new MessagePatched({ 756 | msg: { 757 | MessageId: 'foo', 758 | ReceiptHandle: 'bar', 759 | Body: 'baz', 760 | }, 761 | } as IMessageOpts); 762 | inst!.deleteMessage(msg) 763 | .catch(() => { 764 | // DO NOTHING 765 | }); 766 | return wait().then(() => { 767 | spy.should.be.calledOnce(); 768 | spy.should.be.calledWith( 769 | {message: msg, error: {Code: '404', Id: 'foo', Message: 'Does not exist', SenderFault: true}}); 770 | }); 771 | }); 772 | it('emits error when delete call fails', () => { 773 | const spy = sinon.spy(); 774 | inst = new SquissPatched({queueUrl: 'foo', deleteBatchSize: 1} as ISquissOptions); 775 | inst!.sqs = new SQSStub(1) as any as SQS; 776 | (inst!.sqs as any as SQSStub).deleteMessageBatch = () => { 777 | return Promise.reject(new Error('test')); 778 | }; 779 | inst!.on('error', spy); 780 | const msg = new EventEmitter() as any; 781 | msg.raw = { 782 | MessageId: 'foo', 783 | ReceiptHandle: 'bar', 784 | }; 785 | inst!.deleteMessage(msg as Message); 786 | return wait().then(() => { 787 | spy.should.be.calledOnce(); 788 | spy.should.be.calledWith(sinon.match.instanceOf(Error)); 789 | }); 790 | }); 791 | it('emits error when receive call fails', () => { 792 | const spy = sinon.spy(); 793 | inst = new SquissPatched({queueUrl: 'foo'} as ISquissOptions); 794 | inst!.sqs = new SQSStub(1) as any as SQS; 795 | (inst!.sqs as any as SQSStub).receiveMessage = () => { 796 | return Promise.reject(new Error('test')); 797 | }; 798 | inst!.on('error', spy); 799 | inst!.start(); 800 | return wait().then(() => { 801 | spy.should.be.calledOnce(); 802 | spy.should.be.calledWith(sinon.match.instanceOf(Error)); 803 | }); 804 | }); 805 | it('attempts to restart polling after a receive call fails', () => { 806 | const msgSpy = sinon.spy(); 807 | const errSpy = sinon.spy(); 808 | inst = new SquissPatched({queueUrl: 'foo', receiveBatchSize: 1, pollRetryMs: 5} as ISquissOptions); 809 | inst!.sqs = new SQSStub(2) as any as SQS; 810 | (sinon.stub(inst!.sqs, 'receiveMessage').callsFake(() => { 811 | ((inst!.sqs as any as SQSStub).receiveMessage as any).restore(); 812 | return Promise.reject(new Error('test')); 813 | })); 814 | inst!.on('message', msgSpy); 815 | inst!.on('error', errSpy); 816 | inst!.start(); 817 | return wait().then(() => { 818 | errSpy.should.be.calledOnce(); 819 | msgSpy.should.be.calledTwice(); 820 | }); 821 | }); 822 | it('throws error when GetQueueURL call fails on start', () => { 823 | inst = new SquissPatched({queueName: 'foo'} as ISquissOptions); 824 | (inst!.sqs as any as SQSStub).getQueueUrl = (params: GetQueueUrlCommandInput) => { 825 | return Promise.reject(new Error('test')); 826 | }; 827 | return inst!.start().should.be.rejected('not rejected'); 828 | }); 829 | }); 830 | describe('Testing', () => { 831 | it('allows queue URLs to be corrected to the endpoint hostname', () => { 832 | inst = new SquissPatched({queueName: 'foo', correctQueueUrl: true} as ISquissOptions); 833 | inst!.sqs = new SQSStub(1) as any as SQS; 834 | return inst!.getQueueUrl().then((url: string) => { 835 | url.should.equal('http://foo.bar/queues/foo'); 836 | }); 837 | }); 838 | }); 839 | describe('createQueue', () => { 840 | it('rejects if Squiss was instantiated without queueName', () => { 841 | inst = new SquissPatched({queueUrl: 'foo'} as ISquissOptions); 842 | inst!.sqs = new SQSStub(1) as any as SQS; 843 | return inst!.createQueue().should.be.rejected('not rejected'); 844 | }); 845 | it('calls SQS SDK createQueue method with default attributes', () => { 846 | inst = new SquissPatched({queueName: 'foo'} as ISquissOptions); 847 | inst!.sqs = new SQSStub(1) as any as SQS; 848 | const spy = sinon.spy(inst!.sqs, 'createQueue'); 849 | return inst!.createQueue().then((queueUrl: string) => { 850 | queueUrl.should.be.a('string'); 851 | spy.should.be.calledOnce(); 852 | spy.should.be.calledWith({ 853 | QueueName: 'foo', 854 | Attributes: { 855 | ReceiveMessageWaitTimeSeconds: '20', 856 | DelaySeconds: '0', 857 | MaximumMessageSize: '262144', 858 | MessageRetentionPeriod: '345600', 859 | }, 860 | }); 861 | }); 862 | }); 863 | it('configures VisibilityTimeout if specified', () => { 864 | inst = new SquissPatched({queueName: 'foo', visibilityTimeoutSecs: 15} as ISquissOptions); 865 | inst!.sqs = new SQSStub(1) as any as SQS; 866 | const spy = sinon.spy(inst!.sqs, 'createQueue'); 867 | return inst!.createQueue().then((queueUrl: string) => { 868 | queueUrl.should.be.a('string'); 869 | spy.should.be.calledOnce(); 870 | spy.should.be.calledWith({ 871 | QueueName: 'foo', 872 | Attributes: { 873 | ReceiveMessageWaitTimeSeconds: '20', 874 | DelaySeconds: '0', 875 | MaximumMessageSize: '262144', 876 | MessageRetentionPeriod: '345600', 877 | VisibilityTimeout: '15', 878 | }, 879 | }); 880 | }); 881 | }); 882 | it('calls SQS SDK createQueue method with custom attributes', () => { 883 | inst = new SquissPatched({ 884 | queueName: 'foo', 885 | receiveWaitTimeSecs: 10, 886 | delaySecs: 300, 887 | maxMessageBytes: 100, 888 | messageRetentionSecs: 60, 889 | visibilityTimeoutSecs: 10, 890 | queuePolicy: 'foo', 891 | } as ISquissOptions); 892 | inst!.sqs = new SQSStub(1) as any as SQS; 893 | const spy = sinon.spy(inst!.sqs, 'createQueue'); 894 | return inst!.createQueue().then((queueUrl: string) => { 895 | queueUrl.should.be.a('string'); 896 | spy.should.be.calledOnce(); 897 | spy.should.be.calledWith({ 898 | QueueName: 'foo', 899 | Attributes: { 900 | ReceiveMessageWaitTimeSeconds: '10', 901 | DelaySeconds: '300', 902 | MaximumMessageSize: '100', 903 | MessageRetentionPeriod: '60', 904 | VisibilityTimeout: '10', 905 | Policy: 'foo', 906 | }, 907 | }); 908 | }); 909 | }); 910 | }); 911 | describe('changeMessageVisibility', () => { 912 | it('calls SQS SDK changeMessageVisibility method', () => { 913 | inst = new SquissPatched({queueUrl: 'foo'} as ISquissOptions); 914 | inst!.sqs = new SQSStub(1) as any as SQS; 915 | const spy = sinon.spy(inst!.sqs, 'changeMessageVisibility'); 916 | return inst!.changeMessageVisibility('bar', 1).then(() => { 917 | spy.should.be.calledWith({ 918 | QueueUrl: 'foo', 919 | ReceiptHandle: 'bar', 920 | VisibilityTimeout: 1, 921 | }); 922 | }); 923 | }); 924 | it('calls SQS SDK changeMessageVisibility method 2', () => { 925 | inst = new SquissPatched({queueUrl: 'foo'} as ISquissOptions); 926 | inst!.sqs = new SQSStub(1) as any as SQS; 927 | const spy = sinon.spy(inst!.sqs, 'changeMessageVisibility'); 928 | const msg = new MessagePatched({ 929 | msg: { 930 | ReceiptHandle: 'bar', 931 | }, 932 | } as IMessageOpts); 933 | return inst!.changeMessageVisibility(msg, 1).then(() => { 934 | spy.should.be.calledWith({ 935 | QueueUrl: 'foo', 936 | ReceiptHandle: 'bar', 937 | VisibilityTimeout: 1, 938 | }); 939 | }); 940 | }); 941 | }); 942 | describe('deleteQueue', () => { 943 | it('calls SQS SDK deleteQueue method with queue URL', () => { 944 | inst = new SquissPatched({queueUrl: 'foo'}); 945 | inst!.sqs = new SQSStub(1) as any as SQS; 946 | const spy = sinon.spy(inst!.sqs, 'deleteQueue'); 947 | return inst!.deleteQueue().then(() => { 948 | spy.should.be.calledOnce(); 949 | spy.should.be.calledWith({QueueUrl: 'foo'}); 950 | }); 951 | }); 952 | }); 953 | describe('getQueueUrl', () => { 954 | it('resolves with the provided queueUrl without hitting SQS', () => { 955 | inst = new SquissPatched({queueUrl: 'foo'}); 956 | inst!.sqs = new SQSStub(1) as any as SQS; 957 | const spy = sinon.spy(inst!.sqs, 'getQueueUrl'); 958 | return inst!.getQueueUrl().then((queueUrl: string) => { 959 | queueUrl.should.equal('foo'); 960 | spy.should.not.be.called(); 961 | }); 962 | }); 963 | it('asks SQS for the URL if queueUrl was not provided', () => { 964 | inst = new SquissPatched({queueName: 'foo'}); 965 | inst!.sqs = new SQSStub(1) as any as SQS; 966 | const spy = sinon.spy(inst!.sqs, 'getQueueUrl'); 967 | return inst!.getQueueUrl().then((queueUrl: string) => { 968 | queueUrl.indexOf('http').should.equal(0); 969 | spy.should.be.calledOnce(); 970 | spy.should.be.calledWith({QueueName: 'foo'}); 971 | }); 972 | }); 973 | it('caches the queueUrl after the first call to SQS', () => { 974 | inst = new SquissPatched({queueName: 'foo'}); 975 | inst!.sqs = new SQSStub(1) as any as SQS; 976 | const spy = sinon.spy(inst!.sqs, 'getQueueUrl'); 977 | return inst!.getQueueUrl().then(() => { 978 | spy.should.be.calledOnce(); 979 | return inst!.getQueueUrl(); 980 | }).then(() => { 981 | spy.should.be.calledOnce(); 982 | }); 983 | }); 984 | it('includes the account number if provided', () => { 985 | inst = new SquissPatched({queueName: 'foo', accountNumber: 1234}); 986 | inst!.sqs = new SQSStub(1) as any as SQS; 987 | const spy = sinon.spy(inst!.sqs, 'getQueueUrl'); 988 | return inst!.getQueueUrl().then((queueUrl: string) => { 989 | queueUrl.indexOf('http').should.equal(0); 990 | spy.should.be.calledOnce(); 991 | spy.should.be.calledWith({ 992 | QueueName: 'foo', 993 | QueueOwnerAWSAccountId: '1234', 994 | }); 995 | }); 996 | }); 997 | }); 998 | describe('getQueueVisibilityTimeout', () => { 999 | it('makes a successful API call', () => { 1000 | inst = new SquissPatched({queueUrl: 'https://foo'}); 1001 | inst!.sqs = new SQSStub() as any as SQS; 1002 | const spy = sinon.spy(inst!.sqs, 'getQueueAttributes'); 1003 | return inst!.getQueueVisibilityTimeout().then((timeout: number) => { 1004 | should.exist(timeout); 1005 | timeout.should.equal(31); 1006 | spy.should.be.calledOnce(); 1007 | spy.should.be.calledWith({ 1008 | AttributeNames: ['VisibilityTimeout'], 1009 | QueueUrl: 'https://foo', 1010 | }); 1011 | }); 1012 | }); 1013 | it('caches the API call for successive function calls', () => { 1014 | inst = new SquissPatched({queueUrl: 'https://foo'}); 1015 | inst!.sqs = new SQSStub() as any as SQS; 1016 | const spy = sinon.spy(inst!.sqs, 'getQueueAttributes'); 1017 | return inst!.getQueueVisibilityTimeout().then((timeout: number) => { 1018 | timeout.should.equal(31); 1019 | spy.should.be.calledOnce(); 1020 | return inst!.getQueueVisibilityTimeout(); 1021 | }).then((timeout: number) => { 1022 | should.exist(timeout); 1023 | timeout.should.equal(31); 1024 | spy.should.be.calledOnce(); 1025 | }); 1026 | }); 1027 | it('catches badly formed AWS responses', () => { 1028 | inst = new SquissPatched({queueUrl: 'foo'}); 1029 | inst!.sqs = new SQSStub() as any as SQS; 1030 | (inst!.sqs as any as SQSStub).getQueueAttributes = sinon.stub().returns({ 1031 | foo: 'bar', 1032 | }); 1033 | return inst!.getQueueVisibilityTimeout().should.be.rejectedWith(/foo/); 1034 | }); 1035 | }); 1036 | describe('getQueueMaximumMessageSize', () => { 1037 | it('makes a successful API call', () => { 1038 | inst = new SquissPatched({queueUrl: 'https://foo'}); 1039 | inst!.sqs = new SQSStub() as any as SQS; 1040 | const spy = sinon.spy(inst!.sqs, 'getQueueAttributes'); 1041 | return inst!.getQueueMaximumMessageSize().then((timeout: number) => { 1042 | should.exist(timeout); 1043 | timeout.should.equal(200); 1044 | spy.should.be.calledOnce(); 1045 | spy.should.be.calledWith({ 1046 | AttributeNames: ['MaximumMessageSize'], 1047 | QueueUrl: 'https://foo', 1048 | }); 1049 | }); 1050 | }); 1051 | it('caches the API call for successive function calls', () => { 1052 | inst = new SquissPatched({queueUrl: 'https://foo'}); 1053 | inst!.sqs = new SQSStub() as any as SQS; 1054 | const spy = sinon.spy(inst!.sqs, 'getQueueAttributes'); 1055 | return inst!.getQueueMaximumMessageSize().then((timeout: number) => { 1056 | timeout.should.equal(200); 1057 | spy.should.be.calledOnce(); 1058 | return inst!.getQueueMaximumMessageSize(); 1059 | }).then((timeout: number) => { 1060 | should.exist(timeout); 1061 | timeout.should.equal(200); 1062 | spy.should.be.calledOnce(); 1063 | }); 1064 | }); 1065 | it('catches badly formed AWS responses', () => { 1066 | inst = new SquissPatched({queueUrl: 'foo'}); 1067 | inst!.sqs = new SQSStub() as any as SQS; 1068 | (inst!.sqs as any as SQSStub).getQueueAttributes = sinon.stub().returns({ 1069 | foo: 'bar', 1070 | }); 1071 | return inst!.getQueueMaximumMessageSize().should.be.rejectedWith(/foo/); 1072 | }); 1073 | }); 1074 | describe('releaseMessage', () => { 1075 | it('marks the message as handled and changes visibility to 0', () => { 1076 | inst = new SquissPatched({queueName: 'foo'}); 1077 | inst!.sqs = new SQSStub(1) as any as SQS; 1078 | const handledSpy = sinon.spy(inst, 'handledMessage'); 1079 | const visibilitySpy = sinon.spy(inst, 'changeMessageVisibility'); 1080 | const msg = new EventEmitter() as any; 1081 | return inst!.releaseMessage(msg).then(() => { 1082 | handledSpy.should.be.calledOnce(); 1083 | visibilitySpy.should.be.calledOnce(); 1084 | visibilitySpy.should.be.calledWith(msg, 0); 1085 | }); 1086 | }); 1087 | }); 1088 | describe('purgeQueue', () => { 1089 | it('calls SQS SDK purgeQueue method with queue URL', () => { 1090 | inst = new SquissPatched({queueUrl: 'foo'}); 1091 | inst!.sqs = new SQSStub() as any as SQS; 1092 | const spy = sinon.spy(inst!.sqs, 'purgeQueue'); 1093 | return inst!.purgeQueue().then(() => { 1094 | spy.should.be.calledOnce(); 1095 | spy.should.be.calledWith({QueueUrl: 'foo'}); 1096 | (inst!.sqs as any as SQSStub).msgs.length.should.equal(0); 1097 | (inst!.sqs as any as SQSStub).msgCount.should.equal(0); 1098 | }); 1099 | }); 1100 | }); 1101 | describe('sendMessage', () => { 1102 | it('sends a string message with no extra arguments', () => { 1103 | inst = new SquissPatched({queueUrl: 'foo'}); 1104 | inst!.sqs = new SQSStub() as any as SQS; 1105 | const spy = sinon.spy(inst!.sqs, 'sendMessage'); 1106 | return inst!.sendMessage('bar').then(() => { 1107 | spy.should.be.calledOnce(); 1108 | spy.should.be.calledWith({QueueUrl: 'foo', MessageBody: 'bar'}); 1109 | }); 1110 | }); 1111 | it('sends a string gzip message with no extra arguments', () => { 1112 | inst = new SquissPatched({queueUrl: 'foo', gzip: true}); 1113 | inst!.sqs = new SQSStub() as any as SQS; 1114 | const spy = sinon.spy(inst!.sqs, 'sendMessage'); 1115 | return inst!.sendMessage('{"i": 1}').then(() => { 1116 | spy.should.be.calledOnce(); 1117 | spy.should.be.calledWith({ 1118 | QueueUrl: 'foo', MessageBody: 'iwOAeyJpIjogMX0D', MessageAttributes: { 1119 | __SQS_GZIP__: { 1120 | DataType: 'Number', 1121 | StringValue: '1', 1122 | }, 1123 | }, 1124 | }); 1125 | }); 1126 | }); 1127 | it('sends a JSON message with no extra arguments', () => { 1128 | inst = new SquissPatched({queueUrl: 'foo'}); 1129 | inst!.sqs = new SQSStub() as any as SQS; 1130 | const spy = sinon.spy(inst!.sqs, 'sendMessage'); 1131 | return inst!.sendMessage({bar: 'baz'}).then(() => { 1132 | spy.should.be.calledOnce(); 1133 | spy.should.be.calledWith({QueueUrl: 'foo', MessageBody: '{"bar":"baz"}'}); 1134 | }); 1135 | }); 1136 | it('sends a message with a delay and attributes', () => { 1137 | inst = new SquissPatched({queueUrl: 'foo'}); 1138 | inst!.sqs = new SQSStub() as any as SQS; 1139 | const buffer = Buffer.from('s'); 1140 | const spy = sinon.spy(inst!.sqs, 'sendMessage'); 1141 | return inst!.sendMessage('bar', 10, { 1142 | baz: 'fizz', 1143 | num: 1, 1144 | boolean1: true, 1145 | boolean2: false, 1146 | bin: buffer, 1147 | empty: undefined, 1148 | }).then(() => { 1149 | spy.should.be.calledWith({ 1150 | QueueUrl: 'foo', 1151 | MessageBody: 'bar', 1152 | DelaySeconds: 10, 1153 | MessageAttributes: { 1154 | baz: { 1155 | DataType: 'String', 1156 | StringValue: 'fizz', 1157 | }, 1158 | boolean1: { 1159 | DataType: 'String', 1160 | StringValue: 'true', 1161 | }, 1162 | boolean2: { 1163 | DataType: 'String', 1164 | StringValue: 'false', 1165 | }, 1166 | empty: { 1167 | DataType: 'String', 1168 | StringValue: '', 1169 | }, 1170 | num: { 1171 | DataType: 'Number', 1172 | StringValue: '1', 1173 | }, 1174 | bin: { 1175 | DataType: 'Binary', 1176 | BinaryValue: buffer, 1177 | }, 1178 | }, 1179 | }); 1180 | }); 1181 | }); 1182 | it('sends a S3 message with a delay and attributes', () => { 1183 | const blobs: Blobs = {}; 1184 | const s3Stub = getS3Stub(blobs); 1185 | const bucket = 'my_bucket'; 1186 | inst = new SquissPatched({S3: s3Stub, queueUrl: 'foo', s3Fallback: true, s3Bucket: bucket}); 1187 | inst!.sqs = new SQSStub() as any as SQS; 1188 | const buffer = Buffer.from('s'); 1189 | const spy = sinon.spy(inst!.sqs, 'sendMessage'); 1190 | const largeMessage = generateLargeMessage(300); 1191 | let squissS3UploadEventEmitted = false; 1192 | inst!.on('s3Upload', (data) => { 1193 | data.bucket.should.eql(bucket); 1194 | data.key.should.eql('my_uuid'); 1195 | data.uploadSize.should.eql(300); 1196 | squissS3UploadEventEmitted = true; 1197 | }); 1198 | return inst!.sendMessage(largeMessage, 10, { 1199 | baz: 'fizz', 1200 | num: 1, 1201 | boolean1: true, 1202 | boolean2: false, 1203 | bin: buffer, 1204 | empty: undefined, 1205 | }).then(() => { 1206 | squissS3UploadEventEmitted.should.eql(true); 1207 | blobs.my_bucket.my_uuid.should.be.eq(largeMessage); 1208 | spy.should.be.calledWith({ 1209 | QueueUrl: 'foo', 1210 | MessageBody: '{"uploadSize":300,"bucket":"my_bucket","key":"my_uuid"}', 1211 | DelaySeconds: 10, 1212 | MessageAttributes: { 1213 | __SQS_S3__: {DataType: 'Number', StringValue: '300'}, 1214 | baz: { 1215 | DataType: 'String', 1216 | StringValue: 'fizz', 1217 | }, 1218 | boolean1: { 1219 | DataType: 'String', 1220 | StringValue: 'true', 1221 | }, 1222 | boolean2: { 1223 | DataType: 'String', 1224 | StringValue: 'false', 1225 | }, 1226 | empty: { 1227 | DataType: 'String', 1228 | StringValue: '', 1229 | }, 1230 | num: { 1231 | DataType: 'Number', 1232 | StringValue: '1', 1233 | }, 1234 | bin: { 1235 | DataType: 'Binary', 1236 | BinaryValue: buffer, 1237 | }, 1238 | }, 1239 | }); 1240 | }); 1241 | }); 1242 | it('sends a S3 message with a delay and attributes and s3 prefix', () => { 1243 | const blobs: Blobs = {}; 1244 | const s3Stub = getS3Stub(blobs); 1245 | inst = new SquissPatched({S3: s3Stub, queueUrl: 'foo', s3Fallback: true, s3Bucket: 'my_bucket', 1246 | s3Prefix: 'my_prefix/'}); 1247 | inst!.sqs = new SQSStub() as any as SQS; 1248 | const buffer = Buffer.from('s'); 1249 | const spy = sinon.spy(inst!.sqs, 'sendMessage'); 1250 | const largeMessage = generateLargeMessage(300); 1251 | return inst!.sendMessage(largeMessage, 10, { 1252 | baz: 'fizz', 1253 | num: 1, 1254 | boolean1: true, 1255 | boolean2: false, 1256 | bin: buffer, 1257 | empty: undefined, 1258 | }).then(() => { 1259 | blobs.my_bucket!['my_prefix/my_uuid'].should.be.eq(largeMessage); 1260 | spy.should.be.calledWith({ 1261 | QueueUrl: 'foo', 1262 | MessageBody: '{"uploadSize":300,"bucket":"my_bucket","key":"my_prefix/my_uuid"}', 1263 | DelaySeconds: 10, 1264 | MessageAttributes: { 1265 | __SQS_S3__: {DataType: 'Number', StringValue: '300'}, 1266 | baz: { 1267 | DataType: 'String', 1268 | StringValue: 'fizz', 1269 | }, 1270 | boolean1: { 1271 | DataType: 'String', 1272 | StringValue: 'true', 1273 | }, 1274 | boolean2: { 1275 | DataType: 'String', 1276 | StringValue: 'false', 1277 | }, 1278 | empty: { 1279 | DataType: 'String', 1280 | StringValue: '', 1281 | }, 1282 | num: { 1283 | DataType: 'Number', 1284 | StringValue: '1', 1285 | }, 1286 | bin: { 1287 | DataType: 'Binary', 1288 | BinaryValue: buffer, 1289 | }, 1290 | }, 1291 | }); 1292 | }); 1293 | }); 1294 | it('sends a S3 message with a delay and no attributes', () => { 1295 | const blobs: Blobs = {}; 1296 | const s3Stub = getS3Stub(blobs); 1297 | inst = new SquissPatched({S3: s3Stub, queueUrl: 'foo', s3Fallback: true, s3Bucket: 'my_bucket'}); 1298 | inst!.sqs = new SQSStub() as any as SQS; 1299 | const spy = sinon.spy(inst!.sqs, 'sendMessage'); 1300 | const largeMessage = generateLargeMessage(300); 1301 | return inst!.sendMessage(largeMessage, 10).then(() => { 1302 | blobs.my_bucket.my_uuid.should.be.eq(largeMessage); 1303 | spy.should.be.calledWith({ 1304 | QueueUrl: 'foo', 1305 | MessageBody: '{"uploadSize":300,"bucket":"my_bucket","key":"my_uuid"}', 1306 | DelaySeconds: 10, 1307 | MessageAttributes: { 1308 | __SQS_S3__: {DataType: 'Number', StringValue: '300'}, 1309 | }, 1310 | }); 1311 | }); 1312 | }); 1313 | it('sends a S3 message if it is bigger than minS3Size', () => { 1314 | const blobs: Blobs = {}; 1315 | const s3Stub = getS3Stub(blobs); 1316 | inst = new SquissPatched({S3: s3Stub, queueUrl: 'foo', s3Fallback: true, s3Bucket: 'my_bucket', minS3Size: 250}); 1317 | inst!.sqs = new SQSStub() as any as SQS; 1318 | const spy = sinon.spy(inst!.sqs, 'sendMessage'); 1319 | const largeMessage = generateLargeMessage(300); 1320 | return inst!.sendMessage(largeMessage, 10).then(() => { 1321 | blobs.my_bucket.my_uuid.should.be.eq(largeMessage); 1322 | spy.should.be.calledWith({ 1323 | QueueUrl: 'foo', 1324 | MessageBody: '{"uploadSize":300,"bucket":"my_bucket","key":"my_uuid"}', 1325 | DelaySeconds: 10, 1326 | MessageAttributes: { 1327 | __SQS_S3__: {DataType: 'Number', StringValue: '300'}, 1328 | }, 1329 | }); 1330 | }); 1331 | }); 1332 | it('does not send a S3 message if it is smaller than minS3Size', () => { 1333 | const blobs: Blobs = {}; 1334 | const s3Stub = getS3Stub(blobs); 1335 | inst = new SquissPatched({S3: s3Stub, queueUrl: 'foo', s3Fallback: true, s3Bucket: 'my_bucket', minS3Size: 500}); 1336 | inst!.sqs = new SQSStub() as any as SQS; 1337 | const spy = sinon.spy(inst!.sqs, 'sendMessage'); 1338 | const largeMessage = generateLargeMessage(300); 1339 | return inst!.sendMessage(largeMessage, 10).then(() => { 1340 | Object.keys(blobs).length.should.be.eq(0); 1341 | spy.should.be.calledWith({ 1342 | QueueUrl: 'foo', 1343 | MessageBody: largeMessage, 1344 | DelaySeconds: 10, 1345 | }); 1346 | }); 1347 | }); 1348 | it('sends a skipped S3 message with a delay and attributes', () => { 1349 | const blobs: Blobs = {}; 1350 | const s3Stub = getS3Stub(blobs); 1351 | inst = new SquissPatched({S3: s3Stub, queueUrl: 'foo', s3Fallback: true, s3Bucket: 'my_bucket'}); 1352 | inst!.sqs = new SQSStub() as any as SQS; 1353 | const spy = sinon.spy(inst!.sqs, 'sendMessage'); 1354 | const smallMessage = generateLargeMessage(50); 1355 | return inst!.sendMessage(smallMessage, 10, { 1356 | baz: 'fizz', 1357 | }).then(() => { 1358 | blobs.should.not.have.property('my_bucket'); 1359 | spy.should.be.calledWith({ 1360 | QueueUrl: 'foo', 1361 | MessageBody: smallMessage, 1362 | DelaySeconds: 10, 1363 | MessageAttributes: { 1364 | baz: { 1365 | DataType: 'String', 1366 | StringValue: 'fizz', 1367 | }, 1368 | }, 1369 | }); 1370 | }); 1371 | }); 1372 | it('sends a message with a delay and not allowed internal gzip attribute', (done) => { 1373 | inst = new SquissPatched({queueUrl: 'foo'}); 1374 | inst!.sqs = new SQSStub() as any as SQS; 1375 | const buffer = Buffer.from('s'); 1376 | const spy = sinon.spy(inst!.sqs, 'sendMessage'); 1377 | inst!.sendMessage('bar', 10, { 1378 | baz: 'fizz', 1379 | num: 1, 1380 | __SQS_GZIP__: true, 1381 | boolean1: true, 1382 | boolean2: false, 1383 | bin: buffer, 1384 | empty: undefined, 1385 | }).catch((err: Error) => { 1386 | spy.should.have.callCount(0); 1387 | err.should.be.instanceOf(Error); 1388 | err.message.should.be.eq('Using of internal attribute __SQS_GZIP__ is not allowed'); 1389 | done(); 1390 | }); 1391 | }); 1392 | it('sends a message with a delay and not allowed internal s3 attribute', (done) => { 1393 | inst = new SquissPatched({queueUrl: 'foo'}); 1394 | inst!.sqs = new SQSStub() as any as SQS; 1395 | const buffer = Buffer.from('s'); 1396 | const spy = sinon.spy(inst!.sqs, 'sendMessage'); 1397 | inst!.sendMessage('bar', 10, { 1398 | baz: 'fizz', 1399 | num: 1, 1400 | __SQS_S3__: true, 1401 | boolean1: true, 1402 | boolean2: false, 1403 | bin: buffer, 1404 | empty: undefined, 1405 | }).catch((err: Error) => { 1406 | spy.should.have.callCount(0); 1407 | err.should.be.instanceOf(Error); 1408 | err.message.should.be.eq('Using of internal attribute __SQS_S3__ is not allowed'); 1409 | done(); 1410 | }); 1411 | }); 1412 | it('sends a gzip message with a delay and attributes', () => { 1413 | inst = new SquissPatched({queueUrl: 'foo', gzip: true}); 1414 | inst!.sqs = new SQSStub() as any as SQS; 1415 | const buffer = Buffer.from('s'); 1416 | const spy = sinon.spy(inst!.sqs, 'sendMessage'); 1417 | return inst!.sendMessage({'i': 1}, 10, { 1418 | baz: 'fizz', 1419 | num: 1, 1420 | boolean1: true, 1421 | boolean2: false, 1422 | bin: buffer, 1423 | empty: undefined, 1424 | }).then(() => { 1425 | spy.should.be.calledWith({ 1426 | QueueUrl: 'foo', 1427 | MessageBody: 'CwOAeyJpIjoxfQM=', 1428 | DelaySeconds: 10, 1429 | MessageAttributes: { 1430 | __SQS_GZIP__: { 1431 | DataType: 'Number', 1432 | StringValue: '1', 1433 | }, 1434 | baz: { 1435 | DataType: 'String', 1436 | StringValue: 'fizz', 1437 | }, 1438 | boolean1: { 1439 | DataType: 'String', 1440 | StringValue: 'true', 1441 | }, 1442 | boolean2: { 1443 | DataType: 'String', 1444 | StringValue: 'false', 1445 | }, 1446 | empty: { 1447 | DataType: 'String', 1448 | StringValue: '', 1449 | }, 1450 | num: { 1451 | DataType: 'Number', 1452 | StringValue: '1', 1453 | }, 1454 | bin: { 1455 | DataType: 'Binary', 1456 | BinaryValue: buffer, 1457 | }, 1458 | }, 1459 | }); 1460 | }); 1461 | }); 1462 | it('sends a gzip message with a delay and attributes when gzip limit is passed', () => { 1463 | inst = new SquissPatched({queueUrl: 'foo', gzip: true, minGzipSize: 20}); 1464 | inst!.sqs = new SQSStub() as any as SQS; 1465 | const buffer = Buffer.from('s'); 1466 | const largeMessage = generateLargeMessage(200); 1467 | const spy = sinon.spy(inst!.sqs, 'sendMessage'); 1468 | return inst!.sendMessage(largeMessage, 10, { 1469 | baz: 'fizz', 1470 | num: 1, 1471 | boolean1: true, 1472 | boolean2: false, 1473 | bin: buffer, 1474 | empty: undefined, 1475 | }).then(() => { 1476 | spy.should.be.calledWith({ 1477 | QueueUrl: 'foo', 1478 | MessageBody: 'G8cA+CXmYrFAIAA=', 1479 | DelaySeconds: 10, 1480 | MessageAttributes: { 1481 | __SQS_GZIP__: { 1482 | DataType: 'Number', 1483 | StringValue: '1', 1484 | }, 1485 | baz: { 1486 | DataType: 'String', 1487 | StringValue: 'fizz', 1488 | }, 1489 | boolean1: { 1490 | DataType: 'String', 1491 | StringValue: 'true', 1492 | }, 1493 | boolean2: { 1494 | DataType: 'String', 1495 | StringValue: 'false', 1496 | }, 1497 | empty: { 1498 | DataType: 'String', 1499 | StringValue: '', 1500 | }, 1501 | num: { 1502 | DataType: 'Number', 1503 | StringValue: '1', 1504 | }, 1505 | bin: { 1506 | DataType: 'Binary', 1507 | BinaryValue: buffer, 1508 | }, 1509 | }, 1510 | }); 1511 | }); 1512 | }); 1513 | it('sends a non gzip message with a delay and attributes when gzip limit is not passed', () => { 1514 | inst = new SquissPatched({queueUrl: 'foo', gzip: true, minGzipSize: 500}); 1515 | inst!.sqs = new SQSStub() as any as SQS; 1516 | const buffer = Buffer.from('s'); 1517 | const largeMessage = generateLargeMessage(200); 1518 | const spy = sinon.spy(inst!.sqs, 'sendMessage'); 1519 | return inst!.sendMessage(largeMessage, 10, { 1520 | baz: 'fizz', 1521 | num: 1, 1522 | boolean1: true, 1523 | boolean2: false, 1524 | bin: buffer, 1525 | empty: undefined, 1526 | }).then(() => { 1527 | spy.should.be.calledWith({ 1528 | QueueUrl: 'foo', 1529 | MessageBody: largeMessage, 1530 | DelaySeconds: 10, 1531 | MessageAttributes: { 1532 | baz: { 1533 | DataType: 'String', 1534 | StringValue: 'fizz', 1535 | }, 1536 | boolean1: { 1537 | DataType: 'String', 1538 | StringValue: 'true', 1539 | }, 1540 | boolean2: { 1541 | DataType: 'String', 1542 | StringValue: 'false', 1543 | }, 1544 | empty: { 1545 | DataType: 'String', 1546 | StringValue: '', 1547 | }, 1548 | num: { 1549 | DataType: 'Number', 1550 | StringValue: '1', 1551 | }, 1552 | bin: { 1553 | DataType: 'Binary', 1554 | BinaryValue: buffer, 1555 | }, 1556 | }, 1557 | }); 1558 | }); 1559 | }); 1560 | it('sends a message with a delay and attributes and fifo attributes', () => { 1561 | inst = new SquissPatched({queueUrl: 'foo'}); 1562 | inst!.sqs = new SQSStub() as any as SQS; 1563 | const buffer = Buffer.from('s'); 1564 | const spy = sinon.spy(inst!.sqs, 'sendMessage'); 1565 | return inst!.sendMessage('bar', 10, { 1566 | FIFO_MessageGroupId: 'groupId', 1567 | FIFO_MessageDeduplicationId: 'dedupId', 1568 | baz: 'fizz', 1569 | num: 1, 1570 | bin: buffer, 1571 | empty: undefined, 1572 | }).then(() => { 1573 | spy.should.be.calledWith({ 1574 | QueueUrl: 'foo', 1575 | MessageBody: 'bar', 1576 | DelaySeconds: 10, 1577 | MessageDeduplicationId: 'dedupId', 1578 | MessageGroupId: 'groupId', 1579 | MessageAttributes: { 1580 | baz: { 1581 | DataType: 'String', 1582 | StringValue: 'fizz', 1583 | }, 1584 | empty: { 1585 | DataType: 'String', 1586 | StringValue: '', 1587 | }, 1588 | num: { 1589 | DataType: 'Number', 1590 | StringValue: '1', 1591 | }, 1592 | bin: { 1593 | DataType: 'Binary', 1594 | BinaryValue: buffer, 1595 | }, 1596 | }, 1597 | }); 1598 | }); 1599 | }); 1600 | }); 1601 | describe('sendMessages', () => { 1602 | it('sends a single string message with no extra arguments', () => { 1603 | inst = new SquissPatched({queueUrl: 'foo'}); 1604 | inst!.sqs = new SQSStub() as any as SQS; 1605 | const spy = sinon.spy(inst!.sqs, 'sendMessageBatch'); 1606 | return inst!.sendMessages('bar').then((res: SendMessageBatchResult) => { 1607 | spy.should.be.calledOnce(); 1608 | spy.should.be.calledWith({ 1609 | QueueUrl: 'foo', 1610 | Entries: [ 1611 | {Id: '0', MessageBody: 'bar'}, 1612 | ], 1613 | }); 1614 | res.should.have.property('Successful').with.length(1); 1615 | res.Successful![0].should.have.property('Id').equal('0'); 1616 | }); 1617 | }); 1618 | it('sends a single JSON message with no extra arguments', () => { 1619 | inst = new SquissPatched({queueUrl: 'foo'}); 1620 | inst!.sqs = new SQSStub() as any as SQS; 1621 | const spy = sinon.spy(inst!.sqs, 'sendMessageBatch'); 1622 | return inst!.sendMessages({bar: 'baz'}).then(() => { 1623 | spy.should.be.calledOnce(); 1624 | spy.should.be.calledWith({ 1625 | QueueUrl: 'foo', 1626 | Entries: [ 1627 | {Id: '0', MessageBody: '{"bar":"baz"}'}, 1628 | ], 1629 | }); 1630 | }); 1631 | }); 1632 | it('sends a multiple JSON message with no extra arguments', () => { 1633 | inst = new SquissPatched({queueUrl: 'foo'}); 1634 | inst!.sqs = new SQSStub() as any as SQS; 1635 | const spy = sinon.spy(inst!.sqs, 'sendMessageBatch'); 1636 | return inst!.sendMessages([{bar: 'baz'}, {bar1: 'baz1'}]).then(() => { 1637 | spy.should.be.calledOnce(); 1638 | spy.should.be.calledWith({ 1639 | QueueUrl: 'foo', 1640 | Entries: [ 1641 | {Id: '0', MessageBody: '{"bar":"baz"}'}, 1642 | {Id: '1', MessageBody: '{"bar1":"baz1"}'}, 1643 | ], 1644 | }); 1645 | }); 1646 | }); 1647 | it('sends a single message with delay and attributes', () => { 1648 | inst = new SquissPatched({queueUrl: 'foo'}); 1649 | inst!.sqs = new SQSStub() as any as SQS; 1650 | const spy = sinon.spy(inst!.sqs, 'sendMessageBatch'); 1651 | return inst!.sendMessages('bar', 10, {baz: 'fizz'}).then(() => { 1652 | spy.should.be.calledOnce(); 1653 | spy.should.be.calledWith({ 1654 | QueueUrl: 'foo', 1655 | Entries: [{ 1656 | Id: '0', 1657 | MessageBody: 'bar', 1658 | DelaySeconds: 10, 1659 | MessageAttributes: {baz: {StringValue: 'fizz', DataType: 'String'}}, 1660 | }], 1661 | }); 1662 | }); 1663 | }); 1664 | it('sends multiple messages with delay and single attributes object', () => { 1665 | inst = new SquissPatched({queueUrl: 'foo'}); 1666 | inst!.sqs = new SQSStub() as any as SQS; 1667 | const spy = sinon.spy(inst!.sqs, 'sendMessageBatch'); 1668 | return inst!.sendMessages(['bar', 'baz'], 10, { 1669 | baz: 'fizz', FIFO_MessageGroupId: 'groupId', 1670 | FIFO_MessageDeduplicationId: 'dedupId', 1671 | }).then(() => { 1672 | spy.should.be.calledOnce(); 1673 | spy.should.be.calledWith({ 1674 | QueueUrl: 'foo', 1675 | Entries: [{ 1676 | Id: '0', 1677 | MessageBody: 'bar', 1678 | MessageDeduplicationId: 'dedupId', 1679 | MessageGroupId: 'groupId', 1680 | DelaySeconds: 10, 1681 | MessageAttributes: {baz: {StringValue: 'fizz', DataType: 'String'}}, 1682 | }, { 1683 | Id: '1', 1684 | MessageBody: 'baz', 1685 | MessageDeduplicationId: 'dedupId', 1686 | MessageGroupId: 'groupId', 1687 | DelaySeconds: 10, 1688 | MessageAttributes: {baz: {StringValue: 'fizz', DataType: 'String'}}, 1689 | }], 1690 | }); 1691 | }); 1692 | }); 1693 | it('sends multiple gzip messages with delay and single attributes object', () => { 1694 | inst = new SquissPatched({queueUrl: 'foo', gzip: true}); 1695 | inst!.sqs = new SQSStub() as any as SQS; 1696 | const spy = sinon.spy(inst!.sqs, 'sendMessageBatch'); 1697 | return inst!.sendMessages(['bar', 'baz'], 10, { 1698 | baz: 'fizz', FIFO_MessageGroupId: 'groupId', 1699 | FIFO_MessageDeduplicationId: 'dedupId', 1700 | }).then(() => { 1701 | spy.should.be.calledOnce(); 1702 | spy.should.be.calledWith({ 1703 | QueueUrl: 'foo', 1704 | Entries: [{ 1705 | Id: '0', 1706 | MessageBody: 'CwGAYmFyAw==', 1707 | MessageDeduplicationId: 'dedupId', 1708 | MessageGroupId: 'groupId', 1709 | DelaySeconds: 10, 1710 | MessageAttributes: { 1711 | baz: {StringValue: 'fizz', DataType: 'String'}, 1712 | __SQS_GZIP__: {DataType: 'Number', StringValue: '1'}, 1713 | }, 1714 | }, { 1715 | Id: '1', 1716 | MessageBody: 'CwGAYmF6Aw==', 1717 | MessageDeduplicationId: 'dedupId', 1718 | MessageGroupId: 'groupId', 1719 | DelaySeconds: 10, 1720 | MessageAttributes: { 1721 | baz: {StringValue: 'fizz', DataType: 'String'}, 1722 | __SQS_GZIP__: {DataType: 'Number', StringValue: '1'}, 1723 | }, 1724 | }], 1725 | }); 1726 | }); 1727 | }); 1728 | it('sends multiple messages with delay and multiple attributes objects', () => { 1729 | inst = new SquissPatched({queueUrl: 'foo'}); 1730 | inst!.sqs = new SQSStub() as any as SQS; 1731 | const spy = sinon.spy(inst!.sqs, 'sendMessageBatch'); 1732 | return inst!.sendMessages(['bar', 'baz'], 10, [{ 1733 | baz: 'fizz', FIFO_MessageGroupId: 'groupId', 1734 | FIFO_MessageDeduplicationId: 'dedupId', 1735 | }, { 1736 | baz1: 'fizz1', FIFO_MessageGroupId: 'groupId1', 1737 | FIFO_MessageDeduplicationId: 'dedupId1', 1738 | }]).then(() => { 1739 | spy.should.be.calledOnce(); 1740 | spy.should.be.calledWith({ 1741 | QueueUrl: 'foo', 1742 | Entries: [{ 1743 | Id: '0', 1744 | MessageBody: 'bar', 1745 | DelaySeconds: 10, 1746 | MessageDeduplicationId: 'dedupId', 1747 | MessageGroupId: 'groupId', 1748 | MessageAttributes: {baz: {StringValue: 'fizz', DataType: 'String'}}, 1749 | }, { 1750 | Id: '1', 1751 | MessageBody: 'baz', 1752 | DelaySeconds: 10, 1753 | MessageDeduplicationId: 'dedupId1', 1754 | MessageGroupId: 'groupId1', 1755 | MessageAttributes: {baz1: {StringValue: 'fizz1', DataType: 'String'}}, 1756 | }], 1757 | }); 1758 | }); 1759 | }); 1760 | it('sends multiple batches of messages and merges successes', () => { 1761 | inst = new SquissPatched({queueUrl: 'foo'}); 1762 | inst!.sqs = new SQSStub() as any as SQS; 1763 | const spy = sinon.spy(inst!.sqs, 'sendMessageBatch'); 1764 | const msgs = 'a.b.c.d.e.f.g.h.i.j.k.l.m.n.o'.split('.'); 1765 | return inst!.sendMessages(msgs).then((res: SendMessageBatchResult) => { 1766 | spy.should.be.calledTwice(); 1767 | (inst!.sqs as any as SQSStub).msgs.length.should.equal(15); 1768 | res.should.have.property('Successful').with.length(15); 1769 | res.should.have.property('Failed').with.length(0); 1770 | }); 1771 | }); 1772 | it('sends multiple batches of messages and merges successes with batch size is too big', () => { 1773 | inst = new SquissPatched({queueUrl: 'foo'}); 1774 | inst!.sqs = new SQSStub() as any as SQS; 1775 | const spy = sinon.spy(inst!.sqs, 'sendMessageBatch'); 1776 | const msgs = 'a.b.c.d.e.f.g.h.i.j.k.l.m.n.o'.split('.'); 1777 | msgs.unshift(generateLargeMessage(300)); 1778 | return inst!.sendMessages(msgs).then((res: SendMessageBatchResult) => { 1779 | spy.should.be.calledThrice(); 1780 | (inst!.sqs as any as SQSStub).msgs.length.should.equal(16); 1781 | res.should.have.property('Successful').with.length(16); 1782 | res.should.have.property('Failed').with.length(0); 1783 | }); 1784 | }); 1785 | it('sends multiple batches of messages and merges failures', () => { 1786 | inst = new SquissPatched({queueUrl: 'foo'}); 1787 | inst!.sqs = new SQSStub() as any as SQS; 1788 | const spy = sinon.spy(inst!.sqs, 'sendMessageBatch'); 1789 | const msgs = 'a.FAIL.c.d.e.f.g.h.i.j.k.l.m.n.FAIL'.split('.'); 1790 | return inst!.sendMessages(msgs).then((res: SendMessageBatchResult) => { 1791 | spy.should.be.calledTwice(); 1792 | (inst!.sqs as any as SQSStub).msgs.length.should.equal(13); 1793 | res.should.have.property('Successful').with.length(13); 1794 | res.should.have.property('Failed').with.length(2); 1795 | }); 1796 | }); 1797 | }); 1798 | describe('auto-extensions', () => { 1799 | it('initializes a TimeoutExtender', () => { 1800 | inst = new SquissPatched({queueUrl: 'foo', autoExtendTimeout: true}); 1801 | inst!.sqs = new SQSStub() as any as SQS; 1802 | return inst!.start().then(() => { 1803 | should.exist(inst!._timeoutExtender); 1804 | inst!._timeoutExtender!.should.not.equal(null); 1805 | inst!._timeoutExtender!._opts.visibilityTimeoutSecs!.should.equal(31); 1806 | inst!._timeoutExtender!._opts.noExtensionsAfterSecs!.should.equal(43200); 1807 | inst!._timeoutExtender!._opts.advancedCallMs!.should.equal(5000); 1808 | }); 1809 | }); 1810 | it('constructs a TimeoutExtender with custom options', () => { 1811 | inst = new SquissPatched({ 1812 | queueUrl: 'foo', 1813 | autoExtendTimeout: true, 1814 | visibilityTimeoutSecs: 53, 1815 | noExtensionsAfterSecs: 400, 1816 | advancedCallMs: 4500, 1817 | }); 1818 | inst!.sqs = new SQSStub() as any as SQS; 1819 | return inst!.start().then(() => { 1820 | should.exist(inst!._timeoutExtender); 1821 | inst!._timeoutExtender!.should.not.equal(null); 1822 | inst!._timeoutExtender!._opts.visibilityTimeoutSecs!.should.equal(53); 1823 | inst!._timeoutExtender!._opts.noExtensionsAfterSecs!.should.equal(400); 1824 | inst!._timeoutExtender!._opts.advancedCallMs!.should.equal(4500); 1825 | }); 1826 | }); 1827 | }); 1828 | }); 1829 | --------------------------------------------------------------------------------