@fedify/fedify
Version:
An ActivityPub server framework
35 lines (34 loc) • 1.38 kB
JavaScript
import { Temporal } from "@js-temporal/polyfill";
import "urlpattern-polyfill";
globalThis.addEventListener = () => {};
//#region src/federation/retry.ts
/**
* 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
*/
function createExponentialBackoffPolicy(options = {}) {
const initialDelay = Temporal.Duration.from(options.initialDelay ?? { seconds: 1 });
const maxDelay = 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 = Temporal.Duration.from({ milliseconds });
return Temporal.Duration.compare(delay, maxDelay) > 0 ? maxDelay : delay;
};
}
//#endregion
export { createExponentialBackoffPolicy as t };