/
utils.ts
658 lines (601 loc) · 18.7 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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import Long from "long";
import { logger, receiverLogger, messageLogger } from "../log";
import { OperationTimeoutError, generate_uuid } from "rhea-promise";
import isBuffer from "is-buffer";
import { Buffer } from "buffer";
import * as Constants from "../util/constants";
import { AbortError, AbortSignalLike } from "@azure/abort-controller";
import { HttpOperationResponse, HttpResponse, isNode } from "@azure/core-http";
// This is the only dependency we have on DOM types, so rather than require
// the DOM lib we can just shim this in.
/**
* @hidden
* @internal
*/
interface Navigator {
hardwareConcurrency: number;
}
/**
* @hidden
* @internal
*/
declare const navigator: Navigator;
/**
* @internal
* @hidden
* Provides a uniue name by appending a string guid to the given string in the following format:
* `{name}-{uuid}`.
* @param name The nme of the entity
*/
export function getUniqueName(name: string): string {
return `${name}-${generate_uuid()}`;
}
/**
* @internal
* @hidden
* If you try to turn a Guid into a Buffer in .NET, the bytes of the first three groups get
* flipped within the group, but the last two groups don't get flipped, so we end up with a
* different byte order. This is the order of bytes needed to make Service Bus recognize the token.
*
* @param lockToken The lock token whose bytes need to be reorded.
* @returns Buffer - Buffer representing reordered bytes.
*/
export function reorderLockToken(lockTokenBytes: Buffer): Buffer {
if (!lockTokenBytes || !Buffer.isBuffer(lockTokenBytes)) {
return lockTokenBytes;
}
return Buffer.from([
lockTokenBytes[3],
lockTokenBytes[2],
lockTokenBytes[1],
lockTokenBytes[0],
lockTokenBytes[5],
lockTokenBytes[4],
lockTokenBytes[7],
lockTokenBytes[6],
lockTokenBytes[8],
lockTokenBytes[9],
lockTokenBytes[10],
lockTokenBytes[11],
lockTokenBytes[12],
lockTokenBytes[13],
lockTokenBytes[14],
lockTokenBytes[15]
]);
}
/**
* @internal
* @hidden
* Provides the time in milliseconds after which the lock renewal should occur.
* @param lockedUntilUtc - The time until which the message is locked.
*/
export function calculateRenewAfterDuration(lockedUntilUtc: Date): number {
const now = Date.now();
const lockedUntil = lockedUntilUtc.getTime();
const remainingTime = lockedUntil - now;
receiverLogger.verbose("Locked until utc : %d", lockedUntil);
receiverLogger.verbose("Current time is : %d", now);
receiverLogger.verbose("Remaining time is : %d", remainingTime);
if (remainingTime < 1000) {
return 0;
}
const buffer = Math.min(remainingTime / 2, 10000); // 10 seconds
const renewAfter = remainingTime - buffer;
receiverLogger.verbose("Renew after : %d", renewAfter);
return renewAfter;
}
/**
* @internal
* @hidden
* Converts the .net ticks to a JS Date object.
*
* - The epoch for the DateTimeOffset type is `0000-01-01`, while the epoch for JS Dates is
* `1970-01-01`.
* - The DateTimeOffset ticks value for the date `1970-01-01` is `621355968000000000`.
* - Hence, to convert it to the JS epoch; we `subtract` the delta from the given value.
* - Ticks in DateTimeOffset is `1/10000000` second, while ticks in JS Date is `1/1000` second.
* - Thus, we `divide` the value by `10000` to convert it to JS Date ticks.
*
* @param buf Input as a Buffer
* @returns Date The JS Date object.
*/
export function convertTicksToDate(buf: number[]): Date {
const epochMicroDiff: number = 621355968000000000;
const longValue: Long = Long.fromBytesBE(buf);
const timeInMS = longValue
.sub(epochMicroDiff)
.div(10000)
.toNumber();
const result = new Date(timeInMS);
logger.verbose("The converted date is: %s", result.toString());
return result;
}
/**
* @internal
* @hidden
* Returns the number of logical processors in the system.
*/
export function getProcessorCount(): number {
if (isNode) {
const os = require("os");
return os.cpus().length;
} else {
return navigator.hardwareConcurrency || 1;
}
}
/**
* @internal
* @hidden
* Converts any given input to a Buffer.
* @param input The input that needs to be converted to a Buffer.
*/
export function toBuffer(input: any): Buffer {
let result: any;
messageLogger.verbose(
"[utils.toBuffer] The given message body that needs to be converted to buffer is: ",
input
);
if (isBuffer(input)) {
result = input;
} else {
// string, undefined, null, boolean, array, object, number should end up here
// coercing undefined to null as that will ensure that null value will be given to the
// customer on receive.
if (input === undefined) input = null;
try {
const inputStr = JSON.stringify(input);
result = Buffer.from(inputStr, "utf8");
} catch (err) {
const msg =
`An error occurred while executing JSON.stringify() on the given input ` +
input +
`${err instanceof Error ? err.stack : JSON.stringify(err)}`;
messageLogger.warning("[utils.toBuffer] " + msg);
throw err instanceof Error ? err : new Error(msg);
}
}
messageLogger.verbose("[utils.toBuffer] The converted buffer is: %O.", result);
return result;
}
/**
* @internal
* @hidden
* Helper utility to retrieve `string` value from given string,
* or throws error if undefined.
* @param value
*/
export function getString(value: any, nameOfProperty: string): string {
const result = getStringOrUndefined(value);
if (result == undefined) {
throw new Error(
`"${nameOfProperty}" received from service expected to be a string value and not undefined.`
);
}
return result;
}
/**
* @internal
* @hidden
* Helper utility to retrieve `string` value from given input,
* or undefined if not passed in.
* @param value
*/
export function getStringOrUndefined(value: any): string | undefined {
if (value == undefined) {
return undefined;
}
return value.toString();
}
/**
* @internal
* @hidden
* Helper utility to retrieve `integer` value from given string,
* or throws error if undefined.
* @param value
*/
export function getInteger(value: any, nameOfProperty: string): number {
const result = getIntegerOrUndefined(value);
if (result == undefined) {
throw new Error(
`"${nameOfProperty}" received from service expected to be a number value and not undefined.`
);
}
return result;
}
/**
* @internal
* @hidden
* Helper utility to retrieve `integer` value from given string,
* or undefined if not passed in.
* @param value
*/
export function getIntegerOrUndefined(value: any): number | undefined {
if (value == undefined) {
return undefined;
}
const result = parseInt(value.toString());
return result == NaN ? undefined : result;
}
/**
* @internal
* @hidden
* Helper utility to convert ISO-8601 time into Date type.
* @param value
*/
export function getDate(value: string, nameOfProperty: string): Date {
return new Date(getString(value, nameOfProperty));
}
/**
* @internal
* @hidden
* Helper utility to retrieve `boolean` value from given string,
* or throws error if undefined.
* @param value
*/
export function getBoolean(value: any, nameOfProperty: string): boolean {
const result = getBooleanOrUndefined(value);
if (result == undefined) {
throw new Error(
`"${nameOfProperty}" received from service expected to be a boolean value and not undefined.`
);
}
return result;
}
/**
* @internal
* @hidden
* Helper utility to retrieve `boolean` value from given string,
* or undefined if not passed in.
* @param value
*/
export function getBooleanOrUndefined(value: any): boolean | undefined {
if (value == undefined) {
return undefined;
}
return (
value
.toString()
.trim()
.toLowerCase() === "true"
);
}
/**
* @internal
* @hidden
* Helps in differentiating JSON like objects from other kinds of objects.
*/
const EMPTY_JSON_OBJECT_CONSTRUCTOR = {}.constructor;
/**
* @internal
* @hidden
* Returns `true` if given input is a JSON like object.
* @param value
*/
export function isJSONLikeObject(value: any): boolean {
// `value.constructor === {}.constructor` differentiates among the "object"s,
// would filter the JSON objects and won't match any array or other kinds of objects
// -------------------------------------------------------------------------------
// Few examples | typeof obj ==="object" | obj.constructor==={}.constructor
// -------------------------------------------------------------------------------
// {abc:1} | true | true
// ["a","b"] | true | false
// [{"a":1},{"b":2}] | true | false
// new Date() | true | false
// 123 | false | false
// -------------------------------------------------------------------------------
return typeof value === "object" && value.constructor === EMPTY_JSON_OBJECT_CONSTRUCTOR;
}
/**
* @internal
* @hidden
* Helper utility to retrieve message count details from given input,
* @param value
*/
export function getMessageCountDetails(value: any): MessageCountDetails {
if (value == undefined) {
value = {};
}
return {
activeMessageCount: parseInt(value["d2p1:ActiveMessageCount"]) || 0,
deadLetterMessageCount: parseInt(value["d2p1:DeadLetterMessageCount"]) || 0,
scheduledMessageCount: parseInt(value["d2p1:ScheduledMessageCount"]) || 0,
transferMessageCount: parseInt(value["d2p1:TransferMessageCount"]) || 0,
transferDeadLetterMessageCount: parseInt(value["d2p1:TransferDeadLetterMessageCount"]) || 0
};
}
/**
* Represents type of message count details in ATOM based management operations.
* @internal
* @hidden
*/
export type MessageCountDetails = {
activeMessageCount: number;
deadLetterMessageCount: number;
scheduledMessageCount: number;
transferMessageCount: number;
transferDeadLetterMessageCount: number;
};
/**
* Represents type of `AuthorizationRule` in ATOM based management operations.
*/
export interface AuthorizationRule {
/**
* The claim type.
*/
claimType: string;
/**
* The list of rights("Manage" | "Send" | "Listen").
*/
accessRights?: ("Manage" | "Send" | "Listen")[];
/**
* The authorization rule key name.
*/
keyName: string;
/**
* The primary key for the authorization rule.
*/
primaryKey?: string;
/**
* The secondary key for the authorization rule.
*/
secondaryKey?: string;
}
/**
* @internal
* @hidden
* Helper utility to retrieve array of `AuthorizationRule` from given input,
* or undefined if not passed in.
* @param value
*/
export function getAuthorizationRulesOrUndefined(value: any): AuthorizationRule[] | undefined {
const authorizationRules: AuthorizationRule[] = [];
// Ignore special case as Service Bus treats "" as a valid value for authorization rules
if (typeof value === "string" && value.trim() === "") {
return undefined;
}
if (value == undefined) {
return undefined;
}
const rawAuthorizationRules = value.AuthorizationRule;
if (Array.isArray(rawAuthorizationRules)) {
for (let i = 0; i < rawAuthorizationRules.length; i++) {
authorizationRules.push(buildAuthorizationRule(rawAuthorizationRules[i]));
}
} else {
authorizationRules.push(buildAuthorizationRule(rawAuthorizationRules));
}
return authorizationRules;
}
/**
* @internal
* @hidden
* Helper utility to build an instance of parsed authorization rule as `AuthorizationRule` from given input.
* @param value
*/
function buildAuthorizationRule(value: any): AuthorizationRule {
let accessRights;
if (value["Rights"] != undefined) {
accessRights = value["Rights"]["AccessRights"];
}
const authorizationRule: AuthorizationRule = {
claimType: value["ClaimType"],
accessRights,
keyName: value["KeyName"],
primaryKey: value["PrimaryKey"],
secondaryKey: value["SecondaryKey"]
};
if (authorizationRule.accessRights && !Array.isArray(authorizationRule.accessRights)) {
authorizationRule.accessRights = [authorizationRule.accessRights];
}
return authorizationRule;
}
/**
* @internal
* @hidden
* Helper utility to extract output containing array of `RawAuthorizationRule` instances from given input,
* or undefined if not passed in.
* @param value
*/
export function getRawAuthorizationRules(authorizationRules: AuthorizationRule[] | undefined): any {
if (authorizationRules == undefined) {
return undefined;
}
if (!Array.isArray(authorizationRules)) {
throw new TypeError(
`authorizationRules must be an array of AuthorizationRule objects or undefined, but received ${JSON.stringify(
authorizationRules,
undefined,
2
)}`
);
}
const rawAuthorizationRules: any[] = [];
for (let i = 0; i < authorizationRules.length; i++) {
rawAuthorizationRules.push(buildRawAuthorizationRule(authorizationRules[i]));
}
return { AuthorizationRule: rawAuthorizationRules };
}
/**
* @internal
* @hidden
* Helper utility to build an instance of raw authorization rule as RawAuthorizationRule from given `AuthorizationRule` input.
* @param authorizationRule parsed Authorization Rule instance
*/
function buildRawAuthorizationRule(authorizationRule: AuthorizationRule): any {
if (!isJSONLikeObject(authorizationRule) || authorizationRule === null) {
throw new TypeError(
`Expected authorizationRule input to be a JS object value, but received ${JSON.stringify(
authorizationRule,
undefined,
2
)}`
);
}
const rawAuthorizationRule: any = {
ClaimType: authorizationRule.claimType,
// ClaimValue is not settable by the users, but service expects the value for PUT requests
ClaimValue: "None",
Rights: {
AccessRights: authorizationRule.accessRights
},
KeyName: authorizationRule.keyName,
PrimaryKey: authorizationRule.primaryKey,
SecondaryKey: authorizationRule.secondaryKey
};
rawAuthorizationRule[Constants.XML_METADATA_MARKER] = {
"p5:type": "SharedAccessAuthorizationRule",
"xmlns:p5": "http://www.w3.org/2001/XMLSchema-instance"
};
return rawAuthorizationRule;
}
/**
* @internal
* @hidden
* Helper utility to check if given string is an absolute URL
* @param url
*/
export function isAbsoluteUrl(url: string) {
const _url = url.toLowerCase();
return _url.startsWith("sb://") || _url.startsWith("http://") || _url.startsWith("https://");
}
/**
* Possible values for `status` of the Service Bus messaging entities.
*/
export type EntityStatus =
| "Active"
| "Creating"
| "Deleting"
| "ReceiveDisabled"
| "SendDisabled"
| "Disabled"
| "Renaming"
| "Restoring"
| "Unknown";
/**
* Possible values for `availabilityStatus` of the Service Bus messaging entities.
*/
export type EntityAvailabilityStatus =
| "Available"
| "Limited"
| "Renaming"
| "Restoring"
| "Unknown";
/**
* @internal
* @hidden
*/
export const StandardAbortMessage = "The operation was aborted.";
/**
* An executor for a function that returns a Promise that obeys both a timeout and an
* optional AbortSignal.
* @param timeoutMs - The number of milliseconds to allow before throwing an OperationTimeoutError.
* @param timeoutMessage - The message to place in the .description field for the thrown exception for Timeout.
* @param abortSignal - The abortSignal associated with containing operation.
* @param abortErrorMsg - The abort error message associated with containing operation.
* @param value - The value to be resolved with after a timeout of t milliseconds.
* @returns {Promise<T>} - Resolved promise
*
* @internal
* @hidden
*/
export async function waitForTimeoutOrAbortOrResolve<T>(args: {
actionFn: () => Promise<T>;
timeoutMs: number;
timeoutMessage: string;
abortSignal?: AbortSignalLike;
// these are optional and only here for testing.
timeoutFunctions?: {
setTimeoutFn: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => any;
clearTimeoutFn: (timeoutId: any) => void;
};
}): Promise<T> {
if (args.abortSignal && args.abortSignal.aborted) {
throw new AbortError(StandardAbortMessage);
}
let timer: any | undefined = undefined;
let clearAbortSignal: (() => void) | undefined = undefined;
const clearAbortSignalAndTimer = (): void => {
(args.timeoutFunctions?.clearTimeoutFn ?? clearTimeout)(timer);
if (clearAbortSignal) {
clearAbortSignal();
}
};
// eslint-disable-next-line promise/param-names
const abortOrTimeoutPromise = new Promise<T>((_resolve, reject) => {
clearAbortSignal = checkAndRegisterWithAbortSignal(reject, args.abortSignal);
timer = (args.timeoutFunctions?.setTimeoutFn ?? setTimeout)(() => {
reject(new OperationTimeoutError(args.timeoutMessage));
}, args.timeoutMs);
});
try {
return await Promise.race([abortOrTimeoutPromise, args.actionFn()]);
} finally {
clearAbortSignalAndTimer();
}
}
/**
* Registers listener to the abort event on the abortSignal to call your abortFn and
* returns a function that will clear the same listener.
*
* If abort signal is already aborted, then throws an AbortError and returns a function that does nothing
*
* @returns A function that removes any of our attached event listeners on the abort signal or an empty function if
* the abortSignal was not defined.
*
* @internal
* @hidden
*/
export function checkAndRegisterWithAbortSignal(
onAbortFn: (abortError: AbortError) => void,
abortSignal?: AbortSignalLike
): () => void {
if (abortSignal == null) {
return () => {};
}
if (abortSignal.aborted) {
throw new AbortError(StandardAbortMessage);
}
const onAbort = (): void => {
abortSignal.removeEventListener("abort", onAbort);
onAbortFn(new AbortError(StandardAbortMessage));
};
abortSignal.addEventListener("abort", onAbort);
return () => abortSignal.removeEventListener("abort", onAbort);
}
/**
* @internal
* @hidden
* @property {string} libInfo The user agent prefix string for the ServiceBus client.
* See guideline at https://azure.github.io/azure-sdk/general_azurecore.html#telemetry-policy
*/
export const libInfo: string = `azsdk-js-azureservicebus/${Constants.packageJsonInfo.version}`;
/**
* @internal
* @hidden
* Returns the formatted prefix by removing the spaces, by appending the libInfo.
*
* @param {string} [prefix]
* @returns {string}
*/
export function formatUserAgentPrefix(prefix?: string): string {
let userAgentPrefix = `${(prefix || "").replace(" ", "")}`;
userAgentPrefix = userAgentPrefix.length > 0 ? userAgentPrefix + " " : "";
return `${userAgentPrefix}${libInfo}`;
}
/**
* @internal
* @hidden
* Helper method which returns `HttpResponse` from an object of shape `HttpOperationResponse`.
* @returns {HttpResponse}
*/
export const getHttpResponseOnly = ({
request,
status,
headers
}: HttpOperationResponse): HttpResponse => ({
request,
status,
headers
});