@adobe/helix-admin-support 1.3.15 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,17 @@
1
+ # [1.5.0](https://github.com/adobe/helix-admin-support/compare/v1.4.0...v1.5.0) (2022-10-11)
2
+
3
+
4
+ ### Features
5
+
6
+ * less verbose polling ([#76](https://github.com/adobe/helix-admin-support/issues/76)) ([b00cc7c](https://github.com/adobe/helix-admin-support/commit/b00cc7cdbd6fca407a3e98d42b1764a03be92eef))
7
+
8
+ # [1.4.0](https://github.com/adobe/helix-admin-support/compare/v1.3.15...v1.4.0) (2022-10-11)
9
+
10
+
11
+ ### Features
12
+
13
+ * add BatchedQueueClient ([39edd3b](https://github.com/adobe/helix-admin-support/commit/39edd3bbdd52588bf41889945e3a842dd3d95761))
14
+
1
15
  ## [1.3.15](https://github.com/adobe/helix-admin-support/compare/v1.3.14...v1.3.15) (2022-10-08)
2
16
 
3
17
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adobe/helix-admin-support",
3
- "version": "1.3.15",
3
+ "version": "1.5.0",
4
4
  "description": "Helix Admin Support Library",
5
5
  "main": "src/index.js",
6
6
  "type": "module",
@@ -35,6 +35,7 @@
35
35
  "@adobe/helix-shared-config": "9.1.1",
36
36
  "@adobe/helix-shared-utils": "2.1.0",
37
37
  "@aws-sdk/client-s3": "3.186.0",
38
+ "@aws-sdk/client-sqs": "3.121.0",
38
39
  "@aws-sdk/node-http-handler": "3.186.0"
39
40
  },
40
41
  "devDependencies": {
@@ -0,0 +1,81 @@
1
+ /*
2
+ * Copyright 2022 Adobe. All rights reserved.
3
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License. You may obtain a copy
5
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
+ *
7
+ * Unless required by applicable law or agreed to in writing, software distributed under
8
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
+ * OF ANY KIND, either express or implied. See the License for the specific language
10
+ * governing permissions and limitations under the License.
11
+ */
12
+
13
+ export declare interface Message {
14
+ MessageBody: string;
15
+ MessageAttributes: object;
16
+ MessageGroupId: string;
17
+ MessageDeduplicationId: string;
18
+ }
19
+
20
+ export declare interface BatchedQueueClientOptions {
21
+ log:Console;
22
+ maxSqsPollTime: number;
23
+ s3ClientOpts: object;
24
+ sqsClientOpts: object;
25
+ swapBucket: string;
26
+ swapPrefix: string;
27
+ inQueue:string;
28
+ outQueue:string;
29
+ }
30
+
31
+ export declare class BatchedQueueClient {
32
+ /**
33
+ * Creates a message specific to the pump queue
34
+ * @param {string} owner
35
+ * @param {string} repo
36
+ * @param {object} record
37
+ */
38
+ static createMessage(owner, repo, record): Message;
39
+
40
+ /**
41
+ * Creates a new client
42
+ * @param {BatchedQueueClientOptions} opts
43
+ */
44
+ constructor(opts:BatchedQueueClientOptions);
45
+
46
+ /**
47
+ * Extended version of the SQS ReceiveMessageCommand, that supports long polling for wait times
48
+ * over 20s and max messages for over 10.
49
+ *
50
+ * @param [maxTime = 10]
51
+ * @param [maxMessages = 1000]
52
+ * @returns {Promise<*[]>}
53
+ */
54
+ receive(maxTime:number, maxMessages:number): Promise<Message[]>;
55
+
56
+ /**
57
+ * Delete messages from the inQueue
58
+ * @param {Message[]} messages
59
+ * @returns {Promise<void>}
60
+ */
61
+ delete(messages: Message[]): Promise<void>;
62
+
63
+ /**
64
+ * Serializes a message to the swap storage.
65
+ * @param {Message} message
66
+ * @returns {Promise<Message>} a new message containing the information about the swap location.
67
+ */
68
+ serialize(message: Message): Promise<Message>;
69
+
70
+ /**
71
+ * Sends a batch of messages to the `outQueue`.
72
+ * @param {Message[]} messages
73
+ * @returns {Promise<void>}
74
+ */
75
+ send(messages:Message[]): Promise<void>;
76
+
77
+ /**
78
+ * Closes this client and destroys the underlying datastructures
79
+ */
80
+ close(): void;
81
+ }
@@ -0,0 +1,257 @@
1
+ /*
2
+ * Copyright 2022 Adobe. All rights reserved.
3
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License. You may obtain a copy
5
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
+ *
7
+ * Unless required by applicable law or agreed to in writing, software distributed under
8
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
+ * OF ANY KIND, either express or implied. See the License for the specific language
10
+ * governing permissions and limitations under the License.
11
+ */
12
+ import {
13
+ DeleteMessageBatchCommand,
14
+ ReceiveMessageCommand,
15
+ SendMessageBatchCommand,
16
+ SQSClient,
17
+ } from '@aws-sdk/client-sqs';
18
+ import {
19
+ S3Client,
20
+ PutObjectCommand,
21
+ } from '@aws-sdk/client-s3';
22
+
23
+ const MAX_BATCH_SIZE = 256 * 1024;
24
+
25
+ const DEFAULT_BUCKET_ID = 'helix-content-bus';
26
+
27
+ const DEFAULT_MESSAGE_SWAP_PREFIX = 'default/sqs-swap';
28
+
29
+ export function hsize(bytes, decimals = 2) {
30
+ if (bytes === 0) {
31
+ return '0 bytes';
32
+ }
33
+ const k = 1024;
34
+ const sizes = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
35
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
36
+ // eslint-disable-next-line no-restricted-properties
37
+ return `${parseFloat((bytes / k ** i).toFixed(decimals))} ${sizes[i]}`;
38
+ }
39
+
40
+ /**
41
+ * @typedef BatchedQueueClientOpts
42
+ * @property {Console} [log=Console] Console like logger
43
+ * @property {number} [maxSqsPollTime=20] Time to poll for messages
44
+ * @property {string} inQueue Name of the receiving queue
45
+ * @property {string} outQueue Name of the output queue
46
+ * @property {object} s3ClientOpts S3 client options
47
+ * @property {object} sqsClientOpts SQS client options
48
+ * @property {Array<string>} headerKeys Name of the properties that common to all message properties
49
+ * @property {string} swapBucket Name of the bucket used for swap space
50
+ * @property {string} swapPrefix Prefix for the swap objects
51
+ */
52
+
53
+ /**
54
+ * Creates a new BatchedQueueClient. It allows to read and write from a SQS queue in batches,
55
+ * supporting larger batch sizes than the default of 10. If a message gets too big for SQS it is
56
+ * automatically swapped out to S3.
57
+ */
58
+ export class BatchedQueueClient {
59
+ static createMessage(owner, repo, data) {
60
+ return {
61
+ MessageBody: JSON.stringify({
62
+ owner,
63
+ repo,
64
+ ...data,
65
+ }),
66
+ MessageAttributes: {
67
+ owner: {
68
+ DataType: 'String',
69
+ StringValue: owner,
70
+ },
71
+ repo: {
72
+ DataType: 'String',
73
+ StringValue: repo,
74
+ },
75
+ },
76
+ };
77
+ }
78
+
79
+ /**
80
+ * Creates a new client
81
+ * @param {BatchedQueueClientOpts} opts Options
82
+ */
83
+ constructor(opts) {
84
+ this.sqs = new SQSClient(opts.sqsClientOpts);
85
+ this.s3 = new S3Client(opts.s3ClientOpts);
86
+ this.log = opts.log || console;
87
+ this.maxSqsPollTime = opts.maxSqsPollTime || 20;
88
+ this.inQueue = opts.inQueue;
89
+ this.outQueue = opts.outQueue;
90
+ this.swapPrefix = opts.swapPrefix || DEFAULT_MESSAGE_SWAP_PREFIX;
91
+ this.swapBucket = opts.swapBucket || DEFAULT_BUCKET_ID;
92
+ }
93
+
94
+ /**
95
+ * Extended version of the SQS ReceiveMessageCommand, that supports long polling for wait times
96
+ * over 20s and max messages for over 10.
97
+ *
98
+ * @param maxTime
99
+ * @param maxMessages
100
+ * @returns {Promise<Message[]>}
101
+ */
102
+ async receive(maxTime = 10, maxMessages = 1000) {
103
+ const { log, sqs } = this;
104
+ const messages = [];
105
+ const endTime = Date.now() + maxTime * 1000;
106
+
107
+ log.info(`starting polling loop on ${this.inQueue} during ${maxTime}s and ${maxMessages} max message.`);
108
+
109
+ while (messages.length < maxMessages) {
110
+ const timeRemaining = Math.round((endTime - Date.now()) / 1000);
111
+ if (timeRemaining <= 0) {
112
+ break;
113
+ }
114
+ const waitTime = Math.min(this.maxSqsPollTime, timeRemaining);
115
+ const maxMgs = Math.min(10, maxMessages - messages.length);
116
+
117
+ log.debug(`polling ${this.inQueue} for ${waitTime}s (${maxTime - timeRemaining}s/${maxTime}s (max ${maxMgs} msgs)...`);
118
+ // eslint-disable-next-line no-await-in-loop
119
+ const result = await sqs.send(new ReceiveMessageCommand({
120
+ MaxNumberOfMessages: maxMgs,
121
+ WaitTimeSeconds: waitTime,
122
+ QueueUrl: this.inQueue,
123
+ MessageAttributeNames: ['All'],
124
+ }));
125
+ const { Messages = [] } = result;
126
+ messages.push(...Messages);
127
+ log.debug(`last poll received ${Messages.length} messages from queue (${messages.length}).`);
128
+ }
129
+ log.info(`received ${messages.length} messages from queue ${this.inQueue}`);
130
+ return messages;
131
+ }
132
+
133
+ /**
134
+ * Delete messages from the inQueue
135
+ * @param {Message[]} messages
136
+ * @returns {Promise<void>}
137
+ */
138
+ async delete(messages) {
139
+ const { log, sqs } = this;
140
+ const total = messages.length;
141
+ let deleted = 0;
142
+ while (messages.length) {
143
+ const batch = messages.splice(0, 10);
144
+ log.info(`deleting ${batch.length} messages from ${this.inQueue}...`);
145
+ // eslint-disable-next-line no-await-in-loop
146
+ const result = await sqs.send(new DeleteMessageBatchCommand({
147
+ QueueUrl: this.inQueue,
148
+ Entries: batch.map((msg, idx) => ({
149
+ Id: idx,
150
+ ReceiptHandle: msg.ReceiptHandle,
151
+ })),
152
+ }));
153
+ const { Successful = [], Failed = [] } = result;
154
+ if (Failed.length) {
155
+ log.warn(`failed to delete ${Failed.length} from queue.`);
156
+ }
157
+ deleted += Successful.length;
158
+ log.info(`deleted. ${deleted}/${total} from ${this.inQueue} done.`);
159
+ }
160
+ }
161
+
162
+ /**
163
+ * Serializes a message to the swap storage.
164
+ * @param {Message} msg
165
+ * @returns {Promise<Message>} a new message containing the information about the swap location.
166
+ */
167
+ async serialize(msg) {
168
+ const { log } = this;
169
+ const oldBody = JSON.parse(msg.MessageBody);
170
+ const { owner, repo, key } = oldBody;
171
+ const swapKey = `${this.swapPrefix}/${key}-${Date.now()}.json`;
172
+ await this.s3.send(new PutObjectCommand({
173
+ Body: msg.MessageBody,
174
+ Bucket: this.swapBucket,
175
+ ContentType: 'application/json',
176
+ Key: swapKey,
177
+ }));
178
+ const swapS3Url = `s3://${this.swapBucket}/${swapKey}`;
179
+ log.info(`[${key}]message serialized to ${swapS3Url}`);
180
+ const newBody = {
181
+ owner,
182
+ repo,
183
+ key,
184
+ swapS3Url,
185
+ };
186
+ return {
187
+ MessageGroupId: msg.MessageGroupId,
188
+ MessageDeduplicationId: msg.MessageDeduplicationId,
189
+ MessageBody: JSON.stringify(newBody),
190
+ };
191
+ }
192
+
193
+ /**
194
+ * Sends a batch of messages to the `outQueue`.
195
+ * @param {Message[]} messages
196
+ * @returns {Promise<void>}
197
+ */
198
+ async send(messages) {
199
+ const { log, sqs } = this;
200
+ const total = messages.length;
201
+ let sent = 0;
202
+ let batchSize = 0;
203
+ let batch = [];
204
+ let send = false;
205
+ while (messages.length) {
206
+ let msg = messages.shift();
207
+ let size = JSON.stringify(msg).length;
208
+ if (batchSize + size < MAX_BATCH_SIZE) {
209
+ batch.push(msg);
210
+ batchSize += size;
211
+ } else if (batch.length === 0) {
212
+ // message doesn't fit in any batch - serializing to s3
213
+ log.info(`[${msg.MessageGroupId}] message to big: ${hsize(size)}. serializing to s3...`);
214
+ // eslint-disable-next-line no-await-in-loop
215
+ msg = await this.serialize(msg);
216
+ size = JSON.stringify(msg).length;
217
+ batch.push(msg);
218
+ batchSize += size;
219
+ } else {
220
+ // put message back
221
+ log.info(`[${msg.MessageGroupId}] message to big: ${hsize(size)}. sending current batch...`);
222
+ messages.unshift(msg);
223
+ send = true;
224
+ }
225
+
226
+ // if the size limit or the num-messages limit is reached, or of we are done, send the batch
227
+ if (send || batch.length === 10 || messages.length === 0) {
228
+ log.info(`sending ${batch.length} messages to ${this.outQueue}...`);
229
+ // eslint-disable-next-line no-await-in-loop
230
+ const result = await sqs.send(new SendMessageBatchCommand({
231
+ QueueUrl: this.outQueue,
232
+ Entries: batch.map((data, idx) => ({
233
+ Id: idx,
234
+ ...data,
235
+ })),
236
+ }));
237
+ const { Successful = [], Failed = [] } = result;
238
+ if (Failed.length) {
239
+ log.warn(`failed to send ${Failed.length} to queue.`);
240
+ }
241
+ sent += Successful.length;
242
+ log.info(`sent. ${sent}/${total} (${hsize(batchSize)} to ${this.outQueue} done.`);
243
+ batch = [];
244
+ batchSize = 0;
245
+ send = false;
246
+ }
247
+ }
248
+ }
249
+
250
+ /**
251
+ * Closes this client and destroys the underlying datastructures
252
+ */
253
+ close() {
254
+ this.sqs.destroy();
255
+ this.s3.destroy();
256
+ }
257
+ }
package/src/index.d.ts CHANGED
@@ -30,6 +30,7 @@ export * from './fetch-index';
30
30
  export * from './fetch-s3';
31
31
  export * from './fetch-sitemap';
32
32
  export * from './flatJson2Object';
33
+ export * from './BatchedQueueClient';
33
34
 
34
35
  export declare interface ErrorResponse {
35
36
  /**
package/src/index.js CHANGED
@@ -20,3 +20,4 @@ export * from './fetch-index.js';
20
20
  export * from './fetch-s3.js';
21
21
  export * from './fetch-sitemap.js';
22
22
  export * from './flatJson2Object.js';
23
+ export * from './BatchedQueueClient.js';