import { describe, expect, it } from "vitest"; import { calculateBackoff, parseRetryAfter, retryDelay, shouldRetry, } from "../../src/adapters/http/retry-policy.ts"; describe("HTTP retry policy", () => { it("uses capped exponential full jitter", () => { expect(calculateBackoff(0, () => 0.5)).toBe(125); expect(calculateBackoff(8, () => 1)).toBe(2_000); }); it("parses retry-after and chooses the longer bounded delay", () => { expect(parseRetryAfter("2", 0)).toBe(2_000); expect(parseRetryAfter(" 2 ", 0)).toBe(2_000); expect(parseRetryAfter("Thu, 01 Jan 1970 00:00:05 GMT", 1_000)).toBe( 4_000, ); expect(retryDelay({ kind: "RATE_LIMITED", retryAfterMs: 500 }, 0, () => 0)).toBe( 500, ); }); it("rejects Retry-After values that are not delta-seconds or an HTTP date", () => { for (const value of ["", " ", "1e3", "1.5", "-1", "0x10", "2024-01-01"]) { expect(parseRetryAfter(value, 0)).toBeNull(); } }); it("allows at most two retries for safe or keyed requests", () => { const failure = { kind: "SERVER_FAILURE" }; expect(shouldRetry({ idempotency: "safe" }, failure, 0)).toBe(true); expect(shouldRetry({ idempotency: "keyed" }, failure, 1)).toBe(true); expect(shouldRetry({ idempotency: "safe" }, failure, 2)).toBe(false); expect(shouldRetry({ idempotency: "none" }, failure, 0)).toBe(false); expect( shouldRetry( { idempotency: "safe" }, { kind: "SERVER_FAILURE", httpStatus: 500 }, 0, ), ).toBe(false); }); // R3-1. 408/425 server failures share the 502/503/504 rule and honor // Retry-After with the same 30s ceiling. it("retries 408 and 425 server failures only for safe or keyed requests", () => { for (const httpStatus of [408, 425]) { const failure = { kind: "SERVER_FAILURE", httpStatus }; expect(shouldRetry({ idempotency: "safe" }, failure, 0)).toBe(true); expect(shouldRetry({ idempotency: "keyed" }, failure, 0)).toBe(true); expect(shouldRetry({ idempotency: "none" }, failure, 0)).toBe(false); expect( shouldRetry({ idempotency: "safe", retry: "never" }, failure, 0), ).toBe(false); expect( retryDelay({ ...failure, retryAfterMs: 1_500 }, 0, () => 0), ).toBe(1_500); expect( shouldRetry( { idempotency: "safe" }, { ...failure, retryAfterMs: 31_000 }, 0, ), ).toBe(false); } }); it("does not automatically wait beyond 30 seconds", () => { expect( shouldRetry( { idempotency: "safe" }, { kind: "RATE_LIMITED", retryAfterMs: 31_000 }, 0, ), ).toBe(false); }); });