UNPKG

@fedify/fedify

Version:

An ActivityPub server framework

35 lines (34 loc) 1.43 kB
/** * The context passed to a {@link RetryPolicy} callback. * @since 0.12.0 */ import * as dntShim from "../_dnt.shims.js"; /** * Creates an exponential backoff retry policy. The delay between retries * starts at the `initialDelay` and is multiplied by the `factor` for each * subsequent retry, up to the `maxDelay`. The policy will give up after * `maxAttempts` attempts. The actual delay is randomized to avoid * synchronization (jitter). * @param options The options for the policy. * @returns The retry policy. * @since 0.12.0 */ export function createExponentialBackoffPolicy(options = {}) { const initialDelay = dntShim.Temporal.Duration.from(options.initialDelay ?? { seconds: 1 }); const maxDelay = dntShim.Temporal.Duration.from(options.maxDelay ?? { hours: 12 }); const maxAttempts = options.maxAttempts ?? 10; const factor = options.factor ?? 2; const jitter = options.jitter ?? true; return ({ attempts }) => { if (attempts >= maxAttempts) return null; let milliseconds = initialDelay.total("millisecond"); milliseconds *= factor ** attempts; if (jitter) { milliseconds *= 1 + Math.random(); milliseconds = Math.round(milliseconds); } const delay = dntShim.Temporal.Duration.from({ milliseconds }); return dntShim.Temporal.Duration.compare(delay, maxDelay) > 0 ? maxDelay : delay; }; }