@daiso-tech/core
Version:
The library offers flexible, framework-agnostic solutions for modern web applications, built on adaptable components that integrate seamlessly with popular frameworks like Next Js.
72 lines • 2.56 kB
JavaScript
/**
* @module BackoffPolicy
*/
import {} from "../../../backoff-policies/contracts/_module.js";
import { TO_MILLISECONDS, } from "../../../time-span/contracts/_module.js";
import { TimeSpan } from "../../../time-span/implementations/_module.js";
import { callInvokable, isInvokable, withJitter } from "../../../utilities/_module.js";
/**
* @internal
*/
export function resolveExponentialBackoffSettings(settings) {
const { maxDelay = TimeSpan.fromSeconds(60), minDelay = TimeSpan.fromMilliseconds(500), multiplier = 2, jitter = 0.5, _mathRandom = Math.random, } = settings;
if (!(minDelay[TO_MILLISECONDS]() > 0)) {
throw new TypeError("'minDelay' must be positive");
}
if (!(maxDelay[TO_MILLISECONDS]() >= minDelay[TO_MILLISECONDS]())) {
throw new TypeError("'maxDelay' must be greater than or equal to 'minDelay'");
}
if (!(multiplier > 0)) {
throw new TypeError("'multiplier' must be positive");
}
if (jitter !== null && !(jitter >= 0 && jitter <= 1)) {
throw new TypeError("'jitter' must be between 0 and 1 or null");
}
return {
maxDelay,
minDelay,
multiplier,
jitter,
_mathRandom,
};
}
/**
* Exponential backoff policy with jitter
*
* IMPORT_PATH: `"@daiso-tech/core/backoff-policies"`
* @group Implementations
*/
export function exponentialBackoff(settings = {}) {
return (attempt, error) => {
if (isInvokable(settings)) {
const dynamicSettings = callInvokable(settings, error);
if (dynamicSettings === undefined) {
settings = {};
}
else {
settings = dynamicSettings;
}
}
const { jitter, _mathRandom, multiplier, maxDelay, minDelay } = resolveExponentialBackoffSettings(settings);
const exponential = Math.min(maxDelay[TO_MILLISECONDS](), minDelay[TO_MILLISECONDS]() * Math.pow(multiplier, attempt));
return TimeSpan.fromMilliseconds(withJitter({
jitter,
value: exponential,
randomValue: _mathRandom(),
}));
};
}
/**
* @internal
*/
export function serializeExponentialBackoffSettings(settings) {
const { maxDelay, minDelay, multiplier, jitter, _mathRandom } = resolveExponentialBackoffSettings(settings);
return {
maxDelay: maxDelay[TO_MILLISECONDS](),
minDelay: minDelay[TO_MILLISECONDS](),
multiplier,
jitter,
_mathRandom: _mathRandom(),
};
}
//# sourceMappingURL=exponential-backoff.js.map