1 /* eslint-disable security/detect-object-injection */
5 * Assorted utility functions.
8 const { common
} = require('@squeep/api-dingus');
10 const { randomBytes
, getHashes
} = require('crypto');
11 const { promisify
} = require('util');
15 * Wrap this in a promise, as crypto.randomBytes is capable of blocking.
17 const randomBytesAsync
= promisify(randomBytes
);
21 * The HMAC hashes we are willing to support.
22 * @param {String} algorithm
25 const validHash
= (algorithm
) => getHashes()
26 .filter((h
) => h
.match(/^sha[0-9]+$/))
31 * Return an array containing x if x is not an array.
34 const ensureArray
= (x
) => {
35 if (x
=== undefined) {
38 if (!Array
.isArray(x
)) {
46 * Recursively freeze an object.
50 const freezeDeep
= (o
) => {
52 Object
.getOwnPropertyNames(o
).forEach((prop
) => {
53 if (Object
.hasOwnProperty
.call(o
, prop
)
54 && ['object', 'function'].includes(typeof o
[prop
])
55 && !Object
.isFrozen(o
[prop
])) {
56 return freezeDeep(o
[prop
]);
64 * Pick out useful axios response fields.
68 const axiosResponseLogData
= (res
) => {
69 const data
= common
.pick(res
, [
77 data
.data
= logTruncate(data
.data
, 100);
84 * Fallback values, if not configured.
87 const topicLeaseDefaults
= () => {
88 return Object
.freeze({
89 leaseSecondsPreferred: 86400 * 10,
90 leaseSecondsMin: 86400 * 1,
91 leaseSecondsMax: 86400 * 365,
97 * Pick from a range, constrained, with some fuzziness.
98 * @param {Number} attempt
99 * @param {Number[]} delays
100 * @param {Number} jitter
103 const attemptRetrySeconds
= (attempt
, retryBackoffSeconds
= [60, 120, 360, 1440, 7200, 43200, 86400], jitter
= 0.618) => {
104 const maxAttempt
= retryBackoffSeconds
.length
- 1;
105 if (typeof attempt
!== 'number' || attempt
< 0) {
107 } else if (attempt
> maxAttempt
) {
108 attempt
= maxAttempt
;
110 // eslint-disable-next-line security/detect-object-injection
111 let seconds
= retryBackoffSeconds
[attempt
];
112 seconds
+= Math
.floor(Math
.random() * seconds
* jitter
);
118 * Return array items split as an array of arrays of no more than per items each.
119 * @param {Array} array
120 * @param {Number} per
122 const arrayChunk
= (array
, per
= 1) => {
123 const nChunks
= Math
.ceil(array
.length
/ per
);
124 return Array
.from(Array(nChunks
), (_
, i
) => array
.slice(i
* per
, (i
+ 1) * per
));
129 * Be paranoid about blowing the stack when pushing to an array.
133 const stackSafePush
= (dst
, src
) => {
134 const jsEngineMaxArguments
= 2**16; // Current as of Node 12
135 arrayChunk(src
, jsEngineMaxArguments
).forEach((items
) => {
136 Array
.prototype.push
.apply(dst
, items
);
142 * Limit length of string to keep logs sane
143 * @param {String} str
144 * @param {Number} len
147 const logTruncate
= (str
, len
) => {
148 if (typeof str
!== 'string' || str
.toString().length
<= len
) {
151 return str
.toString().slice(0, len
) + `... (${str.toString().length} bytes)`;
158 axiosResponseLogData
,