/** * Retry wrapper for SublimePDF render calls, as published in /guides/pdf-api-error-handling. * Node.js 22.18+ (runs as .ts via type stripping), no dependencies. */ import { randomUUID } from "node:crypto"; export interface ApiError { status: number | null; // null = no HTTP response (timeout, connection error) type: string; message: string; field?: string; retryable: boolean; } export type RenderResult = | { ok: true; pdf: Buffer; attempts: number; idempotencyKey: string } | { ok: false; error: ApiError; attempts: number; idempotencyKey: string }; export interface RetryOptions { apiKey?: string; baseUrl?: string; maxAttempts?: number; // total tries, including the first baseDelayMs?: number; // first backoff step maxDelayMs?: number; // cap for one backoff step maxRetryAfterMs?: number; // give up instead of waiting longer than this attemptTimeoutMs?: number; // per request deadlineMs?: number; // whole operation, all retries included idempotencyKey?: string; // pass your own to make retries span process restarts log?: (event: Record) => void; } const RETRYABLE = new Set([429, 500, 502, 503, 504]); const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); /** Retry-After is either delay-seconds or an HTTP-date (RFC 9110, section 10.2.3). */ export function parseRetryAfter(value: string | null, now = Date.now()): number | null { if (!value) return null; if (/^\d+$/.test(value.trim())) return Number(value) * 1000; const date = Date.parse(value); return Number.isNaN(date) ? null : Math.max(0, date - now); } /** "Full jitter": a random delay between 0 and the exponential step. */ const backoff = (attempt: number, base: number, cap: number) => Math.random() * Math.min(cap, base * 2 ** (attempt - 1)); async function toApiError(res: Response): Promise { let body: any = null; try { body = await res.json(); } catch { // not JSON, e.g. an HTML page from a proxy } const e = body?.error ?? {}; return { status: res.status, type: typeof e.type === "string" ? e.type : `http_${res.status}`, message: typeof e.message === "string" ? e.message : res.statusText || `HTTP ${res.status}`, ...(typeof e.field === "string" ? { field: e.field } : {}), retryable: RETRYABLE.has(res.status), }; } export async function renderWithRetry(path: string, body: unknown, opts: RetryOptions = {}): Promise { const { apiKey = process.env.SUBLIMEPDF_API_KEY, baseUrl = process.env.SUBLIMEPDF_API_BASE_URL ?? "https://api.sublimepdf.com/v1", maxAttempts = 4, baseDelayMs = 500, maxDelayMs = 8_000, maxRetryAfterMs = 30_000, attemptTimeoutMs = 60_000, deadlineMs = 120_000, idempotencyKey = randomUUID(), // one key per logical render, reused by every retry log = () => {}, } = opts; if (!apiKey) throw new Error("SUBLIMEPDF_API_KEY is not set"); const started = Date.now(); let lastError: ApiError = { status: null, type: "not_attempted", message: "No attempt made", retryable: false }; let attempt = 0; while (++attempt <= maxAttempts) { let waitMs: number | null = null; try { const res = await fetch(`${baseUrl}${path}`, { method: "POST", headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", Accept: "application/pdf", "Idempotency-Key": idempotencyKey, }, body: JSON.stringify(body), signal: AbortSignal.timeout(Math.min(attemptTimeoutMs, deadlineMs - (Date.now() - started))), }); if (res.ok) { const pdf = Buffer.from(await res.arrayBuffer()); log({ attempt, status: res.status, outcome: "success", idempotencyKey }); return { ok: true, pdf, attempts: attempt, idempotencyKey }; } lastError = await toApiError(res); if (res.status === 429) waitMs = parseRetryAfter(res.headers.get("retry-after")); } catch (e: any) { const timedOut = e?.name === "TimeoutError"; lastError = { status: null, type: timedOut ? "timeout" : "network_error", message: timedOut ? "No response before the timeout. The render may still have run." : String(e?.cause?.code ?? e?.message ?? e), retryable: true, }; } log({ attempt, status: lastError.status, type: lastError.type, retryable: lastError.retryable, idempotencyKey }); if (!lastError.retryable || attempt === maxAttempts) break; const delay = Math.max(waitMs ?? 0, backoff(attempt, baseDelayMs, maxDelayMs)); if ((waitMs ?? 0) > maxRetryAfterMs || Date.now() - started + delay >= deadlineMs) { log({ attempt, outcome: "give_up", reason: "wait exceeds budget", waitMs: Math.round(delay) }); break; } await sleep(delay); } return { ok: false, error: lastError, attempts: Math.min(attempt, maxAttempts), idempotencyKey }; }