forked from taskforcesh/bullmq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.ts
383 lines (337 loc) · 9.63 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
import { Cluster, Redis } from 'ioredis';
// Note: this Polyfill is only needed for Node versions < 15.4.0
import { AbortController } from 'node-abort-controller';
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import { CONNECTION_CLOSED_ERROR_MSG } from 'ioredis/built/utils';
import {
ChildMessage,
ContextManager,
RedisClient,
Span,
Tracer,
} from './interfaces';
import { EventEmitter } from 'events';
import * as semver from 'semver';
import { SpanKind, TelemetryAttributes } from './enums';
export const errorObject: { [index: string]: any } = { value: null };
export function tryCatch(
fn: (...args: any) => any,
ctx: any,
args: any[],
): any {
try {
return fn.apply(ctx, args);
} catch (e) {
errorObject.value = e;
return errorObject;
}
}
/**
* Checks the size of string for ascii/non-ascii characters
* @see https://stackoverflow.com/a/23318053/1347170
* @param str -
*/
export function lengthInUtf8Bytes(str: string): number {
return Buffer.byteLength(str, 'utf8');
}
export function isEmpty(obj: object): boolean {
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
return false;
}
}
return true;
}
export function array2obj(arr: string[]): Record<string, string> {
const obj: { [index: string]: string } = {};
for (let i = 0; i < arr.length; i += 2) {
obj[arr[i]] = arr[i + 1];
}
return obj;
}
export function objectToFlatArray(obj: Record<string, any>): string[] {
const arr = [];
for (const key in obj) {
if (
Object.prototype.hasOwnProperty.call(obj, key) &&
obj[key] !== undefined
) {
arr[arr.length] = key;
arr[arr.length] = obj[key];
}
}
return arr;
}
export function delay(
ms: number,
abortController?: AbortController,
): Promise<void> {
return new Promise(resolve => {
let timeout: ReturnType<typeof setTimeout> | undefined;
const callback = () => {
abortController?.signal.removeEventListener('abort', callback);
clearTimeout(timeout);
resolve();
};
timeout = setTimeout(callback, ms);
abortController?.signal.addEventListener('abort', callback);
});
}
export function increaseMaxListeners(
emitter: EventEmitter,
count: number,
): void {
const maxListeners = emitter.getMaxListeners();
emitter.setMaxListeners(maxListeners + count);
}
type Invert<T extends Record<PropertyKey, PropertyKey>> = {
[V in T[keyof T]]: {
[K in keyof T]: T[K] extends V ? K : never;
}[keyof T];
};
export function invertObject<T extends Record<PropertyKey, PropertyKey>>(
obj: T,
): Invert<T> {
return Object.entries(obj).reduce((result, [key, value]) => {
(result as Record<PropertyKey, PropertyKey>)[value] = key;
return result;
}, {} as Invert<T>);
}
export function isRedisInstance(obj: any): obj is Redis | Cluster {
if (!obj) {
return false;
}
const redisApi = ['connect', 'disconnect', 'duplicate'];
return redisApi.every(name => typeof obj[name] === 'function');
}
export function isRedisCluster(obj: unknown): obj is Cluster {
return isRedisInstance(obj) && (<Cluster>obj).isCluster;
}
export function decreaseMaxListeners(
emitter: EventEmitter,
count: number,
): void {
increaseMaxListeners(emitter, -count);
}
export async function removeAllQueueData(
client: RedisClient,
queueName: string,
prefix = process.env.BULLMQ_TEST_PREFIX || 'bull',
): Promise<void | boolean> {
if (client instanceof Cluster) {
// todo compat with cluster ?
// @see https://github.com/luin/ioredis/issues/175
return Promise.resolve(false);
}
const pattern = `${prefix}:${queueName}:*`;
const removing = await new Promise<void>((resolve, reject) => {
const stream = client.scanStream({
match: pattern,
});
stream.on('data', (keys: string[]) => {
if (keys.length) {
const pipeline = client.pipeline();
keys.forEach(key => {
pipeline.del(key);
});
pipeline.exec().catch(error => {
reject(error);
});
}
});
stream.on('end', () => resolve());
stream.on('error', error => reject(error));
});
await removing;
await client.quit();
}
export function getParentKey(opts: {
id: string;
queue: string;
}): string | undefined {
if (opts) {
return `${opts.queue}:${opts.id}`;
}
}
export const clientCommandMessageReg =
/ERR unknown command ['`]\s*client\s*['`]/;
export const DELAY_TIME_5 = 5000;
export const DELAY_TIME_1 = 100;
export function isNotConnectionError(error: Error): boolean {
const errorMessage = `${(error as Error).message}`;
return (
errorMessage !== CONNECTION_CLOSED_ERROR_MSG &&
!errorMessage.includes('ECONNREFUSED')
);
}
interface procSendLike {
send?(message: any, callback?: (error: Error | null) => void): boolean;
postMessage?(message: any): void;
}
export const asyncSend = <T extends procSendLike>(
proc: T,
msg: any,
): Promise<void> => {
return new Promise((resolve, reject) => {
if (typeof proc.send === 'function') {
proc.send(msg, (err: Error | null) => {
if (err) {
reject(err);
} else {
resolve();
}
});
} else if (typeof proc.postMessage === 'function') {
resolve(proc.postMessage(msg));
} else {
resolve();
}
});
};
export const childSend = (
proc: NodeJS.Process,
msg: ChildMessage,
): Promise<void> => asyncSend<NodeJS.Process>(proc, msg);
export const isRedisVersionLowerThan = (
currentVersion: string,
minimumVersion: string,
): boolean => {
const version = semver.valid(semver.coerce(currentVersion)) as string;
return semver.lt(version, minimumVersion);
};
export const parseObjectValues = (obj: {
[key: string]: string;
}): Record<string, any> => {
const accumulator: Record<string, any> = {};
for (const value of Object.entries(obj)) {
accumulator[value[0]] = JSON.parse(value[1]);
}
return accumulator;
};
const getCircularReplacer = (rootReference: any) => {
const references = new WeakSet();
references.add(rootReference);
return (_: string, value: any) => {
if (typeof value === 'object' && value !== null) {
if (references.has(value)) {
return '[Circular]';
}
references.add(value);
}
return value;
};
};
export const errorToJSON = (value: any): Record<string, any> => {
const error: Record<string, any> = {};
Object.getOwnPropertyNames(value).forEach(function (propName: string) {
error[propName] = value[propName];
});
return JSON.parse(JSON.stringify(error, getCircularReplacer(value)));
};
const INFINITY = 1 / 0;
export const toString = (value: any): string => {
if (value == null) {
return '';
}
// Exit early for strings to avoid a performance hit in some environments.
if (typeof value === 'string') {
return value;
}
if (Array.isArray(value)) {
// Recursively convert values (susceptible to call stack limits).
return `${value.map(other => (other == null ? other : toString(other)))}`;
}
if (
typeof value == 'symbol' ||
Object.prototype.toString.call(value) == '[object Symbol]'
) {
return value.toString();
}
const result = `${value}`;
return result === '0' && 1 / value === -INFINITY ? '-0' : result;
};
export const QUEUE_EVENT_SUFFIX = ':qe';
export function removeUndefinedFields<T extends Record<string, any>>(
obj: Record<string, any>,
) {
const newObj: any = {};
for (const key in obj) {
if (obj[key] !== undefined) {
newObj[key] = obj[key];
}
}
return newObj as T;
}
/**
* Wraps the code with telemetry and provides a span for configuration.
*
* @param telemetry - telemetry configuration. If undefined, the callback will be executed without telemetry.
* @param spanKind - kind of the span: Producer, Consumer, Internal
* @param queueName - queue name
* @param operation - operation name (such as add, process, etc)
* @param destination - destination name (normally the queue name)
* @param callback - code to wrap with telemetry
* @param srcPropagationMedatada -
* @returns
*/
export async function trace<T>(
telemetry:
| {
tracer: Tracer;
contextManager: ContextManager;
}
| undefined,
spanKind: SpanKind,
queueName: string,
operation: string,
destination: string,
callback: (span?: Span, dstPropagationMetadata?: string) => Promise<T> | T,
srcPropagationMetadata?: string,
) {
if (!telemetry) {
return callback();
} else {
const { tracer, contextManager } = telemetry;
const currentContext = contextManager.active();
let parentContext;
if (srcPropagationMetadata) {
parentContext = contextManager.fromMetadata(
currentContext,
srcPropagationMetadata,
);
}
const spanName = destination ? `${operation} ${destination}` : operation;
const span = tracer.startSpan(
spanName,
{
kind: spanKind,
},
parentContext,
);
try {
span.setAttributes({
[TelemetryAttributes.QueueName]: queueName,
[TelemetryAttributes.QueueOperation]: operation,
});
let messageContext;
let dstPropagationMetadata: undefined | string;
if (spanKind === SpanKind.CONSUMER && parentContext) {
messageContext = span.setSpanOnContext(parentContext);
} else {
messageContext = span.setSpanOnContext(currentContext);
}
if (callback.length == 2) {
dstPropagationMetadata = contextManager.getMetadata(messageContext);
}
return await contextManager.with(messageContext, () =>
callback(span, dstPropagationMetadata),
);
} catch (err) {
span.recordException(err as Error);
throw err;
} finally {
span.end();
}
}
}