@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.
59 lines • 2.01 kB
JavaScript
/**
* @module BackoffPolicy
*/
import {} from "../../backoff-policies/_shared.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.fromMilliseconds(60_000), minDelay = TimeSpan.fromMilliseconds(1_000), multiplier = 2, jitter = 0.5, _mathRandom = Math.random, } = settings;
return {
maxDelay,
minDelay,
multiplier,
jitter,
_mathRandom,
};
}
/**
* Exponential backoff policy with jitter
*
* IMPORT_PATH: `"@daiso-tech/core/backoff-policies"`
*/
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