UNPKG

@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.

61 lines 1.93 kB
/** * @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 resolveConstantBackoffSettings(settings) { const { delay = TimeSpan.fromSeconds(1), jitter = 0.5, _mathRandom = Math.random, } = settings; if (!(delay[TO_MILLISECONDS]() > 0)) { throw new TypeError("'delay' must be positive"); } if (jitter !== null && !(jitter >= 0 && jitter <= 1)) { throw new TypeError("'jitter' must be between 0 and 1 or null"); } return { delay, jitter, _mathRandom, }; } /** * Constant backoff policy with jitter * * IMPORT_PATH: `"@daiso-tech/core/backoff-policies"` * @group Implementations */ export function constantBackoff(settings = {}) { return (_attempt, error) => { if (isInvokable(settings)) { const dynamicSettings = callInvokable(settings, error); if (dynamicSettings === undefined) { settings = {}; } else { settings = dynamicSettings; } } const { delay, jitter, _mathRandom } = resolveConstantBackoffSettings(settings); return TimeSpan.fromMilliseconds(withJitter({ jitter, value: delay[TO_MILLISECONDS](), randomValue: _mathRandom(), })); }; } /** * @internal */ export function serializeConstantBackoffSettings(settings) { const { delay, jitter, _mathRandom } = resolveConstantBackoffSettings(settings); return { delay: delay[TO_MILLISECONDS](), jitter, _mathRandom: _mathRandom(), }; } //# sourceMappingURL=constant-backoff.js.map