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.

67 lines 2.32 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 resolveLinearBackoffSettings(settings) { const { maxDelay = TimeSpan.fromSeconds(60), minDelay = TimeSpan.fromMilliseconds(500), 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 (jitter !== null && !(jitter >= 0 && jitter <= 1)) { throw new TypeError("'jitter' must be between 0 and 1 or null"); } return { maxDelay, minDelay, jitter, _mathRandom, }; } /** * Linear backoff policy with jitter * * IMPORT_PATH: `"@daiso-tech/core/backoff-policies"` * @group Implementations */ export function linearBackoff(settings = {}) { return (attempt, error) => { if (isInvokable(settings)) { const dynamicSettings = callInvokable(settings, error); if (dynamicSettings === undefined) { settings = {}; } else { settings = dynamicSettings; } } const { maxDelay, minDelay, jitter, _mathRandom } = resolveLinearBackoffSettings(settings); const linear = Math.min(maxDelay[TO_MILLISECONDS](), minDelay[TO_MILLISECONDS]() * attempt); return TimeSpan.fromMilliseconds(withJitter({ jitter, value: linear, randomValue: _mathRandom(), })); }; } /** * @internal */ export function serializeLinearBackoffSettings(settings) { const { maxDelay, minDelay, jitter, _mathRandom } = resolveLinearBackoffSettings(settings); return { maxDelay: maxDelay[TO_MILLISECONDS](), minDelay: minDelay[TO_MILLISECONDS](), jitter, _mathRandom: _mathRandom(), }; } //# sourceMappingURL=linear-backoff.js.map