All files / packages/retry/src strategy.ts

100% Statements 18/18
100% Branches 0/0
100% Functions 18/18
100% Lines 8/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54                                              13x       7x       14x       5x       10x       340x       9x       10x    
import type { RetryConfig } from './config.js'
import type { RetryContext } from './context.js'
 
/**
 * Strategy to calculate delay.
 * @param ctx - Context for retry operation
 * @param cfg - Options for retry configuration
 * @returns Delay in milliseconds
 *
 * @example
 * ```ts
 * import { retry, fixed } from '@ydbjs/retry'
 *
 * await retry(() => fetch('https://example.com'), {
 *     strategy: fixed(1000),
 * })
 * ```
 */
export interface RetryStrategy {
	(ctx: RetryContext, cfg: RetryConfig): number
}
 
export function fixed(ms: number): RetryStrategy {
	return () => ms
}
 
export function linear(ms: number): RetryStrategy {
	return (ctx) => ctx.attempt * ms
}
 
export function exponential(ms: number): RetryStrategy {
	return (ctx) => Math.pow(2, ctx.attempt) * ms
}
 
export function random(min: number, max: number): RetryStrategy {
	return () => Math.floor(Math.random() * (max - min + 1) + min)
}
 
export function jitter(ms: number): RetryStrategy {
	return (ctx) => Math.floor(Math.random() * ms) + ctx.attempt
}
 
export function backoff(base: number, max: number): RetryStrategy {
	return (ctx) => Math.min(Math.pow(2, ctx.attempt) * base, max)
}
 
export function combine(...strategies: RetryStrategy[]): RetryStrategy {
	return (ctx, cfg) => strategies.reduce((acc, strategy) => acc + strategy(ctx, cfg), 0)
}
 
export function compose(...strategies: RetryStrategy[]): RetryStrategy {
	return (ctx, cfg) => strategies.reduce((acc, strategy) => Math.max(acc, strategy(ctx, cfg)), 0)
}