// post-retry — client→server POST delivery with bounded retries. // // Functional core: `classifyStatus` and `planPostStep` decide what an // attempt's outcome means and whether to retry. Imperative shell: // `attemptPost` performs one bounded fetch, and `postWithRetry` runs the // loop as a task in the transport's scope. // // Abort is not a retry decision, so the core never sees it: the shell checks // its signal after every await and returns when it has been aborted. import { shouldReconnect, sleep } from "@kyneta/transport" import { CONNECTION_KEY_HEADER, type ConnectionKey } from "./connection-key.js" // --------------------------------------------------------------------------- // Options // --------------------------------------------------------------------------- export interface PostRetryOptions { /** Total attempts, including the first. */ maxAttempts: number baseDelay: number maxDelay: number /** One attempt is abandoned, and counts as failed, after this many ms. */ attemptTimeoutMs: number } export const DEFAULT_POST_RETRY: PostRetryOptions = { maxAttempts: 3, baseDelay: 1000, maxDelay: 10000, attemptTimeoutMs: 10000, } // --------------------------------------------------------------------------- // Functional core // --------------------------------------------------------------------------- export type PostOutcome = | { kind: "delivered" } /** 4xx: the server refused the request, so a retry would be refused too. */ | { kind: "rejected"; status: number } /** Network error, 5xx, or the attempt timed out. */ | { kind: "failed"; reason: string } export type PostStep = | { kind: "done" } | { kind: "retry"; delayMs: number } | { kind: "give-up"; attempts: number; reason: string } export function classifyStatus(status: number): PostOutcome { if (status >= 200 && status < 300) return { kind: "delivered" } if (status >= 400 && status < 500) return { kind: "rejected", status } return { kind: "failed", reason: `HTTP ${status}` } } /** * Decide what follows `attempt` (1-based), given its outcome. Backoff is * `shouldReconnect`'s, whose `maxAttempts` counts retries after the first * try; `opts.maxAttempts` counts every attempt, hence the `- 1`s. */ export function planPostStep( outcome: PostOutcome, attempt: number, opts: PostRetryOptions, random: () => number, ): PostStep { switch (outcome.kind) { case "delivered": return { kind: "done" } case "rejected": return { kind: "give-up", attempts: attempt, reason: `HTTP ${outcome.status}`, } case "failed": { const decision = shouldReconnect( { enabled: true, maxAttempts: opts.maxAttempts - 1, baseDelay: opts.baseDelay, maxDelay: opts.maxDelay, fullJitter: false, }, attempt - 1, random, ) return decision.reconnect ? { kind: "retry", delayMs: decision.delayMs } : { kind: "give-up", attempts: attempt, reason: outcome.reason } } } } // --------------------------------------------------------------------------- // Imperative shell // --------------------------------------------------------------------------- /** * One POST, abandoned after `timeoutMs`. Never rejects. * * When `signal` aborts, the timeout branch wins the race and reports a * timeout. Callers check `signal.aborted` before using the outcome, so that * report is discarded. */ export async function attemptPost( url: string, body: Uint8Array, key: ConnectionKey, signal: AbortSignal, timeoutMs: number, ): Promise { const attempt = new AbortController() const forward = (): void => attempt.abort() if (signal.aborted) attempt.abort() else signal.addEventListener("abort", forward) try { return await Promise.race([ fetch(url, { method: "POST", headers: { "Content-Type": "application/octet-stream", [CONNECTION_KEY_HEADER]: key, }, body, signal: attempt.signal, }).then( (response): PostOutcome => classifyStatus(response.status), (error: unknown): PostOutcome => ({ kind: "failed", reason: error instanceof Error ? error.message : String(error), }), ), sleep(timeoutMs, attempt.signal).then( (): PostOutcome => ({ kind: "failed", reason: `timed out after ${timeoutMs}ms`, }), ), ]) } finally { // Ends whichever branch lost: the timer, or the request. attempt.abort() signal.removeEventListener("abort", forward) } } /** * Deliver `body`, retrying per `opts`. Returns when delivered or when * `signal` aborts; throws when it gives up, so the task scope reports it. */ export async function postWithRetry( url: string, body: Uint8Array, key: ConnectionKey, signal: AbortSignal, opts: PostRetryOptions, random: () => number = Math.random, ): Promise { for (let attempt = 1; ; attempt++) { const outcome = await attemptPost( url, body, key, signal, opts.attemptTimeoutMs, ) if (signal.aborted) return const step = planPostStep(outcome, attempt, opts, random) switch (step.kind) { case "done": return case "give-up": throw new Error( `${step.reason} (after ${step.attempts} attempt${step.attempts === 1 ? "" : "s"})`, ) case "retry": await sleep(step.delayMs, signal) if (signal.aborted) return } } }