@elastic.io/maester-client
Version:
The official object-storage client
61 lines (60 loc) • 2.92 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.exponentialDelay = exports.exponentialSleep = exports.validateAndGetRetryOptions = exports.getFreshStreamChecker = exports.streamFromData = exports.parseJson = void 0;
const stream_1 = require("stream");
const errors_1 = require("./errors");
const interfaces_1 = require("./interfaces");
const ENV_RETRIES_COUNT = process.env.REQUEST_MAX_RETRY ? parseInt(process.env.REQUEST_MAX_RETRY, 10) : null;
const ENV_REQUEST_TIMEOUT = process.env.REQUEST_TIMEOUT ? parseInt(process.env.REQUEST_TIMEOUT, 10) : null;
const parseJson = (source) => {
let parsedJson;
try {
parsedJson = JSON.parse(source);
}
catch (parseError) {
throw new Error('Could not parse Maester object as it is not a JSON object');
}
return parsedJson;
};
exports.parseJson = parseJson;
// 'undefined' throws error, but 'null' is ok (as an option - convert 'undefined' to 'null')
const streamFromData = async (data) => {
const dataString = JSON.stringify(data);
const stream = new stream_1.Readable();
stream.push(dataString);
stream.push(null);
return stream;
};
exports.streamFromData = streamFromData;
const getFreshStreamChecker = () => {
let previousStream;
return (stream) => {
// defensive check
if (previousStream && previousStream === stream) {
throw new errors_1.PotentiallyConsumedStreamError('The stream callback must always return a new stream');
}
previousStream = stream;
};
};
exports.getFreshStreamChecker = getFreshStreamChecker;
/**
* if values are higher or lower the limit - they'll be overwritten.
* returns valid values for RetryOptions
*/
const validateAndGetRetryOptions = ({ retriesCount = ENV_RETRIES_COUNT || interfaces_1.RETRIES_COUNT.defaultValue, requestTimeout = ENV_REQUEST_TIMEOUT || interfaces_1.REQUEST_TIMEOUT.defaultValue }) => ({
retriesCount: (retriesCount > interfaces_1.RETRIES_COUNT.maxValue || retriesCount < interfaces_1.RETRIES_COUNT.minValue) ? interfaces_1.RETRIES_COUNT.defaultValue : retriesCount,
requestTimeout: (requestTimeout > interfaces_1.REQUEST_TIMEOUT.maxValue || requestTimeout < interfaces_1.REQUEST_TIMEOUT.minValue) ? interfaces_1.REQUEST_TIMEOUT.defaultValue : requestTimeout
});
exports.validateAndGetRetryOptions = validateAndGetRetryOptions;
const exponentialSleep = async (currentRetries) => sleep((0, exports.exponentialDelay)(currentRetries));
exports.exponentialSleep = exponentialSleep;
const sleep = async (ms) => new Promise((resolve) => {
setTimeout(resolve, ms);
});
const exponentialDelay = (currentRetries) => {
const maxBackoff = 15000;
const delay = (2 ** currentRetries) * 100;
const randomSum = delay * 0.2 * Math.random(); // 0-20% of the delay
return Math.min(delay + randomSum, maxBackoff);
};
exports.exponentialDelay = exponentialDelay;